如何实现同时支持指定角色与特定权限可用的Discord机器人命令
问题原因
discord.py 中多个命令校验装饰器叠加时默认执行逻辑与校验,即用户必须同时满足所有装饰器的校验规则才能调用命令。你叠加了@commands.has_permissions(manage_guild=True)和@commands.has_role('DJ')后,要求用户同时持有DJ角色+管理服务器权限才能调用,和你「满足任意一个条件即可使用」的需求不符,因此会抛出权限缺失错误。
正确实现方案
使用自定义校验器实现逻辑或的校验规则,示例代码如下:
首先定义可复用的自定义校验装饰器:
from discord.ext import commands # 自定义校验:满足DJ角色 或 管理频道权限任意一项即可通过 def has_dj_role_or_manage_channels_perm(): async def check_rule(ctx): # 校验两个条件任意一个成立即可 has_dj = commands.has_role("DJ").predicate(ctx) has_manage_perm = commands.has_permissions(manage_channels=True).predicate(ctx) return any([await has_dj, await has_manage_perm]) return commands.check(check_rule)
然后在你需要做校验的命令上使用该装饰器即可:
@bot.command() @has_dj_role_or_manage_channels_perm() async def your_command(ctx): # 你的命令逻辑 await ctx.send("命令执行成功")
如果你实际需要的是管理服务器权限而非管理频道权限,将上述代码中的manage_channels=True替换为manage_guild=True即可。
可选优化
- 若要避免DJ角色改名后校验失效,可以将
commands.has_role("DJ")替换为commands.has_role(你的DJ角色数字ID) - 可以添加自定义错误提示,避免抛出默认的无意义错误信息:
@your_command.error async def your_command_error(ctx, error): if isinstance(error, commands.CheckFailure): await ctx.send("⚠️ 你需要持有DJ角色或拥有对应管理权限才能使用该命令", delete_after=5)
内容的提问来源于stack exchange,提问作者felixoofed
相关产品推荐
相关产品推荐

