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

如何在DSharpPlus中修改帮助格式化器?自定义实现无响应问题

问题分析与解决方案

你的自定义帮助格式化器没有返回内容,核心原因有两个:

  1. 未处理无参数调用;help的场景
  2. Build方法存在冗余的死代码

具体问题拆解

  • 当用户输入不带参数的;help时,DSharpPlus会调用WithDefault方法而非WithCommand,但你没有重写该方法,导致生成的Embed只有颜色,没有任何有效内容,Discord会拒绝接收这类空Embed。
  • Build方法中第二个return语句永远不会被执行,属于无效代码,虽然不影响第一个返回,但会造成逻辑混乱。

修改后的完整代码

public class CustomHelpFormatter : DefaultHelpFormatter
{
    // 使用静态Random避免短时间内生成重复颜色
    private static readonly Random _rand = new Random();
    protected DiscordEmbedBuilder _embed;

    public CustomHelpFormatter(CommandContext ctx) : base(ctx)
    {
        _embed = new DiscordEmbedBuilder
        {
            Color = new DiscordColor((byte)_rand.Next(0, 255), (byte)_rand.Next(0, 255), (byte)_rand.Next(0, 255))
        };
    }

    // 处理无参数的;help命令,生成全命令列表
    public override BaseHelpFormatter WithDefault()
    {
        _embed.Title = "帮助菜单";
        _embed.Description = "以下是所有可用命令:\n";
        
        // 遍历所有注册的顶级命令,跳过隐藏命令
        foreach (var command in Context.Commands.RegisteredCommands.Values)
        {
            if (!command.IsHidden)
            {
                _embed.Description += $"`;{command.Name}` - {command.Description ?? "无描述信息"}\n";
            }
        }

        return this;
    }

    // 处理带参数的;help <命令>,生成指定命令的详细帮助
    public override BaseHelpFormatter WithCommand(Command command)
    {
        _embed.Title = $"命令帮助: {command.Name}";
        _embed.Description = command.Description ?? "无描述信息";

        // 添加命令用法(如果有定义)
        if (!string.IsNullOrEmpty(command.Usage))
        {
            _embed.AddField("用法示例", $"`;{command.Usage}`", inline: false);
        }

        // 添加子命令列表(如果存在)
        if (command.Children.Any())
        {
            var subcommandList = string.Join("\n", command.Children
                .Where(c => !c.IsHidden)
                .Select(c => $"`;{c.Name}` - {c.Description ?? "无描述信息"}"));
            _embed.AddField("子命令", subcommandList, inline: false);
        }

        return this;
    }

    public override CommandHelpMessage Build()
    {
        // 仅返回构建好的Embed,移除冗余return
        return new CommandHelpMessage(embed: _embed);
    }
}

注册代码保持不变

Commands.SetHelpFormatter<CustomHelpFormatter>();

优化说明

  • 用静态Random实例替代每次构造时新建,避免短时间内生成重复的Embed颜色。
  • 动态遍历注册命令生成帮助内容,无需硬编码,扩展性更强。
  • 区分无参数和带参数的help调用场景,覆盖所有使用情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 15:24:07