簡體   English   中英

如何在 discord.python 中使用 asyncio 打破 while 循環?

[英]How to break a while loop using asyncio in discord python?

client = commands.Bot(command_prefix = '!')
stop_var = False

@client.event
async def on_ready():
  print('Bot is ready.')

@client.command()
async def hello(ctx):
  while (stop_var==False):
    await asyncio.sleep(1)
    await ctx.send('Hello!')
    if stop_var:
      break

@client.command()
async def stop(ctx):
  await ctx.send('Stopped!')
  stop_var = True

我試圖做到這一點,所以當我輸入時,停止,.hello 命令循環結束,但我的代碼不起作用。

這似乎有效:

@client.command()
async def hello(ctx):
    stop_var = False
    while (not stop_var):
        await asyncio.sleep(1)
        await ctx.send('Hello!')
        def check(msg: discord.Message):
            return not msg.author.bot and msg.content.lower() == "!stop"
        try:
            if await client.wait_for("message", check=check, timeout=1.5):
                await ctx.send("Stopped")
                stop_var = True
        except asyncio.TimeoutError:
            print("no stop")

此外,如果您覆蓋on_command_error事件,您可以使用它來避免觸發它:

@client.command()
async def hello(ctx):
    stop_var = False
    while (not stop_var):
        await asyncio.sleep(1)
        await ctx.send('Hello!')
        def check(ctx):
            return not ctx.author.bot and ctx.command.name == "stop"
        try:
            if await client.wait_for("command", check=check, timeout=1.5):
                stop_var = True
        except asyncio.TimeoutError:
            print("no stop")


@client.command()
async def stop(ctx):
    await ctx.send("Stopped")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM