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
相关产品推荐
相关产品推荐

