Hello I want to make a fun Discord bot with Python, I wrote a spam command. 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 (i.e. stop
), and instantiate that value to False
. Inside the spam function. Inside the spam function, declare global stop
and re-instantiate stop
to 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.
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)
.