如何在discord.py中将Cog设为前缀命令根组?
实现Cog作为根组并优化帮助命令显示
一、正确用GroupCog实现!cog cmd1式调用
你之前用GroupCog无效大概率是用法不对,正确姿势是让Cog继承GroupCog并指定组名:
from discord.ext import commands class CogRoot(commands.GroupCog, name="cog"): def __init__(self, bot): self.bot = bot super().__init__() # 子命令直接用@commands.command装饰 @commands.command(name="cmd1") async def sub_cmd1(self, ctx): await ctx.send("执行cmd1逻辑") @commands.command(name="cmd2") async def sub_cmd2(self, ctx): await ctx.send("执行cmd2逻辑") # 注册到bot bot.add_cog(CogRoot(bot))
这样就能通过!cog cmd1、!cog cmd2调用命令,GroupCog本身就是名为cog的根组,无需额外定义@commands.group()。
二、修改帮助命令显示子命令
默认帮助命令只会展示组名,不会展开子命令,必须自定义帮助命令实现需求,以下是两种实用方案:
方案1:全局帮助直接列出所有子命令
重写send_bot_help方法,让!help直接显示cog组下的所有子命令:
from discord.ext.commands import DefaultHelpCommand class CustomHelp(DefaultHelpCommand): async def send_bot_help(self, mapping): help_content = "所有可用命令:\n" for cog, cmds in mapping.items(): if cog: # 处理GroupCog的子命令 if isinstance(cog, commands.GroupCog): help_content += f"\n▶️ **{cog.qualified_name}**:\n" # 遍历组下所有子命令 for cmd in cog.walk_commands(): if not cmd.hidden: help_content += f" !{cog.qualified_name} {cmd.name}:{cmd.short_doc or '无说明'}\n" # 普通Cog的命令正常显示 else: help_content += f"\n▶️ **{cog.qualified_name}**:\n" for cmd in cmds: if not cmd.hidden: help_content += f" !{cmd.name}:{cmd.short_doc or '无说明'}\n" await self.context.send(help_content) # 给bot绑定自定义帮助命令 bot.help_command = CustomHelp()
方案2:查看组帮助时展开子命令
如果希望用户输入!help cog才显示子命令,重写send_group_help方法即可:
class CustomHelp(DefaultHelpCommand): async def send_group_help(self, group): help_content = f"**{group.name}** 下的子命令:\n" for cmd in group.walk_commands(): if not cmd.hidden: help_content += f" !{group.name} {cmd.name}:{cmd.short_doc or '无说明'}\n" await self.context.send(help_content)
三、注意事项
- 确保discord.py版本为2.0及以上,GroupCog是2.0新增特性
- 如果用
@commands.group()在Cog内定义根组,子命令必须用@group.command()装饰,而非@commands.command(),否则子命令不会归到组下
内容的提问来源于stack exchange,提问作者Daniel Baulig
相关产品推荐
相关产品推荐

