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

Discord Bot权限错误处理失效,非管理员执行命令异常求助

修复你的Discord Bot错误处理逻辑

我看到你的问题了——你的错误处理逻辑没生效,核心原因是你把on_command_error事件错误地定义成了一个命令,而不是事件处理器。让我帮你一步步修复:

主要问题分析

  • 错误的事件定义:你用@bot.command()装饰on_command_error,但这是Discord Bot的内置事件,必须用@bot.event装饰,且参数格式不正确。
  • 过时的API用法:pass_context=True和bot.say()都是Discord.py旧版本的用法,现在已经被废弃。
  • 缺失的导入:捕获CheckFailure需要显式导入该异常类,避免名称错误。

修正后的完整代码

token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
prefix = "?"

import discord
from discord.ext import commands
from discord.ext.commands import CheckFailure  # 显式导入需要捕获的异常

bot = commands.Bot(command_prefix=prefix)
bot.remove_command("help")

@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')

@bot.event
async def on_command_error(ctx, error):
    # 处理权限不足的情况
    if isinstance(error, CheckFailure):
        print(f"{ctx.message.author} does not have permission to run `{ctx.command.name}`")
        # 如果想替换默认的提示消息,可以取消下面这行注释
        # await ctx.send("You don't have permission to use this command.")
    # 处理未知命令的情况
    elif isinstance(error, commands.CommandNotFound):
        # 这里可以添加你自定义的未知命令处理逻辑
        pass
    # 处理其他未捕获的错误
    else:
        print(f"Unexpected error: {error}")
        await ctx.send("An unexpected error occurred while executing this command.")

@bot.command()
@commands.has_any_role("Admin", "Moderator")
async def hello(ctx):
    msg = f'Hello... {ctx.author.mention}'
    await ctx.send(msg)

bot.run(token)

关键修改说明

  1. 修复on_command_error事件:

    • 用@bot.event替代@bot.command()装饰,确保Discord Bot识别这是事件处理器。
    • 修正参数为ctx, error,符合事件的标准签名(因为你没有使用类继承commands.Bot,所以不需要self参数)。
  2. 更新过时API:

    • 移除所有pass_context=True,Discord.py v1.0+会自动传递上下文。
    • 用await ctx.send()替代await bot.say(),这是当前推荐的消息发送方式。
  3. 完善错误处理:

    • 显式导入CheckFailure,避免运行时名称错误。
    • 可以选择是否覆盖默认的权限提示消息(默认情况下,Discord.py会自动发送权限不足的提示,如果你想自定义,可以取消代码中的注释)。
  4. 优化字符串格式化:使用f-string替代旧的.format()方式,代码更简洁易读。

现在你的错误处理逻辑应该能正常工作了:当非管理员执行?hello命令时,bash端会打印你自定义的日志,同时用户会收到对应的提示(默认或自定义),不会再出现未处理的错误信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 09:05:40