using JOBot.TClient.Commands; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace JOBot.TClient.Core.HostedServices; using Telegram.Bot; using Telegram.Bot.Types; using Microsoft.Extensions.Hosting; public sealed class BotBackgroundService( ITelegramBotClient botClient, IServiceProvider services, ILogger logger) : BackgroundService { protected override Task ExecuteAsync(CancellationToken stoppingToken) { botClient.StartReceiving( updateHandler: HandleUpdateAsync, errorHandler: HandleErrorAsync, cancellationToken: stoppingToken); return Task.CompletedTask; } private async Task HandleUpdateAsync(ITelegramBotClient bot, Update update, CancellationToken ct) { using var scope = services.CreateScope(); var commands = new Dictionary { ["/start"] = scope.ServiceProvider.GetRequiredService() }; if (update.Message?.Text is { } text && commands.TryGetValue(text, out var command)) await command.ExecuteAsync(update, ct); } private Task HandleErrorAsync(ITelegramBotClient bot, Exception ex, CancellationToken ct) { services.CreateScope(); logger.LogError(ex, ex.Message); return Task.CompletedTask; } }