discord.py中无法向Cog添加命令,命令未找到问题求助
Discord.py Cogs命令未找到问题解决
问题场景
使用discord.py的Cogs功能拆分机器人代码后,运行主文件时明明定义了ping命令,却提示“命令未找到”;通过打印语句发现test_cog.py中的Test类构造函数和setup函数都从未被调用。
核心错误原因
bot.load_extension()的参数使用错误:该方法需要传入Python模块路径,而非文件路径。原代码中./cogs/test_cog.py是文件路径格式,discord.py无法正确识别并加载模块,导致setup函数完全没被执行,Cog自然没有被添加到机器人中。
修复步骤
- 将cogs目录转为Python包:在
cogs文件夹内创建空的__init__.py文件,让Python识别这个目录为模块包。 - 修正扩展加载路径:把
load_extension的参数改为模块路径格式,即cogs.test_cog。 - 优化加载时机(可选但推荐):将扩展加载代码放在
bot.run()之前,避免on_ready事件因重连重复触发导致的重复加载报错;如果一定要在on_ready中加载,需添加已加载判断。
修改后的代码示例
主文件(main_cog.py)
from discord.ext import commands from discord import Intents intents = Intents.default() intents.message_content = True bot = commands.Bot(command_prefix=">", intents=intents) # 在run前加载扩展,更稳定 try: bot.load_extension("cogs.test_cog") print("Test cog 加载成功") except Exception as e: print(f"加载扩展失败: {str(e)}") @bot.event async def on_ready(): print(f'{bot.user} 已启动运行..') bot.run("你的机器人TOKEN")
Cog文件(cogs/test_cog.py)
无需修改,保持原代码即可:
from discord.ext import commands class Test(commands.Cog): def __init__(self, bot): self.bot = bot print("Test cog 初始化完成") @commands.command() async def ping(self, ctx): print("触发ping命令") await ctx.send("Pong from Cogs file!") def setup(bot): print("执行setup函数") bot.add_cog(Test(bot))
验证效果
运行主文件后,控制台会依次输出:
执行setup函数 Test cog 初始化完成 Test cog 加载成功 [机器人用户名] 已启动运行..
此时发送>ping命令,机器人会回复Pong from Cogs file!,问题解决。
内容的提问来源于stack exchange,提问作者Ahmed
相关产品推荐
相关产品推荐

