0

I am coding a command (/mc, / is the prefix) for my discord bot to get and message a result. But getting the result takes a lot of time. To prevent multiple request at a time, I placed the code of getting the results in a separate function mainmc() (not async) and call mainmc as a thread by creating a new class mainThreadMC(threading.Thread) to start the thread, and create a new class object and start it, so that when there's multiple request the command will run instantly without having to wait for the previous one. But quickly after I run it, I've found out that it's not possible as sending a message needs await or else it won't work. But if you have await in a function the function needs async. That means I have to edit the module threading to make it work? And surely this is not the way to do it. But what should I do?

Here's the code (simplified):

class mainThreadMC(threading.Thread):
    def __init__(self, threadID, name, ctx,args):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.args = args
        self.ctx = ctx
    def run(self):
        logger.info("Starting " + self.name)
        mainmc(self.ctx,self.args)
        logger.info(f'Exiting {self.name}')

def mainmc(ctx,args):
    # fetching data... creating / editing variable embed
    ctx.send(embed=embed)  #ERROR!!!!!!!!!!!
    # finalize...
    return

@bot.command(name='mc',pass_content=True)
async def mc(ctx,*,args=""):
    global runno
    threadMainMC = mainThreadMC(runno,f"MainMC_{str(runno)}",ctx,args)
    threadMainMC.start()

(I just want it to work, so if you have some alternative solutions you can also tell me.)

Thanks for helping.

  • what is it you are trying to do in mainmc? It may be possible to do with the `discord.py` library or with coroutines – Benjin Mar 23 '20 at 15:10
  • Basically getting the info of Minecraft servers. Here's the code: [bot.py](https://github.com/windowsboy111/KCCS-official) I used the library mcstatus to get the info. It will open ANOTHER THREAD (yeah you heard it right) to get the info. –  Mar 23 '20 at 16:36
  • Have a look at this: https://stackoverflow.com/questions/53587063/using-subprocess-to-avoid-long-running-task-from-disconnecting-discord-py-bot/53597795#53597795 It may point you in the right direction. – Benjin Mar 23 '20 at 19:40
  • I've tried the answer. When there's multiple request it stills don't process them at the same time despite i can pass back the message. –  Mar 24 '20 at 01:19
  • Can't your thread return a value then you send it in the command function? – Gugu72 Mar 24 '20 at 07:40
  • threads can NOT return values, so i get the value from the thread via editing / getting global values. –  Mar 24 '20 at 07:59

0 Answers0