using Discord; using Discord.WebSocket; using Discord.Interactions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Configuration; namespace TentacleBot.Services; public class BotService { private readonly DiscordSocketClient _client; private readonly InteractionService _interactionService; private readonly ILogger _logger; private readonly IConfiguration _configuration; private readonly IServiceProvider _serviceProvider; public BotService( DiscordSocketClient client, InteractionService interactionService, ILogger logger, IConfiguration configuration, IServiceProvider serviceProvider) { _client = client; _interactionService = interactionService; _logger = logger; _configuration = configuration; _serviceProvider = serviceProvider; } public async Task InitializeAsync() { _client.Log += LogAsync; _interactionService.Log += LogAsync; _client.Ready += ClientReadyAsync; _client.InteractionCreated += InteractionCreatedAsync; var token = Environment.GetEnvironmentVariable("DISCORD_BOT_TOKEN"); if (string.IsNullOrWhiteSpace(token)) { token = _configuration["Discord:BotToken"]; } if (string.IsNullOrEmpty(token)) { throw new InvalidOperationException("Discord bot token not found. Set DISCORD_BOT_TOKEN or Discord:BotToken in appsettings.json"); } await _client.LoginAsync(TokenType.Bot, token); await _client.StartAsync(); _logger.LogInformation("Bot service initialized"); } private async Task ClientReadyAsync() { _logger.LogInformation("Bot connected as {BotName}#{Discriminator}", _client.CurrentUser?.Username, _client.CurrentUser?.Discriminator); // Register slash commands await _interactionService.RegisterCommandsGloballyAsync(); _logger.LogInformation("Slash commands registered"); } private async Task InteractionCreatedAsync(SocketInteraction interaction) { try { var ctx = new SocketInteractionContext(_client, interaction); await _interactionService.ExecuteCommandAsync(ctx, _serviceProvider); } catch (Exception ex) { _logger.LogError(ex, "Error handling interaction"); if (interaction.Type == InteractionType.ApplicationCommand) { await interaction.GetOriginalResponseAsync().ContinueWith(async msg => { if (msg.IsCompletedSuccessfully) { await interaction.FollowupAsync("An error occurred while executing the command."); } }); } } } private static Task LogAsync(LogMessage message) { Console.WriteLine($"[{message.Severity}] {message.Source}: {message.Message}"); return Task.CompletedTask; } public async Task StopAsync() { await _client.StopAsync(); _client.Dispose(); _logger.LogInformation("Bot service stopped"); } }