refactor: extract loggin commands and retry to extensions

This commit is contained in:
Guillermo Marcel 2025-03-26 15:39:55 -03:00
parent 5133e80273
commit 0fd63ce192
3 changed files with 88 additions and 0 deletions

View File

@ -0,0 +1,50 @@
using AutoScan;
using Microsoft.Extensions.Logging;
namespace CasaBotApp.Extensions;
public static class CommandRegister
{
public static void RegisterCommands(BotHandler botHandler, AutoScanApp autoScanApp)
{
botHandler.RegisterCommand(new BotCommand
{
Command = "/soyandre",
Description = "Soy Andre",
Action = async (message, ctx) =>
{
await ctx.Responder(message, "Hola vida, te amo mucho ❤️");
}
});
botHandler.RegisterCommand(new BotCommand
{
Command = "/startScan",
Description = "Start a scan of last night images",
Action = async (message, ctx) =>
{
await ctx.Responder(message, "Starting scan 🔍📼");
await autoScanApp.StartNewScan();
}
});
}
public static void UpdateOnScanCompleted(BotHandler botHandler, AutoScanApp autoScanApp, ILogger logger)
{
autoScanApp.OnScanCompleted = async options =>
{
logger.LogInformation("Scan completed at {At}", DateTime.Now);
try
{
//list all the images in the detection folder
if (options.Scanner?.DetectionFolder is null)
return;
var images = Directory.GetFiles(options.Scanner.DetectionFolder , "*.jpg");
await botHandler.Update($"Scan completed, found {images.Length} images");
await botHandler.UpdatePhotos(images);
}catch(Exception ex)
{
logger.LogError(ex, "Error while sending message");
}
};
}
}

View File

@ -0,0 +1,23 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace CasaBotApp.Extensions;
public static class LoggingExtensions
{
public static void AddLogging(this IServiceCollection services, IConfiguration configuration)
{
services.AddLogging(builder =>
{
builder.AddConfiguration(configuration.GetSection("Logging"));
//add time to logs
builder.AddSimpleConsole(options =>
{
options.IncludeScopes = true;
options.SingleLine = true;
options.TimestampFormat = "[HH:mm:ss] ";
});
});
}
}

View File

@ -0,0 +1,15 @@
using Polly;
using Polly.Extensions.Http;
namespace CasaBotApp.Extensions;
public class RetryPolicyExtension
{
public static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
{
return HttpPolicyExtensions
.HandleTransientHttpError()
.WaitAndRetryForeverAsync(retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
}
}