discord.py机器人接入cog模块触发ModuleNotFoundError问题求助
discord.py Cog改造崩溃问题排查与修复方案
常见错误原因及修复
- Cog加载API版本不兼容
discord.py v2.x 版本调整了扩展加载逻辑,所有加载/卸载/重载Cog的方法都改为异步接口,禁止在全局同步调用bot.load_extension(),必须放在异步函数内通过await关键字调用,这是Cog改造后最常见的崩溃原因。 - Cog文件结构不符合规范
Cog文件必须满足两个核心要求:自定义的Cog类继承discord.ext.commands.Cog,文件末尾对外暴露异步setup函数,标准的example.py代码模板如下:
from discord.ext import commands class MathCog(commands.Cog): def __init__(self, bot): self.bot = bot # 示例数学计算指令 @commands.command() async def calc(self, ctx, expression: str): try: # 简单表达式计算,生产环境建议加沙箱限制 result = eval(expression, {"__builtins__": {}}) await ctx.send(f"计算结果:`{result}`") except: await ctx.send("表达式无效,请重新输入") # 必须实现的setup入口函数 async def setup(bot): await bot.add_cog(MathCog(bot))
- 事件装饰器误用
在Cog内部定义Discord事件不能使用@bot.event装饰器,必须替换为@commands.Cog.listener(),否则会出现事件冲突、注册失败导致崩溃。 - 导入路径错误
如果Cog文件存放在单独的文件夹(如/cogs)下,加载路径需要写为await bot.load_extension('cogs.example'),同时文件夹内必须存在空的__init__.py文件,标识为Python可导入包。
主程序加载逻辑正确示例
import discord from discord.ext import commands # 显式声明Intents,新版本Discord API要求必须开启对应的权限 intents = discord.Intents.default() intents.message_content = True # 需要读取消息内容必须开启该权限 bot = commands.Bot(command_prefix='!', intents=intents) @bot.event async def on_ready(): print(f"机器人已登录:{bot.user}") # 在on_ready异步事件内加载Cog try: await bot.load_extension('example') print("Cog加载成功") except Exception as e: print(f"Cog加载失败,错误信息:{e}") # 热更新指令,仅机器人所有者可调用 @bot.command() @commands.is_owner() async def reload(ctx, ext_name: str): try: await bot.reload_extension(ext_name) await ctx.send(f"模块`{ext_name}`热更新完成") except Exception as e: await ctx.send(f"模块`{ext_name}`更新失败:`{e}`") bot.run("你的机器人Token")
如果以上通用排查点无法定位问题,可以补充上传你实际的代码内容和完整报错栈,即可精准定位错误行。
内容的提问来源于stack exchange,提问作者Daniesh Rieza
相关产品推荐
相关产品推荐

