Home > OS >  async functions as callback for threading.Timer
async functions as callback for threading.Timer

Time:11-26

I'm having trouble with using threading package in Python. I want to create discord bot that sends message after some time. Previously i was using time.sleep() but it makes my bot useless for a given period of time. I found that i can use threading.Timer() but I can't make it work. Sample code:

async def send_sth(channel):
    await channel.send("some message")


client = discord.Client()


@client.event
async def on_message(message):
    if message.content == 'send sth':
        timer = threading.Timer(10.0, send_sth, [message.channel])
        timer.start()

after 10 seconds i have error saying RuntimeWarning: coroutine 'send_sth' was never awaited. Is it possible to run async functions with Timer callback?

CodePudding user response:

It was easier than i thought

client = discord.Client()


@client.event
async def on_message(message):
    if message.content == 'send sth':
        await asyncio.sleep(10)
        await message.channel.send("some message")
  • Related