简体   繁体   English

Python Discord 机器人取消命令

[英]Python Discord Bot cancel command

Hello I want to make a fun Discord bot with Python, I wrote a spam command.您好,我想用 Python 制作一个有趣的 Discord 机器人,我写了一个垃圾邮件命令。 Now I want to make a new command that stop this.现在我想做一个新的命令来阻止它。

Here is the command:这是命令:

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

Is there a way to do this?有没有办法做到这一点?

There is an easy solution to this.有一个简单的解决方案。 Outside of the function spam , declare a bool variable with any name (ie stop ), and instantiate that value to False .在 function spam之外,声明一个具有任何名称(即stop )的bool变量,并将该值实例化为False Inside the spam function.内部垃圾邮件 function。 Inside the spam function, declare global stop and re-instantiate stop to False .在垃圾邮件 function 中,声明global stop并将stop重新实例化为False Then just use a while loop to know when to stop, and create another command that will update the stop value to True ending the spam command.然后只需使用 while 循环来知道何时停止,并创建另一个命令,将停止值更新为True结束垃圾邮件命令。

The solution would look like the following:解决方案如下所示:

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

From here, you can add any other logic necessary regarding your command.从这里,您可以添加有关您的命令所需的任何其他逻辑。

It is also recommended to sleep the thread in between messages as to not overload your server.还建议在消息之间休眠线程,以免服务器过载。 This can be done by importing the time module and injecting the line time.sleep(1) after the line await ctx.send(msg) .这可以通过导入time模块并在await ctx.send(msg)行之后注入行 time.sleep time.sleep(1)来完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM