Search code examples
pythondiscorddiscord.pyconfirmation

Is there a way to make a confirmation in Discord.py?


I have a Discord bot and I'd like to know how I can create a confirmation for my purgeroles command. Here's the command currently:

@client.command(aliases = ['delroles', 'deleteroles', 'cleanseroles'])
async def purgeroles(ctx):
  embed=discord.Embed(title="Purging (deleting) roles...")
  embedcomplete=discord.Embed(title="All possible roles have been purged (deleted)!")
  if (not ctx.author.guild_permissions.manage_roles):
    await ctx.reply("Error: User is missing permission `Manage Roles`")
    return
  await ctx.reply(embed=embed)
  for role in ctx.guild.roles:
    try:
      await role.delete()
    except:
      pass
  await ctx.reply(embed=embedcomplete)

I don't want the bot to just delete all of the roles on command, in case someone runs the command by accident. Is there anyway I can make the bot wait until the author says a message to confirm whether or not the bot should continue?


Solution

  • You can use wait_for for this type of stuff.

    @client.command(aliases = ['delroles', 'deleteroles', 'cleanseroles'])
    async def purgeroles(ctx):
        await ctx.send("Are you sure you want to run this command? (yes/no)")
    
        def check(m): # checking if it's the same user and channel
            return m.author == ctx.author and m.channel == ctx.channel
    
        try: # waiting for message
            response = await client.wait_for('message', check=check, timeout=30.0) # timeout - how long bot waits for message (in seconds)
        except asyncio.TimeoutError: # returning after timeout
            return
    
        # if response is different than yes / y - return
        if response.content.lower() not in ("yes", "y"): # lower() makes everything lowercase to also catch: YeS, YES etc.
            return
    
        # rest of your code