Table of Contents

Introduction

Adding commands with the .NET Generic Host is very easy. Use AddCommands(IServiceCollection) to add the command service to your host builder. Then, use AddCommand to add a command using the minimal APIs way and/or use AddModules(IHost, Assembly) to add command modules from an assembly. You also need to use UseGatewayEventHandlers(IHost) to bind the service event handlers.

using Microsoft.Extensions.Hosting;

using NetCord.Hosting.Gateway;
using NetCord.Hosting.Services;
using NetCord.Hosting.Services.Commands;

var builder = Host.CreateApplicationBuilder(args);

builder.Services
    .AddDiscordGateway()
    .AddCommands();

var host = builder.Build();

// Add a command using minimal APIs
host.AddCommand(["ping"], () => "Pong!");

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

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

await host.RunAsync();

Specifying a prefix

You can specify a prefix in the configuration. You can for example use appsettings.json file. It should look like this:

{
  "Discord": {
    "Prefix": "!"
    // You can also specify multiple prefixes using 'Prefixes'
    // "Prefixes": [ "!", "?" ]
  }
}

Example Module

using NetCord.Services.Commands;

namespace MyBot;

public class ExampleModule : CommandModule<CommandContext>
{
    [Command("pong")]
    public static string Pong() => "Ping!";
}