Files
telegram-bot/modules/ChatQuotes/QuoteGeneratorService.cs
T

43 lines
1.3 KiB
C#
Raw Normal View History

2022-01-21 00:10:27 +02:00
using System.Net.Http.Headers;
using System.Text;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Telegram.Bot.Types;
using West.TelegramBot.ChatQuotes.Model;
2022-01-21 14:18:56 +02:00
using West.TelegramBot.ChatQuotes.Model.Quote;
using Message = Telegram.Bot.Types.Message;
2022-01-21 00:10:27 +02:00
namespace West.TelegramBot.ChatQuotes;
public class QuoteGeneratorService
{
private readonly HttpClient _httpClient;
2022-01-21 14:18:56 +02:00
private readonly MediaTypeHeaderValue _mediaType;
2022-01-21 00:10:27 +02:00
public QuoteGeneratorService(IConfiguration configuration)
{
_httpClient = new HttpClient
{
BaseAddress = new Uri(configuration.GetValue<string>("QuoteApiUrl"))
};
2022-01-21 14:18:56 +02:00
_mediaType = MediaTypeHeaderValue.Parse("application/json");
2022-01-21 00:10:27 +02:00
}
2022-01-21 14:18:56 +02:00
public async Task<Stream?> GenerateQuoteImage(Message msg)
2022-01-21 00:10:27 +02:00
{
2022-01-21 14:18:56 +02:00
var request = new Request(msg);
2022-01-21 00:10:27 +02:00
var content = new ByteArrayContent(Encoding.UTF8.GetBytes(request.ToJson().ToCharArray()))
{
Headers =
{
2022-01-21 14:18:56 +02:00
ContentType = _mediaType
2022-01-21 00:10:27 +02:00
}
};
var resp = await _httpClient.PostAsync("/generate", content);
2022-01-21 14:18:56 +02:00
var quoteResponse = JsonConvert.DeserializeObject<Response>(await resp.Content.ReadAsStringAsync());
2022-01-21 00:10:27 +02:00
2022-01-21 14:18:56 +02:00
return quoteResponse.Ok ? new MemoryStream(Convert.FromBase64String(quoteResponse.Result.Image)) : null;
2022-01-21 00:10:27 +02:00
}
}