Skip to content

Instantly share code, notes, and snippets.

@poqdavid
Last active June 23, 2024 01:31
Show Gist options
  • Save poqdavid/21d21c9624c3efee69df2af7bf6101d3 to your computer and use it in GitHub Desktop.
Save poqdavid/21d21c9624c3efee69df2af7bf6101d3 to your computer and use it in GitHub Desktop.
internal class DiscordBotHostedService(ILogger<DiscordBotHostedService> logger, DiscordClient discord) : IHostedService
{
private readonly ILogger<DiscordBotHostedService> _logger = logger;
private readonly DiscordClient _discordClient = discord;
public async Task StartAsync(CancellationToken cancellationToken)
{
_discordClient.SessionCreated += OnSessionCreated;
_discordClient.GuildAvailable += OnGuildAvailable;
_discordClient.ClientErrored += OnClientError;
await _discordClient.ConnectAsync();
await Task.Delay(-1);
}
public Task StopAsync(CancellationToken cancellationToken)
{
return _discordClient.DisconnectAsync();
}
private async Task OnSessionCreated(DiscordClient sender, SessionCreatedEventArgs e)
{
sender.Logger.LogInformation(Program.BotEventId, "Client is ready to process events.");
await sender.UpdateStatusAsync(new DiscordActivity()
{
ActivityType = Program.Config.Discord.DefaultActivityType,
Name = Program.Config.Discord.DefaultActivity
}, DiscordUserStatus.Online);
}
private Task OnGuildAvailable(DiscordClient sender, GuildAvailableEventArgs e)
{
Thread.CurrentThread.Name = "MainThread";
sender.Logger.LogInformation(Program.BotEventId, "Guild available: {GuildName}", e.Guild.Name);
return Task.CompletedTask;
}
private Task OnClientError(DiscordClient sender, ClientErrorEventArgs e)
{
Thread.CurrentThread.Name = "MainThread";
sender.Logger.LogError(Program.BotEventId, e.Exception, "Exception occured");
return Task.CompletedTask;
}
private async Task OnCommandExecuted(CommandsExtension sender, DSharpPlus.Commands.EventArgs.CommandExecutedEventArgs e)
{
e.Context.Client.Logger.LogInformation(Program.BotEventId, "{Username} successfully executed '{CommandName}'", e.Context.User.Username, e.Context.Command.Name);
await e.Context.Client.UpdateStatusAsync(new DiscordActivity()
{
ActivityType = Program.Config.Discord.DefaultActivityType,
Name = Program.Config.Discord.DefaultActivity
}, DiscordUserStatus.Online);
}
private async Task OnCommandErrored(CommandsExtension sender, DSharpPlus.Commands.EventArgs.CommandErroredEventArgs e)
{
e.Context.Client.Logger.LogError(Program.BotEventId, "{Username} tried executing '{CommandName}' but it errored: {Type}: {Message}", e.Context.User.Username, e.Context?.Command.Name ?? "<unknown command>", e.Exception.GetType(), e.Exception.Message ?? "<no message>");
if (e.Exception is ChecksFailedException)
{
var emoji = DiscordEmoji.FromName(e.Context.Client, ":no_entry:");
var embed = new DiscordEmbedBuilder
{
Title = "Access denied",
Description = $"{emoji} You do not have the permissions required to execute this command.",
Color = new DiscordColor(0xFF0000)
};
await e.Context.RespondAsync(new DiscordInteractionResponseBuilder().WithContent($"{embed}"));
}
await e.Context.Client.UpdateStatusAsync(new DiscordActivity()
{
ActivityType = DiscordActivityType.Watching,
Name = "Errors!"
}, DiscordUserStatus.DoNotDisturb);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment