Python Discord Bot取消命令



你好,我想用Python制作一个有趣的Discord机器人,我写了一个垃圾邮件命令。现在我想制作一个新的命令来阻止这种情况。

这是命令:

@commands.command()
async def spam(self,ctx, msg="hi", *, amount=1):
for i in range(0, amount):
await ctx.send(msg)

有办法做到这一点吗?

有一个简单的解决方案。在函数spam之外,声明一个具有任意名称的bool变量(即stop(,并将该值实例化为False。垃圾邮件功能内部。在垃圾邮件函数中,声明global stop并将stop重新实例化为False。然后只需使用while循环来知道何时停止,并创建另一个命令,将停止值更新为True,结束垃圾邮件命令。

解决方案如下所示:

stop = False
@commands.command()
async def spam(self, ctx, msg='hi', *, amount=1):
global stop
stop = False
i = 0
while not stop and i < amount:
await ctx.send(msg)
i += 1
@commands.command()
async def stop(self, ctx):
global stop
stop = True

从这里,您可以添加与您的命令相关的任何其他必要逻辑。

还建议在消息之间休眠线程,以免服务器过载。这可以通过导入time模块并在线路await ctx.send(msg)之后注入线路time.sleep(1)来实现。

最新更新