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 没有定义。上面的代码是 cog 的一部分。在我的主文件中,我有一个可以加载和卸载齿轮的命令,但这不会停止任务。
解决方案
您可以创建自己的任务函数并将其添加到机器人的循环中,而不是使用循环装饰器。这样您就可以存储具有取消功能的任务对象。
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 - 使用 MIMEApplication 将 Pandas Dataframe 转换为电子邮件附件
- json - 无法将道具传递给Vue js中的子组件
- javascript - 在表格元素上传递对象
- python - 使用 glob ** 根据递归参数匹配文件扩展名
- python - 无法使用 scrapy 从 Johns Hopkins covid-19 网站抓取
- java - 当一个方法返回一个 String 时,它是一个字面量还是一个 String 对象?
- html - 为了使文本在图像上居中,为什么必须将容器设置为位置:相对?
- python - Python Selenium SyntaxError:无法在“文档”上执行“评估”:字符串'//div [包含(@class,'product-card__subtitle')
- javascript - Flagging cells in grid (Minesweeper in plain JavaScript + p5.js framework)
- html - 粘性元素在 Flex 框中不起作用