using System.Net.Http.Json;
using System.Text;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.InlineQueryResults;
using TelegramBot.DTOs;
namespace TelegramBot.Commands;
public class LinkMessage : IMessage
{
///
/// Create message from API
///
///
///
///
///
async Task<(string? message, string? preview)> GetMessage(ITelegramBotClient botClient, string inputUrl,
CancellationToken cancellationToken)
{
try
{
using var client = new HttpClient();
var res = await client.GetAsync($"{Program.Config.ApiPath}/link/getService?link=" + inputUrl,
cancellationToken);
var typeRes = await res.Content.ReadFromJsonAsync(cancellationToken: cancellationToken);
if (!res.IsSuccessStatusCode)
{
return (string.Empty, $"Произошла ошибка при обработке запроса\n{res.StatusCode.ToString()}");
}
var message = new StringBuilder();
var preview = new StringBuilder();
foreach (var service in typeRes?.service.Another()!)
{
res = await client.PostAsJsonAsync($"{Program.Config.ApiPath}/link/fromLink", new
{
link = inputUrl,
service,
}, cancellationToken: cancellationToken);
if (!res.IsSuccessStatusCode)
{
preview.AppendLine($"❌ {service}\n");
message.AppendLine(
$"❌ {service}: 🤨👨🏿🦰😡😮💨😰 {(await res.Content.ReadFromJsonAsync(cancellationToken: cancellationToken))?.title}");
message.AppendLine();
continue;
}
var apiRes = await res.Content.ReadFromJsonAsync(cancellationToken: cancellationToken);
preview.AppendLine($"✅ {service}\n");
message.AppendLine($"✅ {service} - {apiRes?.link}");
message.AppendLine();
}
return (message.ToString(), preview.ToString());
}
catch (Exception e)
{
Console.WriteLine("Ошибка:\n--------------------------");
Console.WriteLine(e);
return (e.ToString(), "Произошла ошибка при обработке запроса\nдетали в сообщении");
}
}
public async Task InvokeFromMessage(ITelegramBotClient botClient, Update update,
CancellationToken cancellationToken)
{
var result = (await GetMessage(botClient, update.Message?.Text!, cancellationToken)).message;
await botClient.SendTextMessageAsync(update.Message?.Chat!, string.IsNullOrEmpty(result) ? "Ошибка🤔:\nНе удалось определить сервис исходной ссылки.\nДоступные сервисы для конвертации:\nTidal\nYandex\nSpotify" : result, cancellationToken: cancellationToken);
}
public async Task InvokeFromInlineQuery(ITelegramBotClient botClient, Update update,
CancellationToken cancellationToken)
{
if(string.IsNullOrEmpty(update.InlineQuery!.Query))
return;
var message = await new LinkMessage().GetMessage(botClient, update.InlineQuery!.Query, cancellationToken);
if(message.message != null)
try
{
await botClient.AnswerInlineQueryAsync(update.InlineQuery.Id,
new[]
{
new InlineQueryResultArticle("0", message.preview!,
new InputTextMessageContent(message.message))
}, cancellationToken: cancellationToken);
}
catch (Exception e)
{
Console.WriteLine($"Failed to send answer to {update.Message?.Chat.Username}");
}
}
}