Python开发Discord机器人跨文件导入命令出现CommandNotFound错误如何解决
问题根源及修复方案
核心报错原因
你重写了on_message事件但没有调用commands框架内置的bot.process_commands()方法,框架会默认把带前缀的消息当作注册命令处理,找不到对应注册命令就抛出CommandNotFound错误。除此之外你的代码还存在多处语法、逻辑错误,下面是逐点修复方案:
需修正的问题点
- 重复实例化客户端:
commands.Bot本身已继承discord.Client,不需要额外实例化discord.Client() - 方法属性错误:
Comandos类的方法未接收消息对象、不是异步函数,且错误调用了不存在的self.channel属性 - 消息处理逻辑错误:
- 错误修改
message.channel.content属性,实际应该处理的是message.content - 字符串不能作为函数调用:
message.content('cumprimento')是语法错误,应该用字符串包含/相等判断 - 调用类方法时未加执行括号,且异步方法需要加
await
- 错误修改
- 自定义命令逻辑和框架命令逻辑冲突,推荐直接用官方Cog方案拆分命令文件,不需要自己写前缀判断逻辑
修正后代码
comandos.py(Cog写法)
from discord.ext import commands # 继承commands.Cog类作为命令插件 class Comandos(commands.Cog): def __init__(self, bot): self.bot = bot # 注入bot实例 # 用@commands.command装饰器注册命令 @commands.command(name='cumprimento') async def cumprimento(self, ctx): # ctx是命令上下文,自带channel属性 await ctx.send("Olá,sou Fego! O Robô espacial!") @commands.command(name='historia') async def historia(self, ctx): await ctx.send("Eu existo há apenas alguns dias!") # 加载Cog的入口函数 async def setup(bot): await bot.add_cog(Comandos(bot))
主运行文件
import discord from discord.ext import commands # 只实例化commands.Bot即可,注意手动开启对应网关意图,这里全开方便测试 bot = commands.Bot(command_prefix='fg.', intents=discord.Intents.all()) @bot.event async def on_ready(): print('Logged as {0.user}'.format(bot)) # 启动时加载命令插件 await bot.load_extension('comandos') # 如果不需要额外的全局消息处理,可以不用重写on_message,框架会自动处理命令 # 如果确实需要重写on_message,必须在末尾加await bot.process_commands(message) @bot.event async def on_message(message): if message.author.bot: return # 你的自定义消息处理逻辑可以写在这里 await bot.process_commands(message) # 必须加这一行,否则框架命令不会生效 bot.run('你的bot token')
额外注意事项
- 新版本discord.py要求手动开启网关意图,需要在Discord开发者后台的Bot设置里打开
Message Content Intent,否则无法读取消息内容 - 不需要自己写前缀匹配、命令判断逻辑,commands框架会自动处理前缀匹配和命令调用
- 所有涉及IO操作的方法(比如发消息)都必须是异步函数,调用时加
await关键字
内容的提问来源于stack exchange,提问作者PedroDevilirio18
相关产品推荐
相关产品推荐

