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

Discord机器人自定义角色注册命令权限检查失效求助

自定义角色注册命令权限检查无响应问题

我正在实现白名单机制,仅允许特定角色使用自定义角色注册命令,将角色绑定给用户并记录至数据库。调试时能正常打印admin列表,但权限检查逻辑完全没执行——既不写入数据库,也不发送任何提示消息,命令调用后无任何响应。

相关代码

cogs/roles.py

import discord
from discord.ext import commands
from utils.databases import roles_db
from utils.variables import admin

class Roles(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.hybrid_group()
    async def custom(self, ctx: commands.Context):
        return

    @custom.command(name="register", description="Registers a custom role to a user")
    async def register(self, ctx: commands.Context, role: discord.Role, member: discord.Member):
        print(admin)
        if any(r.id in admin for r in ctx.author.roles):
            roles_db.insert_one({"user_id": member.id, "role_id": role.id})
            await ctx.send(":white_check_mark: Role registered!")
        else:
            await ctx.send(":x: You do not have the required role.")

async def setup(bot):
    await bot.add_cog(Roles(bot))

utils/variables.py

admin = [
    1408442799925235794,
    1445017368123277460
    1079504634772738078
    1272691594591473695
    1379137477192843264

]

问题根源与修复方案

1. 核心问题:列表语法错误

utils/variables.py中的admin列表多个元素之间缺少逗号,导致Python解析该模块时抛出语法错误,直接导致Roles cog无法加载,bot根本识别不到custom register命令,因此调用后无任何响应。

修复后的utils/variables.py:

admin = [
    1408442799925235794,
    1445017368123277460,
    1079504634772738078,
    1272691594591473695,
    1379137477192843264
]

2. 优化组命令配置

为custom组命令添加invoke_without_command=True参数,避免用户直接调用/custom时无响应,同时确保子命令触发逻辑正常:

@commands.hybrid_group(invoke_without_command=True)
async def custom(self, ctx: commands.Context):
    await ctx.send("请使用子命令:`custom register` 来注册自定义角色。")

3. 增加错误捕获

为命令执行逻辑添加异常捕获,避免因数据库操作或其他意外错误导致无响应,同时方便调试:

@custom.command(name="register", description="Registers a custom role to a user")
async def register(self, ctx: commands.Context, role: discord.Role, member: discord.Member):
    print(admin)
    try:
        if any(r.id in admin for r in ctx.author.roles):
            roles_db.insert_one({"user_id": member.id, "role_id": role.id})
            await ctx.send(":white_check_mark: 角色已成功注册!")
        else:
            await ctx.send(":x: 你没有使用该命令的权限。")
    except Exception as e:
        print(f"命令执行错误:{str(e)}")
        await ctx.send(":x: 命令执行失败,请联系管理员排查问题。")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.01 13:12:32