You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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。

错误分析

  1. 核心触发原因:discord.py v2.x版本要求扩展的setup函数必须是异步函数(async def)。原代码中setup是普通函数,调用后返回None,框架尝试await setup(self)时,await None直接触发NoneType无法用于await表达式的错误。
  2. 潜在额外问题:遍历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

验证步骤

  1. 替换原cogs/help.py中的代码
  2. 重启Bot或重新加载cogs.help扩展
  3. 发送前缀+help(如!help)测试自定义帮助命令是否正常发送Embed

内容的提问来源于stack exchange,提问作者Sten

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 13:01:44