Available as a NuGet package both on GitHub and nuget.org
Extremely simple and lightweight library for hooking up a Discord webhook meant to be used with ASP.NET Core or the Generic Host.
Built-in support for Microsoft.Extensions.Logging
's ILogger<T>
(does not work without it, injected via DI) and embeds via TraceLd.DiscordWebhook.Models.Embed
.
The following example will use ASP.NET Core but the setup is almost identical with the Generic Host.
- Add
WebhookSettings
as a singleton. Where it comes from is up to you - it can be config files, environment variables etc. In this simple example we will useappsettings.json
. (It is not the most secure option as the credentials are stored in plaintext, but it's very simple).
- Add the following section to
appsettings.json
and fill it in with your credentials:
"WebhookSettings": {
"Id": 0000000,
"Token": "token"
}
- Add the following code to the
ConfigureServices
method inStartup.cs
:
services.Configure<WebhookSettings>(Configuration.GetSection(nameof(WebhookSettings)));
services.AddSingleton(provider => provider.GetRequiredService<IOptions<WebhookSettings>>().Value);
- Add
IWebhookService
:
- Add the following code to
Startup.cs
below the previously added code:
services.AddHttpClient<IWebhookService, WebhookService>();
- Now you can use the webhook service in your own services, for example:
- Create the service:
public interface IHelloService
{
Task SendHelloAsync();
}
public class HelloService : IHelloService
{
private readonly ILogger<HelloService> _logger;
private readonly IWebhookService _webhookService;
public HelloService(ILogger<HelloService> logger, IWebhookService webhookService)
{
_logger = logger;
_webhookService = webhookService;
}
public async Task SendHelloAsync()
{
await _webhookService.ExecuteWebhookAsync("Hello from C#");
}
}
- Add the service in
Startup.cs
(below the previous code):
services.AddScoped<IHelloService, HelloService>();