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

discord.py权限问题:无对应角色用户执行命令致机器人崩溃求助

解决discord.py混合命令无权限用户执行时崩溃的问题

你的问题出在未捕获commands.MissingRole异常,默认情况下discord.py不会自动处理这类权限异常,导致机器人直接崩溃。以下是两种可行的解决方法:

方法一:为单个命令添加专属错误处理

在你的cookie_recipe命令下方添加对应的错误处理函数,仅针对该命令的权限异常进行处理:

@commands.has_role("Buying/Selling Support")
@bot.hybrid_command(name="cookie_recipe", description="Sends Cookie Recipe")
async def cookie_recipe(ctx):
    await ctx.send("Currently Uploading...")
    file = discord.File("SHOP/src/cookie_recipe.txt")
    await ctx.send(file=file)

# 命令专属错误处理
@cookie_recipe.error
async def cookie_recipe_error(ctx, error):
    # 捕获缺少角色的异常
    if isinstance(error, commands.MissingRole):
        # 适配混合命令的两种上下文(前缀命令/斜杠命令)
        if isinstance(ctx, discord.Interaction):
            # 斜杠命令用respond,ephemeral=True让回复仅用户可见
            await ctx.response.send_message("你没有执行该命令的权限,需要拥有「Buying/Selling Support」角色。", ephemeral=True)
        else:
            # 前缀命令用send
            await ctx.send("你没有执行该命令的权限,需要拥有「Buying/Selling Support」角色。")
    else:
        # 其他错误重新抛出,避免掩盖问题
        raise error

方法二:添加全局错误处理(适合多命令场景)

如果你的机器人有多个需要权限检查的命令,可以添加全局错误处理函数,统一处理所有命令的权限异常:

@bot.event
async def on_command_error(ctx, error):
    # 捕获缺少角色的异常
    if isinstance(error, commands.MissingRole):
        # 自动提取缺失的角色名称,无需硬编码
        if isinstance(ctx, discord.Interaction):
            await ctx.response.send_message(f"你没有执行该命令的权限,需要拥有「{error.missing_role}」角色。", ephemeral=True)
        else:
            await ctx.send(f"你没有执行该命令的权限,需要拥有「{error.missing_role}」角色。")
    # 可扩展处理其他常见异常
    elif isinstance(error, commands.MissingPermissions):
        await ctx.send(f"你缺少必要的权限:{', '.join(error.missing_permissions)}")
    else:
        # 未处理的错误重新抛出
        raise error

注意事项

  • 混合命令同时支持前缀触发和斜杠触发,需区分上下文类型(discord.Interaction是斜杠命令的上下文),确保回复方式正确。
  • 使用ephemeral=True可让权限不足的提示仅对执行命令的用户可见,避免刷屏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 21:42:48