首页 > 解决方案 > 只允许特定角色使用命令

问题描述

我一直在发出命令来更改用户的角色,但目前,每个人都可以使用它。我已经尝试过做一些事情。这是我的代码:

async def addrole(ctx, user: discord.Member, role: discord.Role):
    await user.add_roles(role)
    await ctx.send(f"I gave {user.name} the role {role.name}")

这是我唯一能想到的:

allowed = ["Role 1"]
if message.author.role in allowed:
   async def addrole(ctx, user: discord.Member, role: discord.Role):
      await user.add_roles(role)
      await ctx.send(f"I gave {user.name} the role {role.name}")

提前致谢!

标签: discord.py

解决方案


只需添加@commands.has_any_roles()

@bot.command()
@commands.has_any_roles("Role 1", "Role 2")
async def addrole(ctx, user: discord.Member, role: discord.Role):
    await user.add_roles(role)
    await ctx.send(f"I gave {user.name} the role {role.name}")

如果不允许用户使用该命令,则会引发commands.MissingAnyRole错误。


推荐阅读