Home > database >  How to break a while loop using asyncio in discord python?
How to break a while loop using asyncio in discord python?

Time:04-02

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

I'm trying to make it so when I type !stop, the !hello command loop ends, but my code does not work.

CodePudding user response:

This seems to work:

@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")

Also if you have overridden on_command_error event you can use this to avoid triggering it:

@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")
  • Related