python - 停止任务discord.py

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

最佳答案

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

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))

关于python - 停止任务discord.py,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64463973/

相关文章:

python - 使用 groupby 按条件对 pandas 列求和

python - 使用 re.sub 并出现错误

python - 为什么这个 PIL 图像没有越过另一个?

python - 有没有办法让我们在discord.py中一次获取多个命令的剩余冷却时间?

python - 使用包在多个模块之间拆分 Python 类

python - 矩阵类定义

python - 从 blob 中删除文件 - TypeError : quote_from_bytes() expected bytes

python - 如何检查用户是否提供了参数 discord.py

youtube - 使用 YouTube API 搜索 channel 返回错误结果

python - Discord.py 的 on_member_leave 事件不起作用