根据新命令中断循环



我有一个控制一些RGB灯光的discord机器人。我想要一个重复的模式。但是,我需要在键入任何新命令后立即中断循环。

@client.command()
async def rainbow(ctx):
await ctx.send("It is rainbow")
while True:
rainbow_cycle(0.001)

我知道真正的循环不能被打破,但我不知道循环这个函数的另一种方法。如果需要完整的代码,这里是Github链接https://github.com/MichaelMediaGroup/Discord_controlled_lights/blob/main/discord/main.py

感谢的帮助

我认为这不是最好的选择,但它应该有效:

您可以为循环创建一个新的全局值,如下所示:

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

在这里进行while循环可能不是最佳做法。相反,请使用您正在使用的discord模块中提供的tasks.loop()。请注意,必须从discord.ext手动导入所以它看起来像这样:

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)

现在我们已经创建了一个非阻塞循环,可以使用您的命令启动/停止这个循环。

注意

1] 不要在任务中使用像sleep这样的阻塞命令(如果你想睡觉,请使用asyncio.sleep(foo)(

2] 不要在on_ready下启动rainbow_,因为on_ready会被多次调用,可能会创建不必要的实例,但若您确实希望在准备就绪时启动任务,请确保它还没有首先运行。

最新更新