Add telegram logging handler (#10)

Reviewed-on: #10
Co-authored-by: Sergey Nazarov <insight.appdev@gmail.com>
Co-committed-by: Sergey Nazarov <insight.appdev@gmail.com>
This commit is contained in:
Sergey Nazarov 2024-05-03 07:55:30 +00:00 committed by nazarovsa
parent b678675851
commit 03b6f52488
6 changed files with 106 additions and 1 deletions

View File

@ -0,0 +1,91 @@
using Insight.TelegramBot.Handling.Handlers;
using Insight.TelegramBot.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Nocr.TelegramClient.AppServices.Bots.MessageDispatcher;
using Nocr.TelegramClient.AppServices.Options;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
namespace Nocr.TelegramClient.AppServices.Handlers;
public sealed class UpdateTelegramLoggingHandler : IUpdateHandler
{
private readonly ILogger<UpdateTelegramLoggingHandler> _logger;
private readonly IMessageDispatcherQueue _messageDispatcherQueue;
private readonly AdministrationOptions _options;
public UpdateTelegramLoggingHandler(ILogger<UpdateTelegramLoggingHandler> logger,
IMessageDispatcherQueue messageDispatcherQueue,
IOptionsSnapshot<AdministrationOptions> options)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_messageDispatcherQueue =
messageDispatcherQueue ?? throw new ArgumentNullException(nameof(messageDispatcherQueue));
_options = options.Value ?? throw new ArgumentNullException(nameof(options));
}
public Task Handle(Update update, CancellationToken cancellationToken = default)
{
_logger.LogDebug("Received update:\n{@Update}", update);
if (_options.EnableUpdateTelegramLogging)
{
var from = GetFrom(update);
if (from == null)
{
_logger.LogWarning("Failed to extract `from` from update:\n{@Update}", update);
return Task.CompletedTask;
}
var text = GetText(update);
foreach (var updateReceiverId in _options.UpdateReceiverIds)
{
var message = new TextMessage(updateReceiverId)
{
Text = GetMessageText(from.Id, update.Type.ToString(), from.Username, text)
};
_messageDispatcherQueue.Enqueue(message);
}
}
return Task.CompletedTask;
}
private string? GetText(Update update)
{
switch (update.Type)
{
case UpdateType.Message:
return update.Message.Text;
case UpdateType.CallbackQuery:
return update.CallbackQuery.Data;
default:
return null;
}
}
private User? GetFrom(Update update)
{
switch (update.Type)
{
case UpdateType.Message:
return update.Message.From;
case UpdateType.CallbackQuery:
return update.CallbackQuery.From;
default:
return null;
}
}
private string GetMessageText(long fromId, string type, string? fromUsername = null, string? text = null)
{
if (!string.IsNullOrWhiteSpace(fromUsername))
{
fromUsername = "@" + fromUsername;
}
return $"#update\nПолучено обновление от {fromId} ({fromUsername})\nТип: {type}\nТекст/CallbackData: {text}";
}
}

View File

@ -11,4 +11,9 @@ public sealed class AdministrationOptions
/// Список telegram идентификаторов для получения обновлений /// Список telegram идентификаторов для получения обновлений
/// </summary> /// </summary>
public long[] UpdateReceiverIds { get; set; } = Array.Empty<long>(); public long[] UpdateReceiverIds { get; set; } = Array.Empty<long>();
/// <summary>
/// Пересылать ли тексты обновлений от пользователей в админ канал
/// </summary>
public bool EnableUpdateTelegramLogging { get; set; }
} }

View File

@ -1,7 +1,9 @@
using Insight.TelegramBot.Handling.Handlers;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Nocr.TelegramClient.AppServices.Bots.MessageDispatcher; using Nocr.TelegramClient.AppServices.Bots.MessageDispatcher;
using Nocr.TelegramClient.AppServices.Handlers;
using Nocr.TelegramClient.AppServices.Handlers.Messages.FeedbackMessage; using Nocr.TelegramClient.AppServices.Handlers.Messages.FeedbackMessage;
using Nocr.TelegramClient.AppServices.Options; using Nocr.TelegramClient.AppServices.Options;
using Nocr.TelegramClient.AppServices.TextSubscriptions.Handlers; using Nocr.TelegramClient.AppServices.TextSubscriptions.Handlers;
@ -25,6 +27,7 @@ public static class ServiceCollectionExtensions
services.AddHttpClient(); services.AddHttpClient();
services.Configure<AdministrationOptions>(configuration.GetSection(nameof(AdministrationOptions))); services.Configure<AdministrationOptions>(configuration.GetSection(nameof(AdministrationOptions)));
services.AddScoped<IUpdateHandler, UpdateTelegramLoggingHandler>();
services.Configure<UsersRestEaseOptions>(configuration.GetSection(nameof(UsersRestEaseOptions))); services.Configure<UsersRestEaseOptions>(configuration.GetSection(nameof(UsersRestEaseOptions)));
services.AddScoped<IUsersController>(ctx => services.AddScoped<IUsersController>(ctx =>

View File

@ -11,7 +11,7 @@ using Telegram.Bot.Types.Enums;
namespace Nocr.TelegramClient.AppServices.TextSubscriptions.Handlers; namespace Nocr.TelegramClient.AppServices.TextSubscriptions.Handlers;
public class TextSubscriptionMatchedHandler : IHandleMessages<TextMatcher.Async.Api.Contracts.TextSubscriptionMatched> public sealed class TextSubscriptionMatchedHandler : IHandleMessages<TextMatcher.Async.Api.Contracts.TextSubscriptionMatched>
{ {
private readonly ILogger<TextSubscriptionMatchedHandler> _logger; private readonly ILogger<TextSubscriptionMatchedHandler> _logger;
private readonly ILocalizer _localizer; private readonly ILocalizer _localizer;

View File

@ -17,5 +17,8 @@
}, },
"TextMatcherRestEaseOptions": { "TextMatcherRestEaseOptions": {
"BasePath": "http://localhost:5001" "BasePath": "http://localhost:5001"
},
"AdministrationOptions": {
"EnableUpdateTelegramLogging": true
} }
} }

View File

@ -33,5 +33,8 @@
}, },
"TelegramBotOptions": { "TelegramBotOptions": {
"Token": "" "Token": ""
},
"AdministrationOptions": {
"EnableUpdateTelegramLogging": true
} }
} }