在Discord Bot独立Cog中创建Help命令时遇命令重复错误
解决Discord Bot自定义Help命令冲突问题
错误原因
Discord.py的commands.Bot默认内置了help命令,当你在Cog中注册同名的help命令时,就会触发CommandRegistrationError,提示该命令已存在。
解决方案
方案一:禁用内置Help命令(适配你的Cog写法)
在创建Bot实例时,添加help_command=None参数,直接禁用内置的help命令,这样你的自定义help命令就能正常注册:
# 主文件中的Bot初始化代码 from discord.ext import commands client = commands.Bot(command_prefix="你的命令前缀", help_command=None)
修改后,你的现有Help Cog代码可以正常使用,同时注意修正代码里的小问题:将ctx.author.avatar改为ctx.author.avatar.url,否则无法正确获取头像链接:
# 修正后的Help Cog代码片段 help_embed.set_footer(text=f"Requested by {ctx.author}", icon_url=ctx.author.avatar.url)
方案二:替换内置HelpCommand类(更规范的实现方式)
如果想基于内置Help系统扩展功能,推荐自定义HelpCommand子类并替换内置实现,这种方式不需要用Cog注册命令:
# 可以放在主文件或者单独的模块中 import discord from discord.ext import commands class CustomHelpCommand(commands.HelpCommand): async def send_bot_help(self, mapping): # 构建自定义帮助Embed help_embed = discord.Embed(title="Placeholder", description="All Commands ph", color=discord.Color.purple()) help_embed.set_author(name="Ph hold") help_embed.add_field(name="Clear", value="Deletes message", inline=False) help_embed.set_footer(text=f"Requested by {self.context.author}", icon_url=self.context.author.avatar.url) await self.context.send(embed=help_embed) # 初始化Bot时替换内置帮助命令 client = commands.Bot(command_prefix="你的命令前缀", help_command=CustomHelpCommand())
内容的提问来源于stack exchange,提问作者Mortibi The Bat
相关产品推荐
相关产品推荐

