First Events
The preferred way to receive events with the .NET Generic Host is by implementing IGatewayEventHandler or IGatewayEventHandler<T>.
First, use AddGatewayEventHandlers(IServiceCollection, Assembly) to add all event handlers in an assembly. You also need to call UseGatewayEventHandlers(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;
})
.AddGatewayEventHandlers(typeof(Program).Assembly);
var host = builder.Build()
.UseGatewayEventHandlers();
await host.RunAsync();
Note
All gateway event handlers require GatewayEventAttribute that specifies the event to bind to. The event argument must match the type of the handler, otherwise an exception will be thrown.
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;
[GatewayEvent(nameof(GatewayClient.MessageCreate))]
public class MessageCreateHandler(ILogger<MessageCreateHandler> logger) : IGatewayEventHandler<Message>
{
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;
[GatewayEvent(nameof(GatewayClient.MessageReactionAdd))]
public class MessageReactionAddHandler(RestClient client) : IGatewayEventHandler<MessageReactionAddEventArgs>
{
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 IShardedGatewayEventHandler or IShardedGatewayEventHandler<T> instead. You also need to use AddShardedGatewayEventHandlers to add event handlers and UseShardedGatewayEventHandlers to bind them instead. See Sharding for more information.