/Discord.Addons.Hosting

Simplifying Discord.Net hosting with .NET Generic Host (Microsoft.Extensions.Hosting)

Primary LanguageC#Apache License 2.0Apache-2.0

Discord.Addons.Hosting

Build Status NuGet

Discord.Net hosting with Microsoft.Extensions.Hosting. This package provides extensions to a .NET Generic Host (IHostBuilder) that will run a Discord.Net socket/sharded client as a controllable IHostedService. This simplifies initial bot creation and moves the usual boilerplate to a convenient builder pattern.

Discord.Net 2.1.1+ & .NET Core 2.0+ is required.

var builder = new HostBuilder()               
  .ConfigureAppConfiguration(x =>
  {
    //..configuration
  })
  .ConfigureLogging(x =>
  {
    //..logging
  })
  .ConfigureDiscordHost<DiscordSocketClient>((context, configurationBuilder) =>
  {
     configurationBuilder.SetDiscordConfiguration(new DiscordSocketConfig
     {
       LogLevel = LogSeverity.Verbose,
       AlwaysDownloadUsers = true,
       MessageCacheSize = 200
     });

    configurationBuilder.SetToken(context.Configuration["token"]);
  })
  //Omit this if you don't use the command service
  .UseCommandService()
  .ConfigureServices((context, services) =>
  {
    //Add any other services here
    services.AddSingleton<CommandHandler>();
  })
  .UseConsoleLifetime();

var host = builder.Build();
using (host)
{
  await host.Services.GetRequiredService<CommandHandler>().InitializeAsync();
  await host.RunAsync();
}

Basic Usage

  1. Create a .NET Core application (or retrofit your existing one)

  2. Add the following NuGet packages (at the absolute minimum):

    Discord.Addons.Hosting Microsoft.Extensions.Hosting

  3. Create and start your application using a HostBuilder as shown above and in the examples linked below

Examples

Fully working examples are available here

If you want something more advanced, one of my bots CitizenEnforcer uses this extension. You can find it here

Serilog

Serilog should be added to the host with Serilog.Extensions.Hosting.

See the Serilog example for usage

Shutdown

When shutdown is requested, the host will wait a maximum of 5 seconds for services to stop before timing out.

If you're finding that this isn't enough time, you can modify the shutdown timeout via the ShutdownTimeout host setting.

Reliability

Discord.Net can occasionally give up trying to reconnect after an extended outage. This library provides a basic solution that will automatically attempt to restart the host on a failure. Please note that this functionality is experimental and won't do much if the client completely deadlocks. This feature is also affected by the shutdown timeout set above.

To use the reliability extensions, start the host with await host.RunReliablyAsync().

To shutdown the host, it's recommended to add a shutdown command to your bot and call host.StopReliablyAsync().

This behaviour is similar to the usage of RunAsync() and StopAsync()