feat: added DI to Client
This commit is contained in:
45
JOBot.TClient/Core/HostedServices/BotBackgroundService.cs
Normal file
45
JOBot.TClient/Core/HostedServices/BotBackgroundService.cs
Normal file
@@ -0,0 +1,45 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user