使用Discord.py Cogs拆分代码文件时出现NameError报错的解决方法咨询
搞定Discord.py Cogs的NameError问题!
嘿,看你的报错信息,问题出在cogs/news.py的类定义上,一眼就能揪出来——你写了class news(news.Cog),但这时候news这个类还没被定义呢,Python当然找不到它,所以才抛出NameError。
先改核心错误:Cog类的继承写法
你得把继承的基类改成commands.Cog,还要记得导入discord.ext.commands模块。另外,每个Cog文件都必须有setup(bot)函数,这是Discord.py加载Cog的入口,你之前的代码里好像漏掉了这个,这也会导致加载失败。修改后的news.py应该是这样:
from discord.ext import commands # 类名用大驼峰更符合Python规范,当然小写也能跑,但看着更专业~ class News(commands.Cog): def __init__(self, bot): self.bot = bot # 命令方法名最好别和类名重复,避免混淆,比如改成news_command @commands.command(name='news') async def news_command(self, ctx): # 这里写你的命令逻辑 await ctx.send("这是新闻命令的内容哦!") # 必须加这个函数,不然Discord.py不知道怎么加载这个Cog def setup(bot): bot.add_cog(News(bot))
再检查主文件的加载逻辑
你的app.py里的加载代码有个小问题:你既定义了extension列表,又遍历目录加载,这样会重复加载Cog哦。推荐二选一:
方式一:指定要加载的Cog列表
import os from discord.ext import commands # 记得设置你的命令前缀和所需的intents client = commands.Bot(command_prefix='!', intents=...) extensions = ["cogs.commands", "cogs.news", "cogs.manage"] for ext in extensions: try: client.load_extension(ext) print(f"✅ 成功加载扩展:{ext}") except Exception as e: print(f"❌ 加载扩展{ext}失败:{str(e)}")
方式二:自动遍历cogs目录加载所有.py文件
import os from discord.ext import commands client = commands.Bot(command_prefix='!', intents=...) for filename in os.listdir('./cogs'): # 排除以_开头的文件,避免加载临时文件或配置文件 if filename.endswith('.py') and not filename.startswith('_'): try: ext_name = f'cogs.{filename[:-3]}' client.load_extension(ext_name) print(f"✅ 成功加载扩展:{ext_name}") except Exception as e: print(f"❌ 加载扩展{ext_name}失败:{str(e)}")
这样改完之后,你的Cog应该就能正常加载,不会再报NameError啦!
内容的提问来源于stack exchange,提问作者sevrino
相关产品推荐
相关产品推荐

