Table of Contents

Sharding

Sharding allows your bot to split its responsibilities across multiple gateway connections. In NetCord, this is managed by the ShardedGatewayClient, which acts as a controller for multiple instances of GatewayClient. Each shard, represented by a GatewayClient, handles a specific subset of guilds.

When to Shard

Sharding becomes necessary when your bot exceeds 2,500 guilds. However, it's recommended to implement sharding earlier, typically when targeting 1,000+ guilds, to ensure smoother scaling and performance.

How to Shard

When using the .NET Generic Host, you can add the ShardedGatewayClient by calling AddDiscordShardedGateway.

using Microsoft.Extensions.Hosting;

using NetCord.Hosting.Gateway;

var builder = Host.CreateApplicationBuilder(args);

builder.Services
    .AddDiscordShardedGateway();

var host = builder.Build();

await host.RunAsync();

How to Register Events

To register event handlers with sharding in the .NET Generic Host, use AddShardedGatewayEventHandlers to add all event handlers in an assembly and then call AddShardedGatewayEventHandlers to bind these handlers to the sharded client.

var builder = Host.CreateApplicationBuilder(args);

builder.Services
    .AddDiscordShardedGateway(options =>
    {
        options.Intents = GatewayIntents.GuildMessages
                          | GatewayIntents.DirectMessages
                          | GatewayIntents.MessageContent;
    })
    .AddShardedGatewayEventHandlers(typeof(Program).Assembly);

var host = builder.Build()
    .UseShardedGatewayEventHandlers();

await host.RunAsync();

When creating event handlers, implement IShardedGatewayEventHandler or IShardedGatewayEventHandler<T>. Note the additional parameter representing the GatewayClient that received the event.

using NetCord.Gateway;
using NetCord.Hosting.Gateway;

namespace MyBot;

[GatewayEvent(nameof(GatewayClient.MessageUpdate))]
public class MessageUpdateHandler : IShardedGatewayEventHandler<Message>
{
    public async ValueTask HandleAsync(GatewayClient client, Message message)
    {
        await message.ReplyAsync("Message updated!");
    }
}