using System.Reflection; using Discord; using Discord.Interactions; using Discord.WebSocket; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace GodReplacementProduct; public class InteractionHandler : IHostedService { private readonly DiscordSocketClient _client; private readonly InteractionService _handler; private readonly IServiceProvider _services; private readonly ILogger _logger; public InteractionHandler(DiscordSocketClient client, InteractionService handler, IServiceProvider services, ILogger logger) { _client = client; _handler = handler; _services = services; _logger = logger; } public async Task StartAsync(CancellationToken cancellationToken) { _client.Ready += ReadyAsync; await _handler.AddModulesAsync(Assembly.GetEntryAssembly(), _services); _client.InteractionCreated += HandleInteraction; } private async Task ReadyAsync() { var options = _services.GetService>(); if (options is not null) { _logger.LogInformation("Development mode, registering commands to guild {0}", options.Value.TestGuildId); await _handler.RegisterCommandsToGuildAsync(options.Value.TestGuildId, true); } else { _logger.LogInformation("Registering commands globally"); await _handler.RegisterCommandsGloballyAsync(true); } } private async Task HandleInteraction(SocketInteraction interaction) { try { // Create an execution context that matches the generic type parameter of your InteractionModuleBase modules. var context = new SocketInteractionContext(_client, interaction); // Execute the incoming command. var result = await _handler.ExecuteCommandAsync(context, _services); if (!result.IsSuccess) switch (result.Error) { case InteractionCommandError.UnmetPrecondition: break; default: break; } } catch { // If Slash Command execution fails it is most likely that the original interaction acknowledgement will persist. It is a good idea to delete the original // response, or at least let the user know that something went wrong during the command execution. if (interaction.Type is InteractionType.ApplicationCommand) await interaction.GetOriginalResponseAsync().ContinueWith(async (msg) => await msg.Result.DeleteAsync()); } } public Task StopAsync(CancellationToken cancellationToken) { _client.Ready -= ReadyAsync; _client.InteractionCreated -= HandleInteraction; return Task.CompletedTask; } }