我怎样才能做到只有特定角色才能使用带 discord.py 的命令?

How can I make it so only a certain role can use a command with discord.py?

我正在尝试创建一个仅适用于特定角色的命令。我不是 100% 确定如何执行此操作,而且我在其他任何地方都找不到解决方案。我的代码停止了,因为我还不太熟悉编码,但这里是:

@bot.command()
async def sign(ctx, member: discordMember):
 if ctx.author.server_roles

从这里我完全迷路了,不知道该做什么。

使命令只能用于特定角色的最有效方法是 .has_role() 装饰器。您可以在其中放置一个包含角色名称(区分大小写)或角色 ID(推荐)的字符串,更多信息可以在 documentation 中找到,这是一个示例:

@bot.command()
@commands.has_role("Administrator")
async def foo(ctx)
   await ctx.send("bar")

如果你想让用户只有在他有任何角色时才能使用这个命令,那么 .has_any_role() 将是可行的方法,它也需要字符串或整数。您可以找到有关它的更多信息 here。这是一个简单的例子,说明它是如何工作的:

@bot.command()
@commands.has_any_role("Administrators", "Moderators", 492212595072434186)
async def foo(ctx):
    await ctx.send("bar")

编码愉快!

通常当有人试图用 .has_role 装饰器执行这样的命令时,会引发 discord.ext.commands.MissingRole,因此处理它会是这样的:

@bot.command()
@commands.has_any_role("Administrators", "Moderators", 492212595072434186)
async def foo(ctx):
    try:
       await ctx.send("bar")
    except commands.MissingRole:
       await ctx.send("lol")

当然,如果你有很多命令,那么我会推荐使用全局错误处理程序。