Python Discord Bot 取消命令

Python Discord Bot cancel command

你好,我想用 Python 制作一个有趣的 Discord 机器人,我写了一个垃圾邮件命令。现在我想创建一个新命令来停止它。

命令如下:

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

有办法吗?

有一个简单的解决方案。在函数 spam 之外,声明一个具有任意名称(即 stop)的 bool 变量,并将该值实例化为 False。在垃圾邮件功能中。在 spam 函数中,声明 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) 来完成