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

70 lines
2.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using JOBot.TClient.Commands;
using JOBot.TClient.Commands.Buttons;
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<StartCommand>(),
//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)
await authorizedTelegramCommand.ExecuteAsync(update, user, ct);
else await command.ExecuteAsync(update, ct); //А если вызвать /start когда зареган? То-то и оно, но всё равно надо подумать
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;
}
}