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

Python开发Discord Bot命令注册失败 触发CommandNotFound报错

问题排查与修复

核心错误:命令装饰器使用不当

discord.ext.commands提供的client.command是装饰器工厂,必须加括号调用才能正确将函数注册为Bot命令。你代码中写的@client.command漏了括号,导致hello函数没有被注册到Bot的命令列表,因此client.get_command("hello")返回None,发送!hello也会触发CommandNotFound错误。

额外兼容项:开启Message Content Intent

如果你使用的是discord.py 2.0及以上版本,还需要完成两个配置才能正常响应前缀命令:

  • 前往Discord开发者后台的Bot设置页,开启Message Content Intent权限
  • 代码初始化Bot时显式声明开启消息内容读取权限
修正后的完整代码
import discord
from discord.ext import commands

# 配置Intent,开启消息内容读取
intents = discord.Intents.default()
intents.message_content = True

client = commands.Bot(command_prefix="!", intents=intents)
TOKEN = "你的Bot令牌"

# 装饰器添加括号
@client.command()
async def hello(ctx, arg):
    await ctx.channel.send(arg)

print(client.get_command("hello")) # 此时会正常输出命令对象,不再返回None

client.run(TOKEN)
补充说明
  • 当前hello命令要求必须携带一个参数,如果直接发送!hello不带内容会抛出MissingRequiredArgument错误,需要参数可选的话可以修改函数定义为async def hello(ctx, arg="默认返回内容"):
  • 如果不需要参数直接删除arg参数即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 22:06:00