首页 > 解决方案 > 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)

有没有办法做到这一点?

标签: pythoncommanddiscordbots

解决方案


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

解决方案如下所示:

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注入该行来完成。time.sleep(1)await ctx.send(msg)


推荐阅读