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

Nextcord @commands.check()在高级斜杠命令中失效问题求助

问题排查与解决

核心原因:前缀命令装饰器不兼容斜杠命令

@commands.check是为前缀触发的传统命令设计的装饰器,Nextcord的斜杠命令需要使用专门的检查机制,直接套用会导致验证失效。

解决方法1:使用斜杠命令专属检查装饰器

替换原有的@commands.check为@bot.check,同时注意检查函数的参数适配,以及JSON数据类型的匹配问题:

# 修正后的检查函数(兼容异步场景)
async def check_premium(interaction: nextcord.Interaction):
    with open("premium_users.json") as f:
        premium_users_list = json.load(f)
        user_id = interaction.user.id
        # 关键:处理JSON中ID可能是字符串的情况(很多时候存数据会转成字符串)
        if str(user_id) not in premium_users_list and user_id not in premium_users_list:
            await interaction.response.send_message("你没有权限执行此命令", ephemeral=True)
            return False
    return True

# 单个命令生效的检查装饰器
@bot.slash_command(name="test",description="Just a Test Command")
@bot.check(check_premium)
async def test(interaction: nextcord.Interaction):
    embed = nextcord.Embed(title="Test Command",
                          description="(random words)",
                          color=nextcord.Color.red(),
                          timestamp=datetime.datetime.now())
    embed.add_field(name="This is a test Command",
                    value="*It does not matter what I put here*",
                    inline=False)

    await interaction.response.send_message(embed=embed)

解决方法2:自定义专属装饰器(更灵活)

如果需要对不同命令设置独立的权限逻辑,可以写一个自定义装饰器:

def premium_only():
    def predicate(interaction: nextcord.Interaction):
        with open("premium_users.json") as f:
            premium_users_list = json.load(f)
            user_id = interaction.user.id
            # 同时匹配整数和字符串类型的ID
            if str(user_id) not in premium_users_list and user_id not in premium_users_list:
                # 异步发送权限提示,避免交互超时
                async def send_no_perm():
                    await interaction.response.send_message("无权限执行此命令", ephemeral=True)
                bot.loop.create_task(send_no_perm())
                return False
            return True
    return nextcord.check(predicate)

# 应用自定义装饰器
@bot.slash_command(name="test",description="Just a Test Command")
@premium_only()
async def test(interaction: nextcord.Interaction):
    # 命令内容保持不变
    embed = nextcord.Embed(title="Test Command",
                          description="(random words)",
                          color=nextcord.Color.red(),
                          timestamp=datetime.datetime.now())
    embed.add_field(name="This is a test Command",
                    value="*It does not matter what I put here*",
                    inline=False)

    await interaction.response.send_message(embed=embed)

额外注意事项

  • JSON数据类型匹配:检查premium_users.json中的用户ID是整数还是字符串,确保和interaction.user.id(整数类型)的判断逻辑一致,避免因类型不匹配导致验证失效。
  • 交互响应时机:权限验证不通过时,必须先发送响应消息再返回False,否则Discord会因交互超时抛出错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:45:33