首页 > 解决方案 > 使用此功能自动为 commands.group 子命令生成帮助的“帮助”命令

问题描述

我尝试制作帮助命令,但我不知道如何为命令组创建帮助命令,这是主要命令与组分开,我尝试做help modmail channelmodmail 是组,频道是子命令,它只是说命令不存在 这是功能:

请注意,我不是在问如何使用 commands.group,我是在问如何使用我的函数为commands.group() 上的子命令创建帮助

    async def cmdhelp(self, ctx, command):
        params = []
        for key, value in command.params.items():
            if key not in ("self", "ctx"):
                params.append(f"[{key}]" if "NoneType" in str(value) else f"<{key}>")
        params = " ".join(params)
        alias = ", ".join(command.aliases)
        commandhelp = command.help
        commanddesc = command.description
        if not command.help:
            commandhelp = "`None`"
        if not command.description:
            commanddesc = "`None`"
        if not command.aliases:
            alias = "`None`"
        embed = discord.Embed(title=f"Help for {command}",
                              colour=0x59FFE7,
                              description=f"**Description:**\n{commandhelp}\n**Usage:**\n`{command} {params}`\n**Aliases:**\n`{alias}`\n**Permission:**\n`{commanddesc}`")
        await ctx.send(embed=embed)

    @commands.group(invoke_without_command=True)
    async def help(self, ctx, *,cmd=None):
        if cmd is None:
           # lets say this is a embed with a help category list
        else:
            if (command := get(self.bot.commands, name=cmd)):
                await self.cmdhelp(ctx, command)

            else:
                await ctx.send("That command does not exist.")

示例: 我正在尝试制作的帮助命令示例 如果您看到,它可以与普通命令一起使用,help modmail但是我怎样才能为modmail组的子命令创建呢?这是help modmail channel

标签: pythondiscorddiscord.pydiscord.py-rewrite

解决方案


首先,这不是使用子命令的正确方法。这是如何使用它们:

client.remove_command("help")

@client.group()
async def main_cmd(ctx):
    print("main command")

@main_cmd.command()
async def sub_cmd(ctx):
    print("subcommand")

main_cmdin discord 只会打印"main command",但说main_cmd sub_cmdin discord 会打印"main command"然后"subcommand"

如果您不希望在调用子命令时运行原始命令,请使用ctx.invoked_subcommand

client.remove_command("help")

@client.group()
async def main_cmd(ctx):
    if ctx.invoked_subcommand != None:
        return
    print("main command")

@main_cmd.command()
async def sub_cmd(ctx):
    print("subcommand")

编辑(在编辑问题后):要为机器人中的每个命令创建“命令”(它实际上不是命令),请使用bot.commands

client.remove_command("help")

@client.command(description = "THIS IS THE MESSAGE THAT WILL APPEAR IN THE SPECIFIC HELP COMMAND")
async def a_command(ctx):
    pass #look at the decorator

@client.command()
async def help(ctx, cmd = None):
    if cmd == None:
        await ctx.send("DEFAULT HELP")
    elif cmd in (cmds := {command.name: command for command in client.commands}):
        await ctx.send("cmd: " + cmds[cmd].description)
    else:
        await ctx.send("command not found")

这会为机器人中的每个命令创建“子命令”。


推荐阅读