Issue
I am writing a bot for Discord which can create a timer and notify when it runs out. With the code that i have right now the bot sleeps for that amount of time and then messages saying that time is up. (uses discord.py)
@bot.command(name='create')
async def create_schedule(ctx, title: str, mins: float):
await ctx.send(f'Created schedule for {title} in {mins} minutes')
time.sleep(60*mins)
await ctx.send(f'{title} is starting now!')
But the problem is that i can't create two schedules at the same time since the second one will be put in queue, wait for the first one to finish and then start the timer. I have tried to create a new thread and sleep in that thread so that i can accept another create command but that didn't work.
async def wait(ctx, title, mins):
time.sleep(int(60*mins))
await ctx.send(f'{title} is starting now!')
@bot.command(name='create')
async def create_schedule(ctx, title: str, mins: float):
await ctx.send(f'Created schedule for {title} in {mins} minutes')
threading.Thread(target=wait, args=(ctx, title, mins)).start()
I dont want to wait for the wait()
function to finish before i accept another command. I just want to start up the timer, set it aside and continue parsing other commands. How can i do this? BTW The wait()
function has a way of displaying that the time is up (ctx.send(f'{title} is starting now!')
) so it doesn't have to return anything or call any other part of the program after the timer is done sleeping (and i don't want it to do anything else after the time is up).
Thanks in advance
Solution
The following code made it work. I changed from create a thread to using a Task from asyncio. Also as pointed out by @dano, i used asyncio.sleep
instead of time.sleep
async def wait(ctx, title, mins):
await asyncio.sleep(int(60*mins))
await ctx.send(f'{title} is starting now!')
@bot.command(name='create')
async def create_schedule(ctx, title: str, mins: float):
await ctx.send(f'Created schedule for {title} in {mins} minutes')
asyncio.create_task(wait(ctx, title, mins))
Answered By - Tejaswi Hegde
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.