0

I'm trying to make a discord bot which has a tasks.loop() which has loop inside it that takes a while to execute and slows down commands as I have further explained here. I was suggested to use threading for the code inside the tasks.loop() and then start it when the loop is run.

However, I have an await inside that function and when I try to run it I get SyntaxError: 'await' outside async function. How would I use threading and async/await together?

F.M
  • 935
  • 13
  • 28

2 Answers2

0

It's generally not a good idea to run coroutines in another thread, nonetheless you can do it with asyncio.run_coroutine_threadsafe

import asyncio

loop = asyncio.get_event_loop()

async def coroutine():
    return await asyncio.sleep(10, "Coroutine")    


coro = coroutine() # Getting the coroutine object

future = asyncio.run_coroutine_threadsafe(coro, loop) # returns a `concurrent.futures.Future` instance
result = future.result()
print(result)

Also take a look at one of my previous answers to run blocking functions in a non-blocking way (you're not gonna have to mess with concurrent.futures.Future and threading, just with asyncio, a much easier way)

Łukasz Kwieciński
  • 13,310
  • 3
  • 17
  • 33
  • Hi, I don't really understand this code and don't know how I would incorporate it in my current code. What I'm trying to do is have discord send a message using `ctx.send()` within the long-running code, which needs `await`. – F.M May 13 '21 at 20:54
  • Why does it need to be in a separate thread? I assumed that the functions inside of them are blocking, to run a blocking function in a non-blocking way refer to the link in my answer – Łukasz Kwieciński May 13 '21 at 21:15
0

If your code is blocking you may want to take a look at eun_in_executor https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor

Of if your code is asynchronous use loop.create_task

It's usually not a good idea to use threading on an asynchronous program.

ChrisDewa
  • 599
  • 3
  • 8