* Improved filter fallback search logic

* Fixed Environment variable filter logic
* Changed some logs to trace level
* Added new Message extension methods
This commit is contained in:
2025-08-10 02:48:45 +04:00
parent 0cf8ea27b6
commit 3a88feb5f1
12 changed files with 158 additions and 73 deletions
@@ -33,7 +33,7 @@ namespace Telegrator.Hosting.Polling
/// <inheritdoc/> /// <inheritdoc/>
public override Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) public override Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{ {
Logger.LogInformation("Received update of type \"{type}\"", update.Type); //Logger.LogInformation("Received update of type \"{type}\"", update.Type);
return base.HandleUpdateAsync(botClient, update, cancellationToken); return base.HandleUpdateAsync(botClient, update, cancellationToken);
} }
+8
View File
@@ -20,6 +20,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Telegrator.Analyzers", "Tel
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Telegrator.Hosting.Web", "Telegrator.Hosting.Web\Telegrator.Hosting.Web.csproj", "{98AB490F-6A36-CCFF-F6E6-B029D1665965}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Telegrator.Hosting.Web", "Telegrator.Hosting.Web\Telegrator.Hosting.Web.csproj", "{98AB490F-6A36-CCFF-F6E6-B029D1665965}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SosalBot", "..\SosalBot\SosalBot\SosalBot.csproj", "{D6AA4D47-0DCE-520E-5779-A14EA9CB1DEC}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
AnalyzersDebug|Any CPU = AnalyzersDebug|Any CPU AnalyzersDebug|Any CPU = AnalyzersDebug|Any CPU
@@ -63,6 +65,12 @@ Global
{98AB490F-6A36-CCFF-F6E6-B029D1665965}.Debug|Any CPU.Build.0 = Debug|Any CPU {98AB490F-6A36-CCFF-F6E6-B029D1665965}.Debug|Any CPU.Build.0 = Debug|Any CPU
{98AB490F-6A36-CCFF-F6E6-B029D1665965}.Release|Any CPU.ActiveCfg = Release|Any CPU {98AB490F-6A36-CCFF-F6E6-B029D1665965}.Release|Any CPU.ActiveCfg = Release|Any CPU
{98AB490F-6A36-CCFF-F6E6-B029D1665965}.Release|Any CPU.Build.0 = Release|Any CPU {98AB490F-6A36-CCFF-F6E6-B029D1665965}.Release|Any CPU.Build.0 = Release|Any CPU
{D6AA4D47-0DCE-520E-5779-A14EA9CB1DEC}.AnalyzersDebug|Any CPU.ActiveCfg = Release|Any CPU
{D6AA4D47-0DCE-520E-5779-A14EA9CB1DEC}.AnalyzersDebug|Any CPU.Build.0 = Release|Any CPU
{D6AA4D47-0DCE-520E-5779-A14EA9CB1DEC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D6AA4D47-0DCE-520E-5779-A14EA9CB1DEC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D6AA4D47-0DCE-520E-5779-A14EA9CB1DEC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D6AA4D47-0DCE-520E-5779-A14EA9CB1DEC}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
+3 -1
View File
@@ -3,7 +3,9 @@
namespace Telegrator.Attributes namespace Telegrator.Attributes
{ {
/// <summary> /// <summary>
/// Attribute that says if this handler cn await some of await types, that is not listed by its handler base /// Attribute that says if this handler can await some of await types, that is not listed by its handler base.
/// Used for automatic collecting allowed to receiving <see cref="UpdateType"/>'s.
/// If you don't use it, you won't be able to await the updates inside handler.
/// </summary> /// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MightAwaitAttribute : Attribute public class MightAwaitAttribute : Attribute
@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Text;
using Telegram.Bot.Types;
using Telegrator.Filters.Components;
using Telegrator.Handlers;
namespace Telegrator.Filters
{
public class CommandArgumentFilter : Filter<Message>
{
public override bool CanPass(FilterExecutionContext<Message> context)
{
CommandHandlerAttribute attr = context.CompletedFilters.Get<CommandHandlerAttribute>(0);
string[] args = attr.Arguments ??= context.Input.SplitArgs();
return alliases.Contains(ReceivedCommand, StringComparer.InvariantCultureIgnoreCase);
}
}
}
+4 -4
View File
@@ -113,11 +113,11 @@ namespace Telegrator.Filters
{ {
string? envValue = Environment.GetEnvironmentVariable(_variable); string? envValue = Environment.GetEnvironmentVariable(_variable);
if (envValue == null && _value == null)
return true;
if (envValue == null) if (envValue == null)
return false; return _value == null;
if (_value == "{NOT_NULL}")
return true;
return envValue.Equals(_value, _comparison); return envValue.Equals(_value, _comparison);
} }
+2
View File
@@ -16,6 +16,8 @@ namespace Telegrator.Handlers
/// </summary> /// </summary>
public string ReceivedCommand { get; private set; } = null!; public string ReceivedCommand { get; private set; } = null!;
public string[]? Arguments { get; internal set; } = null;
/// <summary> /// <summary>
/// Checks if the update contains a valid bot command and extracts the command text. /// Checks if the update contains a valid bot command and extracts the command text.
/// </summary> /// </summary>
@@ -1,5 +1,4 @@
using Telegram.Bot; using Telegram.Bot.Types;
using Telegram.Bot.Types;
using Telegrator.Attributes.Components; using Telegrator.Attributes.Components;
using Telegrator.Filters.Components; using Telegrator.Filters.Components;
using Telegrator.MadiatorCore.Descriptors; using Telegrator.MadiatorCore.Descriptors;
@@ -39,23 +38,6 @@ namespace Telegrator.Handlers.Components
/// </summary> /// </summary>
public List<FilterFallbackInfo> UpdateFilters { get; } = []; public List<FilterFallbackInfo> UpdateFilters { get; } = [];
/*
public FilterFallbackInfo OfType<T>(int index = 0) where T : IFilter<Update>
{
return UpdateFilters.Where(info => info.Failed is T).ElementAt(index);
}
public FilterFallbackInfo OfAttribute<T>(int index = 0) where T : UpdateFilterAttributeBase
{
return UpdateFilters.Where(info => info.Name == typeof(T).Name).ElementAt(index);
}
public FilterFallbackInfo OfName(string name, int index = 0)
{
return UpdateFilters.Where(info => info.Name == name).ElementAt(index);
}
*/
/// <summary> /// <summary>
/// Checks if the failure is due to a specific attribute type, excluding other failures. /// Checks if the failure is due to a specific attribute type, excluding other failures.
/// </summary> /// </summary>
@@ -65,11 +47,17 @@ namespace Telegrator.Handlers.Components
public bool ExceptAttribute<T>(int index = 0) where T : UpdateFilterAttributeBase public bool ExceptAttribute<T>(int index = 0) where T : UpdateFilterAttributeBase
{ {
string name = typeof(T).Name; string name = typeof(T).Name;
IEnumerable<FilterFallbackInfo> failed = UpdateFilters.Where(info => info.Failed); IEnumerable<FilterFallbackInfo> failed = UpdateFilters.Where(info => info.Failed);
if (failed.Count() > 1) if (failed.Count() != 1)
return false; return false;
return failed.SingleOrDefault()?.Name == name; FilterFallbackInfo info = failed.ElementAt(0);
if (info.Name != name)
return false;
FilterFallbackInfo? target = UpdateFilters.ElementAtOrDefault(index);
return target == info;
} }
} }
+21
View File
@@ -105,6 +105,16 @@ namespace Telegrator.Logging
Log(LogLevel.Trace, message); Log(LogLevel.Trace, message);
} }
/// <summary>
/// Logs a trace message to all registered adapters.
/// </summary>
/// <param name="message">The message to log.</param>
/// <param name="args"></param>
public static void LogTrace(string message, params object[] args)
{
Log(LogLevel.Trace, string.Format(message, args));
}
/// <summary> /// <summary>
/// Logs a debug message to all registered adapters. /// Logs a debug message to all registered adapters.
/// </summary> /// </summary>
@@ -190,5 +200,16 @@ namespace Telegrator.Logging
{ {
Log(LogLevel.Error, exception.Message, exception); Log(LogLevel.Error, exception.Message, exception);
} }
/// <summary>
/// Logs an error message to all registered adapters.
/// </summary>
/// <param name="message">The message to log.</param>
/// <param name="exception">Optional exception.</param>
/// <param name="args"></param>
public static void LogError(string message, Exception? exception = null, params object[] args)
{
Log(LogLevel.Error, string.Format(message, args), exception);
}
} }
} }
+3 -11
View File
@@ -77,7 +77,7 @@ namespace Telegrator.Polling
try try
{ {
Alligator.LogDebug("Described handler '{0}'", handlerInfo.DisplayString); Alligator.LogDebug("Described handler '{0}' (Update {1})", handlerInfo.DisplayString, handlerInfo.HandlingUpdate.Id);
HandlerExecuting?.Invoke(handlerInfo); HandlerExecuting?.Invoke(handlerInfo);
using (UpdateHandlerBase instance = handlerInfo.HandlerInstance) using (UpdateHandlerBase instance = handlerInfo.HandlerInstance)
@@ -88,7 +88,7 @@ namespace Telegrator.Polling
if (lastResult.RouteNext) if (lastResult.RouteNext)
{ {
Alligator.LogDebug("Handler requested route continuation"); Alligator.LogTrace("Handler '{0}' requested route continuation (Update {1})", handlerInfo.DisplayString, handlerInfo.HandlingUpdate.Id);
} }
} }
catch (NotImplementedException) catch (NotImplementedException)
@@ -102,7 +102,7 @@ namespace Telegrator.Polling
} }
catch (Exception ex) catch (Exception ex)
{ {
Alligator.LogError("Failed to process handler!", ex); Alligator.LogError("Failed to process handler '{0}' (Update {1})", exception: ex, handlerInfo.DisplayString, handlerInfo.HandlingUpdate.Id);
} }
if (lastResult != null && !lastResult.RouteNext) if (lastResult != null && !lastResult.RouteNext)
@@ -124,14 +124,6 @@ namespace Telegrator.Polling
ExecutingHandlersSemaphore = null!; ExecutingHandlersSemaphore = null!;
} }
/*
if (AwaitingHandlersQueuedEvent != null)
{
AwaitingHandlersQueuedEvent.Dispose();
AwaitingHandlersQueuedEvent = null!;
}
*/
if (SyncObj != null) if (SyncObj != null)
SyncObj = null!; SyncObj = null!;
+29 -30
View File
@@ -100,7 +100,6 @@ namespace Telegrator.Polling
public virtual async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) public virtual async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{ {
// Logging // Logging
Alligator.LogDebug("Received Update ({0}) of type \"{1}\"", update.Id, update.Type);
LogUpdate(update); LogUpdate(update);
try try
@@ -115,18 +114,18 @@ namespace Telegrator.Polling
// Chicking if awaiting handlers has exclusive routing // Chicking if awaiting handlers has exclusive routing
if (Options.ExclusiveAwaitingHandlerRouting) if (Options.ExclusiveAwaitingHandlerRouting)
{ {
Alligator.LogDebug("Receiving Update ({0}) completed with only awaiting handlers", update.Id); Alligator.LogTrace("Receiving Update ({0}) completed with only awaiting handlers", update.Id);
return; return;
} }
} }
// Queuing reagular handlers for execution // Queuing reagular handlers for execution
await HandlersPool.Enqueue(GetHandlers(HandlersProvider, botClient, update, cancellationToken)); await HandlersPool.Enqueue(GetHandlers(HandlersProvider, botClient, update, cancellationToken));
Alligator.LogDebug("Receiving Update ({0}) finished", update.Id); Alligator.LogTrace("Receiving Update ({0}) finished", update.Id);
} }
catch (OperationCanceledException) catch (OperationCanceledException)
{ {
Alligator.LogDebug("Receiving Update ({0}) cancelled", update.Id); Alligator.LogTrace("Receiving Update ({0}) cancelled", update.Id);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -146,16 +145,16 @@ namespace Telegrator.Polling
/// <returns>A collection of described handler information for the update</returns> /// <returns>A collection of described handler information for the update</returns>
protected virtual IEnumerable<DescribedHandlerInfo> GetHandlers(IHandlersProvider provider, ITelegramBotClient client, Update update, CancellationToken cancellationToken = default) protected virtual IEnumerable<DescribedHandlerInfo> GetHandlers(IHandlersProvider provider, ITelegramBotClient client, Update update, CancellationToken cancellationToken = default)
{ {
Alligator.LogDebug("Requested handlers for UpdateType.{0}", update.Type); Alligator.LogTrace("Requested handlers for UpdateType.{0}", update.Type);
if (!provider.TryGetDescriptorList(update.Type, out HandlerDescriptorList? descriptors)) if (!provider.TryGetDescriptorList(update.Type, out HandlerDescriptorList? descriptors))
{ {
Alligator.LogDebug("No registered, providing Any"); Alligator.LogTrace("No registered, providing Any");
provider.TryGetDescriptorList(UpdateType.Unknown, out descriptors); provider.TryGetDescriptorList(UpdateType.Unknown, out descriptors);
} }
if (descriptors == null || descriptors.Count == 0) if (descriptors == null || descriptors.Count == 0)
{ {
Alligator.LogDebug("No handlers provided"); Alligator.LogTrace("No handlers provided");
return []; return [];
} }
@@ -178,7 +177,7 @@ namespace Telegrator.Polling
/// <returns>A collection of described handler information</returns> /// <returns>A collection of described handler information</returns>
protected virtual IEnumerable<DescribedHandlerInfo> DescribeDescriptors(IHandlersProvider provider, HandlerDescriptorList descriptors, ITelegramBotClient client, Update update, CancellationToken cancellationToken = default) protected virtual IEnumerable<DescribedHandlerInfo> DescribeDescriptors(IHandlersProvider provider, HandlerDescriptorList descriptors, ITelegramBotClient client, Update update, CancellationToken cancellationToken = default)
{ {
Alligator.LogDebug("Describing descriptors of descriptorsList.HandlingType.{0} for Update ({1})", descriptors.HandlingType, update.Id); Alligator.LogTrace("Describing descriptors of descriptorsList.HandlingType.{0} for Update ({1})", descriptors.HandlingType, update.Id);
foreach (HandlerDescriptor descriptor in descriptors.Reverse()) foreach (HandlerDescriptor descriptor in descriptors.Reverse())
{ {
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
@@ -192,7 +191,7 @@ namespace Telegrator.Polling
yield return describedHandler; yield return describedHandler;
} }
Alligator.LogDebug("Describing for Update ({0}) finished", update.Id); Alligator.LogTrace("Describing for Update ({0}) finished", update.Id);
} }
/// <summary> /// <summary>
@@ -245,41 +244,41 @@ namespace Telegrator.Polling
/// <exception cref="NullReferenceException"></exception> /// <exception cref="NullReferenceException"></exception>
protected static void LogUpdate(Update update) protected static void LogUpdate(Update update)
{ {
switch (update.Type) if (Alligator.MinimalLevel > LogLevel.Trace)
return;
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Received Update ({0}) of type \"{1}\"", update.Id, update.Type);
switch (update)
{ {
case UpdateType.Message: case { Message: { } message }:
{ {
Message msg = update.Message ?? throw new NullReferenceException(); if (message is { From: { } from })
StringBuilder sb = new StringBuilder("Update.Message"); sb.AppendFormat(" from '{0}' ({1})", from.Username, from.Id);
if (msg.From != null) if (message is { Text: { } text })
sb.AppendFormat(" from {0} ({1})", msg.From.Username, msg.From.Id); sb.AppendFormat(" with text '{0}'", text);
if (msg.Text != null) if (message is { Sticker: { } sticker })
sb.AppendFormat(" with text '{0}'", msg.Text); sb.AppendFormat(" with sticker '{0}'", sticker.Emoji);
if (msg.Sticker != null)
sb.AppendFormat(" with sticker '{0}'", msg.Sticker.Emoji);
Alligator.LogDebug(sb.ToString());
break; break;
} }
case UpdateType.CallbackQuery: case { CallbackQuery: { } callback }:
{ {
CallbackQuery cq = update.CallbackQuery ?? throw new NullReferenceException(); if (callback is { From: { } from })
StringBuilder sb = new StringBuilder("Update.CallbackQuery"); sb.AppendFormat(" from '{0}' ({1})", from.Username, from.Id);
if (cq.From != null) if (callback is { Data: { } data })
sb.AppendFormat(" from {0} ({1})", cq.From.Username, cq.From.Id); sb.AppendFormat(" with data '{0}'", data);
if (cq.From != null)
sb.AppendFormat(" with data '{0}'", cq.Data);
Alligator.LogDebug(sb.ToString());
break; break;
} }
} }
Alligator.LogTrace(sb.ToString());
} }
private class BreakDescribingException : Exception { } private class BreakDescribingException : Exception { }
+8 -5
View File
@@ -1,5 +1,4 @@
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Runtime.CompilerServices;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.Enums;
using Telegrator.Handlers.Components; using Telegrator.Handlers.Components;
@@ -41,7 +40,7 @@ namespace Telegrator.Providers
AllowedTypes = handlers.AllowedTypes; AllowedTypes = handlers.AllowedTypes;
HandlersDictionary = handlers.Values.ForEach(list => list.Freeze()).ToReadOnlyDictionary(list => list.HandlingType); HandlersDictionary = handlers.Values.ForEach(list => list.Freeze()).ToReadOnlyDictionary(list => list.HandlingType);
Options = options ?? throw new ArgumentNullException(nameof(options)); Options = options ?? throw new ArgumentNullException(nameof(options));
Alligator.LogDebug("{0} created!", GetType().Name); Alligator.LogTrace("{0} created!", GetType().Name);
} }
/// <summary> /// <summary>
@@ -55,7 +54,7 @@ namespace Telegrator.Providers
AllowedTypes = Update.AllTypes; AllowedTypes = Update.AllTypes;
HandlersDictionary = handlers.ForEach(list => list.Freeze()).ToReadOnlyDictionary(list => list.HandlingType); HandlersDictionary = handlers.ForEach(list => list.Freeze()).ToReadOnlyDictionary(list => list.HandlingType);
Options = options ?? throw new ArgumentNullException(nameof(options)); Options = options ?? throw new ArgumentNullException(nameof(options));
Alligator.LogDebug("{0} created!", GetType().Name); Alligator.LogTrace("{0} created!", GetType().Name);
} }
/// <inheritdoc/> /// <inheritdoc/>
@@ -64,22 +63,26 @@ namespace Telegrator.Providers
{ {
try try
{ {
// Checking handler instance status
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
bool useSingleton = UseSingleton(descriptor); bool useSingleton = UseSingleton(descriptor);
// Returning singleton instance
if (useSingleton && descriptor.SingletonInstance != null) if (useSingleton && descriptor.SingletonInstance != null)
return descriptor.SingletonInstance; return descriptor.SingletonInstance;
// Creating instance
UpdateHandlerBase instance = GetHandlerInstanceInternal(descriptor); UpdateHandlerBase instance = GetHandlerInstanceInternal(descriptor);
if (useSingleton) if (useSingleton)
descriptor.TrySetInstance(instance); descriptor.TrySetInstance(instance);
// Lazy initialization execution
descriptor.LazyInitialization?.Invoke(instance); descriptor.LazyInitialization?.Invoke(instance);
return instance; return instance;
} }
catch catch (Exception ex)
{ {
Alligator.LogDebug("Failed to create instance of {0}", descriptor.ToString()); Alligator.LogError("Failed to create instance of '{0}'", exception: ex, descriptor.ToString());
throw; throw;
} }
} }
+50
View File
@@ -41,6 +41,56 @@ namespace Telegrator
return message.Text.Substring(entity.Offset, entity.Length); return message.Text.Substring(entity.Offset, entity.Length);
} }
public static bool IsCommand(this Message message, out string? command)
{
command = null;
if (message is not { Entities.Length: > 0, Text.Length: > 0 })
return false;
MessageEntity commandEntity = message.Entities[0];
if (commandEntity.Type != MessageEntityType.BotCommand)
return false;
command = message.Text.Substring(commandEntity.Offset + 1, commandEntity.Length - 1);
if (command.Contains('@'))
{
string[] split = command.Split('@');
command = split[0];
}
return true;
}
public static string[] SplitArgs(this Message message)
{
if (!message.IsCommand(out string? command))
throw new InvalidDataException("Message does not contain a command");
if (message is not { Text.Length: > 0 })
throw new ArgumentNullException("Command text cannot be null or empty");
if (!message.Text.Contains(' '))
throw new MissingMemberException("Command dont contains arguments");
return message.Text.Split([' '], StringSplitOptions.RemoveEmptyEntries).Skip(1).ToArray();
}
public static bool TrySplitArgs(this Message message, out string[]? args)
{
args = null;
if (!message.IsCommand(out string? command))
return false;
if (message is not { Text.Length: > 0 })
return false;
if (!message.Text.Contains(' '))
return false;
args = message.Text.Split([' '], StringSplitOptions.RemoveEmptyEntries).Skip(1).ToArray();
return true;
}
} }
/// <summary> /// <summary>