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

如何在DSharpPlus中创建命令处理器?实现单命令类自动注册

在DSharpPlus中实现命令类的自动注册(替代手动逐个注册)

核心思路

利用C#反射机制,自动扫描并注册所有继承自BaseCommand的命令类,无需手动逐个调用RegisterCommands<T>()。

实现步骤

1. 定义命令基类

创建一个抽象基类,让所有命令类继承它(基类可以是空的,也可封装通用逻辑):

public abstract class BaseCommand { }

2. 编写独立的命令类

每个命令单独创建一个类,继承自BaseCommand并添加带[SlashCommand]特性的处理方法:

// Ping命令类
public class PingCommand : BaseCommand
{
    [SlashCommand("ping", "返回Pong响应")]
    public async Task PingHandler(InteractionContext ctx)
    {
        await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource,
            new DiscordInteractionResponseBuilder().WithContent("Pong!"));
    }
}

// 问候命令类
public class HelloCommand : BaseCommand
{
    [SlashCommand("hello", "向用户发送问候")]
    public async Task HelloHandler(InteractionContext ctx)
    {
        await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource,
            new DiscordInteractionResponseBuilder().WithContent($"你好,{ctx.User.Username}!"));
    }
}

3. 实现自动注册逻辑

在Bot初始化阶段,通过反射扫描所有符合条件的命令类并批量注册:

// 初始化Slash命令模块
var slash = discord.UseSlashCommands();

// 获取当前程序集中所有继承自BaseCommand的非抽象类
var commandTypes = Assembly.GetExecutingAssembly()
    .GetTypes()
    .Where(t => t.IsSubclassOf(typeof(BaseCommand)) && !t.IsAbstract);

// 批量注册所有命令类
foreach (var type in commandTypes)
{
    slash.RegisterCommands(type);
}

额外说明

  • 如果命令类位于其他程序集(比如单独的类库项目),可将Assembly.GetExecutingAssembly()替换为目标程序集的引用,例如:
    // 通过某个命令类获取其所在程序集
    var commandAssembly = typeof(PingCommand).Assembly;
    var commandTypes = commandAssembly.GetTypes()
        .Where(t => t.IsSubclassOf(typeof(BaseCommand)) && !t.IsAbstract);
    
  • DSharpPlus的RegisterCommands(Type)方法会自动识别类中带有[SlashCommand]特性的方法,无需额外配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 19:17:26