Table of Contents

First Events

The preferred way to receive events with the .NET Generic Host is by implementing appropriate IGatewayHandlers. An example of such an interface is IMessageCreateGatewayHandler.

First, use AddGatewayHandlers(IServiceCollection, Assembly) to add all event handlers in an assembly. You also need to call UseGatewayHandlers(IHost) to bind the handlers to the client.

using Microsoft.Extensions.Hosting;

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

var builder = Host.CreateApplicationBuilder(args);

builder.Services
    .AddDiscordGateway(options =>
    {
        options.Intents = GatewayIntents.GuildMessages
                          | GatewayIntents.DirectMessages
                          | GatewayIntents.MessageContent
                          | GatewayIntents.DirectMessageReactions
                          | GatewayIntents.GuildMessageReactions;
    })
    .AddGatewayHandlers(typeof(Program).Assembly);

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

await host.RunAsync();

MessageCreate Event

Now it's time to implement your MessageCreate event handler!

using Microsoft.Extensions.Logging;

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

namespace MyBot;

public class MessageCreateHandler(ILogger<MessageCreateHandler> logger) : IMessageCreateGatewayHandler
{
    public ValueTask HandleAsync(Message message)
    {
        logger.LogInformation("{}", message.Content);
        return default;
    }
}

When you run this code, when someone sends a message, the message will be printed on a console!

MessageReactionAdd Event

We will also implement a MessageReactionAdd event handler!

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

namespace MyBot;

public class MessageReactionAddHandler(RestClient client) : IMessageReactionAddGatewayHandler
{
    public async ValueTask HandleAsync(MessageReactionAddEventArgs args)
    {
        await client.SendMessageAsync(args.ChannelId, $"<@{args.UserId}> reacted with {args.Emoji.Name}!");
    }
}

When you run this code, when someone reacts to a message, the bot will notify everyone about it!

Other Events

Other events work similar to these. You can play with them if you want!

Note

When using ShardedGatewayClient, you need to implement IShardedGatewayHandler instead. An example of such an interface is IMessageCreateShardedGatewayHandler. You also need to use AddShardedGatewayHandlers to add event handlers and UseShardedGatewayHandlers to bind them instead. See Sharding for more information.