discord.py最新版本加载Cog出现TypeError(NoneType)错误如何解决?
解决discord.py加载Cog时出现的
TypeError: object NoneType can't be used in 'await' expression错误 错误信息
File "C:\Users\MyUsername\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\bot.py", line 946, in _load_from_module_spec await setup(self) TypeError: object NoneType can't be used in 'await' expression
相关代码
main.py
import discord import os from discord.ext import commands # Create bot client = commands.Bot(command_prefix=">", intents=discord.Intents.all()) # Load commands @client.command() async def load(ctx, extension): await client.load_extension(f"Cogs.{extension}") # Unload commands @client.command() async def unload(ctx, extension): await client.unload_extension(f"Cogs.{extension}") # On start @client.event async def on_ready(): # Import all commands on start for filename in os.listdir("./Cogs"): if filename.endswith(".py"): await client.load_extension(f"Cogs.{filename[:-3]}") # 注:Client.run()已省略,实际位于代码末尾
Ping.py(Cog文件)
import discord from discord.ext import commands import time class Ping(commands.Cog): def __init__(self, client): self.client = client @commands.Cog.listener() async def on_ready(self): print("Bot is online") await self.client.change_presence( status=discord.Status.online, activity=discord.Game('SuperBot, >help for help') ) @commands.command() async def ping(self, ctx): embed = discord.Embed( title="Pong!", description=f"I'm up! The bot latency is {self.client.latency}", color=discord.Colour.random() ) embed.set_footer( text=time.strftime("%a : %H : %M") ) await ctx.channel.send(embed=embed) def setup(client): client.add_cog(Ping(client))
问题描述
使用discord.py最新版本开发Discord机器人,已配置intents,启动时始终报上述错误。尝试将加载Cog的代码移出on_ready函数,问题依旧。
解决方案
核心修复:修改Cog的
setup函数为异步
discord.py v2.0+版本要求Cog的setup函数必须是异步函数,当前同步的setup返回None,框架执行await setup(self)时就会触发类型错误。修改Ping.py中的setup函数:async def setup(client): await client.add_cog(Ping(client))优化加载逻辑(可选)
推荐使用setup_hook替代on_ready加载扩展,因为on_ready可能在bot重连时多次触发,而setup_hook仅在启动时执行一次,避免重复加载Cog。修改main.py中的启动逻辑:@client.event async def setup_hook(): # Import all commands on start for filename in os.listdir("./Cogs"): if filename.endswith(".py"): await client.load_extension(f"Cogs.{filename[:-3]}")
内容的提问来源于stack exchange,提问作者Help pls
相关产品推荐
相关产品推荐

