使用discord.py自定义HelpCommand时加载扩展报错求助
解决discord.py自定义HelpCommand扩展加载报错问题
问题背景
基于discord.py框架自定义HelpCommand实现专属帮助命令,但加载cogs.help扩展时持续报错。错误信息为discord.ext.commands.errors.ExtensionFailed,具体触发TypeError: object NoneType can't be used in 'await' expression。
错误分析
- 核心触发原因:discord.py v2.x版本要求扩展的
setup函数必须是异步函数(async def)。原代码中setup是普通函数,调用后返回None,框架尝试await setup(self)时,await None直接触发NoneType无法用于await表达式的错误。 - 潜在额外问题:遍历
mapping.items()时,部分命令不属于任何Cog,对应的cog为None,直接访问cog.qualified_name会引发属性访问报错。
修复方案
1. 将setup/teardown改为异步函数
为setup和teardown添加async关键字,适配discord.py v2.x的扩展规范。
2. 处理mapping中的None值
遍历mapping时过滤掉cog为None的条目,避免无属性可访问的报错。
修复后完整代码
import discord from discord.ext import commands class MyHelpCommand(commands.HelpCommand): async def send_bot_help(self, mapping): embed = discord.Embed(title="Bot 帮助") for cog, cmds in mapping.items(): # 过滤无所属Cog的命令 if cog is None: continue embed.add_field( name=cog.qualified_name, value=f"{len(cmds)} 条命令" ) channel = self.get_destination() await channel.send(embed=embed) async def setup(bot): bot._default_help_command = bot.help_command bot.help_command = MyHelpCommand() async def teardown(bot): bot.help_command = bot._default_help_command
验证步骤
- 替换原
cogs/help.py中的代码 - 重启Bot或重新加载
cogs.help扩展 - 发送前缀+
help(如!help)测试自定义帮助命令是否正常发送Embed
内容的提问来源于stack exchange,提问作者Sten
相关产品推荐
相关产品推荐

