Discord.py机器人cog模块命令无法显示并触发CommandNotFound错误
Discord机器人Cog内命令无法识别故障排查
报错信息:
Ignoring exception in command None: discord.ext.commands.errors.CommandNotFound: Command “{command}" is not found
以下是导致故障的几个核心问题及修复方案:
Cog加载逻辑不符合discord.py版本要求
如果你使用的是discord.py v2.0及以上版本,
load_extension是异步方法,直接同步调用会导致Cog静默加载失败,没有报错但Cog完全不生效。
修复代码示例:# main.py import asyncio, os import discord from discord.ext import commands intents = discord.Intents.default() intents.message_content = True client = commands.Bot(command_prefix="!", intents=intents) # 前缀替换为你自己的配置 async def load_cogs(): for filename in os.listdir("./cogs"): if filename.endswith(".py"): # 2.0+版本必须加await调用异步加载方法 await client.load_extension(f"cogs.{filename[:-3]}") async def main(): async with client: await load_cogs() await client.run("你的机器人Token") asyncio.run(main())另外注意你原代码中
load_extension的字符串末尾是中文全角引号,要替换为英文半角引号,避免语法错误。Cog内部存在语法错误
./cogs/commands.py中on_ready监听函数写法错误:self.client.guilds是客户端属性不是可调用方法,你加了括号会触发异常,导致Cog加载失败。
修复代码:@commands.Cog.listener() async def on_ready(self): # 去掉guilds后的括号 for guild in self.client.guilds: self.song_queue[guild.id] = [] print("Cogs are cogging")未开启消息内容权限
Discord官方要求所有读取用户消息内容的机器人必须在开发者后台开启
Message Content Intent权限,未开启的情况下机器人无法识别前缀命令,只会报找不到命令的错误。
修复步骤:- 进入Discord开发者平台对应应用的「Bot」设置页
- 找到「Privileged Gateway Intents」板块,打开
Message Content Intent开关 - 初始化客户端时必须显式声明启用该intent,参考上面main.py的intent配置代码。
命令前缀不匹配
调用命令时需要加上你初始化客户端时设置的命令前缀,比如你设置前缀为
!,就需要发送!ping触发命令,直接发送ping会识别失败。
内容的提问来源于stack exchange,提问作者dogluva
相关产品推荐
相关产品推荐

