I have a discord bot that controls some RGB lights. I want a pattern to repeat. However, I need the loop to break as soon as any new command is typed.
@client.command()
async def rainbow(ctx):
await ctx.send("It is rainbow")
while True:
rainbow_cycle(0.001)
I know while true loops can't be broken but I do not know another way to loop this function. If the full code is needed here is the Github link https://github.com/MichaelMediaGroup/Discord_controlled_lights/blob/main/discord/main.py
Thank you for the help
CodePudding user response:
This isn't the best option I think but it should work:
You could create a new global value for the loop, like this:
loop = False;
@client.command()
async def rainbow(ctx):
await ctx.send("It is rainbow")
global loop
loop = True
while loop:
rainbow_cycle(0.001)
@client.command()
async def anothercommand(ctx):
global loop
loop = False
#Some other stuff here
CodePudding user response:
It may not be the best practice make a while
loop here. Instead use tasks.loop()
available in the discord module that you are using.
Do note this has to manually imported from discord.ext
So it'll look something like this :
from discord.ext import commands, tasks
@bot.command
async def rainbow(ctx):
await ctx.send("It is rainbow")
if rainbow_.is_running():
rainbow_.stop()
else:
rainbow_.start()
@tasks.loop(seconds=0)
async def rainbow_():
# Do your things here
rainbow_cycle(0.001)
Now we have created a non-blocking loop, this loop can be started / stopped by using your command.
Do note :
1] Do not use blocking commands like sleep
inside your tasks (if you want sleep, use asyncio.sleep(foo)
instead
2] Do not not start rainbow_
under on_ready
, because on_ready
gets called multiple times and can create unnecessary instances, however if you do want to start task when ready then make sure it isn't already running first.