【问题标题】:How can I break a loop in a discord.py command upon execution of another command?如何在执行另一个命令时打破 discord.py 命令中的循环?
【发布时间】:2021-02-22 08:25:55
【问题描述】:
@client.command()
async def activate(ctx, quote, delay: int):
    await ctx.send("Successfully activated SpamMode")
    global a
    a = 1
    while a == 1:
        await ctx.send(quote)
        time.sleep(delay)

所以我在我的 discord 机器人中有这个命令(用 discord.py 制作),它的作用基本上是发送一条消息 quote,每条消息之间有延迟 delay(以秒为单位)我用一个while 循环,有没有办法在执行不同的命令时打破该循环而不必等待 time.sleep(delay) 完成?

@client.command()
async def deactivate(ctx):
    global a
    a = 2
    await ctx.send("Successfully deactivated SpamMode")

所以基本上目前正在发生的事情是,如果我尝试使用这个命令来阻止前一个命令工作,我必须等待time.sleep() 完成,这是我不想要的。任何帮助都将不胜感激。

【问题讨论】:

    标签: python loops command discord.py


    【解决方案1】:

    使用tasks.loop。您可以使用cancel() 方法立即停止它们

    例子:

    from discord.ext import tasks
    
    @client.command()
    async def activate(ctx, quote, delay: int):
        global spam_loop
    
        @tasks.loop(seconds=delay)
        async def spam_loop(q):
            await ctx.send(q)
    
        spam_loop.start(quote)
        await ctx.send("Successfully activated SpamMode")
    
    @client.command()
    async def deactivate(ctx):
        spam_loop.cancel()
        await ctx.send("Successfully deactivated SpamMode")
        
    

    【讨论】:

      猜你喜欢
      • 2020-10-09
      • 2021-06-01
      • 2021-09-19
      • 1970-01-01
      • 2021-01-18
      • 2021-07-27
      • 2015-01-07
      • 1970-01-01
      • 2020-12-31
      相关资源
      最近更新 更多