0

Is it possible to run a function detached from the main loop?

the reason for this is that I have the one function that runs every time a message is sent and if I operate a command from it, it holds until that command is done before exiting the function and allowing a new message to enter. so I need to detach it from the main loop and let it runs on its own until it's done.

I tried running it asynchronously with loop.create_task(run_command(input)) but it still waits for the command to finish before exiting the containing function, not allowing input during that time.

here is a basic example

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith(Config.prefix):
        loop = asyncio.get_event_loop()
        if command in commands.List:
            loop.create_task(getattr(commands, command)().call(message))
  • 3
    Task is [a way](https://stackoverflow.com/a/37345564/1113207) to run coroutine "in background", so everything should work. Can you provide reproducible code example so we could see the problem? – Mikhail Gerasimov Oct 25 '19 at 05:23
  • @MikhailGerasimov I tried using `asyncio.ensure_future` but it still locks up and doesn't accept new input :( – The_RedstoneBldr Oct 25 '19 at 19:41
  • If your command is written asynchrounously, this should happen automatically. You likely have a blocking operation in your code. You should share the code for the command, and we can look for something that could be blocking the event loop. – Patrick Haugh Oct 25 '19 at 23:46
  • @PatrickHaugh yes one of the commands has a blocking operation. but what I want to do is have it run the command and continue to listen for input. because I am trying to make the command be interactive, you say something and the bot responds. so there is a socket thats broadcasting every message and the command has a receiver that holds and waits for input. – The_RedstoneBldr Oct 26 '19 at 00:47
  • The answer is going to depend on what you want the command to do. Anything that interacts with Discord (reacting, sending messages, etc) will have to be done in the same thread/event loop as the bot. – Patrick Haugh Oct 26 '19 at 03:35

0 Answers0