You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py如何设置命令只要通过任意一个校验即可触发执行?

解决方案

完全可以实现该需求,discord.py 内置了check_any装饰器,专门用于组合多个校验规则实现任意一个校验通过即可执行命令的或逻辑。


实现步骤

1. 导入所需依赖

首先从discord.ext.commands中导入需要用到的工具:

from discord.ext.commands import has_permissions, check_any, CheckFailure, check

2. 编写自定义校验规则

你可以根据需求编写任意自定义校验函数,以下是指定用户放行、指定角色放行的示例:

# 自定义校验:允许指定ID的用户跳过其他权限校验执行命令
def allow_specified_users():
    async def predicate(ctx):
        # 替换为你需要放行的用户ID列表
        allowed_user_ids = [123456789012345678, 987654321098765432]
        return ctx.author.id in allowed_user_ids
    return check(predicate)

# 自定义校验:允许持有指定ID角色的用户跳过其他权限校验执行命令
def allow_specified_roles():
    async def predicate(ctx):
        # 替换为你需要放行的角色ID列表
        allowed_role_ids = [111111111111111111, 222222222222222222]
        return any(role.id in allowed_role_ids for role in ctx.author.roles)
    return check(predicate)

3. 替换原有命令的校验装饰器

将原来单独使用的@has_permissions(administrator=True)替换为check_any包裹的多规则组合:

# 原有命令写法(仅管理员可执行)
# @has_permissions(administrator=True)
# @bot.command()
# async def test_cmd(ctx):
#     await ctx.send("执行成功")

# 新的组合校验写法(满足任意一条规则即可执行)
@check_any(
    has_permissions(administrator=True),
    allow_specified_users(),
    allow_specified_roles()
)
@bot.command()
async def test_cmd(ctx):
    # 你的命令业务逻辑
    await ctx.send("执行成功")

注意事项

  • 校验规则按传入check_any的顺序依次判断,只要有一条规则通过,后续规则就不会再执行
  • 若需要自定义校验失败的提示,可以在自定义校验的predicate函数中抛出带提示信息的CheckFailure异常,再全局捕获该异常统一返回提示
  • 上述语法兼容discord.py 1.x、2.x所有主流版本

内容的提问来源于stack exchange,提问作者DavyJonesStockings

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 06:27:02