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.

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(["pong"], () => "Ping!");

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

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("ping")]
    public string Ping() => $"Pong! {Math.Round(Context.Client.Latency.TotalMilliseconds)} ms";
}