我有一个带有嵌套函数的命令on_message。满足特定条件时如何停止它?
例子:
@bot.command()
async def test(ctx):
await ctx.send('started')
@bot.event
async def on_message(mes):
if mes.author.bot:
return
msg = mes.content
if msg != 'break':
await ctx.send('do something')
else:
await ctx.send('stoped')
await bot.process_commands(mes)
return
当您键入时,break机器人会写stoped,但不会停止do something在每条消息上说话。
您正确地注意到
while True: pass这种情况下的循环不是最佳解决方案。毕竟,通过写“ break ”“停止”该功能后,它不再有反应,但仍会工作并使用系统资源。on_message()最好与其他函数分开创建一个事件,并在全局范围内使用它来接收所有机器人消息。一般来说,在这种情况下,最好将函数
on_message()留在 bot 命令test()中。从文档中我们了解了方法
wait_for(),我们将在单独的命令中使用它。在这段代码中,在一个循环中,我们一直在等待一个消息,如果写了“ break ”,
return就会中断函数的执行,完全完成它。