* Added StartReceiving method as ITelegratoBot interface member

* Added missing summaries
* Fixed compiler warning and infos
* Code cleanup and bugfixes
This commit is contained in:
gutii
2026-04-27 22:13:47 +04:00
parent 5433a2de0d
commit 96b3241716
21 changed files with 379 additions and 68 deletions
@@ -6,3 +6,5 @@
using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Roslynator", "RCS1037")]
[assembly: SuppressMessage("Style", "IDE0090")]
[assembly: SuppressMessage("Style", "IDE0270")]
@@ -1,18 +1,22 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Threading;
using System.Threading.Tasks;
using Telegram.Bot;
using Telegram.Bot.Polling;
using Telegrator.Core;
namespace Telegrator.Mediation;
//Hosting.WideBot
/// <summary>
/// Service for receiving updates for Hosted wide telegram bots and queuing them to router
/// </summary>
/// <param name="logger"></param>
/// <param name="botClient"></param>
/// <param name="updateRouter"></param>
/// <param name="options"></param>
public class HostedWideBotUpdateReceiver(ILogger<HostedWideBotUpdateReceiver> logger, ITelegramBotClient botClient, IUpdateRouter updateRouter, IOptions<ReceiverOptions>? options) : BackgroundService
{
/// <inheritdoc/>
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (botClient is not WTelegramBotClient wideBotClient)
@@ -8,12 +8,19 @@ using WUpdate = WTelegram.Types.Update;
namespace Telegrator.Mediation;
/// <summary>
/// Reactive implementation of <see cref="IUpdateReceiver"/> for polling updates from Telegram.
/// Provides custom update receiving logic with error handling and configuration options.
/// </summary>
/// <param name="client">The Telegram bot client for making API requests.</param>
// <param name="options">Optional receiver options for configuring update polling behavior.</param>
public class WideUpdateReceiver(WTelegramBotClient client) : IUpdateReceiver
{
private readonly WTelegramBotClient _client = client;
private IUpdateHandler? _updateHandler = null;
private CancellationToken _cancellation = default;
/// <inheritdoc/>
public async Task ReceiveAsync(IUpdateHandler updateHandler, CancellationToken cancellationToken = default)
{
_updateHandler = updateHandler;
@@ -13,18 +13,33 @@ using Telegrator.States;
namespace Telegrator;
/// <summary>
/// Client class for the Telegrator library with Wider functionality, provided by WTelegramBotClient.
/// Extends TelegramBotClient with reactive capabilities for handling updates.
/// </summary>
public class TelegratorWClient : WTelegramBotClient, ITelegratorBot, ICollectingProvider
{
private IUpdateRouter? _updateRouter = null;
/// <inheritdoc/>
public TelegratorOptions Options { get; }
/// <inheritdoc/>
public IHandlersCollection Handlers { get; }
/// <inheritdoc/>
public ITelegramBotInfo BotInfo { get; }
/// <inheritdoc/>
public IUpdateRouter UpdateRouter => _updateRouter ?? throw new InvalidOperationException("Router's not created yet. Invoke `StartReceiving` to initialize this property.");
/// <summary>
/// Initializes new instance of <see cref="TelegratorWClient"/>
/// </summary>
/// <param name="wOptions"></param>
/// <param name="telegratorOptions"></param>
/// <param name="httpClient"></param>
/// <param name="cancellationToken"></param>
public TelegratorWClient(WTelegramBotClientOptions wOptions, TelegratorOptions? telegratorOptions = null, HttpClient? httpClient = null, CancellationToken cancellationToken = default)
: base(wOptions, httpClient, cancellationToken)
{
@@ -33,7 +48,8 @@ public class TelegratorWClient : WTelegramBotClient, ITelegratorBot, ICollecting
BotInfo = new TelegramBotInfo(GetMe(cancellationToken).Result);
}
public void StartReceiving(CancellationToken cancellationToken = default)
/// <inheritdoc/>
public void StartReceiving(ReceiverOptions? _, CancellationToken cancellationToken = default)
{
if (Options.GlobalCancellationToken == CancellationToken.None)
Options.GlobalCancellationToken = cancellationToken;
@@ -45,10 +61,27 @@ public class TelegratorWClient : WTelegramBotClient, ITelegratorBot, ICollecting
_updateRouter = new UpdateRouter(handlerProvider, awaitingProvider, stateStorage, Options, BotInfo);
TelegratorLogging.LogInformation($"TelegratorW bot starting up - BotId: {BotInfo.User.Id}, Username: {BotInfo.User.Username}");
StartReceivingInternal(Options.GlobalCancellationToken);
StartReceivingInternal(Options.GlobalCancellationToken)
.ConfigureAwait(false).GetAwaiter().GetResult();
}
private async void StartReceivingInternal(CancellationToken cancellationToken)
/// <inheritdoc/>
public async Task StartReceivingAsync(ReceiverOptions? receiverOptions = null,CancellationToken cancellationToken = default)
{
if (Options.GlobalCancellationToken == CancellationToken.None)
Options.GlobalCancellationToken = cancellationToken;
HandlersProvider handlerProvider = new HandlersProvider(Handlers, Options);
AwaitingProvider awaitingProvider = new AwaitingProvider(Options);
DefaultStateStorage stateStorage = new DefaultStateStorage();
_updateRouter = new UpdateRouter(handlerProvider, awaitingProvider, stateStorage, Options, BotInfo);
TelegratorLogging.LogInformation($"TelegratorW bot starting up - BotId: {BotInfo.User.Id}, Username: {BotInfo.User.Username}");
await StartReceivingInternal(Options.GlobalCancellationToken);
}
private async Task StartReceivingInternal(CancellationToken cancellationToken)
{
try
{
@@ -13,15 +13,21 @@ using Telegrator.Hosting;
using Telegrator.Mediation;
using Telegrator.Providers;
using TLUpdate = TL.Update;
using WUpdate = WTelegram.Types.Update;
using TLUpdate = TL.Update;
namespace Telegrator;
/// <summary>
/// Provides extensions memebrs for <see cref="UpdateHandlerBase"/> for easy access to Wider bot functions and update
/// </summary>
public static class HandlersExtensions
{
extension<TUpdate>(AbstractUpdateHandler<TUpdate> handler) where TUpdate : class
{
/// <summary>
/// Casts Update to <see cref="WTelegramBotClient"/>
/// </summary>
public WTelegramBotClient WClient
{
get
@@ -35,6 +41,9 @@ public static class HandlersExtensions
}
/// <summary>
/// Casts Update to <see cref="WUpdate"/>
/// </summary>
public WUpdate WideUpdate
{
get
@@ -47,18 +56,27 @@ public static class HandlersExtensions
}
}
/// <summary>
/// Casts Update to <see cref="TLUpdate"/>
/// </summary>
public TLUpdate? TLUpdate
{
get => handler.WideUpdate.TLUpdate;
}
}
/// <summary>
/// Casts Update to <see cref="WTelegramBotClient"/>
/// </summary>
public static WTelegramBotClient AsWClient(this ITelegramBotClient client)
{
return client as WTelegramBotClient
?? throw new InvalidCastException("Client is not assignable to `WTelegram.Bot.WTelegramBotClient`");
}
/// <summary>
/// Casts Update to <see cref="WUpdate"/>
/// </summary>
public static WUpdate AsWUpdate(this Update update)
{
return update as WUpdate
@@ -149,20 +167,45 @@ public static class WideHostBuilderExtensions
/// </summary>
public static class WideBotServiceCollectionExtensions
{
/// <summary>
/// Adds WTelegramBotClientOptions to services
/// </summary>
/// <param name="services"></param>
/// <param name="options"></param>
/// <returns></returns>
public static IServiceCollection ConfigureWideTelegram(this IServiceCollection services, WTelegramBotClientOptions options)
{
services.RemoveAll<IOptions<WTelegramBotClientOptions>>();
services.AddSingleton(Options.Create(options));
return services;
}
public static IServiceCollection AddMTProtoUpdateReceiver(this IServiceCollection services)
/// <summary>
/// Adds WTelegramBotClient
/// </summary>
/// <param name="services"></param>
/// <param name="useHttp"></param>
/// <returns></returns>
public static IServiceCollection AddMTProtoUpdateReceiver(this IServiceCollection services, bool useHttp = false)
{
services.AddHttpClient<WTelegramBotClient>("tgmtproto").RemoveAllLoggers().AddTypedClient(TypedTelegramBotClientFactory);
services.RemoveAll<ITelegramBotClient>();
services.RemoveAll<HostedWideBotUpdateReceiver>();
if (useHttp)
{
services.AddHttpClient<WTelegramBotClient>("tgmtproto").RemoveAllLoggers().AddTypedClient(TypedTelegramBotClientFactory);
}
else
{
services.AddSingleton(TypedTelegramBotClientFactory);
}
services.AddSingleton<ITelegramBotClient>(sp => sp.GetRequiredService<WTelegramBotClient>());
services.AddHostedService<HostedWideBotUpdateReceiver>();
return services;
}
#pragma warning disable CA2254
private static WTelegramBotClient TypedTelegramBotClientFactory(HttpClient httpClient, IServiceProvider provider)
{
ILogger<WTelegramBotClient> logger = provider.GetRequiredService<ILogger<WTelegramBotClient>>();
@@ -171,6 +214,16 @@ public static class WideBotServiceCollectionExtensions
WTelegram.Helpers.Log = (lvl, str) => logger.Log((LogLevel)lvl, str);
return client;
}
private static WTelegramBotClient TypedTelegramBotClientFactory(IServiceProvider provider)
{
ILogger<WTelegramBotClient> logger = provider.GetRequiredService<ILogger<WTelegramBotClient>>();
WTelegramBotClient client = new WTelegramBotClient(provider.GetRequiredService<IOptions<WTelegramBotClientOptions>>().Value);
WTelegram.Helpers.Log = (lvl, str) => logger.Log((LogLevel)lvl, str);
return client;
}
#pragma warning restore CA2254
}
/// <summary>
@@ -1,9 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Telegrator;
public class WideReceiverOptions
{
}