JOBot/JOBot.TClient/Core/HostedServices/BotBackgroundService.cs

90 lines
3.2 KiB
C#

using JOBot.TClient.Commands;
using JOBot.TClient.Commands.Buttons;
using JOBot.TClient.Commands.Commands;
using JOBot.TClient.Infrastructure.Attributes.Authorization;
using JOBot.TClient.Infrastructure.Extensions;
using JOBot.TClient.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Telegram.Bot;
using Telegram.Bot.Types;
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(
HandleUpdateAsync,
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 is { Text: { } text, From: not null })
{
var user = await userService.GetUser(update, ct); //Проверка существования пользователя
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.SendMessageRemK(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;
}
}