Discord Bot Cog加载异常:命令未被识别问题求助
Discord Bot Cog扩展命令未导入问题排查与解决
问题描述
我使用Cog和扩展创建了一个Discord Bot,但命令未被成功导入。主文件代码如下:
import discord from discord.ext import commands intents = discord.Intents.default() intents.message_content = True intents.members = True bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'), intents=intents) bot.remove_command('help') @bot.event async def on_ready(): print(f'Bot ready as {bot.user}') bot.load_extension('.ext.moderation') bot.run(***)
排查与解决方法
1. 修正扩展加载路径
当前代码中.ext.moderation的路径格式错误。如果你的项目结构为:
项目根目录/ ├── main.py(主文件) └── ext/ ├── __init__.py └── moderation.py
则正确的加载路径应为ext.moderation(移除开头的点)。主文件属于顶层模块,不需要相对路径前缀。修改后的代码:
bot.load_extension('ext.moderation')
2. 确保ext文件夹是Python包
在ext文件夹下必须创建空的__init__.py文件,Python才会将其识别为可导入的包。缺少该文件会导致扩展无法被加载。
3. 检查Cog类的定义规范
moderation.py中的Cog必须遵循正确的定义格式:
- 继承自
commands.Cog - 包含
__init__方法接收bot实例 - 使用
@commands.command()装饰器定义命令 - 必须存在
setup函数作为加载入口
示例正确的moderation.py代码:
from discord.ext import commands import discord class Moderation(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(name="kick") async def kick_member(self, ctx, member: discord.Member): await member.kick() await ctx.send(f"{member.mention} 已被踢出服务器") def setup(bot): bot.add_cog(Moderation(bot))
4. 调整扩展加载时机(可选)
建议将扩展加载放在on_ready事件中,并添加错误捕获,便于排查问题:
@bot.event async def on_ready(): print(f'Bot ready as {bot.user}') try: # Discord.py 2.0+推荐使用异步加载方法 await bot.load_extension('ext.moderation') print("Moderation扩展加载成功") except Exception as e: print(f"扩展加载失败: {str(e)}")
内容的提问来源于stack exchange,提问作者Eduardo Gottert
相关产品推荐
相关产品推荐

