【问题标题】:stopping a task discord.py停止任务 discord.py
【发布时间】:2020-10-21 12:52:57
【问题描述】:

我制作了一个 Discord 机器人,它每 15 分钟循环一次任务。我已经让它按预期工作,但现在我想添加一个命令来停止和启动任务。这是我的部分代码:

class a(commands.Cog):
def __init__(self, client):
    self.client = client

    @tasks.loop(minutes=15.0)
    async def b(self):
        #do something
        
    b.start(self)
    
    @commands.command(pass_context=True)
    async def stopb(self, ctx):
        b.cancel(self)

def setup(client):
    client.add_cog(a(client))

当我使用命令 stopb 时,会返回一个错误,指出该 stopb 未定义。我试图改变缩进,但错误是 b 没有定义。上面的代码是 cog 的一部分。在我的主文件中,我有一个可以加载和卸载齿轮的命令,但这不会停止任务。

【问题讨论】:

    标签: python discord.py


    【解决方案1】:

    您可以创建自己的任务函数并将其添加到机器人的循环中,而不是使用循环装饰器。这样就可以存储具有取消功能的任务对象了。

    class a(commands.Cog):
        def __init__(self, client):
            self.client = client
            self.task = self.client.loop.create_task(self.b())
    
    
        async def b(self):
            while True:
                #do something
    
                await asyncio.sleep(900)
                
        @commands.command(pass_context=True)
        async def stopb(self, ctx):
            self.task.cancel()
    
    
    def setup(client):
        client.add_cog(a(client))
    

    【讨论】:

    • bot.cogs["a"].b.cancel() 应该可以工作,不是吗?
    猜你喜欢
    • 1970-01-01
    • 2011-10-24
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多