如何在不重新启动bot的情况下停止此discord bot命令?

2024-06-17 15:48:11 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在不重新启动bot的情况下停止此discord bot命令

@bot.command()
async def spam(ctx, *args):
    response = ""
    for arg in args:
        response = response + " " + arg
    while True:
        await ctx.channel.send(response)
        time.sleep(1)

1条回答
网友
1楼 · 发布于 2024-06-17 15:48:11

您可以简单地使用一个变量

bot.some_var = True

while bot.some_var:
    await ctx.send(response)
    if 'some condition met':
        loop = False

如果要在命令中停止循环:

bot.some_var = True

@bot.command()
async def spam(ctx, *args):
    response = ' '.join(args)

    while bot.some_var:
        await ctx.send(response)
        await asyncio.sleep(1)


@bot.command()
async def stop(ctx):
   bot.some_var = False

还有两件事:

  1. 你可以简单地str.join(list)代替你做的那个奇怪的for循环
  2. 使用asyncio.sleep而不是time.sleep,这样代码就不会被阻止

相关问题 更多 >