| | | 1 | | using System.Net.Sockets; |
| | | 2 | | using System.Text; |
| | | 3 | | using Microsoft.Extensions.Logging; |
| | | 4 | | using Newtonsoft.Json; |
| | | 5 | | using Services.ApiServices.TelegramBotApi.Models; |
| | | 6 | | |
| | | 7 | | namespace Services.ApiServices.TelegramBotApi; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Тонкий клиент Telegram Bot API. Токен входит в путь запроса, поэтому он вычищается из любого |
| | | 11 | | /// текста ошибки, а стандартное логирование <c>HttpClient</c> для этого клиента отключено при регистрации. |
| | | 12 | | /// </summary> |
| | | 13 | | public class TelegramBotApiClient |
| | | 14 | | { |
| | | 15 | | private readonly HttpClient _httpClient; |
| | | 16 | | private readonly TelegramBotConfig _config; |
| | | 17 | | private readonly ILogger<TelegramBotApiClient>? _logger; |
| | | 18 | | |
| | 14 | 19 | | public TelegramBotApiClient(HttpClient httpClient, TelegramBotConfig config, ILogger<TelegramBotApiClient>? logger = |
| | | 20 | | { |
| | 14 | 21 | | _httpClient = httpClient; |
| | 14 | 22 | | _config = config; |
| | 14 | 23 | | _logger = logger; |
| | 14 | 24 | | } |
| | | 25 | | |
| | 0 | 26 | | public bool IsConfigured => _config.IsConfigured; |
| | | 27 | | |
| | | 28 | | public Task<TelegramApiResult<TelegramBotInfo>> GetMeAsync(CancellationToken ct = default) => |
| | 1 | 29 | | CallAsync<TelegramBotInfo>("getMe", null, ct); |
| | | 30 | | |
| | | 31 | | public Task<TelegramApiResult<TelegramSentMessage>> SendMessageAsync(SendMessageRequest request, CancellationToken c |
| | 15 | 32 | | CallAsync<TelegramSentMessage>("sendMessage", request, ct); |
| | | 33 | | |
| | | 34 | | public Task<TelegramApiResult<TelegramSentMessage>> SendPhotoAsync(SendPhotoRequest request, CancellationToken ct = |
| | 1 | 35 | | CallAsync<TelegramSentMessage>("sendPhoto", request, ct); |
| | | 36 | | |
| | | 37 | | public Task<TelegramApiResult<TelegramChatInfo>> GetChatAsync(long chatId, CancellationToken ct = default) => |
| | 0 | 38 | | CallAsync<TelegramChatInfo>("getChat", new { chat_id = chatId }, ct); |
| | | 39 | | |
| | | 40 | | /// <summary>Для обычных сообщений Telegram возвращает в <c>result</c> объект сообщения, для inline — <c>true</c>, п |
| | | 41 | | public Task<TelegramApiResult<Newtonsoft.Json.Linq.JToken>> EditMessageTextAsync(EditMessageTextRequest request, Can |
| | 2 | 42 | | CallAsync<Newtonsoft.Json.Linq.JToken>("editMessageText", request, ct); |
| | | 43 | | |
| | | 44 | | public Task<TelegramApiResult<bool>> PinChatMessageAsync(PinChatMessageRequest request, CancellationToken ct = defau |
| | 0 | 45 | | CallAsync<bool>("pinChatMessage", request, ct); |
| | | 46 | | |
| | | 47 | | public Task<TelegramApiResult<bool>> UnpinChatMessageAsync(UnpinChatMessageRequest request, CancellationToken ct = d |
| | 0 | 48 | | CallAsync<bool>("unpinChatMessage", request, ct); |
| | | 49 | | |
| | | 50 | | /// <summary>Входящие сообщения — удобно, чтобы узнать <c>chat_id</c> группы или пользователя.</summary> |
| | | 51 | | public Task<TelegramApiResult<List<TelegramUpdate>>> GetUpdatesAsync(long? offset = null, CancellationToken ct = def |
| | 0 | 52 | | CallAsync<List<TelegramUpdate>>("getUpdates", offset.HasValue ? new { offset = offset.Value } : null, ct); |
| | | 53 | | |
| | | 54 | | private async Task<TelegramApiResult<T>> CallAsync<T>(string method, object? body, CancellationToken ct) |
| | | 55 | | { |
| | 19 | 56 | | if (!_config.IsConfigured) |
| | 0 | 57 | | return TelegramApiResult<T>.Failure("Telegram-бот не настроен или выключен"); |
| | | 58 | | |
| | | 59 | | try |
| | | 60 | | { |
| | | 61 | | // «./» обязателен: токен содержит «:», и без него «bot123:ABC/…» разбирается как абсолютный URI со схемой « |
| | 19 | 62 | | using var request = new HttpRequestMessage(HttpMethod.Post, new Uri($"./bot{_config.Token}/{method}", UriKin |
| | 19 | 63 | | if (body != null) |
| | 18 | 64 | | request.Content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json" |
| | | 65 | | |
| | 19 | 66 | | using var response = await _httpClient.SendAsync(request, ct); |
| | 15 | 67 | | var content = await response.Content.ReadAsStringAsync(ct); |
| | 15 | 68 | | var envelope = JsonConvert.DeserializeObject<TelegramEnvelope<T>>(content); |
| | | 69 | | |
| | 15 | 70 | | if (envelope is { Ok: true }) |
| | 11 | 71 | | return TelegramApiResult<T>.Success(envelope.Result); |
| | | 72 | | |
| | 4 | 73 | | var error = Sanitize(envelope?.Description ?? $"HTTP {(int)response.StatusCode}"); |
| | 4 | 74 | | _logger?.LogWarning("Telegram {Method}: {Error}", method, error); |
| | 4 | 75 | | return TelegramApiResult<T>.Failure(error, envelope?.ErrorCode ?? (int)response.StatusCode); |
| | | 76 | | } |
| | 0 | 77 | | catch (OperationCanceledException) when (ct.IsCancellationRequested) |
| | | 78 | | { |
| | 0 | 79 | | throw; |
| | | 80 | | } |
| | 4 | 81 | | catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or SocketException or JsonExcepti |
| | | 82 | | { |
| | 4 | 83 | | var error = Sanitize(ex.Message); |
| | 4 | 84 | | _logger?.LogWarning("Telegram {Method}: сбой запроса ({Type}): {Error}", method, ex.GetType().Name, error); |
| | 4 | 85 | | return TelegramApiResult<T>.Failure(error); |
| | | 86 | | } |
| | 0 | 87 | | catch (Exception ex) |
| | | 88 | | { |
| | 0 | 89 | | var error = Sanitize(ex.Message); |
| | 0 | 90 | | _logger?.LogError("Telegram {Method}: непредвиденная ошибка ({Type}): {Error}", method, ex.GetType().Name, e |
| | 0 | 91 | | return TelegramApiResult<T>.Failure(error); |
| | | 92 | | } |
| | 19 | 93 | | } |
| | | 94 | | |
| | | 95 | | private string Sanitize(string text) => |
| | 8 | 96 | | string.IsNullOrEmpty(_config.Token) ? text : text.Replace(_config.Token, "***"); |
| | | 97 | | } |