88 lines
2.7 KiB
C#
88 lines
2.7 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: 10, IncludeNsfw: false), 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();
|
|
|
|
var tagsLine = item.Tags.Count > 0
|
|
? string.Join(" ", item.Tags.Take(5).Select(t => "#" + t))
|
|
: null;
|
|
|
|
return item.MediaType switch
|
|
{
|
|
MediaType.Photo => new InlineQueryResultCachedPhoto(id, item.FileId!)
|
|
{
|
|
Caption = item.Caption,
|
|
Title = item.InlineTitle,
|
|
Description = item.InlineDescription ?? tagsLine,
|
|
},
|
|
|
|
MediaType.Video => new InlineQueryResultCachedVideo(
|
|
id,
|
|
item.FileId!,
|
|
title: item.InlineTitle ?? item.Caption ?? "Video")
|
|
{
|
|
Caption = item.Caption,
|
|
Description = item.InlineDescription ?? tagsLine,
|
|
},
|
|
|
|
MediaType.Sticker => new InlineQueryResultCachedSticker(id, item.FileId!),
|
|
|
|
MediaType.Animation => new InlineQueryResultCachedMpeg4Gif(id, item.FileId!)
|
|
{
|
|
Caption = item.Caption,
|
|
Title = item.InlineTitle,
|
|
},
|
|
|
|
MediaType.Text => new InlineQueryResultArticle(
|
|
id,
|
|
title: item.InlineTitle ?? item.Caption?[..Math.Min(60, item.Caption.Length)] ?? "Текст",
|
|
inputMessageContent: new InputTextMessageContent(item.Caption ?? ""))
|
|
{
|
|
Description = item.InlineDescription ?? tagsLine,
|
|
},
|
|
|
|
_ => null
|
|
};
|
|
}
|
|
}
|