Python 线程。协同程序的计时器替代方案

Python 线程。协同程序的计时器替代方案,python,discord,discord.py,coroutine,Python,Discord,Discord.py,Coroutine,我正在创建一个discord bot,我想知道是否有任何第三方库可以执行与threading.Timer相同的操作,但具有对discord.client.send的协同路由支持 @client.command(别名=['Timer']) 异步def计时器(ctx,秒,*消息): 等待ctx.send(f“您的计时器{message}已启动,需要{secs}秒才能停止。”) 异步def停止计时器(): 等待ctx.send(如果您的计时器:{message}已结束,它花费了{secs}秒。) de

我正在创建一个discord bot,我想知道是否有任何第三方库可以执行与threading.Timer相同的操作,但具有对discord.client.send的协同路由支持

@client.command(别名=['Timer'])
异步def计时器(ctx,秒,*消息):
等待ctx.send(f“您的计时器{message}已启动,需要{secs}秒才能停止。”)
异步def停止计时器():
等待ctx.send(如果您的计时器:{message}已结束,它花费了{secs}秒。)
def timer_over():
asyncio.run(停止计时器())
simpleTimer=threading.Timer(int(secs),Timer\u over)
simpleTimer.start()

我的代码在上面,我正在寻找一个需要几秒钟的函数,在这几秒钟之后,该函数返回一个协程。有点像闹钟。

discord.ext查看
任务

from discord.ext import tasks

@tasks.loop(seconds=30)
async def my_loop(messageable):
    await messageable.send("Here's some message!")

@bot.command()
async def startloop(ctx):
    my_loop.start(messageable=ctx)
这将发送
以下是一些消息每30秒发送给任何可发送消息的对象


参考资料:
  • -这是文本频道、用户等内容。您可以在文档中看到从中继承的内容
  • -停止循环
  • -启动回路

    • 感谢@Diggy提到
      asyncio.sleep

      这是一个符合我要求的代码:

      @client.command(别名=['Timer'])
      异步def计时器(ctx,秒,*消息):
      globalsecs=secs
      等待ctx.send(f“计时器{message}启动,需要{secs}秒才能结束。”)
      等待异步睡眠(整数秒)
      等待发送消息(message=f'您的计时器:{message}已结束,花费了{secs}秒',ctx=ctx)
      异步def发送消息(ctx,消息):
      等待ctx发送(消息)
      
      这里有一个非常简单的示例(例如您的计时器示例):

      @client.command(别名=['Timer'])
      异步def计时器(ctx,秒,*消息):
      如果秒数小于1:
      等待ctx.send(“你不能给出低于1秒的时间!”)
      其他:
      timer=wait ctx.send(f“您的计时器{message}已启动,需要{secs}秒才能停止。”)
      尽管如此:
      如果秒>0:
      等待asyncio.sleep(1)
      秒-=1
      wait timer.edit(content=f“您的计时器{message}已启动,需要{secs}秒才能停止。”)
      其他:
      等待ctx.send(如果您的计时器:{message}已结束,它花费了{secs}秒。)
      

      也许这对您有所帮助。

      tasks每n秒重复一次消息,我只想做一次,就像警报一样,就像线程一样。Timer@Zac装饰循环时,可以使用
      count
      kwarg。它将指定您希望循环实际循环的次数,即
      @tasks.loop(计数=1,秒=30)
      只会让它运行一次。当我使用
      count=1
      时,它只会在我使用命令并停止时立即发送消息一次。有没有办法使用
      count=2
      并且第一次计数不发送任何消息?@Zac你可以使用
      等待异步。sleep(x)
      睡眠一定时间,然后做些什么?这是
      time.sleep()
      的异步版本,如果有任何帮助的话。还有一个问题,那就是你想要的更多。
      @client.command(aliases = ['Timer'])
      async def timer(ctx, secs, *message):
          if secs < 1:
              await ctx.send("You can't give seconds lower than 1!")
          else:
              timer = await ctx.send(f"Your timer {message} started, and it is gonna take {secs}secs to stop.")
              while True:
                  if secs > 0:
                      await asyncio.sleep(1)
                      secs -= 1
                      await timer.edit(content=f"Your timer {message} started, and it is gonna take {secs}secs to stop.")
                  else:
                      await ctx.send(f'Your timer: {message} is over, it took {secs} secs.')