Initial commit
This commit is contained in:
@@ -0,0 +1,242 @@
|
||||
using MediatR;
|
||||
using MemeVault.Application.Commands.EnsureUser;
|
||||
using MemeVault.Application.Commands.SaveMedia;
|
||||
using MemeVault.Domain.Enums;
|
||||
using MemeVault.Domain.ValueObjects;
|
||||
using Microsoft.Extensions.Caching.Distributed;
|
||||
using System.Text.Json;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types;
|
||||
using Telegram.Bot.Types.Enums;
|
||||
|
||||
namespace MemeVault.Bot.Telegram.Handlers;
|
||||
|
||||
/// <summary>
|
||||
/// Обрабатывает входящие сообщения.
|
||||
/// Поддерживает media groups (альбомы): несколько фото/видео в одном "визуальном" сообщении.
|
||||
/// </summary>
|
||||
public sealed class MessageHandler
|
||||
{
|
||||
private readonly IMediator _mediator;
|
||||
private readonly ITelegramBotClient _bot;
|
||||
private readonly IDistributedCache _cache;
|
||||
private readonly ILogger<MessageHandler> _logger;
|
||||
|
||||
// Сколько ждать, пока все части альбома придут от Telegram
|
||||
private static readonly TimeSpan MediaGroupBuffer = TimeSpan.FromSeconds(2);
|
||||
|
||||
public MessageHandler(
|
||||
IMediator mediator,
|
||||
ITelegramBotClient bot,
|
||||
IDistributedCache cache,
|
||||
ILogger<MessageHandler> logger)
|
||||
{
|
||||
_mediator = mediator;
|
||||
_bot = bot;
|
||||
_cache = cache;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task HandleAsync(Message message, CancellationToken ct)
|
||||
{
|
||||
if (message.From is null) return;
|
||||
|
||||
await _mediator.Send(new EnsureUserCommand(
|
||||
message.From.Id,
|
||||
message.From.Username ?? message.From.Id.ToString(),
|
||||
message.From.FirstName), ct);
|
||||
|
||||
// Альбом — буферизуем через Redis и обрабатываем единым батчем
|
||||
if (message.MediaGroupId is not null)
|
||||
{
|
||||
await HandleMediaGroupAsync(message, ct);
|
||||
return;
|
||||
}
|
||||
|
||||
// Одиночное сообщение
|
||||
var (source, mediaType) = ExtractMedia(message);
|
||||
|
||||
if (source is not null || mediaType == MediaType.Text)
|
||||
{
|
||||
await SaveSingleItemAsync(message.From.Id, message.Chat.Id,
|
||||
source, mediaType,
|
||||
message.Caption ?? message.Text,
|
||||
mediaGroupId: null, ct);
|
||||
}
|
||||
else if (message.Text?.StartsWith('/') == true)
|
||||
{
|
||||
await HandleCommandAsync(message, ct);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Media Group (альбом) ──────────────────────────────────────────────────
|
||||
|
||||
private async Task HandleMediaGroupAsync(Message message, CancellationToken ct)
|
||||
{
|
||||
var groupId = message.MediaGroupId!;
|
||||
var cacheKey = $"mg:{message.From!.Id}:{groupId}";
|
||||
|
||||
// Кладём текущий файл в буфер
|
||||
var (source, mediaType) = ExtractMedia(message);
|
||||
if (source is null) return;
|
||||
|
||||
var entry = new MediaGroupEntry(
|
||||
message.From.Id,
|
||||
message.Chat.Id,
|
||||
source.Origin.ToString(),
|
||||
source.Reference,
|
||||
mediaType.ToString(),
|
||||
message.Caption);
|
||||
|
||||
var existing = await _cache.GetStringAsync(cacheKey, ct);
|
||||
List<MediaGroupEntry> entries;
|
||||
|
||||
if (existing is null)
|
||||
{
|
||||
entries = [entry];
|
||||
|
||||
// Первый файл — запускаем отложенную обработку
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(MediaGroupBuffer, CancellationToken.None);
|
||||
await FlushMediaGroupAsync(cacheKey, groupId, CancellationToken.None);
|
||||
}, CancellationToken.None);
|
||||
}
|
||||
else
|
||||
{
|
||||
entries = JsonSerializer.Deserialize<List<MediaGroupEntry>>(existing)!;
|
||||
entries.Add(entry);
|
||||
}
|
||||
|
||||
var options = new DistributedCacheEntryOptions
|
||||
{
|
||||
AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10)
|
||||
};
|
||||
await _cache.SetStringAsync(cacheKey, JsonSerializer.Serialize(entries), options, ct);
|
||||
}
|
||||
|
||||
private async Task FlushMediaGroupAsync(string cacheKey, string groupId, CancellationToken ct)
|
||||
{
|
||||
var raw = await _cache.GetStringAsync(cacheKey, ct);
|
||||
if (raw is null) return;
|
||||
|
||||
await _cache.RemoveAsync(cacheKey, ct);
|
||||
|
||||
var entries = JsonSerializer.Deserialize<List<MediaGroupEntry>>(raw)!;
|
||||
if (entries.Count == 0) return;
|
||||
|
||||
var first = entries[0];
|
||||
var tags = ExtractHashtags(first.Caption ?? "");
|
||||
var caption = StripHashtags(first.Caption ?? "");
|
||||
long chatId = first.ChatId;
|
||||
|
||||
// Сохраняем каждый файл группы как отдельный MediaItem, но с общим MediaGroupId
|
||||
var savedIds = new List<Guid>();
|
||||
foreach (var e in entries)
|
||||
{
|
||||
var origin = Enum.Parse<MediaOrigin>(e.Origin);
|
||||
var source = origin == MediaOrigin.Telegram
|
||||
? MediaSource.FromTelegram(e.Reference)
|
||||
: MediaSource.FromS3(e.Reference);
|
||||
|
||||
var mediaType = Enum.Parse<MediaType>(e.MediaType);
|
||||
|
||||
var id = await _mediator.Send(new SaveMediaCommand(
|
||||
e.OwnerTelegramId,
|
||||
source,
|
||||
mediaType,
|
||||
string.IsNullOrWhiteSpace(caption) ? null : caption,
|
||||
tags,
|
||||
MediaGroupId: groupId), ct);
|
||||
|
||||
savedIds.Add(id);
|
||||
}
|
||||
|
||||
_logger.LogInformation("Saved media group {GroupId}: {Count} items", groupId, savedIds.Count);
|
||||
|
||||
await _bot.SendMessage(
|
||||
chatId,
|
||||
$"✅ Альбом сохранён ({savedIds.Count} файлов)" +
|
||||
(tags.Count > 0 ? $"\nТеги: {string.Join(", ", tags.Select(t => "#" + t))}" : ""),
|
||||
cancellationToken: ct);
|
||||
}
|
||||
|
||||
// ── Одиночный элемент ─────────────────────────────────────────────────────
|
||||
|
||||
private async Task SaveSingleItemAsync(
|
||||
long ownerId, long chatId,
|
||||
MediaSource? source, MediaType mediaType,
|
||||
string? rawText,
|
||||
string? mediaGroupId,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var tags = ExtractHashtags(rawText ?? "");
|
||||
var caption = StripHashtags(rawText ?? "");
|
||||
|
||||
var id = await _mediator.Send(new SaveMediaCommand(
|
||||
ownerId,
|
||||
source,
|
||||
mediaType,
|
||||
string.IsNullOrWhiteSpace(caption) ? null : caption,
|
||||
tags,
|
||||
mediaGroupId), ct);
|
||||
|
||||
_logger.LogInformation("Saved {Type} for user {UserId}, item {ItemId}", mediaType, ownerId, id);
|
||||
|
||||
await _bot.SendMessage(
|
||||
chatId,
|
||||
$"✅ Сохранено!\nТеги: {(tags.Count > 0 ? string.Join(", ", tags.Select(t => "#" + t)) : "нет")}",
|
||||
cancellationToken: ct);
|
||||
}
|
||||
|
||||
// ── Команды ───────────────────────────────────────────────────────────────
|
||||
|
||||
private async Task HandleCommandAsync(Message message, CancellationToken ct)
|
||||
{
|
||||
var reply = message.Text switch
|
||||
{
|
||||
"/start" => "👋 Привет! Отправь мне картинку, видео, стикер или текст — я сохраню.\n" +
|
||||
"Теги прямо в подписи: #мем #кот\n" +
|
||||
"Поиск в инлайне: @bot #мем #кот -#толстый",
|
||||
"/help" => "📖 Команды:\n/start — приветствие\n/help — помощь\n\n" +
|
||||
"Поддерживаю: фото, видео, GIF, стикеры, текст и альбомы.",
|
||||
_ => "Неизвестная команда. Попробуй /help"
|
||||
};
|
||||
|
||||
await _bot.SendMessage(message.Chat.Id, reply, cancellationToken: ct);
|
||||
}
|
||||
|
||||
// ── Вспомогательные ───────────────────────────────────────────────────────
|
||||
|
||||
private static (MediaSource? source, MediaType type) ExtractMedia(Message message) =>
|
||||
message.Type switch
|
||||
{
|
||||
MessageType.Photo => (MediaSource.FromTelegram(message.Photo!.Last().FileId), MediaType.Photo),
|
||||
MessageType.Video => (MediaSource.FromTelegram(message.Video!.FileId), MediaType.Video),
|
||||
MessageType.Sticker => (MediaSource.FromTelegram(message.Sticker!.FileId), MediaType.Sticker),
|
||||
MessageType.Animation => (MediaSource.FromTelegram(message.Animation!.FileId), MediaType.Animation),
|
||||
MessageType.Text => (null, MediaType.Text),
|
||||
_ => (null, MediaType.Text)
|
||||
};
|
||||
|
||||
private static List<string> ExtractHashtags(string text) =>
|
||||
text.Split(' ', StringSplitOptions.RemoveEmptyEntries)
|
||||
.Where(w => w.StartsWith('#') && w.Length > 1)
|
||||
.Select(w => w[1..].ToLowerInvariant().Trim('#', ',', '.'))
|
||||
.Where(t => t.Length > 0)
|
||||
.Distinct()
|
||||
.ToList();
|
||||
|
||||
private static string StripHashtags(string text) =>
|
||||
string.Join(' ', text.Split(' ', StringSplitOptions.RemoveEmptyEntries)
|
||||
.Where(w => !w.StartsWith('#'))).Trim();
|
||||
|
||||
// DTO для сериализации в Redis
|
||||
private sealed record MediaGroupEntry(
|
||||
long OwnerTelegramId,
|
||||
long ChatId,
|
||||
string Origin,
|
||||
string Reference,
|
||||
string MediaType,
|
||||
string? Caption);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
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
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Polling;
|
||||
using Telegram.Bot.Types;
|
||||
using Telegram.Bot.Types.Enums;
|
||||
|
||||
namespace MemeVault.Bot.Telegram;
|
||||
|
||||
/// <summary>
|
||||
/// Long-polling фоновый сервис. Активен при Bot:Mode=Polling.
|
||||
/// Каждый апдейт обрабатывается в отдельном DI-скоупе.
|
||||
/// </summary>
|
||||
public sealed class PollingService(
|
||||
ITelegramBotClient bot,
|
||||
IServiceProvider services,
|
||||
ILogger<PollingService> logger) : BackgroundService
|
||||
{
|
||||
private static readonly ReceiverOptions ReceiverOptions = new()
|
||||
{
|
||||
AllowedUpdates = [UpdateType.Message, UpdateType.InlineQuery],
|
||||
DropPendingUpdates = true,
|
||||
};
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
logger.LogInformation("Telegram polling started");
|
||||
|
||||
await bot.ReceiveAsync(
|
||||
updateHandler: HandleUpdateAsync,
|
||||
errorHandler: HandleErrorAsync,
|
||||
receiverOptions: ReceiverOptions,
|
||||
cancellationToken: stoppingToken);
|
||||
}
|
||||
|
||||
private async Task HandleUpdateAsync(
|
||||
ITelegramBotClient _,
|
||||
Update update,
|
||||
CancellationToken ct)
|
||||
{
|
||||
await using var scope = services.CreateAsyncScope();
|
||||
var dispatcher = scope.ServiceProvider.GetRequiredService<UpdateDispatcher>();
|
||||
await dispatcher.DispatchAsync(update, ct);
|
||||
}
|
||||
|
||||
private Task HandleErrorAsync(
|
||||
ITelegramBotClient _,
|
||||
Exception ex,
|
||||
CancellationToken ct)
|
||||
{
|
||||
logger.LogError(ex, "Telegram polling error");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using System.Diagnostics;
|
||||
using MemeVault.Bot.Telegram.Handlers;
|
||||
using MemeVault.Bot.Telegram.InlineMode;
|
||||
using MemeVault.Bot.Telemetry;
|
||||
using Telegram.Bot.Types;
|
||||
using Telegram.Bot.Types.Enums;
|
||||
|
||||
namespace MemeVault.Bot.Telegram;
|
||||
|
||||
/// <summary>
|
||||
/// Центральный диспетчер: получает Update от Telegram и маршрутизирует к нужному хендлеру.
|
||||
/// Попутно фиксирует метрики через <see cref="BotMetrics"/>.
|
||||
/// </summary>
|
||||
public sealed class UpdateDispatcher(
|
||||
MessageHandler messageHandler,
|
||||
InlineQueryHandler inlineQueryHandler,
|
||||
BotMetrics metrics,
|
||||
ILogger<UpdateDispatcher> logger)
|
||||
{
|
||||
public async Task DispatchAsync(Update update, CancellationToken ct)
|
||||
{
|
||||
var updateType = update.Type.ToString();
|
||||
metrics.UpdatesReceived.WithLabels(updateType).Inc();
|
||||
|
||||
var sw = Stopwatch.StartNew();
|
||||
try
|
||||
{
|
||||
await (update.Type switch
|
||||
{
|
||||
UpdateType.Message when update.Message is not null
|
||||
=> messageHandler.HandleAsync(update.Message, ct),
|
||||
|
||||
UpdateType.InlineQuery when update.InlineQuery is not null
|
||||
=> inlineQueryHandler.HandleAsync(update.InlineQuery, ct),
|
||||
|
||||
_ => Task.CompletedTask
|
||||
});
|
||||
|
||||
metrics.UpdatesProcessed.WithLabels(updateType).Inc();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
metrics.UpdateErrors.WithLabels(updateType).Inc();
|
||||
logger.LogError(ex, "Error dispatching update {UpdateId} ({Type})",
|
||||
update.Id, update.Type);
|
||||
}
|
||||
finally
|
||||
{
|
||||
metrics.UpdateDuration.WithLabels(updateType).Observe(sw.Elapsed.TotalSeconds);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user