54 lines
1.9 KiB
C#
54 lines
1.9 KiB
C#
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
using Telegram.Bot;
|
|
using Telegram.Bot.Polling;
|
|
using Telegram.Bot.Types.Enums;
|
|
|
|
namespace GymLogAI.TelegramBot;
|
|
|
|
public sealed class TelegramBotHostedService(
|
|
ITelegramBotClient botClient,
|
|
IServiceProvider serviceProvider,
|
|
IOptions<TelegramBotOptions> options,
|
|
ILogger<TelegramBotHostedService> logger) : BackgroundService
|
|
{
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(options.Value.BotToken))
|
|
{
|
|
logger.LogWarning("Telegram bot token is not configured. Bot polling is disabled.");
|
|
return;
|
|
}
|
|
|
|
var receiverOptions = new ReceiverOptions
|
|
{
|
|
AllowedUpdates = [UpdateType.Message]
|
|
};
|
|
|
|
botClient.StartReceiving(
|
|
async (client, update, cancellationToken) =>
|
|
{
|
|
await using var scope = serviceProvider.CreateAsyncScope();
|
|
var handler = scope.ServiceProvider.GetRequiredService<UpdateHandler>();
|
|
await handler.HandleUpdateAsync(client, update, cancellationToken);
|
|
},
|
|
async (client, exception, cancellationToken) =>
|
|
{
|
|
await using var scope = serviceProvider.CreateAsyncScope();
|
|
var handler = scope.ServiceProvider.GetRequiredService<UpdateHandler>();
|
|
await handler.HandleErrorAsync(client, exception, cancellationToken);
|
|
},
|
|
receiverOptions,
|
|
stoppingToken);
|
|
|
|
logger.LogInformation("Telegram bot long polling started.");
|
|
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
{
|
|
await Task.Delay(TimeSpan.FromSeconds(options.Value.PollingTimeoutSeconds), stoppingToken);
|
|
}
|
|
}
|
|
}
|