Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 47 additions & 32 deletions Telegram.Net/Services/TelegramHostedService.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.InteropServices.JavaScript;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
Expand All @@ -15,31 +14,32 @@

namespace Telegram.Net.Services;

[SuppressMessage("ReSharper", "ReturnValueOfPureMethodIsNotUsed")]
public class TelegramHostedService : IHostedService
{
private IServiceCollection isc { get; }
internal TelegramBotClient Client { get; set; }
private ITelegramBotConfig Config { get; }
internal Dictionary<string, Func<ITelegramBotClient, Message, CancellationToken, Task>> CommandHandler { get; set; } = new();
internal List<Func<ITelegramBotClient, Message, CancellationToken, Task>> EditedMessageHandler { get; set; } = new();
internal Dictionary<string, Func<ITelegramBotClient, CallbackQuery,CancellationToken, Task>> CallbackQueryHandler { get; set; } = new();
internal Dictionary<string, Func<ITelegramBotClient, InlineQuery ,CancellationToken, Task>> InlineHandler { get; set; } = new();
private IServiceCollection ServiceCollection { get; } = null!;
internal TelegramBotClient Client { get; set; } = null!;
private ITelegramBotConfig Config { get; } = null!;
internal Dictionary<string, Func<ITelegramBotClient, Message, CancellationToken, Task>?> CommandHandler { get; set; } = new();
internal List<Func<ITelegramBotClient, Message, CancellationToken, Task>?> EditedMessageHandler { get; set; } = new();
internal Dictionary<string, Func<ITelegramBotClient, CallbackQuery, CancellationToken, Task>?> CallbackQueryHandler { get; set; } = new();
internal Dictionary<string, Func<ITelegramBotClient, InlineQuery, CancellationToken, Task>?> InlineHandler { get; set; } = new();
internal Func<ITelegramBotClient, PreCheckoutQuery,CancellationToken, Task>? PreCheckoutHandler { get; set; }
internal List<Func<ITelegramBotClient, Update, CancellationToken, Task>> DefaultUpdateHandler { get; set; } = new();
internal static ILogger<TelegramHostedService> _logger;
internal List<Func<ITelegramBotClient, Update, CancellationToken, Task>?> DefaultUpdateHandler { get; set; } = new();
internal static ILogger<TelegramHostedService> Logger = null!;

public TelegramHostedService(ITelegramBotConfig config, IServiceCollection isc, ILogger<TelegramHostedService> logger)
public TelegramHostedService(ITelegramBotConfig config, IServiceCollection serviceCollection, ILogger<TelegramHostedService> logger)
{
try
{
_logger = logger;
Logger = logger;
Client = new TelegramBotClient(config.Token);
Config = config;
this.isc = isc;
this.ServiceCollection = serviceCollection;
}
catch (Exception ex)
{
_logger.Log(LogLevel.Critical, new EventId(), ex, "Catched exception when creating TelegramHostedService: ");
Logger.Log(LogLevel.Critical, new EventId(), ex, "Catched exception when creating TelegramHostedService: ");
}
}
internal static bool IsValidHandlerMethod(MethodInfo method, Type parameterType)
Expand All @@ -55,12 +55,12 @@ internal static bool IsValidHandlerMethod(MethodInfo method, Type parameterType)
}
catch (Exception ex)
{
_logger.LogError(ex, "Catched exception in parsing and checking params.");
Logger.LogError(ex, "Catched exception in parsing and checking params.");
return false;
}
}

internal static Func<ITelegramBotClient, T, CancellationToken, Task> CreateDelegate<T>(MethodInfo method)
internal static Func<ITelegramBotClient, T, CancellationToken, Task>? CreateDelegate<T>(MethodInfo method)
{
try
{
Expand All @@ -70,7 +70,7 @@ internal static Func<ITelegramBotClient, T, CancellationToken, Task> CreateDeleg
}
catch (Exception ex)
{
_logger.Log(LogLevel.Critical, new EventId(), ex, "Catched exception in CreateDelegate function: ");
Logger.Log(LogLevel.Critical, new EventId(), ex, "Catched exception in CreateDelegate function: ");
return null;
}

Expand Down Expand Up @@ -106,10 +106,10 @@ await Task.Run(async () =>

if (methods.Count == 0)
{
_logger.LogWarning("No methods found with required attributes");
Logger.LogWarning("No methods found with required attributes");
}

var isp = isc.BuildServiceProvider();
var isp = ServiceCollection.BuildServiceProvider();
foreach (var method in methods)
{
var declaringType = method.DeclaringType!;
Expand Down Expand Up @@ -156,7 +156,7 @@ await Task.Run(async () =>
}
catch (Exception ex)
{
_logger.Log(LogLevel.Critical, new EventId(), ex, "Catched new exception when added methods: ");
Logger.Log(LogLevel.Critical, new EventId(), ex, "Catched new exception when added methods: ");
}
}, cancellationToken);
}
Expand All @@ -169,31 +169,46 @@ internal async Task UpdateHandler(ITelegramBotClient client, Update update, Canc
switch (update)
{
case { Message: { } message }:
await CommandHandler.FirstOrDefault(k => message.Text!.StartsWith(k.Key))
.Value(client, message, ctx);
CommandHandler.Where(k => message.Text!.StartsWith(k.Key)).Select(async k =>
{
await k.Value!(client, message, ctx);
return k;
});
break;
case { EditedMessage: { } message }:
EditedMessageHandler.ForEach(async k => await k(client, message, ctx));
// ReSharper disable once AsyncVoidLambda
EditedMessageHandler.ForEach(async k => await k!(client, message, ctx));
break;
case { CallbackQuery: { } callbackQuery }:
await CallbackQueryHandler.FirstOrDefault(k => callbackQuery.Data!.StartsWith(k.Key))
.Value(client, callbackQuery, ctx);
CallbackQueryHandler.Where(k => callbackQuery.Data!.StartsWith(k.Key))
.Select(async k =>
{
await k.Value!(client, callbackQuery, ctx);
return k;
});
break;
case { InlineQuery: { } inlineQuery }:
await InlineHandler.FirstOrDefault(k => inlineQuery.Id.StartsWith(k.Key))
.Value(client, inlineQuery, ctx);
InlineHandler.Where(k => inlineQuery.Id.StartsWith(k.Key)).Select(async k =>
{
await k.Value!(client, inlineQuery, ctx);
return k;
});
break;
case { PreCheckoutQuery: { } preCheckoutQuery }:
if (PreCheckoutHandler != null) await PreCheckoutHandler(client, preCheckoutQuery, ctx);
break;
default:
DefaultUpdateHandler.ForEach(async k => await k(client, update, ctx));
// ReSharper disable once AsyncVoidLambda
DefaultUpdateHandler.ForEach(async k => await k!(client, update, ctx));
break;
}
}
catch (Exception ex)
{
_logger.Log(LogLevel.Error, new EventId(), ex, "Catched exception in UpdateHandler: ");
if (ex is KeyNotFoundException)
Logger.Log(LogLevel.Warning, new EventId(), ex, "Key not found: ");
else
Logger.Log(LogLevel.Error, new EventId(), ex, "Caught exception in UpdateHandler: ");
}
}

Expand All @@ -210,15 +225,15 @@ public async Task StartAsync(CancellationToken cancellationToken)
UpdateHandler,
Config.errorHandler ?? ((_, ex, _) =>
{
_logger.LogError(ex, "Catched error in telegram bot working: ");
Logger.LogError(ex, "Catched error in telegram bot working: ");
return Task.CompletedTask;
}),
Config.ReceiverOptions,
cancellationToken);
}
catch (Exception ex)
{
_logger.Log(LogLevel.Critical, new EventId(), ex, "Failed to start. Catched exception: ");
Logger.Log(LogLevel.Critical, new EventId(), ex, "Failed to start. Catched exception: ");
}
}

Expand All @@ -230,7 +245,7 @@ public async Task StopAsync(CancellationToken cancellationToken)
}
catch (Exception ex)
{
_logger.LogCritical(ex, "Failed to stop. Exception: ");
Logger.LogCritical(ex, "Failed to stop. Exception: ");
}
}
}
8 changes: 4 additions & 4 deletions Telegram.Net/Telegram.Net.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

<PropertyGroup>
<SuppressTfmSupportBuildWarnings>true</SuppressTfmSupportBuildWarnings>
<TargetFramework>net7.0</TargetFramework>
<TargetFrameworks>net6.0;net7.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Version>1.0.2</Version>
<Version>1.0.3</Version>
<Authors>yawaflua</Authors>
<Title>yawaflua.Telegram.Net</Title>
<Description>Telegram.Bots extender pack, what provides to user attributes, which can used with services</Description>
Expand All @@ -19,8 +19,8 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="9.0.3" />
<PackageReference Include="Telegram.Bot" Version="22.4.4" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="(6.0.0,)" />
<PackageReference Include="Telegram.Bot" Version="22.4.*" />
<None Include="..\README.md" Pack="true" PackagePath="\"/>
<None Include="..\LICENSE" Pack="true" PackagePath=""/>
</ItemGroup>
Expand Down
Loading