Skip to content

Commit 2371180

Browse files
authored
Merge pull request #5 from yawaflua/develop
pre-1.0.3 Fix error, when many commands with one base command(/start, /startapp, etc) not working properly. Fix versions of dependencies for better compatability
2 parents 9b05780 + a691064 commit 2371180

2 files changed

Lines changed: 51 additions & 36 deletions

File tree

Telegram.Net/Services/TelegramHostedService.cs

Lines changed: 47 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
using System.Diagnostics.CodeAnalysis;
22
using System.Reflection;
3-
using System.Runtime.InteropServices.JavaScript;
43
using Microsoft.Extensions.DependencyInjection;
54
using Microsoft.Extensions.Hosting;
65
using Microsoft.Extensions.Logging;
@@ -15,31 +14,32 @@
1514

1615
namespace Telegram.Net.Services;
1716

17+
[SuppressMessage("ReSharper", "ReturnValueOfPureMethodIsNotUsed")]
1818
public class TelegramHostedService : IHostedService
1919
{
20-
private IServiceCollection isc { get; }
21-
internal TelegramBotClient Client { get; set; }
22-
private ITelegramBotConfig Config { get; }
23-
internal Dictionary<string, Func<ITelegramBotClient, Message, CancellationToken, Task>> CommandHandler { get; set; } = new();
24-
internal List<Func<ITelegramBotClient, Message, CancellationToken, Task>> EditedMessageHandler { get; set; } = new();
25-
internal Dictionary<string, Func<ITelegramBotClient, CallbackQuery,CancellationToken, Task>> CallbackQueryHandler { get; set; } = new();
26-
internal Dictionary<string, Func<ITelegramBotClient, InlineQuery ,CancellationToken, Task>> InlineHandler { get; set; } = new();
20+
private IServiceCollection ServiceCollection { get; } = null!;
21+
internal TelegramBotClient Client { get; set; } = null!;
22+
private ITelegramBotConfig Config { get; } = null!;
23+
internal Dictionary<string, Func<ITelegramBotClient, Message, CancellationToken, Task>?> CommandHandler { get; set; } = new();
24+
internal List<Func<ITelegramBotClient, Message, CancellationToken, Task>?> EditedMessageHandler { get; set; } = new();
25+
internal Dictionary<string, Func<ITelegramBotClient, CallbackQuery, CancellationToken, Task>?> CallbackQueryHandler { get; set; } = new();
26+
internal Dictionary<string, Func<ITelegramBotClient, InlineQuery, CancellationToken, Task>?> InlineHandler { get; set; } = new();
2727
internal Func<ITelegramBotClient, PreCheckoutQuery,CancellationToken, Task>? PreCheckoutHandler { get; set; }
28-
internal List<Func<ITelegramBotClient, Update, CancellationToken, Task>> DefaultUpdateHandler { get; set; } = new();
29-
internal static ILogger<TelegramHostedService> _logger;
28+
internal List<Func<ITelegramBotClient, Update, CancellationToken, Task>?> DefaultUpdateHandler { get; set; } = new();
29+
internal static ILogger<TelegramHostedService> Logger = null!;
3030

31-
public TelegramHostedService(ITelegramBotConfig config, IServiceCollection isc, ILogger<TelegramHostedService> logger)
31+
public TelegramHostedService(ITelegramBotConfig config, IServiceCollection serviceCollection, ILogger<TelegramHostedService> logger)
3232
{
3333
try
3434
{
35-
_logger = logger;
35+
Logger = logger;
3636
Client = new TelegramBotClient(config.Token);
3737
Config = config;
38-
this.isc = isc;
38+
this.ServiceCollection = serviceCollection;
3939
}
4040
catch (Exception ex)
4141
{
42-
_logger.Log(LogLevel.Critical, new EventId(), ex, "Catched exception when creating TelegramHostedService: ");
42+
Logger.Log(LogLevel.Critical, new EventId(), ex, "Catched exception when creating TelegramHostedService: ");
4343
}
4444
}
4545
internal static bool IsValidHandlerMethod(MethodInfo method, Type parameterType)
@@ -55,12 +55,12 @@ internal static bool IsValidHandlerMethod(MethodInfo method, Type parameterType)
5555
}
5656
catch (Exception ex)
5757
{
58-
_logger.LogError(ex, "Catched exception in parsing and checking params.");
58+
Logger.LogError(ex, "Catched exception in parsing and checking params.");
5959
return false;
6060
}
6161
}
6262

63-
internal static Func<ITelegramBotClient, T, CancellationToken, Task> CreateDelegate<T>(MethodInfo method)
63+
internal static Func<ITelegramBotClient, T, CancellationToken, Task>? CreateDelegate<T>(MethodInfo method)
6464
{
6565
try
6666
{
@@ -70,7 +70,7 @@ internal static Func<ITelegramBotClient, T, CancellationToken, Task> CreateDeleg
7070
}
7171
catch (Exception ex)
7272
{
73-
_logger.Log(LogLevel.Critical, new EventId(), ex, "Catched exception in CreateDelegate function: ");
73+
Logger.Log(LogLevel.Critical, new EventId(), ex, "Catched exception in CreateDelegate function: ");
7474
return null;
7575
}
7676

@@ -106,10 +106,10 @@ await Task.Run(async () =>
106106

107107
if (methods.Count == 0)
108108
{
109-
_logger.LogWarning("No methods found with required attributes");
109+
Logger.LogWarning("No methods found with required attributes");
110110
}
111111

112-
var isp = isc.BuildServiceProvider();
112+
var isp = ServiceCollection.BuildServiceProvider();
113113
foreach (var method in methods)
114114
{
115115
var declaringType = method.DeclaringType!;
@@ -156,7 +156,7 @@ await Task.Run(async () =>
156156
}
157157
catch (Exception ex)
158158
{
159-
_logger.Log(LogLevel.Critical, new EventId(), ex, "Catched new exception when added methods: ");
159+
Logger.Log(LogLevel.Critical, new EventId(), ex, "Catched new exception when added methods: ");
160160
}
161161
}, cancellationToken);
162162
}
@@ -169,31 +169,46 @@ internal async Task UpdateHandler(ITelegramBotClient client, Update update, Canc
169169
switch (update)
170170
{
171171
case { Message: { } message }:
172-
await CommandHandler.FirstOrDefault(k => message.Text!.StartsWith(k.Key))
173-
.Value(client, message, ctx);
172+
CommandHandler.Where(k => message.Text!.StartsWith(k.Key)).Select(async k =>
173+
{
174+
await k.Value!(client, message, ctx);
175+
return k;
176+
});
174177
break;
175178
case { EditedMessage: { } message }:
176-
EditedMessageHandler.ForEach(async k => await k(client, message, ctx));
179+
// ReSharper disable once AsyncVoidLambda
180+
EditedMessageHandler.ForEach(async k => await k!(client, message, ctx));
177181
break;
178182
case { CallbackQuery: { } callbackQuery }:
179-
await CallbackQueryHandler.FirstOrDefault(k => callbackQuery.Data!.StartsWith(k.Key))
180-
.Value(client, callbackQuery, ctx);
183+
CallbackQueryHandler.Where(k => callbackQuery.Data!.StartsWith(k.Key))
184+
.Select(async k =>
185+
{
186+
await k.Value!(client, callbackQuery, ctx);
187+
return k;
188+
});
181189
break;
182190
case { InlineQuery: { } inlineQuery }:
183-
await InlineHandler.FirstOrDefault(k => inlineQuery.Id.StartsWith(k.Key))
184-
.Value(client, inlineQuery, ctx);
191+
InlineHandler.Where(k => inlineQuery.Id.StartsWith(k.Key)).Select(async k =>
192+
{
193+
await k.Value!(client, inlineQuery, ctx);
194+
return k;
195+
});
185196
break;
186197
case { PreCheckoutQuery: { } preCheckoutQuery }:
187198
if (PreCheckoutHandler != null) await PreCheckoutHandler(client, preCheckoutQuery, ctx);
188199
break;
189200
default:
190-
DefaultUpdateHandler.ForEach(async k => await k(client, update, ctx));
201+
// ReSharper disable once AsyncVoidLambda
202+
DefaultUpdateHandler.ForEach(async k => await k!(client, update, ctx));
191203
break;
192204
}
193205
}
194206
catch (Exception ex)
195207
{
196-
_logger.Log(LogLevel.Error, new EventId(), ex, "Catched exception in UpdateHandler: ");
208+
if (ex is KeyNotFoundException)
209+
Logger.Log(LogLevel.Warning, new EventId(), ex, "Key not found: ");
210+
else
211+
Logger.Log(LogLevel.Error, new EventId(), ex, "Caught exception in UpdateHandler: ");
197212
}
198213
}
199214

@@ -210,15 +225,15 @@ public async Task StartAsync(CancellationToken cancellationToken)
210225
UpdateHandler,
211226
Config.errorHandler ?? ((_, ex, _) =>
212227
{
213-
_logger.LogError(ex, "Catched error in telegram bot working: ");
228+
Logger.LogError(ex, "Catched error in telegram bot working: ");
214229
return Task.CompletedTask;
215230
}),
216231
Config.ReceiverOptions,
217232
cancellationToken);
218233
}
219234
catch (Exception ex)
220235
{
221-
_logger.Log(LogLevel.Critical, new EventId(), ex, "Failed to start. Catched exception: ");
236+
Logger.Log(LogLevel.Critical, new EventId(), ex, "Failed to start. Catched exception: ");
222237
}
223238
}
224239

@@ -230,7 +245,7 @@ public async Task StopAsync(CancellationToken cancellationToken)
230245
}
231246
catch (Exception ex)
232247
{
233-
_logger.LogCritical(ex, "Failed to stop. Exception: ");
248+
Logger.LogCritical(ex, "Failed to stop. Exception: ");
234249
}
235250
}
236251
}

Telegram.Net/Telegram.Net.csproj

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22

33
<PropertyGroup>
44
<SuppressTfmSupportBuildWarnings>true</SuppressTfmSupportBuildWarnings>
5-
<TargetFramework>net7.0</TargetFramework>
5+
<TargetFrameworks>net6.0;net7.0</TargetFrameworks>
66
<ImplicitUsings>enable</ImplicitUsings>
77
<Nullable>enable</Nullable>
8-
<Version>1.0.2</Version>
8+
<Version>1.0.3</Version>
99
<Authors>yawaflua</Authors>
1010
<Title>yawaflua.Telegram.Net</Title>
1111
<Description>Telegram.Bots extender pack, what provides to user attributes, which can used with services</Description>
@@ -19,8 +19,8 @@
1919
</PropertyGroup>
2020

2121
<ItemGroup>
22-
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="9.0.3" />
23-
<PackageReference Include="Telegram.Bot" Version="22.4.4" />
22+
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="(6.0.0,)" />
23+
<PackageReference Include="Telegram.Bot" Version="22.4.*" />
2424
<None Include="..\README.md" Pack="true" PackagePath="\"/>
2525
<None Include="..\LICENSE" Pack="true" PackagePath=""/>
2626
</ItemGroup>

0 commit comments

Comments
 (0)