Asynchronous 如何取消discord.py中的asyncio.sleep命令

Asynchronous 如何取消discord.py中的asyncio.sleep命令,asynchronous,discord,python-asyncio,sleep,discord.py,Asynchronous,Discord,Python Asyncio,Sleep,Discord.py,我的机器人中有一个定时器命令,它使用asyncio.sleep。如果用户愿意,我想发出一个取消计时器的命令 @bot.command() async def timer(ctx, time: int): await ctx.send('Timer set for ' + str(time) + ' seconds') await asyncio.sleep(time) await ctx.send('Time over!') 有没有办法做到这一点(我更喜欢不制作新文件的方法,

我的机器人中有一个定时器命令,它使用asyncio.sleep。如果用户愿意,我想发出一个取消计时器的命令

@bot.command()
async def timer(ctx, time: int):
   await ctx.send('Timer set for ' + str(time) + ' seconds')
   await asyncio.sleep(time)
   await ctx.send('Time over!')
有没有办法做到这一点(我更喜欢不制作新文件的方法,在同一个文件中进行)

参考

asyncio代码的贷项为

您可以(由vincent)添加此函数:

这种情况下的用法是:

@bot.command()
async def timer(ctx, time: int):
   await ctx.send('Timer set for ' + str(time) + ' seconds')
   await sleep(time)
   await ctx.send('Time over!')

@bot.command()
async def canceltimers(ctx):
    sleep.cancel_all()
    await asyncio.wait(sleep.tasks)
    await ctx.send('Timers cancelled')
您将在放置
sleep=make\u sleep()
之前运行您的
bot.run(令牌)
,否则它将无法工作

现在,我们面临的问题是这个代码;我们取消了所有的计时器;这当然不是我们想要的,因为会有明显的冲突。你怎么做完全取决于你自己;但是您可以尝试在由userID存储的sleep函数中添加一个标识符。这真的取决于你,但这是背后的理论和基本代码

@bot.command()
async def timer(ctx, time: int):
   await ctx.send('Timer set for ' + str(time) + ' seconds')
   await sleep(time)
   await ctx.send('Time over!')

@bot.command()
async def canceltimers(ctx):
    sleep.cancel_all()
    await asyncio.wait(sleep.tasks)
    await ctx.send('Timers cancelled')