telegram-client/src/Nocr.TelegramClient.AppServices/Matches/Handlers/TextMatchMatchedHandler.cs
2024-03-30 12:08:54 +03:00

53 lines
2.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Insight.TelegramBot;
using Insight.TelegramBot.Models;
using Microsoft.Extensions.Logging;
using Nocr.TelegramClient.AppServices.Users;
using Nocr.TextMatcher.Api.Contracts.TextMatches;
using Nocr.TextMatcher.Async.Api.Contracts;
using Nocr.Users.Api.Contracts.Users;
using Rebus.Handlers;
using Telegram.Bot.Types.Enums;
namespace Nocr.TelegramClient.AppServices.Matches.Handlers;
public class TextMatchMatchedHandler : IHandleMessages<TextSubscriptionMatched>
{
private readonly ILogger<TextMatchMatchedHandler> _logger;
private readonly IBot _bot;
private readonly IUsersService _usersService;
public TextMatchMatchedHandler(ILogger<TextMatchMatchedHandler> logger, IBot bot, IUsersService usersService)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_bot = bot ?? throw new ArgumentNullException(nameof(bot));
_usersService = usersService ?? throw new ArgumentNullException(nameof(usersService));
}
public async Task Handle(TextSubscriptionMatched message)
{
var user = await _usersService.GetById(message.SubscriptionUserId);
if (user == null)
{
_logger.LogWarning("User [{UserId}] of [{MatchId}] from message {MessageId} not found", message.SubscriptionUserId,
message.SubscriptionId, message.Id);
return;
}
var identity = user.Identities.FirstOrDefault(x => x.Type == UserIdentityType.TelegramId);
if (identity == null)
{
_logger.LogWarning("There is no identity with type '{IdentityType}' for user '{UserId}'",
UserIdentityType.TelegramId, user.Id);
return;
}
var fromUsername = string.IsNullOrWhiteSpace(message.From) ? "anonymous" : message.From;
var textMessage = new TextMessage(long.Parse(identity.Identity))
{
Text = $"[{message.PublishedDateTime:MM.dd.yyyy HH:mm:ss}] Найдено совпадение.\nТип совпадения: <b>'{message.Rule.TextView()}'</b>\nШаблон: <b>'{message.Template}'</b>\n{fromUsername} в @{message.ChatUsername}: <i>{message.Text}</i>",
ParseMode = ParseMode.Html
};
await _bot.SendMessageAsync(textMessage);
}
}