0

I have a issue that I need help. I created a bot that takes input from Discord Users and runs it to analyze for some calculations. These calculations takes 40-50 seconds usually and return the result as a reply in Discord. So far everything is fine.

But when other users or same user types another words in Discord while the previous one is in progress (calculation), the new one doesn't start to get calculated until the previous one gets done. I want the new one starts while the previous one is in progress. How can I edit this to make it right? Illuminate me. Thanks.

import discord
from threading import Thread
import asyncio

client = discord.Client()

async def init():
   loop = asyncio.get_event_loop()
   loop.create_task(client.start('TOKEN'))
   await Thread(target=loop.run_forever).start()

@client.event
async def on_ready():
   print("we've logged in as {0.user}".format(client))  

@client.event
async def on_message(message):
   if message.author == client.user:
       return
   if message.content.startswith('!'):
       try:
           #calculation codes
           await message.reply("calculation results")
       except:
           await message.reply("bla bla bla")
  • Why are you using multithreading with discord.py? It works perfectly fine with the standard await/async – TheFungusAmongUs May 19 '22 at 22:24
  • @TheFungusAmongUs no it doesn't work the way I mention above, still waiting for the previous one to get done to start the next one – Calvin Belfort May 19 '22 at 22:31
  • But that's not how it works. If you run the bot simply with `client.run`, messages will be processed concurrently. – TheFungusAmongUs May 19 '22 at 22:39
  • @TheFungusAmongUs I also tried it simply with 'client.run' and take out def init func. but it's not taking it concurrently, I'm tryna get a solution for days, it's a very interesting issue – Calvin Belfort May 20 '22 at 11:10
  • What exactly is your calculation code doing? It may be blocking, causing the rest of your bot to freeze – Benjin May 20 '22 at 12:22
  • @Benjin I was just looking over there. Yes you are right, a function which I imported to calculate is causing to block it. When I take out the imported function while calculating it, it takes concurrently. What should I do in such a case? Should I run the imported function(calculation function) in an another thread? What kind of logic should I think? – Calvin Belfort May 20 '22 at 12:44
  • @TheFungusAmongUs I took one more step, you are right. Even simply with `client.run` it runs concurrently. An imported function in the calculation causes to block it. I'm tryna get a solution for that now. – Calvin Belfort May 20 '22 at 12:47
  • If there is not an `async` version of the function, then you can run it like [this](https://stackoverflow.com/questions/53587063/using-subprocess-to-avoid-long-running-task-from-disconnecting-discord-py-bot/53597795#53597795) – Benjin May 20 '22 at 12:50

0 Answers0