JOBot/JOBot.TClient/Core/HostedServices/BotBackgroundService.cs
Lisoveliy a526dbf6c6 feat: implemented registration stage of preparation on PrepareUserState
implemented auth, added auth tools AcceptNotPreparedAttribute.cs, IAuthorizedTelegramCommand.cs
2025-07-12 01:52:16 +03:00

81 lines
3.0 KiB
C#

using JOBot.TClient.Commands;
using JOBot.TClient.Commands.Buttons;
using JOBot.TClient.Infrastructure.Attributes.Authorization;
using JOBot.TClient.Infrastructure.Extensions;
using JOBot.TClient.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Telegram.Bot;
using Telegram.Bot.Types;
using Microsoft.Extensions.Hosting;
namespace JOBot.TClient.Core.HostedServices;
public sealed class BotBackgroundService(
ITelegramBotClient botClient,
IServiceProvider services,
ILogger<BotBackgroundService> logger,
UserService userService)
: 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>
{
//Commands
["/start"] = scope.ServiceProvider.GetRequiredService<StartCommand>(),
["/menu"] = scope.ServiceProvider.GetRequiredService<MenuCommand>(),
["/info"] = scope.ServiceProvider.GetRequiredService<InfoCommand>(),
//Buttons
[ButtonResource.EULAAgrement] = scope.ServiceProvider.GetRequiredService<EulaAgreementButtonCommand>(),
};
if (update.Message?.Text is { } text && update.Message?.From != null)
{
var user = await userService.GetUser(update, ct); //Check user for existance
if (user == null)
{
await commands["/start"].ExecuteAsync(update, ct);
return;
}
if (commands.TryGetValue(text, out var command))
{
if (command is IAuthorizedTelegramCommand authorizedTelegramCommand)
{
var attribute = Attribute.GetCustomAttribute(command.GetType(), typeof(AcceptNotPreparedAttribute));
if (!user.IsPrepared() && attribute is not AcceptNotPreparedAttribute)
{
await commands["/start"].ExecuteAsync(update, ct); //заставляем пользователя завершить регистрацию
return;
}
await authorizedTelegramCommand.ExecuteAsync(update, user, ct);
}
else await command.ExecuteAsync(update, ct);
return;
}
await bot.SendMessage(update.Message.From.Id, TextResource.CommandNotFound, cancellationToken: ct);
}
}
private Task HandleErrorAsync(ITelegramBotClient bot, Exception ex, CancellationToken ct)
{
services.CreateScope();
logger.LogError(ex, ex.Message);
return Task.CompletedTask;
}
}