74 lines
2.2 KiB
C#
74 lines
2.2 KiB
C#
using MediatR;
|
|||
|
|
using MemeVault.Application.Queries.SearchMedia;
|
||
|
|
using MemeVault.Domain.Enums;
|
||
|
|
using Telegram.Bot;
|
||
|
|
using Telegram.Bot.Types;
|
||
|
|
using Telegram.Bot.Types.InlineQueryResults;
|
||
|
|
|
||
|
|
namespace MemeVault.Bot.Telegram.InlineMode;
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// Обрабатывает inline-запросы: @bot #мем #кот -#толстый
|
||
|
|
/// </summary>
|
||
|
|
public sealed class InlineQueryHandler
|
||
|
|
{
|
||
|
|
private readonly IMediator _mediator;
|
||
|
|
private readonly ITelegramBotClient _bot;
|
||
|
|
|
||
|
|
public InlineQueryHandler(IMediator mediator, ITelegramBotClient bot)
|
||
|
|
{
|
||
|
|
_mediator = mediator;
|
||
|
|
_bot = bot;
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task HandleAsync(InlineQuery inlineQuery, CancellationToken ct)
|
||
|
|
{
|
||
|
|
var results = await _mediator.Send(
|
||
|
|
new SearchMediaQuery(inlineQuery.From.Id, inlineQuery.Query, Limit: 50), ct);
|
||
|
|
|
||
|
|
var answers = results
|
||
|
|
.Select(ToInlineResult)
|
||
|
|
.OfType<InlineQueryResult>()
|
||
|
|
.ToArray();
|
||
|
|
|
||
|
|
await _bot.AnswerInlineQuery(
|
||
|
|
inlineQuery.Id,
|
||
|
|
answers,
|
||
|
|
cacheTime: 10,
|
||
|
|
isPersonal: true,
|
||
|
|
cancellationToken: ct);
|
||
|
|
}
|
||
|
|
|
||
|
|
private static InlineQueryResult? ToInlineResult(MediaItemDto item)
|
||
|
|
{
|
||
|
|
var id = item.Id.ToString();
|
||
|
|
|
||
|
|
return item.Type switch
|
||
|
|
{
|
||
|
|
MediaType.Photo => new InlineQueryResultCachedPhoto(id, item.FileId!)
|
||
|
|
{
|
||
|
|
Caption = item.Caption,
|
||
|
|
},
|
||
|
|
|
||
|
|
MediaType.Video => new InlineQueryResultCachedVideo(id, item.FileId!, item.Caption ?? "Video"),
|
||
|
|
|
||
|
|
MediaType.Sticker => new InlineQueryResultCachedSticker(id, item.FileId!),
|
||
|
|
|
||
|
|
MediaType.Animation => new InlineQueryResultCachedMpeg4Gif(id, item.FileId!)
|
||
|
|
{
|
||
|
|
Caption = item.Caption,
|
||
|
|
},
|
||
|
|
|
||
|
|
MediaType.Text => new InlineQueryResultArticle(
|
||
|
|
id,
|
||
|
|
title: item.Caption?[..Math.Min(60, item.Caption.Length)] ?? "Текст",
|
||
|
|
inputMessageContent: new InputTextMessageContent(item.Caption ?? ""))
|
||
|
|
{
|
||
|
|
Description = string.Join(" ", item.Tags.Take(5).Select(t => "#" + t)),
|
||
|
|
},
|
||
|
|
|
||
|
|
_ => null
|
||
|
|
};
|
||
|
|
}
|
||
|
|
}
|