加载discord.py扩展时出现TypeError: NoneType无法用于await表达式
解决discord.py扩展加载时的TypeError: NoneType不能用于await表达式
核心问题根源
这个错误本质是扩展加载流程中,discord.py内部尝试await一个None值。即便你移除了自定义的await语句、去掉setup的async修饰,也会因为违反discord.py扩展的规范逻辑触发错误。
必须修正的规范点
setup函数必须是异步的:discord.py要求扩展的setup必须定义为async def,因为bot.add_cog()本身是异步方法,必须通过await调用。setup内必须正确await添加Cog:如果省略await直接调用bot.add_cog(),会返回一个协程对象,discord.py加载时会尝试await这个返回值,最终因处理不当抛出NoneType错误。- Cog类初始化必须同步:Cog的
__init__方法不能包含异步操作,若需要异步初始化逻辑,改用cog_load监听器处理。
正确代码示例
Staff_Moderation.py 标准结构
import discord from discord.ext import commands class Staff_Moderation(commands.Cog): def __init__(self, bot): self.bot = bot # 初始化仅保留同步逻辑,异步操作移至cog_load @commands.Cog.listener() async def cog_load(self): # 这里放需要异步初始化的逻辑,比如数据库连接 pass # 示例 moderation 命令 @commands.command() @commands.has_permissions(manage_messages=True) async def clear(self, ctx, amount: int): await ctx.channel.purge(limit=amount + 1) await ctx.send(f"已清除{amount}条消息", delete_after=5) # 严格遵循async setup规范 async def setup(bot): await bot.add_cog(Staff_Moderation(bot))
main.py 扩展加载正确写法
import discord from discord.ext import commands # 按需开启所需权限 intents = discord.Intents.default() intents.message_content = True intents.members = True bot = commands.Bot(command_prefix="!", intents=intents) @bot.event async def on_ready(): print(f"已登录: {bot.user}") # 加载扩展,确保文件名正确(不含.py后缀) try: await bot.load_extension("Staff_Moderation") print("Staff_Moderation扩展加载成功") except Exception as e: print(f"扩展加载失败: {str(e)}") bot.run("你的机器人令牌")
排查 Checklist
- 确认
setup函数是async def,且内部用await bot.add_cog(...)完成Cog注册。 - 检查Cog的
__init__方法,移除所有异步操作,移至cog_load或cog_ready监听器。 - 确保使用
await bot.load_extension()加载扩展(discord.py v2.x+要求异步加载)。 - 排查所有自定义命令/事件中的
await语句,避免await一个同步函数(同步函数返回None,会触发该错误)。
内容的提问来源于stack exchange,提问作者WannaBeCoder
相关产品推荐
相关产品推荐

