feat: added DI to Client

This commit is contained in:
Lisoveliy
2025-05-01 20:50:14 +03:00
parent da0ca92795
commit 786c63166c
8 changed files with 149 additions and 42 deletions

View 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;
}
}

View File

@@ -0,0 +1,18 @@
using User = JOBot.Proto.User;
namespace JOBot.TClient.Core.Services;
public class UserService(User.UserClient client)
{
public async Task<bool> RegisterAsync(long userId, string? username)
{
var response = await client.RegisterAsync(new()
{
UserId = userId,
Username = username
});
return response.Success;
}
}