简体   繁体   English

threading.Timer 协程的替代方案

[英]threading.Timer alternative for coroutines

Im creating a discord bot and I wanted to know if there is any third party libraries that do the same thing as threading.Timer but with coroutine support for Discord.client.send.我正在创建一个 discord 机器人,我想知道是否有任何第三方库与 threading.Timer 做同样的事情,但支持 Discord.client.send 的协程。

@client.command(aliases = ['Timer'])
async def timer(ctx, secs, *message):
    await ctx.send(f"Your timer {message} started, and it is gonna take {secs}secs to stop.")

    async def stop_timer():
        await ctx.send(f'Your timer: {message} is over, it took {secs} secs.')

    def timer_over():
        asyncio.run(stop_timer())
        
    simpleTimer = threading.Timer(int(secs), timer_over)
    simpleTimer.start()

My code up there, im looking for a function that takes some seconds and after those seconds the function returns a coroutine.我的代码在那里,我正在寻找一个 function 需要几秒钟,然后在几秒钟后 function 返回一个协程。 Kinda like an alarm.有点像闹钟

Check out tasks from discord.ext :查看discord.ext中的tasks

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)

This will send Here's some message!这将发送Here's some message! to whatever messageable object you give it every 30 seconds.你每 30 秒给它一个消息 object。


References:参考:

Thanks @Diggy for mentioning asyncio.sleep感谢@Diggy 提到asyncio.sleep

This is the code that fits what I want and works:这是适合我想要和工作的代码:

@client.command(aliases = ['Timer'])
async def timer(ctx, secs, *message):
    globalsecs = secs
    await ctx.send(f"The timer {message} started and it is going to take {secs} secs to be over.")
    await asyncio.sleep(int(secs))
    await send_message(message = f'Your timer:{message} is over, it took {secs}secs.', ctx = ctx)
    
async def send_message(ctx, message):
    await ctx.send(message)

Here's a pretty simple example (for your example with the timer):这是一个非常简单的示例(对于您的计时器示例):

@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.')

Maybe this helps you..也许这对你有帮助..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM