Table of Contents

Introduction

Adding application commands with the .NET Generic Host is very easy. Use AddApplicationCommands<TInteraction, TContext>(IServiceCollection) to add the application command service to your host builder. Then, use AddSlashCommand, AddUserCommand or AddMessageCommand to add an application command using the minimal APIs way and/or use AddModules(IHost, Assembly) to add application command modules from an assembly. You also need to use UseGatewayEventHandlers(IHost) to bind the service event handlers.

using Microsoft.Extensions.Hosting;

using NetCord;
using NetCord.Hosting.Gateway;
using NetCord.Hosting.Services;
using NetCord.Hosting.Services.ApplicationCommands;
using NetCord.Rest;
using NetCord.Services.ApplicationCommands;

var builder = Host.CreateApplicationBuilder(args);

builder.Services
    .AddDiscordGateway()
    .AddApplicationCommands<ApplicationCommandInteraction, ApplicationCommandContext>();

var host = builder.Build();

// Add commands using minimal APIs
host.AddSlashCommand("ping", "Ping!", () => "Pong!")
    .AddUserCommand("Username", (User user) => user.Username)
    .AddMessageCommand("Length", (RestMessage message) => message.Content.Length.ToString());

// Add commands from modules
host.AddModules(typeof(Program).Assembly);

// Add handlers to handle the commands
host.UseGatewayEventHandlers();

await host.RunAsync();
Note

If you don't see the commands in Discord, try refreshing the Discord client using Ctrl + R on PC or ⌘ + R on Mac.

Important

Please note that names of slash commands must be lowercase.

Example Module

Here you can see an example module showing how to use modules with application commands.

using NetCord;
using NetCord.Rest;
using NetCord.Services.ApplicationCommands;

namespace MyBot;

public class ExampleModule : ApplicationCommandModule<ApplicationCommandContext>
{
    [SlashCommand("pong", "Pong!")]
    public static string Pong() => "Ping!";

    [UserCommand("ID")]
    public static string Id(User user) => user.Id.ToString();

    [MessageCommand("Timestamp")]
    public static string Timestamp(RestMessage message) => message.CreatedAt.ToString();
}