Skip to content

Commit 9171784

Browse files
committed
feat: add more logging and refactor middleware
1 parent 0e06ff9 commit 9171784

5 files changed

Lines changed: 65 additions & 27 deletions

File tree

ZiziBot.TelegramBot.Framework/Extensions/ClientExtension.cs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using Microsoft.Extensions.Configuration;
44
using Microsoft.Extensions.DependencyInjection;
55
using Microsoft.Extensions.Hosting;
6+
using Microsoft.Extensions.Logging;
67
using ZiziBot.TelegramBot.Framework.Engines;
78
using ZiziBot.TelegramBot.Framework.Handlers;
89
using ZiziBot.TelegramBot.Framework.Interfaces;
@@ -43,6 +44,7 @@ public static IServiceCollection AddZiziBotTelegramBot(this IServiceCollection s
4344
using var provider = services.BuildServiceProvider();
4445

4546
var hostingEnvironment = provider.GetRequiredService<IWebHostEnvironment>();
47+
var logger = provider.GetRequiredService<ILogger<BotEngineHandler>>();
4648

4749
var internalEngineConfig = new BotEngineConfig();
4850

@@ -51,8 +53,8 @@ public static IServiceCollection AddZiziBotTelegramBot(this IServiceCollection s
5153
var botConfigurations = new List<BotTokenConfig>();
5254
var configuration = provider.GetRequiredService<IConfiguration>();
5355

54-
configuration.GetSection(BotTokenConfig.CONFIG_PATH).Bind(botConfigurations);
55-
configuration.GetSection(BotEngineConfig.CONFIG_PATH).Bind(internalEngineConfig);
56+
configuration.GetSection(BotTokenConfig.ConfigPath).Bind(botConfigurations);
57+
configuration.GetSection(BotEngineConfig.ConfigPath).Bind(internalEngineConfig);
5658

5759
services.AddSingleton(botConfigurations);
5860
}
@@ -64,6 +66,8 @@ public static IServiceCollection AddZiziBotTelegramBot(this IServiceCollection s
6466
internalEngineConfig = engineConfig;
6567
}
6668

69+
logger.LogInformation("Bot engine mode is {EngineMode}", internalEngineConfig.EngineMode);
70+
6771

6872
switch (internalEngineConfig.EngineMode)
6973
{
@@ -80,11 +84,13 @@ public static IServiceCollection AddZiziBotTelegramBot(this IServiceCollection s
8084
{
8185
if (hostingEnvironment.IsDevelopment())
8286
{
87+
logger.LogInformation("Starting bot in Polling mode because of Development environment");
8388
services.EnablePollingEngine();
8489
internalEngineConfig.ActualEngineMode = BotEngineMode.Polling;
8590
}
8691
else
8792
{
93+
logger.LogInformation("Starting bot in Webhook mode because of non-Development environment");
8894
services.EnableWebhookEngine();
8995
internalEngineConfig.ActualEngineMode = BotEngineMode.Webhook;
9096
}
@@ -103,13 +109,21 @@ public static IServiceCollection AddZiziBotTelegramBot(this IServiceCollection s
103109

104110
private static IServiceCollection EnablePollingEngine(this IServiceCollection services)
105111
{
112+
using var provider = services.BuildServiceProvider();
113+
var logger = provider.GetRequiredService<ILogger<BotPollingEngine>>();
114+
115+
logger.LogInformation("Enabling Polling engine");
106116
services.AddSingleton<IBotEngine, BotPollingEngine>();
107117

108118
return services;
109119
}
110120

111121
private static IServiceCollection EnableWebhookEngine(this IServiceCollection services)
112122
{
123+
using var provider = services.BuildServiceProvider();
124+
var logger = provider.GetRequiredService<ILogger<BotWebhookEngine>>();
125+
126+
logger.LogInformation("Enabling Webhook engine");
113127
services.AddSingleton<IBotEngine, BotWebhookEngine>();
114128

115129
return services;
@@ -127,7 +141,9 @@ public static async Task<IApplicationBuilder> UseZiziBotTelegramBot(this IApplic
127141
private static async Task<IApplicationBuilder> StartTelegramBot(this IApplicationBuilder app)
128142
{
129143
var botEngine = app.ApplicationServices.GetRequiredService<IBotEngine>();
144+
var logger = app.ApplicationServices.GetRequiredService<ILogger<IBotEngine>>();
130145

146+
logger.LogInformation("Starting bot engine");
131147
await botEngine.Start();
132148

133149
return app;

ZiziBot.TelegramBot.Framework/Handlers/BotUpdateHandler.cs

Lines changed: 44 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ BotEngineConfig botEngineConfig
2323
{
2424
private IEnumerable<Type> BotCommands => GetCommands();
2525
private List<MethodInfo> BotMethods => GetMethods();
26-
27-
#region Invocation
26+
27+
#region Type Handling
2828

2929
public async Task<object?> HandleUpdate(ITelegramBotClient botClient, Update update, CancellationToken token)
3030
{
@@ -63,6 +63,7 @@ private async Task TrackUpdate(ITelegramBotClient botClient, CancellationToken t
6363
{
6464
try
6565
{
66+
logger.LogTrace("Finding command for update type: {UpdateType}", update.Type);
6667
var method = update.Type switch
6768
{
6869
UpdateType.InlineQuery => GetMethod(update.InlineQuery!),
@@ -76,6 +77,8 @@ private async Task TrackUpdate(ITelegramBotClient botClient, CancellationToken t
7677
return null;
7778
}
7879

80+
logger.LogTrace("Found command for update type: {UpdateType}", update.Type);
81+
7982
method.Update = update;
8083
var invokeMethod = await InvokeMethod(botClient, method);
8184

@@ -94,6 +97,7 @@ private async Task TrackUpdate(ITelegramBotClient botClient, CancellationToken t
9497
try
9598
{
9699
var message = update.Message ?? update.EditedMessage;
100+
logger.LogTrace("Finding command for message: {MessageText}", message?.Text);
97101
var method = GetMethod(message!);
98102

99103
if (method == null)
@@ -102,6 +106,8 @@ private async Task TrackUpdate(ITelegramBotClient botClient, CancellationToken t
102106
return null;
103107
}
104108

109+
logger.LogTrace("Found command for message: {MessageText}", message?.Text);
110+
105111
method.Update = update;
106112

107113
var invokeMethod = await InvokeMethod(botClient, method);
@@ -116,6 +122,10 @@ private async Task TrackUpdate(ITelegramBotClient botClient, CancellationToken t
116122
return null;
117123
}
118124

125+
#endregion
126+
127+
#region Invocation
128+
119129
private async Task<object?> InvokeMethod(ITelegramBotClient client, BotCommandInfo? botCommandInfo)
120130
{
121131
if (botCommandInfo is null)
@@ -140,15 +150,38 @@ private async Task TrackUpdate(ITelegramBotClient botClient, CancellationToken t
140150
];
141151
}
142152

143-
#region Before Command Middleware
153+
var middlewarePassed = await ExecuteBeforeMiddlewareAsync(commandContext);
154+
if (!middlewarePassed)
155+
{
156+
return null;
157+
}
144158

159+
#region Invoke Command
160+
161+
var controller = (BotCommandController)ActivatorUtilities.CreateInstance(provider, botCommandInfo.ControllerType);
162+
controller.Context = commandContext;
163+
164+
logger.LogTrace("Invoking command: {Controller}/{Method}", botCommandInfo.ControllerType.Name, botCommandInfo.Method.Name);
165+
var invokeResult = await MethodHelper.InvokeMethod(botCommandInfo.Method, paramList, controller);
166+
logger.LogDebug("Successfully handled UpdateId: {UpdateId} for {UpdateType} ", botCommandInfo.Update!.Id, botCommandInfo.Update!.Type);
167+
168+
#endregion
169+
170+
await ExecuteAfterMiddlewareAsync(commandContext);
171+
172+
return invokeResult;
173+
}
174+
175+
private async Task<bool> ExecuteBeforeMiddlewareAsync(CommandContext commandContext)
176+
{
145177
var beforeCommands = provider.GetServices<IBeforeCommand>()
146178
.Where(x => x.GetType().GetCustomAttribute<DisabledMiddlewareAttribute>() == null)
147179
.Where(x => botEngineConfig.DisabledMiddleware?.Contains(x.GetType().Name) == false)
148180
.ToList();
149181

150182
var passedMiddlewareCount = 0;
151183

184+
logger.LogTrace("Found {Count} BeforeMiddlewares", beforeCommands.Count);
152185
foreach (var command in beforeCommands)
153186
{
154187
var middlewareName = command.GetType().Name;
@@ -167,27 +200,20 @@ await command.ExecuteAsync(commandContext, data =>
167200
{
168201
logger.LogDebug("Handler stops because middleware is not passed");
169202

170-
return null;
203+
return false;
171204
}
172205

173-
#endregion
174-
175-
#region Invoke Command
176-
177-
var controller = (BotCommandController)ActivatorUtilities.CreateInstance(provider, botCommandInfo.ControllerType);
178-
controller.Context = commandContext;
179-
180-
var invokeResult = await MethodHelper.InvokeMethod(botCommandInfo.Method, paramList, controller);
181-
logger.LogDebug("Successfully handled UpdateId: {UpdateId} for {UpdateType} ", botCommandInfo.Update!.Id, botCommandInfo.Update!.Type);
182-
183-
#endregion
184-
185-
#region After Command Middleware
206+
logger.LogTrace("All BeforeMiddlewares passed");
207+
return true;
208+
}
186209

210+
private async Task ExecuteAfterMiddlewareAsync(CommandContext commandContext)
211+
{
187212
var afterCommands = provider.GetServices<IAfterCommand>()
188213
.Where(x => x.GetType().GetCustomAttribute<DisabledMiddlewareAttribute>() == null)
189214
.ToList();
190215

216+
logger.LogTrace("Found {Count} AfterMiddlewares", afterCommands.Count);
191217
foreach (var command in afterCommands)
192218
{
193219
var middlewareName = command.GetType().Name;
@@ -196,14 +222,10 @@ await command.ExecuteAsync(commandContext, data =>
196222
await command.ExecuteAsync(commandContext);
197223
logger.LogDebug("AfterMiddleware - Complete: {Middleware}", middlewareName);
198224
}
199-
200-
#endregion
201-
202-
return invokeResult;
203225
}
204226

205227
#endregion
206-
228+
207229
#region Command
208230

209231
private BotCommandInfo? GetMethod(Update update)

ZiziBot.TelegramBot.Framework/Models/Configs/BotEngineConfig.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ namespace ZiziBot.TelegramBot.Framework.Models.Configs;
44

55
public class BotEngineConfig
66
{
7-
public const string CONFIG_PATH = "BotEngine";
7+
public const string ConfigPath = "BotEngine";
88

99
public string? WebhookUrl { get; set; }
1010
public BotEngineMode EngineMode { get; set; }

ZiziBot.TelegramBot.Framework/Models/Configs/BotTokenConfig.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
public class BotTokenConfig
44
{
5-
public const string CONFIG_PATH = "BotEngine:Bot";
5+
public const string ConfigPath = "BotEngine:Bot";
66

77
public required string Name { get; set; }
88
public required string Token { get; set; }

ZiziBot.TelegramBot.Sample/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
var builder = WebApplication.CreateBuilder(args);
55

66
builder.Services.AddSerilog(x => x
7-
.MinimumLevel.Debug()
7+
.MinimumLevel.Verbose()
88
.WriteTo.Console());
99

1010
builder.Services.AddZiziBotTelegramBot();

0 commit comments

Comments
 (0)