So I have written a bot which spams like this :
@bot.command()
async def start (ctx):
while True:
await ctx.send("Pls use correct channels for discussion")
await asyncio.sleep(300)
When i enter $start, the function starts. How to make a new command like $stop to stop the spam?
The answer by Cohen only prevents you from starting it, but it doesn't allow you to stop the infinite loop once it's going. What you should actually do, is check the value of the variable inside of the loop, in order to be able to stop it. Also, use booleans
instead of hardcoding "true" and "false" in strings
.
spam = True
@bot.command()
async def start (ctx):
# EDIT: Set spam to True again so you can restart the loop
global spam
spam = True
while true:
# If "spam" is set to False, stop looping
if not spam:
break
await ctx.send("Pls use correct channels for discussion")
await asyncio.sleep(300)
@bot.command()
async def stop (ctx):
global spam
spam = False
await ctx.send('spam stopped')
This checks whether or not it should keep running on every iteration of the loop. That way, when you set it to False
, the loop stops.