有没有办法在Discord.py中进行确认?

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

我有一个 Discord 机器人,我想知道如何为我的 purgeroles 命令创建确认。这是当前的命令:

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

我不希望机器人根据命令删除所有角色,以防有人意外运行命令。有没有办法让bot一直等到作者发消息确认bot要不要继续?

你可以使用 client.wait_for.

@client.event
async def on_message(message):
    if message.content.startswith('$greet'):
        channel = message.channel
        await channel.send('Say hello!')

        def check(m):
            return m.content == 'hello' and m.channel == channel

        msg = await client.wait_for('message', check=check)
        await channel.send('Hello {.author}!'.format(msg))

More info in the Discord docs.

您可以使用 wait_for 处理此类内容。

@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