4 Commits

Author SHA1 Message Date
Rikitav 3d2d21f6c0 * Added building delegate to UseTelegrator method
* Fixed Webhooker trying to resolve IEndpointRouteBuildr from DI
2026-03-15 17:20:53 +04:00
Rikitav 0dedd3c0f4 * warnings fixes 2026-03-09 13:40:58 +04:00
Rikitav 79d5df8291 * Syntaxual refactoring 2026-03-09 13:23:21 +04:00
Rikitav 899243c62b * Added default state storage registering
* Added extension method for replacing default state storage
2026-03-09 13:10:49 +04:00
146 changed files with 9860 additions and 9893 deletions
@@ -148,6 +148,7 @@ public class ImplicitHandlerBuilderExtensionsGenerator : IIncrementalGenerator
.AddMembers([.. targetters.Values, .. extensions]);
NamespaceDeclarationSyntax namespaceDeclaration = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName("Telegrator"))
.WithLeadingTrivia(SyntaxFactory.ParseLeadingTrivia("#pragma warning disable CS1591"))
.WithMembers([extensionsClass]);
CompilationUnitSyntax compilationUnit = SyntaxFactory.CompilationUnit()
+22 -3
View File
@@ -28,6 +28,9 @@
This application's logger
</summary>
</member>
<member name="P:Telegrator.Hosting.Web.TelegramBotWebHost.Properties">
<inheritdoc/>
</member>
<member name="M:Telegrator.Hosting.Web.TelegramBotWebHost.#ctor(Microsoft.AspNetCore.Builder.WebApplicationBuilder)">
<summary>
Initializes a new instance of the <see cref="T:Microsoft.AspNetCore.Builder.WebApplicationBuilder"/> class.
@@ -181,7 +184,7 @@
Service for receiving updates for Hosted telegram bots via Webhooks
</summary>
</member>
<member name="M:Telegrator.Mediation.HostedUpdateWebhooker.#ctor(Microsoft.AspNetCore.Routing.IEndpointRouteBuilder,Telegram.Bot.ITelegramBotClient,Telegrator.Core.IUpdateRouter,Microsoft.Extensions.Options.IOptions{Telegrator.Hosting.Web.WebhookerOptions})">
<member name="M:Telegrator.Mediation.HostedUpdateWebhooker.#ctor(Telegram.Bot.ITelegramBotClient,Telegrator.Core.IUpdateRouter,Microsoft.Extensions.Options.IOptions{Telegrator.Hosting.Web.WebhookerOptions})">
<summary>
Initiallizes new instance of <see cref="T:Telegrator.Mediation.HostedUpdateWebhooker"/>
</summary>
@@ -197,6 +200,12 @@
<member name="M:Telegrator.Mediation.HostedUpdateWebhooker.StopAsync(System.Threading.CancellationToken)">
<inheritdoc/>
</member>
<member name="M:Telegrator.Mediation.HostedUpdateWebhooker.MapWebhook(Microsoft.AspNetCore.Routing.IEndpointRouteBuilder)">
<summary>
Maps bot webhook to application builder
</summary>
<param name="routeBuilder"></param>
</member>
<member name="T:Telegrator.ServicesCollectionExtensions">
<summary>
Contains extensions for <see cref="T:Microsoft.Extensions.DependencyInjection.IServiceCollection"/>
@@ -211,12 +220,22 @@
<member name="M:Telegrator.ServicesCollectionExtensions.get_Handlers(Microsoft.AspNetCore.Builder.WebApplicationBuilder)">
<inheritdoc cref="P:Telegrator.ServicesCollectionExtensions.&lt;G&gt;$41F16C2D39AF52899E745C9C9F42FF83.Handlers"/>
</member>
<member name="M:Telegrator.ServicesCollectionExtensions.AddTelegratorWeb(Microsoft.Extensions.Hosting.IHostApplicationBuilder,Telegrator.TelegratorOptions,Telegrator.Core.IHandlersCollection)">
<member name="M:Telegrator.ServicesCollectionExtensions.AddTelegratorWeb(Telegrator.Hosting.ITelegramBotHostBuilder,Telegrator.TelegratorOptions,Telegrator.Core.IHandlersCollection,System.Action{Telegrator.Hosting.ITelegramBotHostBuilder})">
<summary>
Replaces TelegramBotWebHostBuilder. Configures DI, options, and handlers.
</summary>
</member>
<member name="M:Telegrator.ServicesCollectionExtensions.UseTelegratorWeb(Microsoft.AspNetCore.Builder.WebApplication)">
<member name="M:Telegrator.ServicesCollectionExtensions.AddTelegratorWeb(Microsoft.AspNetCore.Builder.WebApplicationBuilder,Telegrator.TelegratorOptions,Telegrator.Core.IHandlersCollection,System.Action{Telegrator.Hosting.ITelegramBotHostBuilder})">
<summary>
Replaces TelegramBotWebHostBuilder. Configures DI, options, and handlers.
</summary>
</member>
<member name="M:Telegrator.ServicesCollectionExtensions.AddTelegratorWebInternal(Microsoft.Extensions.Hosting.IHostApplicationBuilder,Telegrator.TelegratorOptions,Telegrator.Core.IHandlersCollection)">
<summary>
Replaces TelegramBotWebHostBuilder. Configures DI, options, and handlers.
</summary>
</member>
<member name="M:Telegrator.ServicesCollectionExtensions.UseTelegratorWeb``1(``0)">
<summary>
Replaces the initialization logic from TelegramBotWebHost constructor.
Initializes the bot and logs handlers on application startup.
+25 -7
View File
@@ -221,7 +221,7 @@
<member name="T:Telegrator.Providers.HostAwaitingProvider">
<inheritdoc/>
</member>
<member name="M:Telegrator.Providers.HostAwaitingProvider.#ctor(Microsoft.Extensions.Options.IOptions{Telegrator.TelegratorOptions},Microsoft.Extensions.Logging.ILogger{Telegrator.Providers.HostAwaitingProvider})">
<member name="M:Telegrator.Providers.HostAwaitingProvider.#ctor(Microsoft.Extensions.Options.IOptions{Telegrator.TelegratorOptions})">
<inheritdoc/>
</member>
<member name="T:Telegrator.Providers.HostHandlersCollection">
@@ -239,7 +239,7 @@
<member name="T:Telegrator.Providers.HostHandlersProvider">
<inheritdoc/>
</member>
<member name="M:Telegrator.Providers.HostHandlersProvider.#ctor(Telegrator.Core.IHandlersCollection,Microsoft.Extensions.Options.IOptions{Telegrator.TelegratorOptions},System.IServiceProvider,Microsoft.Extensions.Logging.ILogger{Telegrator.Providers.HostHandlersProvider})">
<member name="M:Telegrator.Providers.HostHandlersProvider.#ctor(Telegrator.Core.IHandlersCollection,Microsoft.Extensions.Options.IOptions{Telegrator.TelegratorOptions},System.IServiceProvider)">
<inheritdoc/>
</member>
<member name="M:Telegrator.Providers.HostHandlersProvider.GetHandlerInstance(Telegrator.Core.Descriptors.HandlerDescriptor,System.Threading.CancellationToken)">
@@ -255,15 +255,25 @@
The key used to store the <see cref="T:Telegrator.Core.IHandlersCollection"/> in the builder properties.
</summary>
</member>
<member name="M:Telegrator.HostBuilderExtensions.get_Handlers(Microsoft.Extensions.Hosting.IHostApplicationBuilder)">
<inheritdoc cref="P:Telegrator.HostBuilderExtensions.&lt;G&gt;$605D8CCF64349EA050C790D67C500BD9.Handlers"/>
<member name="M:Telegrator.HostBuilderExtensions.get_Handlers(Microsoft.Extensions.Hosting.HostApplicationBuilder)">
<inheritdoc cref="P:Telegrator.HostBuilderExtensions.&lt;G&gt;$BF7227490CCA365283B3A9274C9033C7.Handlers"/>
</member>
<member name="M:Telegrator.HostBuilderExtensions.AddTelegrator(Microsoft.Extensions.Hosting.IHostApplicationBuilder,Telegrator.TelegratorOptions,Telegrator.Core.IHandlersCollection)">
<member name="M:Telegrator.HostBuilderExtensions.AddTelegrator(Telegrator.Hosting.ITelegramBotHostBuilder,Telegrator.TelegratorOptions,Telegrator.Core.IHandlersCollection,System.Action{Telegrator.Hosting.ITelegramBotHostBuilder})">
<summary>
Replaces TelegramBotWebHostBuilder. Configures DI, options, and handlers.
Replaces TelegramBotHostBuilder. Configures DI, options, and handlers.
</summary>
</member>
<member name="P:Telegrator.HostBuilderExtensions.&lt;G&gt;$605D8CCF64349EA050C790D67C500BD9.Handlers">
<member name="M:Telegrator.HostBuilderExtensions.AddTelegrator(Microsoft.Extensions.Hosting.HostApplicationBuilder,Telegrator.TelegratorOptions,Telegrator.Core.IHandlersCollection,System.Action{Telegrator.Hosting.ITelegramBotHostBuilder})">
<summary>
Replaces TelegramBotHostBuilder. Configures DI, options, and handlers.
</summary>
</member>
<member name="M:Telegrator.HostBuilderExtensions.AddTelegratorInternal(Microsoft.Extensions.Hosting.IHostApplicationBuilder,Telegrator.TelegratorOptions,Telegrator.Core.IHandlersCollection)">
<summary>
Replaces TelegramBotHostBuilder. Configures DI, options, and handlers.
</summary>
</member>
<member name="P:Telegrator.HostBuilderExtensions.&lt;G&gt;$BF7227490CCA365283B3A9274C9033C7.Handlers">
<summary>
Gets the <see cref="T:Telegrator.Core.IHandlersCollection"/> from the builder properties.
</summary>
@@ -274,6 +284,14 @@
Provides method to configure Telegram Bot Host
</summary>
</member>
<member name="M:Telegrator.ServicesCollectionExtensions.AddStateStorage``1(Microsoft.Extensions.DependencyInjection.IServiceCollection)">
<summary>
Registers <see cref="T:Telegrator.Core.States.IStateStorage"/> service
</summary>
<typeparam name="TStorage"></typeparam>
<param name="services"></param>
<returns></returns>
</member>
<member name="M:Telegrator.ServicesCollectionExtensions.AddTelegramBotHostDefaults(Microsoft.Extensions.DependencyInjection.IServiceCollection)">
<summary>
Registers <see cref="T:Telegrator.Hosting.TelegramBotHost"/> default services
+5
View File
@@ -7161,6 +7161,11 @@
Provides extension methods for working with Telegram Update objects.
</summary>
</member>
<member name="M:Telegrator.UpdateExtensions.GetUserLanguageCode(Telegram.Bot.Types.Update)">
<summary>
Extracts the IETF language tag of the user's client from the update.
</summary>
</member>
<member name="M:Telegrator.UpdateExtensions.GetSenderId(Telegram.Bot.Types.Update)">
<summary>
Selects from Update an object from which you can get the sender's ID
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<TargetFramework>netstandard2.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
@@ -15,7 +15,7 @@
<EnforceCodeStyleInBuild>True</EnforceCodeStyleInBuild>
<Title>Telegrator.RedisStateStorage</Title>
<Version>1.16.4</Version>
<Version>1.16.6</Version>
<Authors>Rikitav Tim4ik</Authors>
<Company>Rikitav Tim4ik</Company>
<RepositoryUrl>https://github.com/Rikitav/Telegrator</RepositoryUrl>
@@ -31,7 +31,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="StackExchange.Redis" Version="2.11.8 " />
<PackageReference Include="StackExchange.Redis" Version="2.11.8" />
</ItemGroup>
<ItemGroup>
@@ -9,3 +9,4 @@ using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Style", "IDE0090")]
[assembly: SuppressMessage("Usage", "CA2254")]
[assembly: SuppressMessage("Maintainability", "CA1510")]
[assembly: SuppressMessage("Style", "IDE0270")]
@@ -7,13 +7,13 @@ using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Telegrator.Core;
namespace Telegrator.Hosting.Web
namespace Telegrator.Hosting.Web;
/// <summary>
/// Represents a web hosted telegram bot
/// </summary>
public class TelegramBotWebHost : IHost, IApplicationBuilder, IEndpointRouteBuilder, IAsyncDisposable
{
/// <summary>
/// Represents a web hosted telegram bot
/// </summary>
public class TelegramBotWebHost : IHost, IApplicationBuilder, IEndpointRouteBuilder, IAsyncDisposable
{
private readonly WebApplication _innerApp;
private readonly IUpdateRouter _updateRouter;
private readonly ILogger<TelegramBotWebHost> _logger;
@@ -39,11 +39,13 @@ namespace Telegrator.Hosting.Web
/// </summary>
public ILogger<TelegramBotWebHost> Logger => _logger;
/// <inheritdoc/>
public IDictionary<string, object?> Properties => ((IApplicationBuilder)_innerApp).Properties;
// Private interface fields
IServiceProvider IEndpointRouteBuilder.ServiceProvider => Services;
IServiceProvider IApplicationBuilder.ApplicationServices { get => Services; set => throw new NotImplementedException(); }
IFeatureCollection IApplicationBuilder.ServerFeatures => ((IApplicationBuilder)_innerApp).ServerFeatures;
IDictionary<string, object?> IApplicationBuilder.Properties => ((IApplicationBuilder)_innerApp).Properties;
/// <summary>
/// Initializes a new instance of the <see cref="WebApplicationBuilder"/> class.
@@ -68,9 +70,7 @@ namespace Telegrator.Hosting.Web
ArgumentNullException.ThrowIfNull(settings, nameof(settings));
WebApplicationBuilder innerApp = WebApplication.CreateBuilder(settings);
TelegramBotWebHostBuilder builder = new TelegramBotWebHostBuilder(innerApp, settings);
builder.Services.AddTelegramBotHostDefaults();
builder.Services.AddTelegramWebhook();
builder.AddTelegratorWeb();
return builder;
}
@@ -83,9 +83,7 @@ namespace Telegrator.Hosting.Web
ArgumentNullException.ThrowIfNull(settings, nameof(settings));
WebApplicationBuilder innerApp = WebApplication.CreateSlimBuilder(settings);
TelegramBotWebHostBuilder builder = new TelegramBotWebHostBuilder(innerApp, settings);
builder.Services.AddTelegramBotHostDefaults();
builder.Services.AddTelegramWebhook();
builder.AddTelegratorWeb();
return builder;
}
@@ -97,7 +95,9 @@ namespace Telegrator.Hosting.Web
{
ArgumentNullException.ThrowIfNull(settings, nameof(settings));
WebApplicationBuilder innerApp = WebApplication.CreateEmptyBuilder(settings);
return new TelegramBotWebHostBuilder(innerApp, settings);
TelegramBotWebHostBuilder builder = new TelegramBotWebHostBuilder(innerApp, settings);
builder.AddTelegratorWeb();
return builder;
}
/// <inheritdoc/>
@@ -156,5 +156,4 @@ namespace Telegrator.Hosting.Web
GC.SuppressFinalize(this);
_disposed = true;
}
}
}
@@ -7,13 +7,13 @@ using Microsoft.Extensions.Logging;
using Telegrator.Core;
#pragma warning disable IDE0001
namespace Telegrator.Hosting.Web
namespace Telegrator.Hosting.Web;
/// <summary>
/// Represents a web hosted telegram bots and services builder that helps manage configuration, logging, lifetime, and more.
/// </summary>
public class TelegramBotWebHostBuilder : ITelegramBotHostBuilder
{
/// <summary>
/// Represents a web hosted telegram bots and services builder that helps manage configuration, logging, lifetime, and more.
/// </summary>
public class TelegramBotWebHostBuilder : IHostApplicationBuilder, ICollectingProvider
{
private readonly WebApplicationBuilder _innerBuilder;
private readonly WebApplicationOptions _settings;
internal IHandlersCollection _handlers = null!;
@@ -48,8 +48,6 @@ namespace Telegrator.Hosting.Web
{
_innerBuilder = webApplicationBuilder ?? throw new ArgumentNullException(nameof(webApplicationBuilder));
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
this.AddTelegratorWeb();
}
/// <summary>
@@ -62,8 +60,6 @@ namespace Telegrator.Hosting.Web
{
_innerBuilder = webApplicationBuilder ?? throw new ArgumentNullException(nameof(webApplicationBuilder));
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
this.AddTelegratorWeb(options, null);
}
/// <summary>
@@ -76,8 +72,6 @@ namespace Telegrator.Hosting.Web
{
_innerBuilder = webApplicationBuilder ?? throw new ArgumentNullException(nameof(webApplicationBuilder));
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
this.AddTelegratorWeb(null, handlers);
}
/// <summary>
@@ -91,8 +85,6 @@ namespace Telegrator.Hosting.Web
{
_innerBuilder = webApplicationBuilder ?? throw new ArgumentNullException(nameof(webApplicationBuilder));
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
this.AddTelegratorWeb(options, handlers);
}
/// <summary>
@@ -111,5 +103,4 @@ namespace Telegrator.Hosting.Web
{
((IHostApplicationBuilder)_innerBuilder).ConfigureContainer(factory, configure);
}
}
}
@@ -1,13 +1,13 @@
using System.Diagnostics.CodeAnalysis;
namespace Telegrator.Hosting.Web
namespace Telegrator.Hosting.Web;
/// <summary>
/// Configuration options for Telegram bot behavior and execution settings.
/// Controls various aspects of bot operation including concurrency, routing, webhook receiving, and execution policies.
/// </summary>
public class WebhookerOptions
{
/// <summary>
/// Configuration options for Telegram bot behavior and execution settings.
/// Controls various aspects of bot operation including concurrency, routing, webhook receiving, and execution policies.
/// </summary>
public class WebhookerOptions
{
/// <summary>
/// Gets or sets HTTPS URL to send updates to. Use an empty string to remove webhook integration
/// </summary>
@@ -31,5 +31,4 @@ namespace Telegrator.Hosting.Web
/// Pass true to drop all pending updates
/// </summary>
public bool DropPendingUpdates { get; set; } = false;
}
}
@@ -10,16 +10,15 @@ using Telegram.Bot.Types;
using Telegrator.Core;
using Telegrator.Hosting.Web;
namespace Telegrator.Mediation
namespace Telegrator.Mediation;
/// <summary>
/// Service for receiving updates for Hosted telegram bots via Webhooks
/// </summary>
public class HostedUpdateWebhooker : IHostedService
{
/// <summary>
/// Service for receiving updates for Hosted telegram bots via Webhooks
/// </summary>
public class HostedUpdateWebhooker : IHostedService
{
private const string SecretTokenHeader = "X-Telegram-Bot-Api-Secret-Token";
private readonly IEndpointRouteBuilder _botHost;
private readonly ITelegramBotClient _botClient;
private readonly IUpdateRouter _updateRouter;
private readonly WebhookerOptions _options;
@@ -32,12 +31,11 @@ namespace Telegrator.Mediation
/// <param name="updateRouter"></param>
/// <param name="options"></param>
/// <exception cref="ArgumentNullException"></exception>
public HostedUpdateWebhooker(IEndpointRouteBuilder botHost, ITelegramBotClient botClient, IUpdateRouter updateRouter, IOptions<WebhookerOptions> options)
public HostedUpdateWebhooker(ITelegramBotClient botClient, IUpdateRouter updateRouter, IOptions<WebhookerOptions> options)
{
if (string.IsNullOrEmpty(options.Value.WebhookUri))
throw new ArgumentNullException(nameof(options), "Option \"WebhookUrl\" must be set to subscribe for update recieving");
_botHost = botHost;
_botClient = botClient;
_updateRouter = updateRouter;
_options = options.Value;
@@ -52,9 +50,6 @@ namespace Telegrator.Mediation
private async void StartInternal(CancellationToken cancellationToken)
{
string pattern = new UriBuilder(_options.WebhookUri).Path;
_botHost.MapPost(pattern, (Delegate)ReceiveUpdate);
await _botClient.SetWebhook(
url: _options.WebhookUri,
maxConnections: _options.MaxConnections,
@@ -71,6 +66,16 @@ namespace Telegrator.Mediation
return Task.CompletedTask;
}
/// <summary>
/// Maps bot webhook to application builder
/// </summary>
/// <param name="routeBuilder"></param>
public void MapWebhook(IEndpointRouteBuilder routeBuilder)
{
string pattern = new UriBuilder(_options.WebhookUri).Path;
routeBuilder.MapPost(pattern, (Delegate)ReceiveUpdate);
}
private async Task<IResult> ReceiveUpdate(HttpContext ctx)
{
if (_options.SecretToken != null)
@@ -93,5 +98,4 @@ namespace Telegrator.Mediation
await _updateRouter.HandleUpdateAsync(_botClient, update, ctx.RequestAborted);
return Results.Ok();
}
}
}
@@ -15,7 +15,7 @@
<EnforceCodeStyleInBuild>True</EnforceCodeStyleInBuild>
<Title>Telegrator.Hosting.Web</Title>
<Version>1.16.4</Version>
<Version>1.16.6</Version>
<Authors>Rikitav Tim4ik</Authors>
<Company>Rikitav Tim4ik</Company>
<RepositoryUrl>https://github.com/Rikitav/Telegrator</RepositoryUrl>
+28 -5
View File
@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
@@ -42,7 +43,27 @@ namespace Telegrator
/// <summary>
/// Replaces TelegramBotWebHostBuilder. Configures DI, options, and handlers.
/// </summary>
public static IHostApplicationBuilder AddTelegratorWeb(this IHostApplicationBuilder builder, TelegratorOptions? options = null, IHandlersCollection? handlers = null)
public static ITelegramBotHostBuilder AddTelegratorWeb(this ITelegramBotHostBuilder builder, TelegratorOptions? options = null, IHandlersCollection? handlers = null, Action<ITelegramBotHostBuilder>? action = null)
{
builder.AddTelegratorWebInternal(options, handlers);
action?.Invoke(builder);
return builder;
}
/// <summary>
/// Replaces TelegramBotWebHostBuilder. Configures DI, options, and handlers.
/// </summary>
public static IHostApplicationBuilder AddTelegratorWeb(this WebApplicationBuilder builder, TelegratorOptions? options = null, IHandlersCollection? handlers = null, Action<ITelegramBotHostBuilder>? action = null)
{
builder.AddTelegratorWebInternal(options, handlers);
action?.Invoke(new TelegramBotWebHostBuilder(builder));
return builder;
}
/// <summary>
/// Replaces TelegramBotWebHostBuilder. Configures DI, options, and handlers.
/// </summary>
internal static IHostApplicationBuilder AddTelegratorWebInternal(this IHostApplicationBuilder builder, TelegratorOptions? options = null, IHandlersCollection? handlers = null)
{
IServiceCollection services = builder.Services;
IConfigurationManager configuration = builder.Configuration;
@@ -103,11 +124,12 @@ namespace Telegrator
/// Replaces the initialization logic from TelegramBotWebHost constructor.
/// Initializes the bot and logs handlers on application startup.
/// </summary>
public static WebApplication UseTelegratorWeb(this WebApplication app)
public static T UseTelegratorWeb<T>(this T app) where T : IEndpointRouteBuilder, IHost
{
ITelegramBotInfo info = app.Services.GetRequiredService<ITelegramBotInfo>();
IHandlersCollection handlers = app.Services.GetRequiredService<IHandlersCollection>();
ILoggerFactory loggerFactory = app.Services.GetRequiredService<ILoggerFactory>();
HostedUpdateWebhooker webhooker = app.ServiceProvider.GetRequiredService<HostedUpdateWebhooker>();
ITelegramBotInfo info = app.ServiceProvider.GetRequiredService<ITelegramBotInfo>();
IHandlersCollection handlers = app.ServiceProvider.GetRequiredService<IHandlersCollection>();
ILoggerFactory loggerFactory = app.ServiceProvider.GetRequiredService<ILoggerFactory>();
ILogger logger = loggerFactory.CreateLogger("Telegrator.Hosting.Web.TelegratorHost");
if (logger.IsEnabled(LogLevel.Information))
@@ -117,6 +139,7 @@ namespace Telegrator
logger.LogHandlers(handlers);
}
webhooker.MapWebhook(app);
return app;
}
@@ -9,3 +9,4 @@ using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Style", "IDE0090")]
[assembly: SuppressMessage("Usage", "CA2254")]
[assembly: SuppressMessage("Maintainability", "CA1510")]
[assembly: SuppressMessage("Style", "IDE0270")]
@@ -3,17 +3,17 @@ using Telegram.Bot;
using Telegram.Bot.Types;
using Telegrator.Core;
namespace Telegrator.Hosting
namespace Telegrator.Hosting;
/// <summary>
/// Implementation of <see cref="ITelegramBotInfo"/> that provides bot information.
/// Contains metadata about the Telegram bot including user details and service provider for wider filterring abilities
/// </summary>
/// <param name="client"></param>
/// <param name="services"></param>
/// <param name="configuration"></param>
public class HostedTelegramBotInfo(ITelegramBotClient client, IServiceProvider services, IConfiguration configuration) : ITelegramBotInfo
{
/// <summary>
/// Implementation of <see cref="ITelegramBotInfo"/> that provides bot information.
/// Contains metadata about the Telegram bot including user details and service provider for wider filterring abilities
/// </summary>
/// <param name="client"></param>
/// <param name="services"></param>
/// <param name="configuration"></param>
public class HostedTelegramBotInfo(ITelegramBotClient client, IServiceProvider services, IConfiguration configuration) : ITelegramBotInfo
{
/// <inheritdoc/>
public User User { get; } = client.GetMe().Result;
@@ -26,5 +26,4 @@ namespace Telegrator.Hosting
/// Provides access to configuration of this Hosted telegram bot
/// </summary>
public IConfiguration Configuration { get; } = configuration;
}
}
@@ -0,0 +1,12 @@
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Text;
using Telegrator.Core;
namespace Telegrator.Hosting;
public interface ITelegramBotHostBuilder : IHostApplicationBuilder, ICollectingProvider
{
}
@@ -3,13 +3,13 @@ using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Telegrator.Core;
namespace Telegrator.Hosting
namespace Telegrator.Hosting;
/// <summary>
/// Represents a hosted telegram bot
/// </summary>
public class TelegramBotHost : IHost, ITelegratorBot
{
/// <summary>
/// Represents a hosted telegram bot
/// </summary>
public class TelegramBotHost : IHost, ITelegratorBot
{
private readonly IHost _innerHost;
private readonly IUpdateRouter _updateRouter;
private readonly ILogger<TelegramBotHost> _logger;
@@ -111,5 +111,4 @@ namespace Telegrator.Hosting
GC.SuppressFinalize(this);
_disposed = true;
}
}
}
@@ -3,18 +3,16 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.Metrics;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Telegrator.Core;
using Telegrator.Providers;
#pragma warning disable IDE0001
namespace Telegrator.Hosting
namespace Telegrator.Hosting;
/// <summary>
/// Represents a hosted telegram bots and services builder that helps manage configuration, logging, lifetime, and more.
/// </summary>
public class TelegramBotHostBuilder : ITelegramBotHostBuilder
{
/// <summary>
/// Represents a hosted telegram bots and services builder that helps manage configuration, logging, lifetime, and more.
/// </summary>
public class TelegramBotHostBuilder : IHostApplicationBuilder, ICollectingProvider
{
private readonly HostApplicationBuilder _innerBuilder;
private readonly HostApplicationBuilderSettings _settings;
internal IHandlersCollection _handlers = null!;
@@ -49,8 +47,6 @@ namespace Telegrator.Hosting
{
_innerBuilder = hostApplicationBuilder ?? throw new ArgumentNullException(nameof(hostApplicationBuilder));
_settings = settings ?? new HostApplicationBuilderSettings();
this.AddTelegrator();
}
/// <summary>
@@ -63,8 +59,6 @@ namespace Telegrator.Hosting
{
_innerBuilder = hostApplicationBuilder ?? throw new ArgumentNullException(nameof(hostApplicationBuilder));
_settings = settings ?? new HostApplicationBuilderSettings();
this.AddTelegrator(options, null);
}
/// <summary>
@@ -77,8 +71,6 @@ namespace Telegrator.Hosting
{
_innerBuilder = hostApplicationBuilder ?? throw new ArgumentNullException(nameof(hostApplicationBuilder));
_settings = settings ?? new HostApplicationBuilderSettings();
this.AddTelegrator(null, handlers);
}
/// <summary>
@@ -92,8 +84,6 @@ namespace Telegrator.Hosting
{
_innerBuilder = hostApplicationBuilder ?? throw new ArgumentNullException(nameof(hostApplicationBuilder));
_settings = settings ?? new HostApplicationBuilderSettings();
this.AddTelegrator(options, handlers);
}
/// <summary>
@@ -110,7 +100,6 @@ namespace Telegrator.Hosting
/// <inheritdoc/>
public void ConfigureContainer<TContainerBuilder>(IServiceProviderFactory<TContainerBuilder> factory, Action<TContainerBuilder>? configure = null) where TContainerBuilder : notnull
{
this.ConfigureContainer(factory, configure);
}
_innerBuilder.ConfigureContainer(factory, configure);
}
}
@@ -1,20 +1,18 @@
using Microsoft.Extensions.Logging;
namespace Telegrator.Logging;
namespace Telegrator.Logging
/// <summary>
/// Adapter for Microsoft.Extensions.Logging to work with Telegrator logging system.
/// This allows seamless integration with ASP.NET Core logging infrastructure.
/// </summary>
public class MicrosoftLoggingAdapter : ITelegratorLogger
{
/// <summary>
/// Adapter for Microsoft.Extensions.Logging to work with Telegrator logging system.
/// This allows seamless integration with ASP.NET Core logging infrastructure.
/// </summary>
public class MicrosoftLoggingAdapter : ITelegratorLogger
{
private readonly ILogger _logger;
private readonly Microsoft.Extensions.Logging.ILogger _logger;
/// <summary>
/// Initializes a new instance of MicrosoftLoggingAdapter.
/// </summary>
/// <param name="logger">The Microsoft.Extensions.Logging logger instance.</param>
public MicrosoftLoggingAdapter(ILogger logger)
public MicrosoftLoggingAdapter(Microsoft.Extensions.Logging.ILogger logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
@@ -24,11 +22,11 @@ namespace Telegrator.Logging
{
var msLogLevel = level switch
{
Telegrator.Logging.LogLevel.Trace => Microsoft.Extensions.Logging.LogLevel.Trace,
Telegrator.Logging.LogLevel.Debug => Microsoft.Extensions.Logging.LogLevel.Debug,
Telegrator.Logging.LogLevel.Information => Microsoft.Extensions.Logging.LogLevel.Information,
Telegrator.Logging.LogLevel.Warning => Microsoft.Extensions.Logging.LogLevel.Warning,
Telegrator.Logging.LogLevel.Error => Microsoft.Extensions.Logging.LogLevel.Error,
LogLevel.Trace => Microsoft.Extensions.Logging.LogLevel.Trace,
LogLevel.Debug => Microsoft.Extensions.Logging.LogLevel.Debug,
LogLevel.Information => Microsoft.Extensions.Logging.LogLevel.Information,
LogLevel.Warning => Microsoft.Extensions.Logging.LogLevel.Warning,
LogLevel.Error => Microsoft.Extensions.Logging.LogLevel.Error,
_ => Microsoft.Extensions.Logging.LogLevel.Information
};
@@ -41,5 +39,4 @@ namespace Telegrator.Logging
_logger.Log(msLogLevel, default, message, null, (str, _) => str);
}
}
}
}
@@ -7,11 +7,11 @@ using Telegrator.Core;
using Telegrator.Core.States;
using Telegrator.Mediation;
namespace Telegrator.Polling
namespace Telegrator.Polling;
/// <inheritdoc/>
public class HostUpdateRouter : UpdateRouter
{
/// <inheritdoc/>
public class HostUpdateRouter : UpdateRouter
{
/// <summary>
/// <see cref="ILogger"/> of this router
/// </summary>
@@ -56,5 +56,4 @@ namespace Telegrator.Polling
Logger.LogError("Exception was thrown during update routing faulted :\n{exception}", exception.ToString());
}
}
}
@@ -6,17 +6,17 @@ using Telegram.Bot.Polling;
using Telegrator.Core;
using Telegrator.Mediation;
namespace Telegrator.Polling
namespace Telegrator.Polling;
/// <summary>
/// Service for receiving updates for Hosted telegram bots
/// </summary>
/// <param name="botClient"></param>
/// <param name="updateRouter"></param>
/// <param name="options"></param>
/// <param name="logger"></param>
public class HostedUpdateReceiver(ITelegramBotClient botClient, IUpdateRouter updateRouter, IOptions<ReceiverOptions> options, ILogger<HostedUpdateReceiver> logger) : BackgroundService
{
/// <summary>
/// Service for receiving updates for Hosted telegram bots
/// </summary>
/// <param name="botClient"></param>
/// <param name="updateRouter"></param>
/// <param name="options"></param>
/// <param name="logger"></param>
public class HostedUpdateReceiver(ITelegramBotClient botClient, IUpdateRouter updateRouter, IOptions<ReceiverOptions> options, ILogger<HostedUpdateReceiver> logger) : BackgroundService
{
private readonly ReceiverOptions _receiverOptions = options.Value;
private readonly IUpdateRouter _updateRouter = updateRouter;
@@ -28,5 +28,4 @@ namespace Telegrator.Polling
DefaultUpdateReceiver updateReceiver = new DefaultUpdateReceiver(botClient, _receiverOptions);
await updateReceiver.ReceiveAsync(_updateRouter, stoppingToken).ConfigureAwait(false);
}
}
}
@@ -1,11 +1,9 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Options;
namespace Telegrator.Providers
namespace Telegrator.Providers;
/// <inheritdoc/>
public class HostAwaitingProvider(IOptions<TelegratorOptions> options) : AwaitingProvider(options.Value)
{
/// <inheritdoc/>
public class HostAwaitingProvider(IOptions<TelegratorOptions> options, ILogger<HostAwaitingProvider> logger) : AwaitingProvider(options.Value)
{
private readonly ILogger<HostAwaitingProvider> _logger = logger;
}
}
@@ -2,11 +2,11 @@
using Telegrator.Core;
using Telegrator.Core.Descriptors;
namespace Telegrator.Providers
namespace Telegrator.Providers;
/// <inheritdoc/>
public class HostHandlersCollection(IServiceCollection hostServiceColletion, TelegratorOptions options) : HandlersCollection(options)
{
/// <inheritdoc/>
public class HostHandlersCollection(IServiceCollection hostServiceColletion, TelegratorOptions options) : HandlersCollection(options)
{
private readonly IServiceCollection Services = hostServiceColletion;
/// <inheritdoc/>
@@ -58,5 +58,4 @@ namespace Telegrator.Providers
return base.AddDescriptor(descriptor);
}
}
}
@@ -1,27 +1,23 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Telegrator.Core;
using Telegrator.Core.Descriptors;
using Telegrator.Core.Handlers;
namespace Telegrator.Providers
namespace Telegrator.Providers;
/// <inheritdoc/>
public class HostHandlersProvider : HandlersProvider
{
/// <inheritdoc/>
public class HostHandlersProvider : HandlersProvider
{
private readonly IServiceProvider Services;
private readonly ILogger<HostHandlersProvider> Logger;
/// <inheritdoc/>
public HostHandlersProvider(
IHandlersCollection handlers,
IOptions<TelegratorOptions> options,
IServiceProvider serviceProvider,
ILogger<HostHandlersProvider> logger) : base(handlers, options.Value)
IServiceProvider serviceProvider) : base(handlers, options.Value)
{
Services = serviceProvider;
Logger = logger;
}
/// <inheritdoc/>
@@ -41,5 +37,4 @@ namespace Telegrator.Providers
updateHandler.LifetimeToken.OnLifetimeEnded += _ => scope.Dispose();
return updateHandler;
}
}
}
@@ -15,7 +15,7 @@
<EnforceCodeStyleInBuild>True</EnforceCodeStyleInBuild>
<Title>Telegrator.Hosting</Title>
<Version>1.16.4</Version>
<Version>1.16.6</Version>
<Authors>Rikitav Tim4ik</Authors>
<Company>Rikitav Tim4ik</Company>
<RepositoryUrl>https://github.com/Rikitav/Telegrator</RepositoryUrl>
+39 -8
View File
@@ -11,10 +11,12 @@ using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegrator.Core;
using Telegrator.Core.Descriptors;
using Telegrator.Core.States;
using Telegrator.Hosting;
using Telegrator.Logging;
using Telegrator.Polling;
using Telegrator.Providers;
using Telegrator.States;
namespace Telegrator;
@@ -28,7 +30,7 @@ public static class HostBuilderExtensions
/// </summary>
public const string HandlersCollectionPropertyKey = nameof(IHandlersCollection);
extension (IHostApplicationBuilder builder)
extension (HostApplicationBuilder builder)
{
/// <summary>
/// Gets the <see cref="IHandlersCollection"/> from the builder properties.
@@ -37,18 +39,35 @@ public static class HostBuilderExtensions
{
get
{
if (builder is TelegramBotHostBuilder botHostBuilder)
return botHostBuilder.Handlers;
return (IHandlersCollection)builder.Properties[HandlersCollectionPropertyKey];
return (IHandlersCollection)((IHostApplicationBuilder)builder).Properties[HandlersCollectionPropertyKey];
}
}
}
/// <summary>
/// Replaces TelegramBotWebHostBuilder. Configures DI, options, and handlers.
/// Replaces TelegramBotHostBuilder. Configures DI, options, and handlers.
/// </summary>
public static IHostApplicationBuilder AddTelegrator(this IHostApplicationBuilder builder, TelegratorOptions? options = null, IHandlersCollection? handlers = null)
public static ITelegramBotHostBuilder AddTelegrator(this ITelegramBotHostBuilder builder, TelegratorOptions? options = null, IHandlersCollection? handlers = null, Action<ITelegramBotHostBuilder>? action = null)
{
builder.AddTelegratorInternal(options, handlers);
action?.Invoke(builder);
return builder;
}
/// <summary>
/// Replaces TelegramBotHostBuilder. Configures DI, options, and handlers.
/// </summary>
public static IHostApplicationBuilder AddTelegrator(this HostApplicationBuilder builder, TelegratorOptions? options = null, IHandlersCollection? handlers = null, Action<ITelegramBotHostBuilder>? action = null)
{
builder.AddTelegratorInternal(options, handlers);
action?.Invoke(new TelegramBotHostBuilder(builder));
return builder;
}
/// <summary>
/// Replaces TelegramBotHostBuilder. Configures DI, options, and handlers.
/// </summary>
public static IHostApplicationBuilder AddTelegratorInternal(this IHostApplicationBuilder builder, TelegratorOptions? options = null, IHandlersCollection? handlers = null)
{
IServiceCollection services = builder.Services;
IConfigurationManager configuration = builder.Configuration;
@@ -112,6 +131,18 @@ public static class HostBuilderExtensions
/// </summary>
public static class ServicesCollectionExtensions
{
/// <summary>
/// Registers <see cref="IStateStorage"/> service
/// </summary>
/// <typeparam name="TStorage"></typeparam>
/// <param name="services"></param>
/// <returns></returns>
public static IServiceCollection AddStateStorage<TStorage>(this IServiceCollection services) where TStorage : IStateStorage
{
services.Replace(new ServiceDescriptor(typeof(IStateStorage), typeof(TStorage), ServiceLifetime.Singleton));
return services;
}
/// <summary>
/// Registers <see cref="TelegramBotHost"/> default services
/// </summary>
@@ -119,11 +150,11 @@ public static class ServicesCollectionExtensions
/// <returns></returns>
public static IServiceCollection AddTelegramBotHostDefaults(this IServiceCollection services)
{
services.AddLogging(builder => builder.AddConsole().AddDebug());
services.AddSingleton<IAwaitingProvider, HostAwaitingProvider>();
services.AddSingleton<IHandlersProvider, HostHandlersProvider>();
services.AddSingleton<IUpdateRouter, HostUpdateRouter>();
services.AddSingleton<ITelegramBotInfo, HostedTelegramBotInfo>();
services.AddSingleton<IStateStorage, DefaultStateStorage>();
return services;
}
@@ -4,14 +4,13 @@ using System.Threading.Tasks;
using Telegram.Bot.Types;
using Telegrator.Handlers;
namespace Telegrator.Localized
namespace Telegrator.Localized;
public static class LocalizedMessageHandlerExtensions
{
public static class LocalizedMessageHandlerExtensions
{
public static async Task<Message> ResponseLocalized(this ILocalizedHandler<Message> localizedHandler, string localizedReplyIdentifier, params IEnumerable<string> formatArgs)
{
LocalizedString localizedString = localizedHandler.LocalizationProvider[localizedReplyIdentifier, formatArgs];
return await localizedHandler.Container.Responce(localizedString.Value);
}
}
}
@@ -4,15 +4,15 @@ using Telegrator.Attributes;
using Telegrator.Core.Filters;
using Telegrator.Filters;
namespace Telegrator.Annotations
namespace Telegrator.Annotations;
/// <summary>
/// Abstract base attribute for filtering callback-based updates.
/// Supports various message types including regular messages, edited messages, channel posts, and business messages.
/// </summary>
/// <param name="filters">The filters to apply to messages</param>
public abstract class CallbackQueryAttribute(params IFilter<CallbackQuery>[] filters) : UpdateFilterAttribute<CallbackQuery>(filters)
{
/// <summary>
/// Abstract base attribute for filtering callback-based updates.
/// Supports various message types including regular messages, edited messages, channel posts, and business messages.
/// </summary>
/// <param name="filters">The filters to apply to messages</param>
public abstract class CallbackQueryAttribute(params IFilter<CallbackQuery>[] filters) : UpdateFilterAttribute<CallbackQuery>(filters)
{
/// <summary>
/// Gets the allowed update types that this filter can process.
/// </summary>
@@ -25,20 +25,19 @@ namespace Telegrator.Annotations
/// <returns>The message from the update, or null if not present</returns>
public override CallbackQuery? GetFilterringTarget(Update update)
=> update.CallbackQuery;
}
/// <summary>
/// Attribute for filtering <see cref="CallbackQuery"/>'s data
/// </summary>
/// <param name="data"></param>
public class CallbackDataAttribute(string data)
: CallbackQueryAttribute(new CallbackDataFilter(data))
{ }
/// <summary>
/// Attribute to check if <see cref="CallbackQuery"/> belongs to a specific message by its ID
/// </summary>
public class CallbackInlineIdAttribute(string inlineMessageId)
: CallbackQueryAttribute(new CallbackInlineIdFilter(inlineMessageId))
{ }
}
/// <summary>
/// Attribute for filtering <see cref="CallbackQuery"/>'s data
/// </summary>
/// <param name="data"></param>
public class CallbackDataAttribute(string data)
: CallbackQueryAttribute(new CallbackDataFilter(data))
{ }
/// <summary>
/// Attribute to check if <see cref="CallbackQuery"/> belongs to a specific message by its ID
/// </summary>
public class CallbackInlineIdAttribute(string inlineMessageId)
: CallbackQueryAttribute(new CallbackInlineIdFilter(inlineMessageId))
{ }
@@ -3,14 +3,14 @@ using Telegram.Bot.Types.Enums;
using Telegrator.Filters;
using Telegrator.Attributes;
namespace Telegrator.Annotations
namespace Telegrator.Annotations;
/// <summary>
/// Attribute for filtering messages based on command aliases.
/// Allows handlers to respond to multiple command variations using a single attribute.
/// </summary>
public class CommandAlliasAttribute : UpdateFilterAttribute<Message>
{
/// <summary>
/// Attribute for filtering messages based on command aliases.
/// Allows handlers to respond to multiple command variations using a single attribute.
/// </summary>
public class CommandAlliasAttribute : UpdateFilterAttribute<Message>
{
/// <summary>
/// Gets the allowed update types for this filter.
/// </summary>
@@ -56,5 +56,4 @@ namespace Telegrator.Annotations
/// <param name="update">The Telegram update.</param>
/// <returns>The message from the update, or null if not present.</returns>
public override Message? GetFilterringTarget(Update update) => update.Message;
}
}
@@ -1,63 +1,62 @@
using System.Text.RegularExpressions;
using Telegrator.Filters;
namespace Telegrator.Annotations
{
/// <summary>
/// Attribute for filtering messages where a command has arguments count >= <paramref name="count"/>.
/// </summary>
/// <param name="count"></param>
public class ArgumentCountAttribute(int count)
namespace Telegrator.Annotations;
/// <summary>
/// Attribute for filtering messages where a command has arguments count >= <paramref name="count"/>.
/// </summary>
/// <param name="count"></param>
public class ArgumentCountAttribute(int count)
: MessageFilterAttribute(new ArgumentCountFilter(count))
{ }
{ }
/// <summary>
/// Attribute for filtering messages where a command argument starts with the specified content.
/// </summary>
/// <param name="content">The content that the command argument should start with.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
/// <param name="index">The index of the argument to check (0-based).</param>
public class ArgumentStartsWithAttribute(string content, StringComparison comparison = StringComparison.InvariantCulture, int index = 0)
/// <summary>
/// Attribute for filtering messages where a command argument starts with the specified content.
/// </summary>
/// <param name="content">The content that the command argument should start with.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
/// <param name="index">The index of the argument to check (0-based).</param>
public class ArgumentStartsWithAttribute(string content, StringComparison comparison = StringComparison.InvariantCulture, int index = 0)
: MessageFilterAttribute(new ArgumentStartsWithFilter(content, comparison, index))
{ }
{ }
/// <summary>
/// Attribute for filtering messages where a command argument ends with the specified content.
/// </summary>
/// <param name="content">The content that the command argument should end with.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
/// <param name="index">The index of the argument to check (0-based).</param>
public class ArgumentEndsWithAttribute(string content, StringComparison comparison = StringComparison.InvariantCulture, int index = 0)
/// <summary>
/// Attribute for filtering messages where a command argument ends with the specified content.
/// </summary>
/// <param name="content">The content that the command argument should end with.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
/// <param name="index">The index of the argument to check (0-based).</param>
public class ArgumentEndsWithAttribute(string content, StringComparison comparison = StringComparison.InvariantCulture, int index = 0)
: MessageFilterAttribute(new ArgumentEndsWithFilter(content, comparison, index))
{ }
{ }
/// <summary>
/// Attribute for filtering messages where a command argument contains the specified content.
/// </summary>
/// <param name="content">The content that the command argument should contain.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
/// <param name="index">The index of the argument to check (0-based).</param>
public class ArgumentContainsAttribute(string content, StringComparison comparison = StringComparison.InvariantCulture, int index = 0)
/// <summary>
/// Attribute for filtering messages where a command argument contains the specified content.
/// </summary>
/// <param name="content">The content that the command argument should contain.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
/// <param name="index">The index of the argument to check (0-based).</param>
public class ArgumentContainsAttribute(string content, StringComparison comparison = StringComparison.InvariantCulture, int index = 0)
: MessageFilterAttribute(new ArgumentContainsFilter(content, comparison, index))
{ }
{ }
/// <summary>
/// Attribute for filtering messages where a command argument equals the specified content.
/// </summary>
/// <param name="content">The content that the command argument should equal.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
/// <param name="index">The index of the argument to check (0-based).</param>
public class ArgumentEqualsAttribute(string content, StringComparison comparison = StringComparison.InvariantCulture, int index = 0)
/// <summary>
/// Attribute for filtering messages where a command argument equals the specified content.
/// </summary>
/// <param name="content">The content that the command argument should equal.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
/// <param name="index">The index of the argument to check (0-based).</param>
public class ArgumentEqualsAttribute(string content, StringComparison comparison = StringComparison.InvariantCulture, int index = 0)
: MessageFilterAttribute(new ArgumentEqualsFilter(content, comparison, index))
{ }
{ }
/// <summary>
/// Attribute for filtering messages where a command argument matches a regular expression pattern.
/// </summary>
/// <param name="pattern">The regular expression pattern to match against the command argument.</param>
/// <param name="options">The regex options to use for the pattern matching.</param>
/// <param name="index">The index of the argument to check (0-based).</param>
public class ArgumentRegexAttribute(string pattern, RegexOptions options = RegexOptions.None, int index = 0)
/// <summary>
/// Attribute for filtering messages where a command argument matches a regular expression pattern.
/// </summary>
/// <param name="pattern">The regular expression pattern to match against the command argument.</param>
/// <param name="options">The regex options to use for the pattern matching.</param>
/// <param name="index">The index of the argument to check (0-based).</param>
public class ArgumentRegexAttribute(string pattern, RegexOptions options = RegexOptions.None, int index = 0)
: MessageFilterAttribute(new ArgumentRegexFilter(pattern, options, index: index))
{ }
}
{ }
@@ -1,12 +1,11 @@
namespace Telegrator.Annotations
{
/// <summary>
/// Attribute that prevents a class from being automatically collected by the handler collection system.
/// When applied to a class, it will be excluded from domain-wide handler collection operations.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class DontCollectAttribute : Attribute
{
namespace Telegrator.Annotations;
/// <summary>
/// Attribute that prevents a class from being automatically collected by the handler collection system.
/// When applied to a class, it will be excluded from domain-wide handler collection operations.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class DontCollectAttribute : Attribute
{
}
}
@@ -4,15 +4,15 @@ using Telegrator.Filters;
using Telegrator.Attributes;
using Telegrator.Core.Filters;
namespace Telegrator.Annotations
namespace Telegrator.Annotations;
/// <summary>
/// Abstract base attribute for filtering updates based on environment conditions.
/// Can process all types of updates and provides environment-specific filtering logic.
/// </summary>
/// <param name="filters">The environment filters to apply</param>
public abstract class EnvironmentFilterAttribute(params IFilter<Update>[] filters) : UpdateFilterAttribute<Update>(filters)
{
/// <summary>
/// Abstract base attribute for filtering updates based on environment conditions.
/// Can process all types of updates and provides environment-specific filtering logic.
/// </summary>
/// <param name="filters">The environment filters to apply</param>
public abstract class EnvironmentFilterAttribute(params IFilter<Update>[] filters) : UpdateFilterAttribute<Update>(filters)
{
/// <summary>
/// Gets the allowed update types that this filter can process.
/// Environment filters can process all update types.
@@ -27,29 +27,29 @@ namespace Telegrator.Annotations
/// <returns>The update object itself</returns>
public override Update? GetFilterringTarget(Update update)
=> update;
}
}
/// <summary>
/// Attribute for filtering updates that occur in debug environment.
/// Only allows updates when the application is running in debug mode.
/// </summary>
public class IsDebugEnvironmentAttribute()
/// <summary>
/// Attribute for filtering updates that occur in debug environment.
/// Only allows updates when the application is running in debug mode.
/// </summary>
public class IsDebugEnvironmentAttribute()
: EnvironmentFilterAttribute(new IsDebugEnvironmentFilter())
{ }
{ }
/// <summary>
/// Attribute for filtering updates that occur in release environment.
/// Only allows updates when the application is running in release mode.
/// </summary>
public class IsReleaseEnvironmentAttribute()
/// <summary>
/// Attribute for filtering updates that occur in release environment.
/// Only allows updates when the application is running in release mode.
/// </summary>
public class IsReleaseEnvironmentAttribute()
: EnvironmentFilterAttribute(new IsReleaseEnvironmentFilter())
{ }
{ }
/// <summary>
/// Attribute for filtering updates based on environment variable values.
/// </summary>
public class EnvironmentVariableAttribute : EnvironmentFilterAttribute
{
/// <summary>
/// Attribute for filtering updates based on environment variable values.
/// </summary>
public class EnvironmentVariableAttribute : EnvironmentFilterAttribute
{
/// <summary>
/// Initializes the attribute to filter based on an environment variable with a specific value and comparison method.
/// </summary>
@@ -81,5 +81,4 @@ namespace Telegrator.Annotations
/// <param name="comparison">The string comparison method</param>
public EnvironmentVariableAttribute(string variable, StringComparison comparison)
: base(new EnvironmentVariableFilter(variable, comparison)) { }
}
}
@@ -1,14 +1,14 @@
using Telegram.Bot.Types.Enums;
using Telegrator.Filters;
namespace Telegrator.Annotations
namespace Telegrator.Annotations;
/// <summary>
/// Attribute for filtering messages that contain mentions.
/// Allows handlers to respond only to messages that mention the bot or specific users.
/// </summary>
public class MentionedAttribute : MessageFilterAttribute
{
/// <summary>
/// Attribute for filtering messages that contain mentions.
/// Allows handlers to respond only to messages that mention the bot or specific users.
/// </summary>
public class MentionedAttribute : MessageFilterAttribute
{
/// <summary>
/// Initializes a new instance of the MentionedAttribute that matches any mention.
/// </summary>
@@ -36,5 +36,4 @@ namespace Telegrator.Annotations
/// <param name="offset">The offset position where the mention should occur.</param>
public MentionedAttribute(string mention, int offset)
: base(new MessageHasEntityFilter(MessageEntityType.Mention, offset, null), new MentionedFilter(mention)) { }
}
}
@@ -1,28 +1,28 @@
using Telegram.Bot.Types.Enums;
using Telegrator.Filters;
namespace Telegrator.Annotations
{
/// <summary>
/// Attribute for filtering messages sent in forum chats.
/// </summary>
public class ChatIsForumAttribute()
namespace Telegrator.Annotations;
/// <summary>
/// Attribute for filtering messages sent in forum chats.
/// </summary>
public class ChatIsForumAttribute()
: MessageFilterAttribute(new MessageChatIsForumFilter())
{ }
{ }
/// <summary>
/// Attribute for filtering messages sent in a specific chat by ID.
/// </summary>
/// <param name="id">The chat ID to match</param>
public class ChatIdAttribute(long id)
/// <summary>
/// Attribute for filtering messages sent in a specific chat by ID.
/// </summary>
/// <param name="id">The chat ID to match</param>
public class ChatIdAttribute(long id)
: MessageFilterAttribute(new MessageChatIdFilter(id))
{ }
{ }
/// <summary>
/// Attribute for filtering messages sent in chats of a specific type.
/// </summary>
public class ChatTypeAttribute : MessageFilterAttribute
{
/// <summary>
/// Attribute for filtering messages sent in chats of a specific type.
/// </summary>
public class ChatTypeAttribute : MessageFilterAttribute
{
/// <summary>
/// Initialize new instance of <see cref="ChatTypeAttribute"/> to filter messages from chat from specific chats
/// </summary>
@@ -36,13 +36,13 @@ namespace Telegrator.Annotations
/// <param name="flags"></param>
public ChatTypeAttribute(ChatTypeFlags flags)
: base(new MessageChatTypeFilter(flags)) { }
}
}
/// <summary>
/// Attribute for filtering messages based on the chat title.
/// </summary>
public class ChatTitleAttribute : MessageFilterAttribute
{
/// <summary>
/// Attribute for filtering messages based on the chat title.
/// </summary>
public class ChatTitleAttribute : MessageFilterAttribute
{
/// <summary>
/// Initializes the attribute to filter messages from chats with a specific title and comparison method.
/// </summary>
@@ -57,13 +57,13 @@ namespace Telegrator.Annotations
/// <param name="title">The chat title to match</param>
public ChatTitleAttribute(string? title)
: base(new MessageChatTitleFilter(title)) { }
}
}
/// <summary>
/// Attribute for filtering messages based on the chat username.
/// </summary>
public class ChatUsernameAttribute : MessageFilterAttribute
{
/// <summary>
/// Attribute for filtering messages based on the chat username.
/// </summary>
public class ChatUsernameAttribute : MessageFilterAttribute
{
/// <summary>
/// Initializes the attribute to filter messages from chats with a specific username and comparison method.
/// </summary>
@@ -78,13 +78,13 @@ namespace Telegrator.Annotations
/// <param name="userName">The chat username to match</param>
public ChatUsernameAttribute(string? userName)
: base(new MessageChatUsernameFilter(userName, StringComparison.InvariantCulture)) { }
}
}
/// <summary>
/// Attribute for filtering messages based on the chat name (first name and optionally last name).
/// </summary>
public class ChatNameAttribute : MessageFilterAttribute
{
/// <summary>
/// Attribute for filtering messages based on the chat name (first name and optionally last name).
/// </summary>
public class ChatNameAttribute : MessageFilterAttribute
{
/// <summary>
/// Initializes the attribute to filter messages from chats with specific first and last names.
/// </summary>
@@ -101,5 +101,4 @@ namespace Telegrator.Annotations
/// <param name="lastName">The last name to match (optional)</param>
public ChatNameAttribute(string? firstName, string? lastName)
: base(new MessageChatNameFilter(firstName, lastName)) { }
}
}
@@ -5,15 +5,15 @@ using Telegrator.Filters;
using Telegrator.Attributes;
using Telegrator.Core.Filters;
namespace Telegrator.Annotations
namespace Telegrator.Annotations;
/// <summary>
/// Abstract base attribute for filtering message-based updates.
/// Supports various message types including regular messages, edited messages, channel posts, and business messages.
/// </summary>
/// <param name="filters">The filters to apply to messages</param>
public abstract class MessageFilterAttribute(params IFilter<Message>[] filters) : UpdateFilterAttribute<Message>(filters)
{
/// <summary>
/// Abstract base attribute for filtering message-based updates.
/// Supports various message types including regular messages, edited messages, channel posts, and business messages.
/// </summary>
/// <param name="filters">The filters to apply to messages</param>
public abstract class MessageFilterAttribute(params IFilter<Message>[] filters) : UpdateFilterAttribute<Message>(filters)
{
/// <summary>
/// Gets the allowed update types that this filter can process.
/// </summary>
@@ -45,13 +45,13 @@ namespace Telegrator.Annotations
_ => null
};
}
}
}
/// <summary>
/// Attribute for filtering messages based on regular expression patterns.
/// </summary>
public class MessageRegexAttribute : MessageFilterAttribute
{
/// <summary>
/// Attribute for filtering messages based on regular expression patterns.
/// </summary>
public class MessageRegexAttribute : MessageFilterAttribute
{
/// <summary>
/// Initializes the attribute with a regex pattern and options.
/// </summary>
@@ -66,13 +66,13 @@ namespace Telegrator.Annotations
/// <param name="regex">The precompiled regular expression</param>
public MessageRegexAttribute(Regex regex)
: base(new MessageRegexFilter(regex)) { }
}
}
/// <summary>
/// Attribute for filtering messages that contain dice throws with specific values.
/// </summary>
public class DiceThrowedAttribute : MessageFilterAttribute
{
/// <summary>
/// Attribute for filtering messages that contain dice throws with specific values.
/// </summary>
public class DiceThrowedAttribute : MessageFilterAttribute
{
/// <summary>
/// Initializes the attribute to filter dice throws with a specific value.
/// </summary>
@@ -87,41 +87,41 @@ namespace Telegrator.Annotations
/// <param name="value">The dice value to match</param>
public DiceThrowedAttribute(DiceType diceType, int value)
: base(new DiceThrowedFilter(diceType, value)) { }
}
}
/// <summary>
/// Attribute for filtering messages that are automatically forwarded.
/// </summary>
public class IsAutomaticFormwardMessageAttribute()
/// <summary>
/// Attribute for filtering messages that are automatically forwarded.
/// </summary>
public class IsAutomaticFormwardMessageAttribute()
: MessageFilterAttribute(new IsAutomaticFormwardMessageFilter())
{ }
{ }
/// <summary>
/// Attribute for filtering messages sent while the user was offline.
/// </summary>
public class IsFromOfflineMessageAttribute()
/// <summary>
/// Attribute for filtering messages sent while the user was offline.
/// </summary>
public class IsFromOfflineMessageAttribute()
: MessageFilterAttribute(new IsFromOfflineMessageFilter())
{ }
{ }
/// <summary>
/// Attribute for filtering service messages (e.g., user joined, left, etc.).
/// </summary>
public class IsServiceMessageMessageAttribute()
/// <summary>
/// Attribute for filtering service messages (e.g., user joined, left, etc.).
/// </summary>
public class IsServiceMessageMessageAttribute()
: MessageFilterAttribute(new IsServiceMessageMessageFilter())
{ }
{ }
/// <summary>
/// Attribute for filtering topic messages in forum chats.
/// </summary>
public class IsTopicMessageMessageAttribute()
/// <summary>
/// Attribute for filtering topic messages in forum chats.
/// </summary>
public class IsTopicMessageMessageAttribute()
: MessageFilterAttribute(new IsServiceMessageMessageFilter())
{ }
{ }
/// <summary>
/// Attribute for filtering messages based on their entities (mentions, links, etc.).
/// </summary>
public class MessageHasEntityAttribute : MessageFilterAttribute
{
/// <summary>
/// Attribute for filtering messages based on their entities (mentions, links, etc.).
/// </summary>
public class MessageHasEntityAttribute : MessageFilterAttribute
{
/// <summary>
/// Initializes the attribute to filter messages with a specific entity type.
/// </summary>
@@ -157,5 +157,4 @@ namespace Telegrator.Annotations
/// <param name="stringComparison">The string comparison method</param>
public MessageHasEntityAttribute(MessageEntityType type, int offset, int? length, string content, StringComparison stringComparison = StringComparison.CurrentCulture)
: base(new MessageHasEntityFilter(type, offset, length, content, stringComparison)) { }
}
}
@@ -1,27 +1,26 @@
using Telegrator.Filters;
namespace Telegrator.Annotations
{
/// <summary>
/// Attribute for filtering messages with reply to messages of this bot.
/// </summary>
public class MeRepliedAttribute()
namespace Telegrator.Annotations;
/// <summary>
/// Attribute for filtering messages with reply to messages of this bot.
/// </summary>
public class MeRepliedAttribute()
: MessageFilterAttribute(new MeRepliedFilter())
{ }
{ }
/// <summary>
/// Attribute for checking message's reply chain.
/// </summary>
public class HasReplyAttribute(int replyDepth = 1)
/// <summary>
/// Attribute for checking message's reply chain.
/// </summary>
public class HasReplyAttribute(int replyDepth = 1)
: MessageFilterAttribute(new MessageHasReplyFilter(replyDepth))
{ }
{ }
/// <summary>
/// Helper filter class for filters that operate on replied messages.
/// Provides functionality to traverse reply chains and access replied message content.
/// </summary>
/// <param name="replyDepth"></param>
public class FromReplyChainAttribute(int replyDepth = 1)
/// <summary>
/// Helper filter class for filters that operate on replied messages.
/// Provides functionality to traverse reply chains and access replied message content.
/// </summary>
/// <param name="replyDepth"></param>
public class FromReplyChainAttribute(int replyDepth = 1)
: MessageFilterAttribute(new FromReplyChainFilter(replyDepth))
{ }
}
{ }
@@ -1,12 +1,12 @@
using Telegrator.Filters;
namespace Telegrator.Annotations
namespace Telegrator.Annotations;
/// <summary>
/// Attribute for filtering messages based on the sender's username.
/// </summary>
public class FromUsernameAttribute : MessageFilterAttribute
{
/// <summary>
/// Attribute for filtering messages based on the sender's username.
/// </summary>
public class FromUsernameAttribute : MessageFilterAttribute
{
/// <summary>
/// Initializes the attribute to filter messages from a specific username.
/// </summary>
@@ -21,13 +21,13 @@ namespace Telegrator.Annotations
/// <param name="comparison">The string comparison method</param>
public FromUsernameAttribute(string username, StringComparison comparison)
: base(new FromUsernameFilter(username, comparison)) { }
}
}
/// <summary>
/// Attribute for filtering messages based on the sender's name (first name and optionally last name).
/// </summary>
public class FromUserAttribute : MessageFilterAttribute
{
/// <summary>
/// Attribute for filtering messages based on the sender's name (first name and optionally last name).
/// </summary>
public class FromUserAttribute : MessageFilterAttribute
{
/// <summary>
/// Initializes the attribute to filter messages from a user with specific first and last names.
/// </summary>
@@ -59,34 +59,33 @@ namespace Telegrator.Annotations
/// <param name="comparison">The string comparison method</param>
public FromUserAttribute(string firstName, StringComparison comparison)
: base(new FromUserFilter(firstName, null, comparison)) { }
}
/// <summary>
/// Attribute for filtering messages from a specific user ID.
/// </summary>
/// <param name="userId">The user ID to match</param>
public class FromUserIdAttribute(long userId)
: MessageFilterAttribute(new FromUserIdFilter(userId))
{ }
/// <summary>
/// Attribute for filtering messages sent by not bots (users).
/// </summary>
public class NotFromBotAttribute()
: MessageFilterAttribute(new FromBotFilter().Not())
{ }
/// <summary>
/// Attribute for filtering messages sent by bots.
/// </summary>
public class FromBotAttribute()
: MessageFilterAttribute(new FromBotFilter())
{ }
/// <summary>
/// Attribute for filtering messages sent by premium users.
/// </summary>
public class FromPremiumUserAttribute()
: MessageFilterAttribute(new FromPremiumUserFilter())
{ }
}
/// <summary>
/// Attribute for filtering messages from a specific user ID.
/// </summary>
/// <param name="userId">The user ID to match</param>
public class FromUserIdAttribute(long userId)
: MessageFilterAttribute(new FromUserIdFilter(userId))
{ }
/// <summary>
/// Attribute for filtering messages sent by not bots (users).
/// </summary>
public class NotFromBotAttribute()
: MessageFilterAttribute(new FromBotFilter().Not())
{ }
/// <summary>
/// Attribute for filtering messages sent by bots.
/// </summary>
public class FromBotAttribute()
: MessageFilterAttribute(new FromBotFilter())
{ }
/// <summary>
/// Attribute for filtering messages sent by premium users.
/// </summary>
public class FromPremiumUserAttribute()
: MessageFilterAttribute(new FromPremiumUserFilter())
{ }
@@ -1,58 +1,57 @@
using Telegrator.Filters;
namespace Telegrator.Annotations
{
/// <summary>
/// Attribute for filtering messages where the text starts with the specified content.
/// </summary>
/// <param name="content">The string that the message text should start with</param>
/// <param name="comparison">The string comparison type</param>
public class TextStartsWithAttribute(string content, StringComparison comparison = StringComparison.InvariantCulture)
namespace Telegrator.Annotations;
/// <summary>
/// Attribute for filtering messages where the text starts with the specified content.
/// </summary>
/// <param name="content">The string that the message text should start with</param>
/// <param name="comparison">The string comparison type</param>
public class TextStartsWithAttribute(string content, StringComparison comparison = StringComparison.InvariantCulture)
: MessageFilterAttribute(new TextStartsWithFilter(content, comparison))
{ }
{ }
/// <summary>
/// Attribute for filtering messages where the text ends with the specified content.
/// </summary>
/// <param name="content">The string that the message text should end with</param>
/// <param name="comparison">The string comparison type</param>
public class TextEndsWithAttribute(string content, StringComparison comparison = StringComparison.InvariantCulture)
/// <summary>
/// Attribute for filtering messages where the text ends with the specified content.
/// </summary>
/// <param name="content">The string that the message text should end with</param>
/// <param name="comparison">The string comparison type</param>
public class TextEndsWithAttribute(string content, StringComparison comparison = StringComparison.InvariantCulture)
: MessageFilterAttribute(new TextEndsWithFilter(content, comparison))
{ }
{ }
/// <summary>
/// Attribute for filtering messages where the text contains the specified content.
/// </summary>
/// <param name="content">The string that the message text should contain</param>
/// <param name="comparison">The string comparison type</param>
public class TextContainsAttribute(string content, StringComparison comparison = StringComparison.InvariantCulture)
/// <summary>
/// Attribute for filtering messages where the text contains the specified content.
/// </summary>
/// <param name="content">The string that the message text should contain</param>
/// <param name="comparison">The string comparison type</param>
public class TextContainsAttribute(string content, StringComparison comparison = StringComparison.InvariantCulture)
: MessageFilterAttribute(new TextContainsFilter(content, comparison))
{ }
{ }
/// <summary>
/// Attribute for filtering messages where the text equals the specified content.
/// </summary>
/// <param name="content">The string that the message text should equal</param>
/// <param name="comparison">The string comparison type</param>
public class TextEqualsAttribute(string content, StringComparison comparison = StringComparison.InvariantCulture)
/// <summary>
/// Attribute for filtering messages where the text equals the specified content.
/// </summary>
/// <param name="content">The string that the message text should equal</param>
/// <param name="comparison">The string comparison type</param>
public class TextEqualsAttribute(string content, StringComparison comparison = StringComparison.InvariantCulture)
: MessageFilterAttribute(new TextEqualsFilter(content, comparison))
{ }
{ }
/// <summary>
/// Attribute for filtering messages that contain any non-empty text.
/// </summary>
public class HasTextAttribute()
/// <summary>
/// Attribute for filtering messages that contain any non-empty text.
/// </summary>
public class HasTextAttribute()
: MessageFilterAttribute(new TextNotNullOrEmptyFilter())
{ }
{ }
/// <summary>
/// Attribute for filtering messages where the text contains a 'word'.
/// 'Word' must be a separate member of the text, and not have any alphabetic characters next to it.
/// </summary>
/// <param name="word"></param>
/// <param name="comparison"></param>
/// <param name="startIndex"></param>
public class TextContainsWordAttribute(string word, StringComparison comparison = StringComparison.InvariantCulture, int startIndex = 0)
/// <summary>
/// Attribute for filtering messages where the text contains a 'word'.
/// 'Word' must be a separate member of the text, and not have any alphabetic characters next to it.
/// </summary>
/// <param name="word"></param>
/// <param name="comparison"></param>
/// <param name="startIndex"></param>
public class TextContainsWordAttribute(string word, StringComparison comparison = StringComparison.InvariantCulture, int startIndex = 0)
: MessageFilterAttribute(new TextContainsWordFilter(word, comparison, startIndex))
{ }
}
{ }
@@ -1,15 +1,15 @@
using Telegram.Bot.Types.Enums;
namespace Telegrator.Annotations
namespace Telegrator.Annotations;
/// <summary>
/// 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>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MightAwaitAttribute : Attribute
{
/// <summary>
/// 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>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MightAwaitAttribute : Attribute
{
private readonly UpdateType[] _updateTypes;
/// <summary>
@@ -23,5 +23,4 @@ namespace Telegrator.Annotations
/// <param name="updateTypes"></param>
public MightAwaitAttribute(params UpdateType[] updateTypes)
=> _updateTypes = updateTypes;
}
}
@@ -2,14 +2,14 @@
using Telegram.Bot.Types.Enums;
using Telegrator.Filters;
namespace Telegrator.Annotations
namespace Telegrator.Annotations;
/// <summary>
/// Attribute for filtering message with command "start" in bot's private chats.
/// Allows handlers to respond to "welcome" bot commands.
/// </summary>
public class WelcomeAttribute : MessageFilterAttribute
{
/// <summary>
/// Attribute for filtering message with command "start" in bot's private chats.
/// Allows handlers to respond to "welcome" bot commands.
/// </summary>
public class WelcomeAttribute : MessageFilterAttribute
{
/// <summary>
/// Creates new instance of <see cref="WelcomeAttribute"/>
/// </summary>
@@ -19,5 +19,4 @@ namespace Telegrator.Annotations
new CommandAlliasFilter("start"),
Filter<Message>.If(ctx => !onlyFirst || ctx.Input.Id == 0))
{ }
}
}
@@ -1,16 +1,15 @@
namespace Telegrator.Aspects
namespace Telegrator.Aspects;
/// <summary>
/// Attribute that specifies a post-execution processor to be executed after the handler.
/// The processor type must implement <see cref="IPostProcessor"/> interface.
/// </summary>
/// <typeparam name="T">The type of the post-processor that implements <see cref="IPostProcessor"/>.</typeparam>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class AfterExecutionAttribute<T> : Attribute where T : IPostProcessor
{
/// <summary>
/// Attribute that specifies a post-execution processor to be executed after the handler.
/// The processor type must implement <see cref="IPostProcessor"/> interface.
/// </summary>
/// <typeparam name="T">The type of the post-processor that implements <see cref="IPostProcessor"/>.</typeparam>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class AfterExecutionAttribute<T> : Attribute where T : IPostProcessor
{
/// <summary>
/// Gets the type of the post-processor.
/// </summary>
public Type ProcessorType => typeof(T);
}
}
@@ -1,16 +1,15 @@
namespace Telegrator.Aspects
namespace Telegrator.Aspects;
/// <summary>
/// Attribute that specifies a pre-execution processor to be executed before the handler.
/// The processor type must implement <see cref="IPreProcessor"/> interface.
/// </summary>
/// <typeparam name="T">The type of the pre-processor that implements <see cref="IPreProcessor"/>.</typeparam>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class BeforeExecutionAttribute<T> : Attribute where T : IPreProcessor
{
/// <summary>
/// Attribute that specifies a pre-execution processor to be executed before the handler.
/// The processor type must implement <see cref="IPreProcessor"/> interface.
/// </summary>
/// <typeparam name="T">The type of the pre-processor that implements <see cref="IPreProcessor"/>.</typeparam>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class BeforeExecutionAttribute<T> : Attribute where T : IPreProcessor
{
/// <summary>
/// Gets the type of the pre-processor.
/// </summary>
public Type ProcessorType => typeof(T);
}
}
+7 -8
View File
@@ -1,13 +1,13 @@
using Telegrator.Core.Handlers;
namespace Telegrator.Aspects
namespace Telegrator.Aspects;
/// <summary>
/// Interface for post-execution processors that are executed after handler execution.
/// Implement this interface to add cross-cutting concerns like logging, cleanup, or metrics collection.
/// </summary>
public interface IPostProcessor
{
/// <summary>
/// Interface for post-execution processors that are executed after handler execution.
/// Implement this interface to add cross-cutting concerns like logging, cleanup, or metrics collection.
/// </summary>
public interface IPostProcessor
{
/// <summary>
/// Executes after the handler's main execution logic.
/// </summary>
@@ -15,5 +15,4 @@ namespace Telegrator.Aspects
/// <param name="cancellationToken"></param>
/// <returns>A <see cref="Result"/> indicating the final execution result.</returns>
public Task<Result> AfterExecution(IHandlerContainer container, CancellationToken cancellationToken);
}
}
+7 -8
View File
@@ -1,13 +1,13 @@
using Telegrator.Core.Handlers;
namespace Telegrator.Aspects
namespace Telegrator.Aspects;
/// <summary>
/// Interface for pre-execution processors that are executed before handler execution.
/// Implement this interface to add cross-cutting concerns like validation, logging, or authorization.
/// </summary>
public interface IPreProcessor
{
/// <summary>
/// Interface for pre-execution processors that are executed before handler execution.
/// Implement this interface to add cross-cutting concerns like validation, logging, or authorization.
/// </summary>
public interface IPreProcessor
{
/// <summary>
/// Executes before the handler's main execution logic.
/// </summary>
@@ -15,5 +15,4 @@ namespace Telegrator.Aspects
/// <param name="cancellationToken"></param>
/// <returns>A <see cref="Result"/> indicating whether execution should continue or be stopped.</returns>
public Task<Result> BeforeExecution(IHandlerContainer container, CancellationToken cancellationToken = default);
}
}
@@ -3,14 +3,14 @@ using Telegram.Bot.Types.Enums;
using Telegrator.Core.Filters;
using Telegrator.Filters;
namespace Telegrator.Attributes
namespace Telegrator.Attributes;
/// <summary>
/// Reactive way to implement a new <see cref="UpdateFilterAttribute{T}"/> of type <typeparamref name="T"/>
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class FilterAnnotation<T> : UpdateFilterAttribute<T>, IFilter<T>, INamedFilter where T : class
{
/// <summary>
/// Reactive way to implement a new <see cref="UpdateFilterAttribute{T}"/> of type <typeparamref name="T"/>
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class FilterAnnotation<T> : UpdateFilterAttribute<T>, IFilter<T>, INamedFilter where T : class
{
/// <inheritdoc/>
public virtual bool IsCollectible { get; } = false;
@@ -35,5 +35,4 @@ namespace Telegrator.Attributes
/// <inheritdoc/>
public abstract bool CanPass(FilterExecutionContext<T> context);
}
}
+8 -9
View File
@@ -1,12 +1,12 @@
namespace Telegrator.Attributes
namespace Telegrator.Attributes;
/// <summary>
/// Enumeration of filter modifiers that can be applied to update filters.
/// Defines how filters should be combined and applied in filter chains.
/// </summary>
[Flags]
public enum FilterModifier
{
/// <summary>
/// Enumeration of filter modifiers that can be applied to update filters.
/// Defines how filters should be combined and applied in filter chains.
/// </summary>
[Flags]
public enum FilterModifier
{
/// <summary>
/// No modifier applied. Filter is applied as-is.
/// </summary>
@@ -21,5 +21,4 @@
/// NOT modifier. The inverse of this filter should match.
/// </summary>
Not = 4,
}
}
@@ -3,15 +3,15 @@ using Telegrator.Core.Attributes;
using Telegrator.Core.Filters;
using Telegrator.Filters;
namespace Telegrator.Attributes
namespace Telegrator.Attributes;
/// <summary>
/// Abstract base attribute for defining update filters for a specific type of update target.
/// Provides logic for filter composition, modifier processing, and target extraction.
/// </summary>
/// <typeparam name="T">The type of the update target to filter (e.g., Message, Update).</typeparam>
public abstract class UpdateFilterAttribute<T> : UpdateFilterAttributeBase where T : class
{
/// <summary>
/// Abstract base attribute for defining update filters for a specific type of update target.
/// Provides logic for filter composition, modifier processing, and target extraction.
/// </summary>
/// <typeparam name="T">The type of the update target to filter (e.g., Message, Update).</typeparam>
public abstract class UpdateFilterAttribute<T> : UpdateFilterAttributeBase where T : class
{
/// <summary>
/// Gets the compiled anonymous filter for this attribute.
/// </summary>
@@ -81,5 +81,4 @@ namespace Telegrator.Attributes
/// <param name="update">The Telegram update</param>
/// <returns>The target object to filter, or null if not applicable</returns>
public abstract T? GetFilterringTarget(Update update);
}
}
@@ -2,15 +2,15 @@
using Telegrator.Core.Attributes;
using Telegrator.Core.Handlers;
namespace Telegrator.Attributes
namespace Telegrator.Attributes;
/// <summary>
/// Abstract base attribute for marking update handler classes.
/// Provides a type-safe way to associate handler types with specific update types and importance settings.
/// </summary>
/// <typeparam name="T">The type of the update handler that this attribute is applied to.</typeparam>
public abstract class UpdateHandlerAttribute<T> : UpdateHandlerAttributeBase where T : UpdateHandlerBase
{
/// <summary>
/// Abstract base attribute for marking update handler classes.
/// Provides a type-safe way to associate handler types with specific update types and importance settings.
/// </summary>
/// <typeparam name="T">The type of the update handler that this attribute is applied to.</typeparam>
public abstract class UpdateHandlerAttribute<T> : UpdateHandlerAttributeBase where T : UpdateHandlerBase
{
/// <summary>
/// Initializes new instance of <see cref="UpdateHandlerAttribute{T}"/>
/// </summary>
@@ -42,5 +42,4 @@ namespace Telegrator.Attributes
/// <param name="importance">The importance level for this handler</param>
protected UpdateHandlerAttribute(Type[] types, UpdateType updateType, int importance)
: base([.. types, typeof(T)], updateType, importance) { }
}
}
@@ -5,14 +5,14 @@ using Telegrator.Core.Filters;
using Telegrator.Core.Handlers;
using Telegrator.Filters;
namespace Telegrator.Core.Attributes
namespace Telegrator.Core.Attributes;
/// <summary>
/// Defines the <see cref="IFilter{T}"/> to <see cref="Update"/> validation for entry into execution of the <see cref="UpdateHandlerBase"/>
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public abstract class UpdateFilterAttributeBase : Attribute
{
/// <summary>
/// Defines the <see cref="IFilter{T}"/> to <see cref="Update"/> validation for entry into execution of the <see cref="UpdateHandlerBase"/>
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public abstract class UpdateFilterAttributeBase : Attribute
{
/// <summary>
/// Gets the <see cref="UpdateType"/>'s that <see cref="UpdateHandlerBase"/> processing
/// </summary>
@@ -43,5 +43,4 @@ namespace Telegrator.Core.Attributes
/// <param name="previous"></param>
/// <returns></returns>
public abstract bool ProcessModifiers(UpdateFilterAttributeBase? previous);
}
}
@@ -4,14 +4,14 @@ using Telegrator.Core.Descriptors;
using Telegrator.Core.Filters;
using Telegrator.Core.Handlers;
namespace Telegrator.Core.Attributes
namespace Telegrator.Core.Attributes;
/// <summary>
/// Defines the <see cref="UpdateType"/>'s and validator (<see cref="IFilter{T}"/>) of the <see cref="Update"/> that <see cref="UpdateHandlerBase"/> will process
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public abstract class UpdateHandlerAttributeBase : Attribute, IFilter<Update>
{
/// <summary>
/// Defines the <see cref="UpdateType"/>'s and validator (<see cref="IFilter{T}"/>) of the <see cref="Update"/> that <see cref="UpdateHandlerBase"/> will process
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public abstract class UpdateHandlerAttributeBase : Attribute, IFilter<Update>
{
/// <inheritdoc/>
public bool IsCollectible => GetType().HasPublicProperties();
@@ -78,5 +78,4 @@ namespace Telegrator.Core.Attributes
/// <param name="context">The filter execution context containing the update to validate.</param>
/// <returns>True if the update passes validation; otherwise, false.</returns>
public abstract bool CanPass(FilterExecutionContext<Update> context);
}
}
@@ -7,14 +7,14 @@ using Telegrator.Core.Handlers;
using Telegrator.Handlers;
using Telegrator.Handlers.Building;
namespace Telegrator.Core.Descriptors
namespace Telegrator.Core.Descriptors;
/// <summary>
/// Descriptor for creating handlers from methods
/// </summary>
/// <typeparam name="TUpdate"></typeparam>
public class MethodHandlerDescriptor<TUpdate> : HandlerDescriptor where TUpdate : class
{
/// <summary>
/// Descriptor for creating handlers from methods
/// </summary>
/// <typeparam name="TUpdate"></typeparam>
public class MethodHandlerDescriptor<TUpdate> : HandlerDescriptor where TUpdate : class
{
private readonly MethodInfo Method;
/// <summary>
@@ -66,5 +66,4 @@ namespace Telegrator.Core.Descriptors
}
}
}
}
}
@@ -4,13 +4,13 @@ using Telegrator.Core.Filters;
using Telegrator.Core.Handlers;
using Telegrator.Core.States;
namespace Telegrator.Core.Descriptors
namespace Telegrator.Core.Descriptors;
/// <summary>
/// Contains information about a described handler, including its context, client, and execution logic.
/// </summary>
public class DescribedHandlerDescriptor
{
/// <summary>
/// Contains information about a described handler, including its context, client, and execution logic.
/// </summary>
public class DescribedHandlerDescriptor
{
private readonly ManualResetEventSlim ResetEvent = new ManualResetEventSlim(false);
/// <summary>
@@ -133,5 +133,4 @@ namespace Telegrator.Core.Descriptors
/// <inheritdoc/>
public override string ToString()
=> DisplayString ?? From.HandlerType.Name;
}
}
@@ -1,15 +1,15 @@
using Telegrator.Aspects;
using Telegrator.Core.Handlers;
namespace Telegrator.Core.Descriptors
namespace Telegrator.Core.Descriptors;
/// <summary>
/// Manages the execution of pre and post-execution aspects for a handler.
/// This class coordinates between self-processing (handler implements interfaces)
/// and typed processing (external processor classes).
/// </summary>
public sealed class DescriptorAspectsSet
{
/// <summary>
/// Manages the execution of pre and post-execution aspects for a handler.
/// This class coordinates between self-processing (handler implements interfaces)
/// and typed processing (external processor classes).
/// </summary>
public sealed class DescriptorAspectsSet
{
/// <summary>
/// Gets the type of the external pre-processor, if specified via <see cref="BeforeExecutionAttribute{T}"/>.
/// </summary>
@@ -76,5 +76,4 @@ namespace Telegrator.Core.Descriptors
return Result.Ok();
}
}
}
@@ -3,13 +3,13 @@ using Telegrator.Core.Filters;
using Telegrator.Handlers.Diagnostics;
using Telegrator.Logging;
namespace Telegrator.Core.Descriptors
namespace Telegrator.Core.Descriptors;
/// <summary>
/// Represents a set of filters for a handler descriptor, including update and state keeper validators.
/// </summary>
public sealed class DescriptorFiltersSet
{
/// <summary>
/// Represents a set of filters for a handler descriptor, including update and state keeper validators.
/// </summary>
public sealed class DescriptorFiltersSet
{
/// <summary>
/// Validator for the update object.
/// </summary>
@@ -141,5 +141,4 @@ namespace Telegrator.Core.Descriptors
return false;
}
}
}
}
@@ -1,12 +1,12 @@
using Telegrator.Core.Attributes;
namespace Telegrator.Core.Descriptors
namespace Telegrator.Core.Descriptors;
/// <summary>
/// Represents an indexer for handler descriptors, containing importance and priority information.
/// </summary>
public readonly struct DescriptorIndexer(int routerIndex, int importance, int priority) : IComparable<DescriptorIndexer>
{
/// <summary>
/// Represents an indexer for handler descriptors, containing importance and priority information.
/// </summary>
public readonly struct DescriptorIndexer(int routerIndex, int importance, int priority) : IComparable<DescriptorIndexer>
{
/// <summary>
/// Index of this descriptor when it was added to router
/// </summary>
@@ -84,5 +84,4 @@ namespace Telegrator.Core.Descriptors
{
return string.Format("(Ix: {0,2}, Im: {1,2}, Pr: {2,2})", RouterIndex, Importance, Priority);
}
}
}
@@ -4,13 +4,13 @@ using Telegrator.Core.Attributes;
using Telegrator.Core.Filters;
using Telegrator.Core.Handlers;
namespace Telegrator.Core.Descriptors
namespace Telegrator.Core.Descriptors;
/// <summary>
/// Specifies the type of handler descriptor.
/// </summary>
public enum DescriptorType
{
/// <summary>
/// Specifies the type of handler descriptor.
/// </summary>
public enum DescriptorType
{
/// <summary>
/// General handler descriptor.
/// </summary>
@@ -30,13 +30,13 @@ namespace Telegrator.Core.Descriptors
/// Singleton handler descriptor (single instance).
/// </summary>
Singleton
}
}
/// <summary>
/// Describes a handler, its type, filters, and instantiation logic.
/// </summary>
public class HandlerDescriptor
{
/// <summary>
/// Describes a handler, its type, filters, and instantiation logic.
/// </summary>
public class HandlerDescriptor
{
/// <summary>
/// The type of the descriptor.
/// </summary>
@@ -471,5 +471,4 @@ namespace Telegrator.Core.Descriptors
/// <inheritdoc/>
public override string ToString()
=> DisplayString ?? HandlerType.Name;
}
}
@@ -2,13 +2,13 @@
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
namespace Telegrator.Core.Descriptors
namespace Telegrator.Core.Descriptors;
/// <summary>
/// The collection containing the <see cref="HandlerDescriptor"/>'s. Used to route <see cref="Update"/>'s in <see cref="IHandlersProvider"/>
/// </summary>
public sealed class HandlerDescriptorList : IEnumerable<HandlerDescriptor>
{
/// <summary>
/// The collection containing the <see cref="HandlerDescriptor"/>'s. Used to route <see cref="Update"/>'s in <see cref="IHandlersProvider"/>
/// </summary>
public sealed class HandlerDescriptorList : IEnumerable<HandlerDescriptor>
{
private readonly object _lock = new object();
private readonly SortedList<DescriptorIndexer, HandlerDescriptor> _innerCollection;
private readonly TelegratorOptions? _options;
@@ -155,5 +155,4 @@ namespace Telegrator.Core.Descriptors
{
return _innerCollection.Values.GetEnumerator();
}
}
}
@@ -7,13 +7,13 @@ using Telegrator.Aspects;
using Telegrator.Core.Attributes;
using Telegrator.Core.Filters;
namespace Telegrator.Core.Descriptors
namespace Telegrator.Core.Descriptors;
/// <summary>
/// Provides methods for inspecting handler types and retrieving their attributes and filters.
/// </summary>
public static class HandlerInspector
{
/// <summary>
/// Provides methods for inspecting handler types and retrieving their attributes and filters.
/// </summary>
public static class HandlerInspector
{
/// <summary>
/// Gets handler's display name
/// </summary>
@@ -95,5 +95,4 @@ namespace Telegrator.Core.Descriptors
Type? typedPost = handlerType.GetCustomAttribute(typeof(AfterExecutionAttribute<>))?.GetType().GetGenericArguments()[0];
return new DescriptorAspectsSet(typedPre, typedPost);
}
}
}
@@ -2,13 +2,13 @@
using Telegrator.Filters;
using Telegrator.Logging;
namespace Telegrator.Core.Filters
namespace Telegrator.Core.Filters;
/// <summary>
/// Represents a compiled filter that applies a set of filters to an anonymous target type.
/// </summary>
public class AnonymousCompiledFilter : Filter<Update>, INamedFilter
{
/// <summary>
/// Represents a compiled filter that applies a set of filters to an anonymous target type.
/// </summary>
public class AnonymousCompiledFilter : Filter<Update>, INamedFilter
{
private readonly Func<FilterExecutionContext<Update>, object, bool> FilterAction;
private readonly Func<Update, object?> GetFilterringTarget;
private readonly string _name;
@@ -105,5 +105,4 @@ namespace Telegrator.Core.Filters
return false;
}
}
}
}
@@ -2,13 +2,13 @@
using Telegrator.Filters;
using Telegrator.Logging;
namespace Telegrator.Core.Filters
namespace Telegrator.Core.Filters;
/// <summary>
/// Represents a filter that applies a filter action to an anonymous target type extracted from an update.
/// </summary>
public class AnonymousTypeFilter : Filter<Update>, INamedFilter
{
/// <summary>
/// Represents a filter that applies a filter action to an anonymous target type extracted from an update.
/// </summary>
public class AnonymousTypeFilter : Filter<Update>, INamedFilter
{
private static readonly Type[] IgnoreLog = [typeof(CompiledFilter<>), typeof(AnonymousCompiledFilter), typeof(AnonymousTypeFilter)];
private readonly Func<FilterExecutionContext<Update>, object, bool> FilterAction;
@@ -106,5 +106,4 @@ namespace Telegrator.Core.Filters
return false;
}
}
}
}
@@ -1,14 +1,14 @@
using Telegrator.Filters;
using Telegrator.Logging;
namespace Telegrator.Core.Filters
namespace Telegrator.Core.Filters;
/// <summary>
/// Represents a filter that composes multiple filters and passes only if all of them pass.
/// </summary>
/// <typeparam name="T">The type of the input for the filter.</typeparam>
public class CompiledFilter<T> : Filter<T>, INamedFilter where T : class
{
/// <summary>
/// Represents a filter that composes multiple filters and passes only if all of them pass.
/// </summary>
/// <typeparam name="T">The type of the input for the filter.</typeparam>
public class CompiledFilter<T> : Filter<T>, INamedFilter where T : class
{
private readonly IFilter<T>[] Filters;
private readonly string _name;
@@ -60,5 +60,4 @@ namespace Telegrator.Core.Filters
return true;
}
}
}
@@ -1,12 +1,12 @@
using System.Collections;
namespace Telegrator.Core.Filters
namespace Telegrator.Core.Filters;
/// <summary>
/// The list containing filters worked out during Polling to further obtain additional filtering information
/// </summary>
public class CompletedFiltersList : IEnumerable<IFilterCollectable>
{
/// <summary>
/// The list containing filters worked out during Polling to further obtain additional filtering information
/// </summary>
public class CompletedFiltersList : IEnumerable<IFilterCollectable>
{
private readonly List<IFilterCollectable> CompletedFilters = [];
/// <summary>
@@ -82,5 +82,4 @@ namespace Telegrator.Core.Filters
/// <inheritdoc/>
IEnumerator IEnumerable.GetEnumerator() => CompletedFilters.GetEnumerator();
}
}
@@ -1,14 +1,14 @@
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
namespace Telegrator.Core.Filters
namespace Telegrator.Core.Filters;
/// <summary>
/// Represents the context for filter execution, including update, input, and additional data.
/// </summary>
/// <typeparam name="T">The type of the input for the filter.</typeparam>
public class FilterExecutionContext<T> where T : class
{
/// <summary>
/// Represents the context for filter execution, including update, input, and additional data.
/// </summary>
/// <typeparam name="T">The type of the input for the filter.</typeparam>
public class FilterExecutionContext<T> where T : class
{
/// <summary>
/// Gets the <see cref="ITelegramBotInfo"/> for the current context.
/// </summary>
@@ -82,5 +82,4 @@ namespace Telegrator.Core.Filters
/// <returns>A new <see cref="FilterExecutionContext{C}"/> instance.</returns>
public FilterExecutionContext<C> CreateChild<C>(C input) where C : class
=> new FilterExecutionContext<C>(UpdateRouter, BotInfo, Update, input, Data, CompletedFilters);
}
}
+32 -21
View File
@@ -1,39 +1,50 @@
namespace Telegrator.Core.Filters
namespace Telegrator.Core.Filters;
/// <summary>
/// Interface for filters that have a name for identification and debugging purposes.
/// </summary>
public interface INamedFilter
{
/// <summary>
/// Interface for filters that have a name for identification and debugging purposes.
/// </summary>
public interface INamedFilter
{
/// <summary>
/// Gets the name of the filter.
/// </summary>
public string Name { get; }
}
}
/// <summary>
/// Interface for filters that can be collected into a completed filters list.
/// Provides information about whether a filter should be tracked during execution.
/// </summary>
public interface IFilterCollectable
{
/// <summary>
/// Interface for filters that can be collected into a completed filters list.
/// Provides information about whether a filter should be tracked during execution.
/// </summary>
public interface IFilterCollectable
{
/// <summary>
/// Gets if filter can be collected to <see cref="CompletedFiltersList"/>
/// </summary>
public bool IsCollectible { get; }
}
}
/// <summary>
/// Represents a filter for a specific update type.
/// </summary>
/// <typeparam name="T">The type of the update to filter.</typeparam>
public interface IFilter<T> : IFilterCollectable where T : class
{
/// <summary>
/// Represents a filter for a specific update type.
/// </summary>
/// <typeparam name="T">The type of the update to filter.</typeparam>
public interface IFilter<T> : IFilterCollectable where T : class
{
/// <summary>
/// Determines whether the filter can pass for the given context.
/// </summary>
/// <param name="info">The filter execution context.</param>
/// <returns>True if the filter passes; otherwise, false.</returns>
public bool CanPass(FilterExecutionContext<T> info);
}
}
/// <summary>
/// Represents a filter that joins multiple filters together.
/// </summary>
/// <typeparam name="T">The type of the input for the filter.</typeparam>
public interface IJoinedFilter<T> : IFilter<T> where T : class
{
/// <summary>
/// Gets the array of joined filters.
/// </summary>
public IFilter<T>[] Filters { get; }
}
@@ -1,14 +0,0 @@
namespace Telegrator.Core.Filters
{
/// <summary>
/// Represents a filter that joins multiple filters together.
/// </summary>
/// <typeparam name="T">The type of the input for the filter.</typeparam>
public interface IJoinedFilter<T> : IFilter<T> where T : class
{
/// <summary>
/// Gets the array of joined filters.
/// </summary>
public IFilter<T>[] Filters { get; }
}
}
@@ -6,13 +6,13 @@ using Telegrator.Core.Filters;
using Telegrator.Core.States;
using Telegrator.Handlers;
namespace Telegrator.Core.Handlers
namespace Telegrator.Core.Handlers;
/// <summary>
/// Abstract handler for Telegram updates of type <typeparamref name="TUpdate"/>.
/// </summary>
public abstract class AbstractUpdateHandler<TUpdate> : UpdateHandlerBase, IHandlerContainerFactory, IAbstractUpdateHandler<TUpdate> where TUpdate : class
{
/// <summary>
/// Abstract handler for Telegram updates of type <typeparamref name="TUpdate"/>.
/// </summary>
public abstract class AbstractUpdateHandler<TUpdate> : UpdateHandlerBase, IHandlerContainerFactory, IAbstractUpdateHandler<TUpdate> where TUpdate : class
{
/// <summary>
/// Handler container for the current update.
/// </summary>
@@ -92,5 +92,4 @@ namespace Telegrator.Core.Handlers
/// <param name="cancellation">Cancellation token.</param>
/// <returns>A task representing the asynchronous operation.</returns>
public abstract Task<Result> Execute(IHandlerContainer<TUpdate> container, CancellationToken cancellation);
}
}
@@ -6,15 +6,15 @@ using Telegrator.Core.Descriptors;
using Telegrator.Core.Filters;
using Telegrator.Handlers;
namespace Telegrator.Core.Handlers
namespace Telegrator.Core.Handlers;
/// <summary>
/// Abstract base class for handlers that support branching execution based on different methods.
/// Allows multiple handler methods to be defined in a single class, each with its own filters.
/// </summary>
/// <typeparam name="TUpdate">The type of update being handled.</typeparam>
public abstract class BranchingUpdateHandler<TUpdate> : AbstractUpdateHandler<TUpdate>, IHandlerContainerFactory, ICustomDescriptorsProvider where TUpdate : class
{
/// <summary>
/// Abstract base class for handlers that support branching execution based on different methods.
/// Allows multiple handler methods to be defined in a single class, each with its own filters.
/// </summary>
/// <typeparam name="TUpdate">The type of update being handled.</typeparam>
public abstract class BranchingUpdateHandler<TUpdate> : AbstractUpdateHandler<TUpdate>, IHandlerContainerFactory, ICustomDescriptorsProvider where TUpdate : class
{
/// <summary>
/// The method info for the current branch being executed.
/// </summary>
@@ -161,5 +161,4 @@ namespace Telegrator.Core.Handlers
};
}
}
}
}
@@ -5,13 +5,13 @@ using Telegrator.Core.Filters;
using Telegrator.Core.States;
using Telegrator.Filters;
namespace Telegrator.Core.Handlers.Building
namespace Telegrator.Core.Handlers.Building;
/// <summary>
/// Base class for building handler descriptors and managing handler filters.
/// </summary>
public abstract class HandlerBuilderBase(Type buildingHandlerType, UpdateType updateType, IHandlersCollection? handlerCollection) : IHandlerBuilder
{
/// <summary>
/// Base class for building handler descriptors and managing handler filters.
/// </summary>
public abstract class HandlerBuilderBase(Type buildingHandlerType, UpdateType updateType, IHandlersCollection? handlerCollection) : IHandlerBuilder
{
private static int HandlerServiceKeyIndex = 0;
/// <summary>
@@ -176,5 +176,4 @@ namespace Telegrator.Core.Handlers.Building
AnonymousCompiledFilter compiledPollingFilter = AnonymousCompiledFilter.Compile(filters, getFilterringTarget);
Filters.Add(compiledPollingFilter);
}
}
}
@@ -1,13 +1,13 @@
using Telegrator.Core.States;
namespace Telegrator.Core.Handlers.Building
namespace Telegrator.Core.Handlers.Building;
/// <summary>
/// Defines a builder for awaiting handler logic for a specific update type.
/// </summary>
/// <typeparam name="TUpdate">The type of update to await.</typeparam>
public interface IAwaiterHandlerBuilder<TUpdate> : IHandlerBuilder where TUpdate : class
{
/// <summary>
/// Defines a builder for awaiting handler logic for a specific update type.
/// </summary>
/// <typeparam name="TUpdate">The type of update to await.</typeparam>
public interface IAwaiterHandlerBuilder<TUpdate> : IHandlerBuilder where TUpdate : class
{
/// <summary>
/// Awaits an update using the specified key resolver and cancellation token.
/// </summary>
@@ -15,5 +15,4 @@ namespace Telegrator.Core.Handlers.Building
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A <see cref="Task{TUpdate}"/> representing the awaited update.</returns>
public Task<TUpdate> Await(IStateKeyResolver keyResolver, CancellationToken cancellationToken = default);
}
}
@@ -2,13 +2,13 @@
using Telegrator.Core.Filters;
using Telegrator.Core.States;
namespace Telegrator.Core.Handlers.Building
namespace Telegrator.Core.Handlers.Building;
/// <summary>
/// Defines builder actions for configuring handler builders.
/// </summary>
public interface IHandlerBuilder
{
/// <summary>
/// Defines builder actions for configuring handler builders.
/// </summary>
public interface IHandlerBuilder
{
/// <summary>
/// Sets the update validating action for the handler.
/// </summary>
@@ -82,5 +82,4 @@ namespace Telegrator.Core.Handlers.Building
/// <returns>The builder instance.</returns>
public void AddTargetedFilters<TFilterTarget>(Func<Update, TFilterTarget?> getFilterringTarget, params IFilter<TFilterTarget>[] filters)
where TFilterTarget : class;
}
}
@@ -1,17 +1,16 @@
using Telegrator.Handlers.Building;
namespace Telegrator.Core.Handlers.Building
namespace Telegrator.Core.Handlers.Building;
/// <summary>
/// Defines a builder for regular handler logic for a specific update type.
/// </summary>
/// <typeparam name="TUpdate">The type of update to handle.</typeparam>
public interface IRegularHandlerBuilder<TUpdate> : IHandlerBuilder where TUpdate : class
{
/// <summary>
/// Defines a builder for regular handler logic for a specific update type.
/// </summary>
/// <typeparam name="TUpdate">The type of update to handle.</typeparam>
public interface IRegularHandlerBuilder<TUpdate> : IHandlerBuilder where TUpdate : class
{
/// <summary>
/// Builds the handler logic using the specified execution delegate.
/// </summary>
/// <param name="executeHandler">The delegate to execute the handler logic.</param>
public IHandlersCollection Build(AbstractHandlerAction<TUpdate> executeHandler);
}
}
@@ -1,20 +1,20 @@
using Telegram.Bot.Types;
using Telegrator.Core.Filters;
namespace Telegrator.Core.Handlers.Building
{
/// <summary>
/// Delegate for validating an update in a filter context.
/// </summary>
/// <param name="context">The filter execution context.</param>
/// <returns>True if the update is valid; otherwise, false.</returns>
public delegate bool UpdateValidateAction(FilterExecutionContext<Update> context);
namespace Telegrator.Core.Handlers.Building;
/// <summary>
/// Filter that uses a delegate to validate updates.
/// </summary>
public class UpdateValidateFilter : IFilter<Update>
{
/// <summary>
/// Delegate for validating an update in a filter context.
/// </summary>
/// <param name="context">The filter execution context.</param>
/// <returns>True if the update is valid; otherwise, false.</returns>
public delegate bool UpdateValidateAction(FilterExecutionContext<Update> context);
/// <summary>
/// Filter that uses a delegate to validate updates.
/// </summary>
public class UpdateValidateFilter : IFilter<Update>
{
/// <summary>
/// Gets a value indicating whether this filter is collectable. Always false for this filter.
/// </summary>
@@ -37,5 +37,4 @@ namespace Telegrator.Core.Handlers.Building
/// <returns>True if the filter passes; otherwise, false.</returns>
public bool CanPass(FilterExecutionContext<Update> info)
=> UpdateValidateAction.Invoke(info);
}
}
@@ -3,13 +3,13 @@ using Telegram.Bot.Types;
using Telegrator.Core.Filters;
using Telegrator.Core.States;
namespace Telegrator.Core.Handlers
namespace Telegrator.Core.Handlers;
/// <summary>
/// Represents an empty handler container that throws <see cref="NotImplementedException"/> for all members.
/// </summary>
public class EmptyHandlerContainer : IHandlerContainer
{
/// <summary>
/// Represents an empty handler container that throws <see cref="NotImplementedException"/> for all members.
/// </summary>
public class EmptyHandlerContainer : IHandlerContainer
{
/// <inheritdoc/>
public Update HandlingUpdate => throw new NotImplementedException();
@@ -27,5 +27,4 @@ namespace Telegrator.Core.Handlers
/// <inheritdoc/>
public IStateStorage StateStorage => throw new NotImplementedException();
}
}
@@ -1,10 +1,10 @@
namespace Telegrator.Core.Handlers
namespace Telegrator.Core.Handlers;
/// <summary>
/// Represents a token that tracks the lifetime of a handler instance.
/// </summary>
public class HandlerLifetimeToken
{
/// <summary>
/// Represents a token that tracks the lifetime of a handler instance.
/// </summary>
public class HandlerLifetimeToken
{
/// <summary>
/// Event triggered when the handler's lifetime has ended.
/// </summary>
@@ -23,5 +23,4 @@
IsEnded = true;
OnLifetimeEnded?.Invoke(this);
}
}
}
@@ -3,14 +3,14 @@ using Telegram.Bot.Types;
using Telegrator.Core.Filters;
using Telegrator.Core.States;
namespace Telegrator.Core.Handlers
namespace Telegrator.Core.Handlers;
/// <summary>
/// Interface for handler containers that provide context and resources for update handlers.
/// Contains all necessary information and services that handlers need during execution.
/// </summary>
public interface IHandlerContainer
{
/// <summary>
/// Interface for handler containers that provide context and resources for update handlers.
/// Contains all necessary information and services that handlers need during execution.
/// </summary>
public interface IHandlerContainer
{
/// <summary>
/// Gets the <see cref="Update"/> being handled.
/// </summary>
@@ -40,5 +40,4 @@ namespace Telegrator.Core.Handlers
/// Gets the <see cref="IStateStorage"/> for state managment.
/// </summary>
public IStateStorage StateStorage { get; }
}
}
@@ -1,18 +1,17 @@
using Telegrator.Core.Descriptors;
namespace Telegrator.Core.Handlers
namespace Telegrator.Core.Handlers;
/// <summary>
/// Factory interface for creating handler containers.
/// Provides a way to create handler containers with specific providers and handler information.
/// </summary>
public interface IHandlerContainerFactory
{
/// <summary>
/// Factory interface for creating handler containers.
/// Provides a way to create handler containers with specific providers and handler information.
/// </summary>
public interface IHandlerContainerFactory
{
/// <summary>
/// Creates a new <see cref="IHandlerContainer"/> for the specified awaiting provider and handler info.
/// </summary>
/// <param name="handlerInfo">The <see cref="DescribedHandlerDescriptor"/> for the handler.</param>
/// <returns>A new <see cref="IHandlerContainer"/> instance.</returns>
public IHandlerContainer CreateContainer(DescribedHandlerDescriptor handlerInfo);
}
}
@@ -4,13 +4,13 @@ using Telegram.Bot.Types.Enums;
using Telegrator.Core.Descriptors;
using Telegrator.Handlers.Diagnostics;
namespace Telegrator.Core.Handlers
namespace Telegrator.Core.Handlers;
/// <summary>
/// Base class for update handlers, providing execution and lifetime management for Telegram updates.
/// </summary>
public abstract class UpdateHandlerBase(UpdateType handlingUpdateType) : IUpdateHandlerBase
{
/// <summary>
/// Base class for update handlers, providing execution and lifetime management for Telegram updates.
/// </summary>
public abstract class UpdateHandlerBase(UpdateType handlingUpdateType) : IUpdateHandlerBase
{
/// <summary>
/// Gets the <see cref="UpdateType"/> that this handler processes.
/// </summary>
@@ -178,5 +178,4 @@ namespace Telegrator.Core.Handlers
if (Dispose(true))
GC.SuppressFinalize(this);
}
}
}
+6 -7
View File
@@ -1,17 +1,16 @@
using Telegrator.Core.Descriptors;
namespace Telegrator.Core
namespace Telegrator.Core;
/// <summary>
/// Provider for managing awaiting handlers that can wait for specific update types.
/// </summary>
public interface IAwaitingProvider : IHandlersProvider
{
/// <summary>
/// Provider for managing awaiting handlers that can wait for specific update types.
/// </summary>
public interface IAwaitingProvider : IHandlersProvider
{
/// <summary>
/// Registers the usage of a handler and returns a disposable object to manage its lifetime.
/// </summary>
/// <param name="handlerDescriptor">The <see cref="HandlerDescriptor"/> to use.</param>
/// <returns>An <see cref="IDisposable"/> that manages the handler's usage lifetime.</returns>
public IDisposable UseHandler(HandlerDescriptor handlerDescriptor);
}
}
+7 -8
View File
@@ -1,14 +1,13 @@
namespace Telegrator.Core
namespace Telegrator.Core;
/// <summary>
/// Interface for providers that collect and manage handler collections.
/// Provides access to a collection of handlers for various processing operations.
/// </summary>
public interface ICollectingProvider
{
/// <summary>
/// Interface for providers that collect and manage handler collections.
/// Provides access to a collection of handlers for various processing operations.
/// </summary>
public interface ICollectingProvider
{
/// <summary>
/// Gets the collection of handlers managed by this provider.
/// </summary>
public IHandlersCollection Handlers { get; }
}
}
@@ -1,17 +1,16 @@
using Telegrator.Core.Descriptors;
namespace Telegrator.Core
namespace Telegrator.Core;
/// <summary>
/// Interface for classes that can provide custom handler descriptors.
/// Allows classes to define their own handler description logic beyond the standard reflection-based approach.
/// </summary>
public interface ICustomDescriptorsProvider
{
/// <summary>
/// Interface for classes that can provide custom handler descriptors.
/// Allows classes to define their own handler description logic beyond the standard reflection-based approach.
/// </summary>
public interface ICustomDescriptorsProvider
{
/// <summary>
/// Describes the handlers provided by this class.
/// </summary>
/// <returns>A collection of handler descriptors.</returns>
public IEnumerable<HandlerDescriptor> DescribeHandlers();
}
}
+7 -8
View File
@@ -1,14 +1,14 @@
using Telegram.Bot.Types.Enums;
using Telegrator.Core.Descriptors;
namespace Telegrator.Core
namespace Telegrator.Core;
/// <summary>
/// Collection class for managing handler descriptors organized by update type.
/// Provides functionality for collecting, adding, and organizing handlers.
/// </summary>
public interface IHandlersCollection
{
/// <summary>
/// Collection class for managing handler descriptors organized by update type.
/// Provides functionality for collecting, adding, and organizing handlers.
/// </summary>
public interface IHandlersCollection
{
/// <summary>
/// Gets the collection of <see cref="UpdateType"/>'s allowed by registered handlers
/// </summary>
@@ -37,5 +37,4 @@ namespace Telegrator.Core
/// <param name="descriptor">The handler descriptor to add.</param>
/// <returns>The updated <see cref="IHandlersCollection"/>.</returns>
public IHandlersCollection AddDescriptor(HandlerDescriptor descriptor);
}
}
+8 -9
View File
@@ -1,11 +1,10 @@
namespace Telegrator.Core
{
/// <summary>
/// Combines <see cref="IHandlersCollection"/> and <see cref="IHandlersProvider"/>.
/// Provides functionality of collecting, organizing and resolving handlers instances.
/// </summary>
public interface IHandlersManager : IHandlersCollection, IHandlersProvider
{
namespace Telegrator.Core;
/// <summary>
/// Combines <see cref="IHandlersCollection"/> and <see cref="IHandlersProvider"/>.
/// Provides functionality of collecting, organizing and resolving handlers instances.
/// </summary>
public interface IHandlersManager : IHandlersCollection, IHandlersProvider
{
}
}
+6 -7
View File
@@ -2,13 +2,13 @@
using Telegrator.Core.Descriptors;
using Telegrator.Core.Handlers;
namespace Telegrator.Core
namespace Telegrator.Core;
/// <summary>
/// Provides methods to retrieve and describe handler information for updates.
/// </summary>
public interface IHandlersProvider
{
/// <summary>
/// Provides methods to retrieve and describe handler information for updates.
/// </summary>
public interface IHandlersProvider
{
/// <summary>
/// Gets the collection of <see cref="UpdateType"/>'s allowed by registered handlers
/// </summary>
@@ -36,5 +36,4 @@ namespace Telegrator.Core
/// </summary>
/// <returns>True if the provider is empty; otherwise, false.</returns>
public bool IsEmpty();
}
}
@@ -1,14 +1,14 @@
using Telegram.Bot;
using Telegram.Bot.Polling;
namespace Telegrator.Core
namespace Telegrator.Core;
/// <summary>
/// Interface for handling exceptions that occur during update routing operations.
/// Provides a centralized way to handle and log errors that occur during bot operation.
/// </summary>
public interface IRouterExceptionHandler
{
/// <summary>
/// Interface for handling exceptions that occur during update routing operations.
/// Provides a centralized way to handle and log errors that occur during bot operation.
/// </summary>
public interface IRouterExceptionHandler
{
/// <summary>
/// Handles exceptions that occur during update routing.
/// </summary>
@@ -17,5 +17,4 @@ namespace Telegrator.Core
/// <param name="source">The <see cref="HandleErrorSource"/> indicating the source of the error.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public void HandleException(ITelegramBotClient botClient, Exception exception, HandleErrorSource source, CancellationToken cancellationToken);
}
}
+7 -8
View File
@@ -1,16 +1,15 @@
using Telegram.Bot.Types;
namespace Telegrator.Core
namespace Telegrator.Core;
/// <summary>
/// Interface for providing bot information and metadata.
/// Contains information about the bot user and provides initialization capabilities.
/// </summary>
public interface ITelegramBotInfo
{
/// <summary>
/// Interface for providing bot information and metadata.
/// Contains information about the bot user and provides initialization capabilities.
/// </summary>
public interface ITelegramBotInfo
{
/// <summary>
/// Gets the <see cref="User"/> representing the bot.
/// </summary>
public User User { get; }
}
}
+18 -19
View File
@@ -1,24 +1,24 @@
using Telegrator.Core.Descriptors;
namespace Telegrator.Core
namespace Telegrator.Core;
/// <summary>
/// Represents a delegate for when a handler is enqueued.
/// </summary>
/// <param name="args">The <see cref="DescribedHandlerDescriptor"/> for the enqueued handler.</param>
public delegate void HandlerEnqueued(DescribedHandlerDescriptor args);
/// <summary>
/// Represents a delegate for when a handler is executing.
/// </summary>
/// <param name="args">The <see cref="DescribedHandlerDescriptor"/> for the executing handler.</param>
public delegate void HandlerExecuting(DescribedHandlerDescriptor args);
/// <summary>
/// Provides a pool for managing the execution and queuing of update handlers.
/// </summary>
public interface IUpdateHandlersPool : IDisposable
{
/// <summary>
/// Represents a delegate for when a handler is enqueued.
/// </summary>
/// <param name="args">The <see cref="DescribedHandlerDescriptor"/> for the enqueued handler.</param>
public delegate void HandlerEnqueued(DescribedHandlerDescriptor args);
/// <summary>
/// Represents a delegate for when a handler is executing.
/// </summary>
/// <param name="args">The <see cref="DescribedHandlerDescriptor"/> for the executing handler.</param>
public delegate void HandlerExecuting(DescribedHandlerDescriptor args);
/// <summary>
/// Provides a pool for managing the execution and queuing of update handlers.
/// </summary>
public interface IUpdateHandlersPool : IDisposable
{
/// <summary>
/// Occurs when a handler is enqueued.
/// </summary>
@@ -34,5 +34,4 @@ namespace Telegrator.Core
/// </summary>
/// <param name="handlers">The handlers to enqueue.</param>
public Task Enqueue(params IEnumerable<DescribedHandlerDescriptor> handlers);
}
}
+7 -8
View File
@@ -2,14 +2,14 @@
using Telegrator.Core.Handlers;
using Telegrator.Core.States;
namespace Telegrator.Core
namespace Telegrator.Core;
/// <summary>
/// Interface for update routers that handle incoming updates and manage handler execution.
/// Combines update handling capabilities with polling provider functionality and exception handling.
/// </summary>
public interface IUpdateRouter : IUpdateHandler
{
/// <summary>
/// Interface for update routers that handle incoming updates and manage handler execution.
/// Combines update handling capabilities with polling provider functionality and exception handling.
/// </summary>
public interface IUpdateRouter : IUpdateHandler
{
/// <summary>
/// Gets the <see cref="TelegratorOptions"/> for the router.
/// </summary>
@@ -44,5 +44,4 @@ namespace Telegrator.Core
/// Default hand;er container factory
/// </summary>
public IHandlerContainerFactory? DefaultContainerFactory { get; set; }
}
}
+32 -33
View File
@@ -1,11 +1,11 @@
namespace Telegrator
namespace Telegrator;
/// <summary>
/// Enumeration of dice types supported by Telegram.
/// Used for filtering dice messages and determining dice emoji representations.
/// </summary>
public enum DiceType
{
/// <summary>
/// Enumeration of dice types supported by Telegram.
/// Used for filtering dice messages and determining dice emoji representations.
/// </summary>
public enum DiceType
{
/// <summary>
/// Standard dice (🎲).
/// </summary>
@@ -35,15 +35,15 @@
/// Casino slot machine (🎰).
/// </summary>
Casino
}
}
/// <summary>
/// Flags version of <see cref="Telegram.Bot.Types.Enums.ChatType"/>
/// Type of the <see cref="Telegram.Bot.Types.Chat"/>, from which the message or inline query was sent
/// </summary>
[Flags]
public enum ChatTypeFlags
{
/// <summary>
/// Flags version of <see cref="Telegram.Bot.Types.Enums.ChatType"/>
/// Type of the <see cref="Telegram.Bot.Types.Chat"/>, from which the message or inline query was sent
/// </summary>
[Flags]
public enum ChatTypeFlags
{
/// <summary>
/// Normal one-to-one chat with a user or bot
/// </summary>
@@ -68,14 +68,14 @@
/// Value possible only in <see cref="Telegram.Bot.Types.InlineQuery.ChatType"/>: private chat with the inline query sender
/// </summary>
Sender
}
}
/*
/// <summary>
/// Messages from where this filter was originated
/// </summary>
public enum FilterOrigin
{
/*
/// <summary>
/// Messages from where this filter was originated
/// </summary>
public enum FilterOrigin
{
/// <summary>
/// None, empty filter
/// </summary>
@@ -95,16 +95,16 @@
/// From regular <see cref="Attributes.UpdateFilterAttribute{T}"/>
/// </summary>
Regualr
}
*/
}
*/
/*
/// <summary>
/// Levels of debug writing
/// </summary>
[Flags]
public enum DebugLevel
{
/*
/// <summary>
/// Levels of debug writing
/// </summary>
[Flags]
public enum DebugLevel
{
/// <summary>
/// None to write
/// </summary>
@@ -129,6 +129,5 @@
/// Write debug messages from handlers pool execution
/// </summary>
HandlersPool = 0x8
}
*/
}
*/
+19 -20
View File
@@ -1,38 +1,38 @@
using Telegrator.Core.Descriptors;
namespace Telegrator
namespace Telegrator;
/// <summary>
/// Exception thrown when attempting to modify a frozen collection.
/// </summary>
public class CollectionFrozenException : Exception
{
/// <summary>
/// Exception thrown when attempting to modify a frozen collection.
/// </summary>
public class CollectionFrozenException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="CollectionFrozenException"/> class.
/// </summary>
public CollectionFrozenException()
: base("Can't change a frozen collection.") { }
}
}
/// <summary>
/// Exception thrown when a type is not a valid filter type.
/// </summary>
public class NotFilterTypeException : Exception
{
/// <summary>
/// Exception thrown when a type is not a valid filter type.
/// </summary>
public class NotFilterTypeException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="NotFilterTypeException"/> class.
/// </summary>
/// <param name="type">The type that is not a filter type.</param>
public NotFilterTypeException(Type type)
: base(string.Format("\"{0}\" is not a filter type", type.Name)) { }
}
}
/// <summary>
/// Exception thrown when a handler execution fails.
/// Contains information about the handler and the inner exception.
/// </summary>
public class HandlerFaultedException : Exception
{
/// <summary>
/// Exception thrown when a handler execution fails.
/// Contains information about the handler and the inner exception.
/// </summary>
public class HandlerFaultedException : Exception
{
/// <summary>
/// The handler info associated with the faulted handler.
/// </summary>
@@ -48,5 +48,4 @@ namespace Telegrator
{
HandlerInfo = handlerInfo;
}
}
}
+18 -19
View File
@@ -2,13 +2,13 @@
using Telegram.Bot.Types;
using Telegrator.Core.Filters;
namespace Telegrator.Filters
namespace Telegrator.Filters;
/// <summary>
/// Filter thet checks <see cref="CallbackQuery"/>'s data
/// </summary>
public class CallbackDataFilter : Filter<CallbackQuery>
{
/// <summary>
/// Filter thet checks <see cref="CallbackQuery"/>'s data
/// </summary>
public class CallbackDataFilter : Filter<CallbackQuery>
{
private readonly string _data;
/// <summary>
@@ -25,13 +25,13 @@ namespace Telegrator.Filters
{
return context.Input.Data == _data;
}
}
}
/// <summary>
/// Filter that checks if <see cref="CallbackQuery"/> belongs to a specific message
/// </summary>
public class CallbackInlineIdFilter : Filter<CallbackQuery>
{
/// <summary>
/// Filter that checks if <see cref="CallbackQuery"/> belongs to a specific message
/// </summary>
public class CallbackInlineIdFilter : Filter<CallbackQuery>
{
private readonly string _inlineMessageId;
/// <summary>
@@ -48,13 +48,13 @@ namespace Telegrator.Filters
{
return context.Input.InlineMessageId == _inlineMessageId;
}
}
}
/// <summary>
/// Filters callback queries by matching their data with a regular expression.
/// </summary>
public class CallbackRegexFilter : RegexFilterBase<CallbackQuery>
{
/// <summary>
/// Filters callback queries by matching their data with a regular expression.
/// </summary>
public class CallbackRegexFilter : RegexFilterBase<CallbackQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="CallbackRegexFilter"/> class with a pattern and options.
/// </summary>
@@ -69,5 +69,4 @@ namespace Telegrator.Filters
/// <param name="regex">The regex object.</param>
public CallbackRegexFilter(Regex regex)
: base(clb => clb.Data, regex) { }
}
}
+8 -9
View File
@@ -2,15 +2,15 @@
using Telegrator.Core.Filters;
using Telegrator.Handlers;
namespace Telegrator.Filters
namespace Telegrator.Filters;
/// <summary>
/// Filter that checks if a command matches any of the specified aliases.
/// Requires a <see cref="CommandHandlerAttribute"/> to be applied first to extract the command.
/// </summary>
/// <param name="alliases">The command aliases to check against.</param>
public class CommandAlliasFilter(params string[] alliases) : Filter<Message>
{
/// <summary>
/// Filter that checks if a command matches any of the specified aliases.
/// Requires a <see cref="CommandHandlerAttribute"/> to be applied first to extract the command.
/// </summary>
/// <param name="alliases">The command aliases to check against.</param>
public class CommandAlliasFilter(params string[] alliases) : Filter<Message>
{
/// <summary>
/// Gets the command that was received and extracted by the <see cref="CommandHandlerAttribute"/>.
/// </summary>
@@ -28,5 +28,4 @@ namespace Telegrator.Filters
ReceivedCommand = context.CompletedFilters.Get<CommandHandlerAttribute>(0).ReceivedCommand;
return alliases.Contains(ReceivedCommand, StringComparer.InvariantCultureIgnoreCase);
}
}
}
+59 -60
View File
@@ -3,15 +3,15 @@ using Telegram.Bot.Types;
using Telegrator.Core.Filters;
using Telegrator.Handlers;
namespace Telegrator.Filters
namespace Telegrator.Filters;
/// <summary>
/// Abstract base class for filters that operate on command arguments.
/// Provides functionality to extract and validate command arguments from message text.
/// </summary>
/// <param name="index">The index of the argument to filter (0-based).</param>
public abstract class CommandArgumentFilterBase(int index) : Filter<Message>
{
/// <summary>
/// Abstract base class for filters that operate on command arguments.
/// Provides functionality to extract and validate command arguments from message text.
/// </summary>
/// <param name="index">The index of the argument to filter (0-based).</param>
public abstract class CommandArgumentFilterBase(int index) : Filter<Message>
{
/// <summary>
/// Gets the chosen argument at the specified index.
/// </summary>
@@ -40,14 +40,14 @@ namespace Telegrator.Filters
/// <param name="context">The filter execution context.</param>
/// <returns>True if the filter passes; otherwise, false.</returns>
protected abstract bool CanPassNext(FilterExecutionContext<Message> context);
}
}
/// <summary>
/// Filter that checks if a command has arguments count >= <paramref name="count"/>.
/// </summary>
/// <param name="count"></param>
public class ArgumentCountFilter(int count) : Filter<Message>
{
/// <summary>
/// Filter that checks if a command has arguments count >= <paramref name="count"/>.
/// </summary>
/// <param name="count"></param>
public class ArgumentCountFilter(int count) : Filter<Message>
{
private readonly int Count = count;
/// <inheritdoc/>
@@ -57,16 +57,16 @@ namespace Telegrator.Filters
string[] args = attr.Arguments ??= context.Input.SplitArgs();
return args.Length >= Count;
}
}
}
/// <summary>
/// Filter that checks if a command argument starts with a specified content.
/// </summary>
/// <param name="content">The content to check if the argument starts with.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
/// <param name="index">The index of the argument to check (0-based).</param>
public class ArgumentStartsWithFilter(string content, StringComparison comparison = StringComparison.InvariantCulture, int index = 0) : CommandArgumentFilterBase(index)
{
/// <summary>
/// Filter that checks if a command argument starts with a specified content.
/// </summary>
/// <param name="content">The content to check if the argument starts with.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
/// <param name="index">The index of the argument to check (0-based).</param>
public class ArgumentStartsWithFilter(string content, StringComparison comparison = StringComparison.InvariantCulture, int index = 0) : CommandArgumentFilterBase(index)
{
/// <summary>
/// The content to check if the argument starts with.
/// </summary>
@@ -84,16 +84,16 @@ namespace Telegrator.Filters
/// <returns>True if the argument starts with the specified content; otherwise, false.</returns>
protected override bool CanPassNext(FilterExecutionContext<Message> _)
=> Target.StartsWith(Content, Comparison);
}
}
/// <summary>
/// Filter that checks if a command argument ends with a specified content.
/// </summary>
/// <param name="content">The content to check if the argument ends with.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
/// <param name="index">The index of the argument to check (0-based).</param>
public class ArgumentEndsWithFilter(string content, StringComparison comparison = StringComparison.InvariantCulture, int index = 0) : CommandArgumentFilterBase(index)
{
/// <summary>
/// Filter that checks if a command argument ends with a specified content.
/// </summary>
/// <param name="content">The content to check if the argument ends with.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
/// <param name="index">The index of the argument to check (0-based).</param>
public class ArgumentEndsWithFilter(string content, StringComparison comparison = StringComparison.InvariantCulture, int index = 0) : CommandArgumentFilterBase(index)
{
/// <summary>
/// The content to check if the argument ends with.
/// </summary>
@@ -111,16 +111,16 @@ namespace Telegrator.Filters
/// <returns>True if the argument ends with the specified content; otherwise, false.</returns>
protected override bool CanPassNext(FilterExecutionContext<Message> _)
=> Target.EndsWith(Content, Comparison);
}
}
/// <summary>
/// Filter that checks if a command argument contains a specified content.
/// </summary>
/// <param name="content">The content to check if the argument contains.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
/// <param name="index">The index of the argument to check (0-based).</param>
public class ArgumentContainsFilter(string content, StringComparison comparison = StringComparison.InvariantCulture, int index = 0) : CommandArgumentFilterBase(index)
{
/// <summary>
/// Filter that checks if a command argument contains a specified content.
/// </summary>
/// <param name="content">The content to check if the argument contains.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
/// <param name="index">The index of the argument to check (0-based).</param>
public class ArgumentContainsFilter(string content, StringComparison comparison = StringComparison.InvariantCulture, int index = 0) : CommandArgumentFilterBase(index)
{
/// <summary>
/// The content to check if the argument contains.
/// </summary>
@@ -138,16 +138,16 @@ namespace Telegrator.Filters
/// <returns>True if the argument contains the specified content; otherwise, false.</returns>
protected override bool CanPassNext(FilterExecutionContext<Message> _)
=> Target.IndexOf(Content, Comparison) >= 0;
}
}
/// <summary>
/// Filter that checks if a command argument equals a specified content.
/// </summary>
/// <param name="content">The content to check if the argument equals.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
/// <param name="index">The index of the argument to check (0-based).</param>
public class ArgumentEqualsFilter(string content, StringComparison comparison = StringComparison.InvariantCulture, int index = 0) : CommandArgumentFilterBase(index)
{
/// <summary>
/// Filter that checks if a command argument equals a specified content.
/// </summary>
/// <param name="content">The content to check if the argument equals.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
/// <param name="index">The index of the argument to check (0-based).</param>
public class ArgumentEqualsFilter(string content, StringComparison comparison = StringComparison.InvariantCulture, int index = 0) : CommandArgumentFilterBase(index)
{
/// <summary>
/// The content to check if the argument equals.
/// </summary>
@@ -165,15 +165,15 @@ namespace Telegrator.Filters
/// <returns>True if the argument equals the specified content; otherwise, false.</returns>
protected override bool CanPassNext(FilterExecutionContext<Message> _)
=> Target.Equals(Content, Comparison);
}
}
/// <summary>
/// Filter that checks if a command argument matches a regular expression pattern.
/// </summary>
/// <param name="regex">The regular expression to match against the argument.</param>
/// <param name="index">The index of the argument to check (0-based).</param>
public class ArgumentRegexFilter(Regex regex, int index = 0) : CommandArgumentFilterBase(index)
{
/// <summary>
/// Filter that checks if a command argument matches a regular expression pattern.
/// </summary>
/// <param name="regex">The regular expression to match against the argument.</param>
/// <param name="index">The index of the argument to check (0-based).</param>
public class ArgumentRegexFilter(Regex regex, int index = 0) : CommandArgumentFilterBase(index)
{
private readonly Regex _regex = regex;
/// <summary>
@@ -201,5 +201,4 @@ namespace Telegrator.Filters
Match = _regex.Match(Target);
return Match.Success;
}
}
}
+28 -29
View File
@@ -2,14 +2,14 @@
using Telegram.Bot.Types;
using Telegrator.Core.Filters;
namespace Telegrator.Filters
namespace Telegrator.Filters;
/// <summary>
/// Abstract base class for filters that operate based on the current environment.
/// Provides functionality to detect debug vs release environments.
/// </summary>
public abstract class EnvironmentFilter : Filter<Update>
{
/// <summary>
/// Abstract base class for filters that operate based on the current environment.
/// Provides functionality to detect debug vs release environments.
/// </summary>
public abstract class EnvironmentFilter : Filter<Update>
{
/// <summary>
/// Gets a value indicating whether the current environment is debug mode.
/// This is set during static initialization based on the DEBUG conditional compilation symbol.
@@ -28,13 +28,13 @@ namespace Telegrator.Filters
[Conditional("DEBUG")]
private static void SetIsCurrentEnvDebug()
=> IsCurrentEnvDebug = true;
}
}
/// <summary>
/// Filter that only passes in debug environment builds.
/// </summary>
public class IsDebugEnvironmentFilter() : EnvironmentFilter
{
/// <summary>
/// Filter that only passes in debug environment builds.
/// </summary>
public class IsDebugEnvironmentFilter() : EnvironmentFilter
{
/// <summary>
/// Checks if the current environment is debug mode.
/// </summary>
@@ -42,13 +42,13 @@ namespace Telegrator.Filters
/// <returns>True if the current environment is debug mode; otherwise, false.</returns>
public override bool CanPass(FilterExecutionContext<Update> _)
=> IsCurrentEnvDebug;
}
}
/// <summary>
/// Filter that only passes in release environment builds.
/// </summary>
public class IsReleaseEnvironmentFilter() : EnvironmentFilter
{
/// <summary>
/// Filter that only passes in release environment builds.
/// </summary>
public class IsReleaseEnvironmentFilter() : EnvironmentFilter
{
/// <summary>
/// Checks if the current environment is release mode.
/// </summary>
@@ -56,16 +56,16 @@ namespace Telegrator.Filters
/// <returns>True if the current environment is release mode; otherwise, false.</returns>
public override bool CanPass(FilterExecutionContext<Update> _)
=> !IsCurrentEnvDebug;
}
}
/// <summary>
/// Filter that checks environment variable values.
/// </summary>
/// <param name="variable">The environment variable name to check.</param>
/// <param name="value">The expected value of the environment variable (optional).</param>
/// <param name="comparison">The string comparison type to use for value matching.</param>
public class EnvironmentVariableFilter(string variable, string? value, StringComparison comparison) : Filter<Update>
{
/// <summary>
/// Filter that checks environment variable values.
/// </summary>
/// <param name="variable">The environment variable name to check.</param>
/// <param name="value">The expected value of the environment variable (optional).</param>
/// <param name="comparison">The string comparison type to use for value matching.</param>
public class EnvironmentVariableFilter(string variable, string? value, StringComparison comparison) : Filter<Update>
{
/// <summary>
/// The environment variable name to check.
/// </summary>
@@ -121,5 +121,4 @@ namespace Telegrator.Filters
return envValue.Equals(_value, _comparison);
}
}
}
+28 -29
View File
@@ -1,13 +1,13 @@
using Telegrator.Core.Filters;
namespace Telegrator.Filters
namespace Telegrator.Filters;
/// <summary>
/// Base class for filters, providing logical operations and collectability.
/// </summary>
/// <typeparam name="T">The type of the input for the filter.</typeparam>
public abstract class Filter<T> : IFilter<T> where T : class
{
/// <summary>
/// Base class for filters, providing logical operations and collectability.
/// </summary>
/// <typeparam name="T">The type of the input for the filter.</typeparam>
public abstract class Filter<T> : IFilter<T> where T : class
{
/// <summary>
/// Creates a filter from a function.
/// </summary>
@@ -81,25 +81,25 @@ namespace Telegrator.Filters
/// </summary>
/// <param name="filter"></param>
public static implicit operator Filter<T>(Func<FilterExecutionContext<T>, bool> filter) => Filter<T>.If(filter);
}
}
/// <summary>
/// A filter that always passes.
/// </summary>
/// <typeparam name="T">The type of the input for the filter.</typeparam>
public class AnyFilter<T> : Filter<T> where T : class
{
/// <summary>
/// A filter that always passes.
/// </summary>
/// <typeparam name="T">The type of the input for the filter.</typeparam>
public class AnyFilter<T> : Filter<T> where T : class
{
/// <inheritdoc/>
public override bool CanPass(FilterExecutionContext<T> context)
=> true;
}
}
/// <summary>
/// A filter that inverts the result of another filter.
/// </summary>
/// <typeparam name="T">The type of the input for the filter.</typeparam>
public class ReverseFilter<T> : Filter<T> where T : class
{
/// <summary>
/// A filter that inverts the result of another filter.
/// </summary>
/// <typeparam name="T">The type of the input for the filter.</typeparam>
public class ReverseFilter<T> : Filter<T> where T : class
{
private readonly IFilter<T> filter;
/// <summary>
@@ -112,14 +112,14 @@ namespace Telegrator.Filters
/// <inheritdoc/>
public override bool CanPass(FilterExecutionContext<T> context)
=> !filter.CanPass(context);
}
}
/// <summary>
/// A filter that uses a function to determine if it passes.
/// </summary>
/// <typeparam name="T">The type of the input for the filter.</typeparam>
public class FunctionFilter<T> : Filter<T> where T : class
{
/// <summary>
/// A filter that uses a function to determine if it passes.
/// </summary>
/// <typeparam name="T">The type of the input for the filter.</typeparam>
public class FunctionFilter<T> : Filter<T> where T : class
{
private readonly Func<FilterExecutionContext<T>, bool>? FilterFunc;
/// <summary>
/// Initializes a new instance of the <see cref="FunctionFilter{T}"/> class.
@@ -131,5 +131,4 @@ namespace Telegrator.Filters
/// <inheritdoc/>
public override bool CanPass(FilterExecutionContext<T> context)
=> context.Input != null && FilterFunc != null && FilterFunc(context);
}
}
+21 -22
View File
@@ -1,25 +1,25 @@
using Telegrator.Core.Filters;
namespace Telegrator.Filters
namespace Telegrator.Filters;
/// <summary>
/// Base class for filters that join multiple filters together.
/// </summary>
/// <typeparam name="T">The type of the input for the filter.</typeparam>
public abstract class JoinedFilter<T>(params IFilter<T>[] filters) : Filter<T>, IJoinedFilter<T> where T : class
{
/// <summary>
/// Base class for filters that join multiple filters together.
/// </summary>
/// <typeparam name="T">The type of the input for the filter.</typeparam>
public abstract class JoinedFilter<T>(params IFilter<T>[] filters) : Filter<T>, IJoinedFilter<T> where T : class
{
/// <summary>
/// Gets the array of joined filters.
/// </summary>
public IFilter<T>[] Filters { get; } = filters;
}
}
/// <summary>
/// A filter that passes only if both joined filters pass.
/// </summary>
/// <typeparam name="T">The type of the input for the filter.</typeparam>
public class AndFilter<T> : JoinedFilter<T> where T : class
{
/// <summary>
/// A filter that passes only if both joined filters pass.
/// </summary>
/// <typeparam name="T">The type of the input for the filter.</typeparam>
public class AndFilter<T> : JoinedFilter<T> where T : class
{
/// <summary>
/// Initializes a new instance of the <see cref="AndFilter{T}"/> class.
/// </summary>
@@ -31,14 +31,14 @@ namespace Telegrator.Filters
/// <inheritdoc/>
public override bool CanPass(FilterExecutionContext<T> context)
=> Filters[0].CanPass(context) && Filters[1].CanPass(context);
}
}
/// <summary>
/// A filter that passes if at least one of the joined filters passes.
/// </summary>
/// <typeparam name="T">The type of the input for the filter.</typeparam>
public class OrFilter<T> : JoinedFilter<T> where T : class
{
/// <summary>
/// A filter that passes if at least one of the joined filters passes.
/// </summary>
/// <typeparam name="T">The type of the input for the filter.</typeparam>
public class OrFilter<T> : JoinedFilter<T> where T : class
{
/// <summary>
/// Initializes a new instance of the <see cref="OrFilter{T}"/> class.
/// </summary>
@@ -50,5 +50,4 @@ namespace Telegrator.Filters
/// <inheritdoc/>
public override bool CanPass(FilterExecutionContext<T> context)
=> Filters[0].CanPass(context) || Filters[1].CanPass(context);
}
}
+7 -8
View File
@@ -2,14 +2,14 @@
using Telegram.Bot.Types.Enums;
using Telegrator.Core.Filters;
namespace Telegrator.Filters
namespace Telegrator.Filters;
/// <summary>
/// Filter that checks if a message contains a mention of the bot or a specific user.
/// Requires a <see cref="MessageHasEntityFilter"/> to be applied first to identify mention entities.
/// </summary>
public class MentionedFilter : MessageFilterBase
{
/// <summary>
/// Filter that checks if a message contains a mention of the bot or a specific user.
/// Requires a <see cref="MessageHasEntityFilter"/> to be applied first to identify mention entities.
/// </summary>
public class MentionedFilter : MessageFilterBase
{
/// <summary>
/// The username to check for in the mention (null means check for bot's username).
/// </summary>
@@ -60,5 +60,4 @@ namespace Telegrator.Filters
return false;
}
}
}
+42 -43
View File
@@ -3,13 +3,13 @@ using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups;
using Telegrator.Core.Filters;
namespace Telegrator.Filters
namespace Telegrator.Filters;
/// <summary>
/// Base class for filters that operate on the chat of the message being processed.
/// </summary>
public abstract class MessageChatFilter : MessageFilterBase
{
/// <summary>
/// Base class for filters that operate on the chat of the message being processed.
/// </summary>
public abstract class MessageChatFilter : MessageFilterBase
{
/// <summary>
/// Gets the chat of the message being processed.
/// </summary>
@@ -28,35 +28,35 @@ namespace Telegrator.Filters
/// <param name="context">The filter execution context for the chat.</param>
/// <returns>True if the filter passes; otherwise, false.</returns>
protected abstract bool CanPassNext(FilterExecutionContext<Chat> context);
}
}
/// <summary>
/// Filters messages whose chat is a forum.
/// </summary>
public class MessageChatIsForumFilter : MessageChatFilter
{
/// <summary>
/// Filters messages whose chat is a forum.
/// </summary>
public class MessageChatIsForumFilter : MessageChatFilter
{
/// <inheritdoc/>
protected override bool CanPassNext(FilterExecutionContext<Chat> _)
=> Chat.IsForum;
}
}
/// <summary>
/// Filters messages whose chat ID matches the specified value.
/// </summary>
public class MessageChatIdFilter(long id) : MessageChatFilter
{
/// <summary>
/// Filters messages whose chat ID matches the specified value.
/// </summary>
public class MessageChatIdFilter(long id) : MessageChatFilter
{
private readonly long Id = id;
/// <inheritdoc/>
protected override bool CanPassNext(FilterExecutionContext<Chat> _)
=> Chat.Id == Id;
}
}
/// <summary>
/// Filters messages whose chat type matches the specified value.
/// </summary>
public class MessageChatTypeFilter : MessageChatFilter
{
/// <summary>
/// Filters messages whose chat type matches the specified value.
/// </summary>
public class MessageChatTypeFilter : MessageChatFilter
{
private readonly ChatType? Type;
private readonly ChatTypeFlags? Flags;
@@ -98,13 +98,13 @@ namespace Telegrator.Filters
ChatType.Private => ChatTypeFlags.Private,
_ => null
};
}
}
/// <summary>
/// Filters messages whose chat title matches the specified value.
/// </summary>
public class MessageChatTitleFilter : MessageChatFilter
{
/// <summary>
/// Filters messages whose chat title matches the specified value.
/// </summary>
public class MessageChatTitleFilter : MessageChatFilter
{
private readonly string? Title;
private readonly StringComparison Comparison = StringComparison.InvariantCulture;
@@ -130,13 +130,13 @@ namespace Telegrator.Filters
return Chat.Title.Equals(Title, Comparison);
}
}
}
/// <summary>
/// Filters messages whose chat username matches the specified value.
/// </summary>
public class MessageChatUsernameFilter : MessageChatFilter
{
/// <summary>
/// Filters messages whose chat username matches the specified value.
/// </summary>
public class MessageChatUsernameFilter : MessageChatFilter
{
private readonly string? UserName;
private readonly StringComparison Comparison = StringComparison.InvariantCulture;
@@ -162,13 +162,13 @@ namespace Telegrator.Filters
return Chat.Username.Equals(UserName, Comparison);
}
}
}
/// <summary>
/// Filters messages whose chat first and/or last name matches the specified values.
/// </summary>
public class MessageChatNameFilter : MessageChatFilter
{
/// <summary>
/// Filters messages whose chat first and/or last name matches the specified values.
/// </summary>
public class MessageChatNameFilter : MessageChatFilter
{
private readonly string? FirstName;
private readonly string? LastName;
private readonly StringComparison Comparison = StringComparison.InvariantCulture;
@@ -216,5 +216,4 @@ namespace Telegrator.Filters
return true;
}
}
}
+54 -55
View File
@@ -3,13 +3,13 @@ using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegrator.Core.Filters;
namespace Telegrator.Filters
namespace Telegrator.Filters;
/// <summary>
/// Base abstract class for all filter of <see cref="Message"/> updates
/// </summary>
public abstract class MessageFilterBase : Filter<Message>
{
/// <summary>
/// Base abstract class for all filter of <see cref="Message"/> updates
/// </summary>
public abstract class MessageFilterBase : Filter<Message>
{
/// <summary>
/// Target message for filterring
/// </summary>
@@ -42,13 +42,13 @@ namespace Telegrator.Filters
/// <param name="context"></param>
/// <returns></returns>
protected abstract bool CanPassNext(FilterExecutionContext<Message> context);
}
}
/// <summary>
/// Filters messages by their <see cref="MessageType"/>.
/// </summary>
public class MessageTypeFilter : MessageFilterBase
{
/// <summary>
/// Filters messages by their <see cref="MessageType"/>.
/// </summary>
public class MessageTypeFilter : MessageFilterBase
{
private readonly MessageType type;
/// <summary>
@@ -60,53 +60,53 @@ namespace Telegrator.Filters
/// <inheritdoc/>
protected override bool CanPassNext(FilterExecutionContext<Message> context)
=> Target.Type == type;
}
}
/// <summary>
/// Filters messages that are automatic forwards.
/// </summary>
public class IsAutomaticFormwardMessageFilter : MessageFilterBase
{
/// <summary>
/// Filters messages that are automatic forwards.
/// </summary>
public class IsAutomaticFormwardMessageFilter : MessageFilterBase
{
/// <inheritdoc/>
protected override bool CanPassNext(FilterExecutionContext<Message> context)
=> Target.IsAutomaticForward;
}
}
/// <summary>
/// Filters messages that are sent from offline.
/// </summary>
public class IsFromOfflineMessageFilter : MessageFilterBase
{
/// <summary>
/// Filters messages that are sent from offline.
/// </summary>
public class IsFromOfflineMessageFilter : MessageFilterBase
{
/// <inheritdoc/>
protected override bool CanPassNext(FilterExecutionContext<Message> context)
=> Target.IsFromOffline;
}
}
/// <summary>
/// Filters service messages (e.g., chat events).
/// </summary>
public class IsServiceMessageMessageFilter : MessageFilterBase
{
/// <summary>
/// Filters service messages (e.g., chat events).
/// </summary>
public class IsServiceMessageMessageFilter : MessageFilterBase
{
/// <inheritdoc/>
protected override bool CanPassNext(FilterExecutionContext<Message> context)
=> Target.IsServiceMessage;
}
}
/// <summary>
/// Filters messages that are topic messages.
/// </summary>
public class IsTopicMessageMessageFilter : MessageFilterBase
{
/// <summary>
/// Filters messages that are topic messages.
/// </summary>
public class IsTopicMessageMessageFilter : MessageFilterBase
{
/// <inheritdoc/>
protected override bool CanPassNext(FilterExecutionContext<Message> context)
=> Target.IsTopicMessage;
}
}
/// <summary>
/// Filters messages by dice throw value and optionally by dice type.
/// </summary>
public class DiceThrowedFilter : MessageFilterBase
{
/// <summary>
/// Filters messages by dice throw value and optionally by dice type.
/// </summary>
public class DiceThrowedFilter : MessageFilterBase
{
private readonly DiceType Dice;
private readonly int Value;
@@ -148,13 +148,13 @@ namespace Telegrator.Filters
DiceType.Casino => "🎰",
_ => null
};
}
}
/// <summary>
/// Filters messages by matching their text with a regular expression.
/// </summary>
public class MessageRegexFilter : RegexFilterBase<Message>
{
/// <summary>
/// Filters messages by matching their text with a regular expression.
/// </summary>
public class MessageRegexFilter : RegexFilterBase<Message>
{
/// <summary>
/// Initializes a new instance of the <see cref="MessageRegexFilter"/> class with a pattern and options.
/// </summary>
@@ -169,13 +169,13 @@ namespace Telegrator.Filters
/// <param name="regex">The regex object.</param>
public MessageRegexFilter(Regex regex)
: base(msg => msg.Text, regex) { }
}
}
/// <summary>
/// Filters messages that contain a specific entity type, content, offset, or length.
/// </summary>
public class MessageHasEntityFilter : MessageFilterBase
{
/// <summary>
/// Filters messages that contain a specific entity type, content, offset, or length.
/// </summary>
public class MessageHasEntityFilter : MessageFilterBase
{
private readonly StringComparison _stringComparison = StringComparison.CurrentCulture;
private readonly MessageEntityType? EntityType;
private readonly string? Content;
@@ -271,5 +271,4 @@ namespace Telegrator.Filters
return true;
}
}
}
+52 -53
View File
@@ -1,15 +1,55 @@
using Telegram.Bot.Types;
using Telegrator.Core.Filters;
namespace Telegrator.Filters
namespace Telegrator.Filters;
/// <summary>
/// Filter that checks if message has appropriate reply chain.
/// DOES NOT SHiFT MESSAGE FILTERS TARGET
/// </summary>
/// <param name="replyDepth">The depth of reply chain to traverse (default: 1).</param>
public class MessageHasReplyFilter(int replyDepth = 1) : Filter<Message>
{
/// <summary>
/// Filter that checks if message has appropriate reply chain.
/// DOES NOT SHiFT MESSAGE FILTERS TARGET
/// Gets the replied message at the specified depth in the reply chain.
/// </summary>
/// <param name="replyDepth">The depth of reply chain to traverse (default: 1).</param>
public class MessageHasReplyFilter(int replyDepth = 1) : Filter<Message>
public Message Reply { get; private set; } = null!;
/// <summary>
/// Gets the depth of reply chain traversal.
/// </summary>
public int ReplyDepth { get; private set; } = replyDepth;
/// <summary>
/// Determines if the message can pass through the filter by first validating
/// the reply chain and then applying specific filter logic.
/// </summary>
/// <param name="context">The filter execution context containing the message.</param>
/// <returns>True if the message passes both reply validation and specific filter criteria; otherwise, false.</returns>
public override bool CanPass(FilterExecutionContext<Message> context)
{
Message reply = context.Input;
for (int i = ReplyDepth; i > 0; i--)
{
if (reply.ReplyToMessage is not { Id: > 0 } replyMessage)
return false;
reply = replyMessage;
}
Reply = reply;
return true;
}
}
/// <summary>
/// Helper filter class for filters that operate on replied messages.
/// Provides functionality to traverse reply chains and access replied message content
/// and shifts any next message filter to filter the content of found reply.
/// </summary>
/// <param name="replyDepth"></param>
public class FromReplyChainFilter(int replyDepth = 1) : Filter<Message>
{
/// <summary>
/// Gets the replied message at the specified depth in the reply chain.
/// </summary>
@@ -40,54 +80,14 @@ namespace Telegrator.Filters
Reply = reply;
return true;
}
}
}
/// <summary>
/// Helper filter class for filters that operate on replied messages.
/// Provides functionality to traverse reply chains and access replied message content
/// and shifts any next message filter to filter the content of found reply.
/// </summary>
/// <param name="replyDepth"></param>
public class FromReplyChainFilter(int replyDepth = 1) : Filter<Message>
{
/// <summary>
/// Gets the replied message at the specified depth in the reply chain.
/// </summary>
public Message Reply { get; private set; } = null!;
/// <summary>
/// Gets the depth of reply chain traversal.
/// </summary>
public int ReplyDepth { get; private set; } = replyDepth;
/// <summary>
/// Determines if the message can pass through the filter by first validating
/// the reply chain and then applying specific filter logic.
/// </summary>
/// <param name="context">The filter execution context containing the message.</param>
/// <returns>True if the message passes both reply validation and specific filter criteria; otherwise, false.</returns>
public override bool CanPass(FilterExecutionContext<Message> context)
{
Message reply = context.Input;
for (int i = ReplyDepth; i > 0; i--)
{
if (reply.ReplyToMessage is not { Id: > 0 } replyMessage)
return false;
reply = replyMessage;
}
Reply = reply;
return true;
}
}
/// <summary>
/// Filter that checks if the replied message was sent by the bot itself.
/// <para>( ! ): REQUIRES <see cref="MessageHasReplyFilter"/> before</para>
/// </summary>
public class MeRepliedFilter : Filter<Message>
{
/// <summary>
/// Filter that checks if the replied message was sent by the bot itself.
/// <para>( ! ): REQUIRES <see cref="MessageHasReplyFilter"/> before</para>
/// </summary>
public class MeRepliedFilter : Filter<Message>
{
/// <summary>
/// Checks if the replied message was sent by the bot.
/// </summary>
@@ -98,5 +98,4 @@ namespace Telegrator.Filters
MessageHasReplyFilter repliedFilter = context.CompletedFilters.Get<MessageHasReplyFilter>(0);
return context.BotInfo.User == repliedFilter.Reply.From;
}
}
}
+42 -43
View File
@@ -1,14 +1,14 @@
using Telegram.Bot.Types;
using Telegrator.Core.Filters;
namespace Telegrator.Filters
namespace Telegrator.Filters;
/// <summary>
/// Abstract base class for filters that operate on message senders.
/// Provides functionality to access and validate the user who sent the message.
/// </summary>
public abstract class MessageSenderFilter : MessageFilterBase
{
/// <summary>
/// Abstract base class for filters that operate on message senders.
/// Provides functionality to access and validate the user who sent the message.
/// </summary>
public abstract class MessageSenderFilter : MessageFilterBase
{
/// <summary>
/// Gets the user who sent the message.
/// </summary>
@@ -31,14 +31,14 @@ namespace Telegrator.Filters
return CanPassNext(context);
}
}
}
/// <summary>
/// Filter that checks if the message sender has a specific username.
/// </summary>
/// <param name="username">The username to check for.</param>
public class FromUsernameFilter(string username) : MessageSenderFilter
{
/// <summary>
/// Filter that checks if the message sender has a specific username.
/// </summary>
/// <param name="username">The username to check for.</param>
public class FromUsernameFilter(string username) : MessageSenderFilter
{
/// <summary>
/// The username to check for.
/// </summary>
@@ -64,16 +64,16 @@ namespace Telegrator.Filters
/// <returns>True if the sender has the specified username; otherwise, false.</returns>
protected override bool CanPassNext(FilterExecutionContext<Message> context)
=> User.Username != null && User.Username.Equals(_username, _comparison);
}
}
/// <summary>
/// Filter that checks if the message sender has specific first and/or last name.
/// </summary>
/// <param name="firstName">The first name to check for.</param>
/// <param name="lastName">The last name to check for (optional).</param>
/// <param name="comparison">The string comparison type to use.</param>
public class FromUserFilter(string firstName, string? lastName, StringComparison comparison) : MessageSenderFilter
{
/// <summary>
/// Filter that checks if the message sender has specific first and/or last name.
/// </summary>
/// <param name="firstName">The first name to check for.</param>
/// <param name="lastName">The last name to check for (optional).</param>
/// <param name="comparison">The string comparison type to use.</param>
public class FromUserFilter(string firstName, string? lastName, StringComparison comparison) : MessageSenderFilter
{
/// <summary>
/// The first name to check for.
/// </summary>
@@ -130,14 +130,14 @@ namespace Telegrator.Filters
return User.FirstName.Equals(_firstName, _comparison);
}
}
}
/// <summary>
/// Filter that checks if the message sender has a specific user ID.
/// </summary>
/// <param name="userId">The user ID to check for.</param>
public class FromUserIdFilter(long userId) : MessageSenderFilter
{
/// <summary>
/// Filter that checks if the message sender has a specific user ID.
/// </summary>
/// <param name="userId">The user ID to check for.</param>
public class FromUserIdFilter(long userId) : MessageSenderFilter
{
/// <summary>
/// The user ID to check for.
/// </summary>
@@ -150,13 +150,13 @@ namespace Telegrator.Filters
/// <returns>True if the sender has the specified user ID; otherwise, false.</returns>
protected override bool CanPassNext(FilterExecutionContext<Message> _)
=> User.Id == _userId;
}
}
/// <summary>
/// Filter that checks if the message was sent by a bot.
/// </summary>
public class FromBotFilter() : MessageSenderFilter
{
/// <summary>
/// Filter that checks if the message was sent by a bot.
/// </summary>
public class FromBotFilter() : MessageSenderFilter
{
/// <summary>
/// Checks if the message was sent by a bot.
/// </summary>
@@ -164,13 +164,13 @@ namespace Telegrator.Filters
/// <returns>True if the message was sent by a bot; otherwise, false.</returns>
protected override bool CanPassNext(FilterExecutionContext<Message> _)
=> User.IsBot;
}
}
/// <summary>
/// Filter that checks if the message was sent by a premium user.
/// </summary>
public class FromPremiumUserFilter() : MessageSenderFilter
{
/// <summary>
/// Filter that checks if the message was sent by a premium user.
/// </summary>
public class FromPremiumUserFilter() : MessageSenderFilter
{
/// <summary>
/// Checks if the message was sent by a premium user.
/// </summary>
@@ -178,5 +178,4 @@ namespace Telegrator.Filters
/// <returns>True if the message was sent by a premium user; otherwise, false.</returns>
protected override bool CanPassNext(FilterExecutionContext<Message> _)
=> User.IsPremium;
}
}
+52 -54
View File
@@ -1,15 +1,14 @@
using Telegram.Bot.Types;
using Telegrator.Core.Filters;
using static System.Net.Mime.MediaTypeNames;
namespace Telegrator.Filters
namespace Telegrator.Filters;
/// <summary>
/// Abstract base class for filters that operate on message text content.
/// Provides common functionality for extracting and validating message text.
/// </summary>
public abstract class MessageTextFilter : MessageFilterBase
{
/// <summary>
/// Abstract base class for filters that operate on message text content.
/// Provides common functionality for extracting and validating message text.
/// </summary>
public abstract class MessageTextFilter : MessageFilterBase
{
/// <summary>
/// Gets the current message being processed by the filter.
/// </summary>
@@ -37,15 +36,15 @@ namespace Telegrator.Filters
Text = Target.Text;
return CanPassNext(context);
}
}
}
/// <summary>
/// Filter that checks if the message text starts with a specified content.
/// </summary>
/// <param name="content">The content to check if the message text starts with.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
public class TextStartsWithFilter(string content, StringComparison comparison = StringComparison.InvariantCulture) : MessageTextFilter
{
/// <summary>
/// Filter that checks if the message text starts with a specified content.
/// </summary>
/// <param name="content">The content to check if the message text starts with.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
public class TextStartsWithFilter(string content, StringComparison comparison = StringComparison.InvariantCulture) : MessageTextFilter
{
/// <summary>
/// The content to check if the message text starts with.
/// </summary>
@@ -63,15 +62,15 @@ namespace Telegrator.Filters
/// <returns>True if the text starts with the specified content; otherwise, false.</returns>
protected override bool CanPassNext(FilterExecutionContext<Message> _)
=> Text.StartsWith(Content, Comparison);
}
}
/// <summary>
/// Filter that checks if the message text ends with a specified content.
/// </summary>
/// <param name="content">The content to check if the message text ends with.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
public class TextEndsWithFilter(string content, StringComparison comparison = StringComparison.InvariantCulture) : MessageTextFilter
{
/// <summary>
/// Filter that checks if the message text ends with a specified content.
/// </summary>
/// <param name="content">The content to check if the message text ends with.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
public class TextEndsWithFilter(string content, StringComparison comparison = StringComparison.InvariantCulture) : MessageTextFilter
{
/// <summary>
/// The content to check if the message text ends with.
/// </summary>
@@ -89,15 +88,15 @@ namespace Telegrator.Filters
/// <returns>True if the text ends with the specified content; otherwise, false.</returns>
protected override bool CanPassNext(FilterExecutionContext<Message> _)
=> Text.EndsWith(Content, Comparison);
}
}
/// <summary>
/// Filter that checks if the message text contains a specified content.
/// </summary>
/// <param name="content">The content to check if the message text contains.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
public class TextContainsFilter(string content, StringComparison comparison = StringComparison.InvariantCulture) : MessageTextFilter
{
/// <summary>
/// Filter that checks if the message text contains a specified content.
/// </summary>
/// <param name="content">The content to check if the message text contains.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
public class TextContainsFilter(string content, StringComparison comparison = StringComparison.InvariantCulture) : MessageTextFilter
{
/// <summary>
/// The content to check if the message text contains.
/// </summary>
@@ -115,15 +114,15 @@ namespace Telegrator.Filters
/// <returns>True if the text contains the specified content; otherwise, false.</returns>
protected override bool CanPassNext(FilterExecutionContext<Message> _)
=> Text.IndexOf(Content, Comparison) >= 0;
}
}
/// <summary>
/// Filter that checks if the message text equals a specified content.
/// </summary>
/// <param name="content">The content to check if the message text equals.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
public class TextEqualsFilter(string content, StringComparison comparison = StringComparison.InvariantCulture) : MessageTextFilter
{
/// <summary>
/// Filter that checks if the message text equals a specified content.
/// </summary>
/// <param name="content">The content to check if the message text equals.</param>
/// <param name="comparison">The string comparison type to use for the check.</param>
public class TextEqualsFilter(string content, StringComparison comparison = StringComparison.InvariantCulture) : MessageTextFilter
{
/// <summary>
/// The content to check if the message text equals.
/// </summary>
@@ -141,13 +140,13 @@ namespace Telegrator.Filters
/// <returns>True if the text equals the specified content; otherwise, false.</returns>
protected override bool CanPassNext(FilterExecutionContext<Message> _)
=> Text.Equals(Content, Comparison);
}
}
/// <summary>
/// Filter that checks if the message text is not null or empty.
/// </summary>
public class TextNotNullOrEmptyFilter() : MessageTextFilter
{
/// <summary>
/// Filter that checks if the message text is not null or empty.
/// </summary>
public class TextNotNullOrEmptyFilter() : MessageTextFilter
{
/// <summary>
/// Checks if the message text is not null or empty.
/// </summary>
@@ -155,14 +154,14 @@ namespace Telegrator.Filters
/// <returns>True if the text is not null or empty; otherwise, false.</returns>
protected override bool CanPassNext(FilterExecutionContext<Message> _)
=> !string.IsNullOrEmpty(Text);
}
}
/// <summary>
/// Filter that checks if the message text contains a 'word'.
/// 'Word' must be a separate member of the text, and not have any alphabetic characters next to it.
/// </summary>
public class TextContainsWordFilter(string word, StringComparison comparison = StringComparison.InvariantCulture, int startIndex = 0) : MessageTextFilter
{
/// <summary>
/// Filter that checks if the message text contains a 'word'.
/// 'Word' must be a separate member of the text, and not have any alphabetic characters next to it.
/// </summary>
public class TextContainsWordFilter(string word, StringComparison comparison = StringComparison.InvariantCulture, int startIndex = 0) : MessageTextFilter
{
/// <summary>
/// The content to check if the message text equals.
/// </summary>
@@ -181,5 +180,4 @@ namespace Telegrator.Filters
/// <inheritdoc/>
protected override bool CanPassNext(FilterExecutionContext<Message> context)
=> Text.ContainsWord(Word, Comparison, StartIndex);
}
}

Some files were not shown because too many files have changed in this diff Show More