| | | 1 | | using GistBackend.Utils; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | using Microsoft.Extensions.Options; |
| | | 4 | | using Telegram.Bot; |
| | | 5 | | using Telegram.Bot.Types; |
| | | 6 | | using Telegram.Bot.Types.Enums; |
| | | 7 | | using static Telegram.Bot.TelegramBotClient; |
| | | 8 | | |
| | | 9 | | namespace GistBackend.Handlers.TelegramBotClientHandler; |
| | | 10 | | |
| | | 11 | | public interface ITelegramBotClientHandler |
| | | 12 | | { |
| | | 13 | | public void StartBotClient(IEnumerable<BotCommand> commands, OnMessageHandler onMessage, OnErrorHandler onError, |
| | | 14 | | CancellationToken ct); |
| | | 15 | | public Task SendMessageAsync(long chatId, string text, ParseMode parseMode = ParseMode.None); |
| | | 16 | | } |
| | | 17 | | |
| | 0 | 18 | | public class TelegramBotClientHandler( |
| | 0 | 19 | | IOptions<TelegramBotClientHandlerOptions> options, |
| | 0 | 20 | | ILogger<TelegramBotClient>? logger) : ITelegramBotClientHandler |
| | | 21 | | { |
| | | 22 | | private TelegramBotClient? _botClient; |
| | | 23 | | private CancellationToken? _cancellationToken; |
| | | 24 | | |
| | | 25 | | public void StartBotClient(IEnumerable<BotCommand> commands, OnMessageHandler onMessage, OnErrorHandler onError, |
| | | 26 | | CancellationToken ct) |
| | | 27 | | { |
| | 0 | 28 | | _cancellationToken = ct; |
| | 0 | 29 | | if (string.IsNullOrWhiteSpace(options.Value.BotToken)) |
| | 0 | 30 | | throw new ArgumentException("Bot token is not set in the options."); |
| | 0 | 31 | | _botClient = new TelegramBotClient(options.Value.BotToken, cancellationToken: ct); |
| | 0 | 32 | | _botClient.SetMyCommands(commands, cancellationToken: ct).GetAwaiter().GetResult(); |
| | 0 | 33 | | _botClient.OnMessage += onMessage; |
| | 0 | 34 | | _botClient.OnError += onError; |
| | 0 | 35 | | } |
| | | 36 | | |
| | | 37 | | public async Task SendMessageAsync(long chatId, string text, ParseMode parseMode = ParseMode.None) |
| | | 38 | | { |
| | 0 | 39 | | if (_botClient is null) throw new InvalidOperationException("Bot client is not initialized."); |
| | | 40 | | |
| | 0 | 41 | | await _botClient.SendMessage(chatId, text, parseMode, cancellationToken: _cancellationToken!.Value); |
| | 0 | 42 | | logger?.LogInformation(LogEvents.SentTelegramMessage, "Sent message to chat {ChatId}: {Text}", chatId, text); |
| | 0 | 43 | | } |
| | | 44 | | } |