Pycord加载Cog遇TypeError:async setup仍报NoneType await错误
Pycord动态加载Cog异步setup报错问题
我正在使用Pycord开发Discord机器人,尝试通过async def setup(bot)方法动态加载Cog。
相关代码
main.py 核心加载逻辑
async def main(): for filename in os.listdir("cogs"): if filename.endswith(".py"): cog_path = f"cogs.{filename[:-3]}" print(f"📥 Importing {cog_path}") try: module = importlib.import_module(cog_path) setup = getattr(module, "setup", None) print(f"🔍 Checking setup in {cog_path}: {setup}") print(f"🔍 Type of setup: {type(setup)}") if setup: if inspect.iscoroutinefunction(setup): await setup(bot) else: print(f"⚠️ Skipped setup for {cog_path} because it's not async.") except Exception as e: print(f"❌ Failed to load {cog_path}: {e.__class__.__name__} - {e}") await bot.start(TOKEN)
trivia.py Cog代码
async def setup(bot): await bot.add_cog(Trivia(bot))
报错信息
📥 Importing cogs.trivia 🔍 Checking setup in cogs.trivia: <function setup at 0x703c16e92020> 🔍 Type of setup: <class 'function'> ❌ Failed to load cogs.trivia: TypeError - object NoneType can't be used in 'await' expression
我已通过inspect.iscoroutinefunction(setup)确认setup为协程函数,且部分Cog加载正常,使用环境为WSL下的Pycord 2.6.1版本。
问题
- 为何异步setup仍会在await时出现NoneType错误?
- Pycord的Cog加载有哪些需要注意的特殊点?
解答
1. 异步setup触发NoneType错误的原因
错误并非来自setup函数本身,而是你在setup内部错误地对同步方法bot.add_cog()使用了await。
Pycord 2.x中bot.add_cog()是同步函数,调用它不会返回可等待对象(直接返回None)。当你对None使用await时,就会触发TypeError: object NoneType can't be used in 'await' expression。
修正setup函数即可解决:
async def setup(bot): bot.add_cog(Trivia(bot)) # 去掉await
2. Pycord加载Cog的注意事项
setup函数要求:必须是异步函数,参数必须为bot实例,这是Pycord 2.x动态加载Cog的标准接口add_cog是同步方法:绝对不能对它加await,否则会触发NoneType错误- Cog类规范:必须继承自
discord.ext.commands.Cog,构造函数通常接受bot作为参数(如def __init__(self, bot):) - 模块有效性:cogs目录下的文件必须是合法Python模块,避免文件名冲突、语法错误或循环导入
- Bot初始化顺序:加载Cog前,必须确保
bot实例已完成初始化(包括intents配置、前缀设置等) - 依赖处理:如果Cog依赖第三方库或其他自定义模块,需确保这些依赖已正确安装或导入
- Cog初始化逻辑:若Cog需要启动时执行异步初始化,可在
setup函数中先完成异步操作,再调用add_cog
内容的提问来源于stack exchange,提问作者Four
相关产品推荐
相关产品推荐

