停止任务discord.py

时间:2020-10-21 12:52:57

标签: python discord.py

我制作了一个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。上面的代码是齿轮的一部分。在我的主文件中,我有一个可以加载和卸载齿轮的命令,但这不会停止任务。

1 个答案:

答案 0 :(得分: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))