45 lines
1.4 KiB
C#
45 lines
1.4 KiB
C#
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<BotBackgroundService> 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<string, ITelegramCommand>
|
|
{
|
|
["/start"] = scope.ServiceProvider.GetRequiredService<StartCommand>()
|
|
};
|
|
|
|
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;
|
|
}
|
|
} |