获得 discord.py 的角色

Get a role with discord.py

我正在尝试获取用户角色来执行命令:

async def clear (ctx, n):
    if "Mod" in [y.name.lower() for y in ctx.message.author.roles]:
       //delete messages
    else:
       client.send_message(ctx.message.channel, "You are not allowed to use this command!")

普通用户使用!clear时,可以清除消息,但也会出现权限错误。

代码:

@bot.command(pass_context=True)
async def clear(ctx, n):
   if "mod" in [y.name.lower() for y in ctx.message.author.roles]:
       n = int(n)
       tn = n + 1
       async for x in bot.logs_from(ctx.message.channel, limit=tn):
          await bot.delete_messages(x)

          await bot.send_message(ctx.message.channel, "Deleted" + str(n) + "messages")
   elif not "mod" in [y.name.lower() for y in ctx.message.author.roles]:
       await bot.send_message(ctx.message.channel, "You need the **Mod** role to use this command!")

普通用户使用!clear时,可以清除消息,但也会出现权限错误。

解决方案:

@bot.command(pass_context=True)
async def clear(ctx, n):
   if "mod" in [y.name.lower() for y in ctx.message.author.roles]:
       n = int(n)
       msg = []
       tn = n + 1
       async for x in bot.logs_from(ctx.message.channel, limit=tn):
          msg.append(x)
          await bot.delete_messages(x)

       await bot.send_message(ctx.message.channel, "Deleted" + str(n) + "messages")
   elif not "mod" in [y.name.lower() for y in ctx.message.author.roles]:
       await bot.send_message(ctx.message.channel, "You need the **Mod** role to use this command!")

具有 Mod 角色的用户也至少具有 @everyone 角色。所以你需要将 else 更改为 elif not "Mod" in [y.name.lower() for y in ctx.message.author.roles]:.