fix: add comments and fix small warnings in BotHandler.cs
This commit is contained in:
parent
77b4c21571
commit
66aa064e2f
@ -16,22 +16,21 @@ namespace CasaBotApp.TelegramBot;
|
||||
public class BotHandler : IUpdateHandler
|
||||
{
|
||||
private readonly ILogger<BotHandler> _logger;
|
||||
private readonly TelegramOptions _telegramOptions;
|
||||
private readonly List<Chat> _subscribers = [];
|
||||
private readonly List<Chat> _subscribersAlarm = [];
|
||||
private readonly Dictionary<string, BotCommand> _commands;
|
||||
//TODO hacerlo mejor.
|
||||
|
||||
private readonly Dictionary<string, CallbackQueueItem> _callbackFunctions = new();
|
||||
private record CallbackQueueItem(DateTime inserted, Func<string, long, Task<string>> callback);
|
||||
|
||||
public Func<TextMessage, Task>? OnReply { get; set; } = null;
|
||||
public Func<TextMessage, Task>? OnReply { get; set; }
|
||||
|
||||
private readonly IBotClient _bot;
|
||||
|
||||
public BotHandler(IBotClient bot, IOptions<TelegramOptions> telegramConfiguration, ILogger<BotHandler> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
_telegramOptions = telegramConfiguration.Value;
|
||||
var telegramOptions = telegramConfiguration.Value;
|
||||
_bot = bot;
|
||||
_commands = [];
|
||||
RegisterCommand(new()
|
||||
@ -41,28 +40,19 @@ public class BotHandler : IUpdateHandler
|
||||
Action = RegisterUser,
|
||||
Responder = Respond
|
||||
});
|
||||
{
|
||||
RegisterCommand(new()
|
||||
{
|
||||
Command = "/registeralarm",
|
||||
Description = "Register to receive alarms",
|
||||
Action = RegisterUserAlarm,
|
||||
Responder = Respond
|
||||
});
|
||||
}
|
||||
RegisterCommand(new()
|
||||
{
|
||||
Command = "/photo",
|
||||
Description = "Get a photo",
|
||||
Action = SendImageTest,
|
||||
Command = "/registeralarm",
|
||||
Description = "Register to receive alarms",
|
||||
Action = RegisterUserAlarm,
|
||||
Responder = Respond
|
||||
});
|
||||
|
||||
foreach (var subs in _telegramOptions.SubscribedChatIds)
|
||||
foreach (var subs in telegramOptions.SubscribedChatIds)
|
||||
{
|
||||
Subscribe(subs);
|
||||
}
|
||||
foreach(var sub in _telegramOptions.SubscribedAlarmsChatIds)
|
||||
foreach(var sub in telegramOptions.SubscribedAlarmsChatIds)
|
||||
{
|
||||
SubscribeAlarm(sub);
|
||||
}
|
||||
@ -105,12 +95,13 @@ public class BotHandler : IUpdateHandler
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Send text message to all subscribers
|
||||
/// Send a text message to all subscribers
|
||||
/// </summary>
|
||||
/// <param name="message"></param>
|
||||
public Task UpdateText(string message) => UpdateTextInt(_subscribers, message);
|
||||
public Task AlertText(string message) => UpdateTextInt(_subscribersAlarm, message);
|
||||
public async Task UpdateTextInt(List<Chat> subscribers,string message)
|
||||
|
||||
private async Task UpdateTextInt(List<Chat> subscribers,string message)
|
||||
{
|
||||
if (subscribers.Count == 0)
|
||||
{
|
||||
@ -137,7 +128,7 @@ public class BotHandler : IUpdateHandler
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Send photo to all subscribers
|
||||
/// Send a photo to all subscribers
|
||||
/// </summary>
|
||||
/// <param name="path"></param>
|
||||
/// <param name="caption">Optional message with photo</param>
|
||||
@ -145,6 +136,13 @@ public class BotHandler : IUpdateHandler
|
||||
public Task UpdatePhoto(string path, string? caption = null, IEnumerable<MsgOption>? options = null) =>
|
||||
UpdatePhotoInt(_subscribers, path, caption, options);
|
||||
|
||||
/// <summary>
|
||||
/// Send a photo to all alert subscribers
|
||||
/// </summary>
|
||||
/// <param name="path"></param>
|
||||
/// <param name="caption"></param>
|
||||
/// <param name="options"></param>
|
||||
/// <returns></returns>
|
||||
public Task AlertPhoto(string path, string? caption = null, IEnumerable<MsgOption>? options = null) =>
|
||||
UpdatePhotoInt(_subscribersAlarm, path, caption, options);
|
||||
|
||||
@ -194,7 +192,7 @@ public class BotHandler : IUpdateHandler
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleQueueExpiration()
|
||||
private Task HandleQueueExpiration()
|
||||
{
|
||||
//remove expired items with more than 3 hs
|
||||
var expired = _callbackFunctions.Where(x => x.Value.inserted.AddHours(3) < DateTime.Now).ToArray();
|
||||
@ -203,6 +201,7 @@ public class BotHandler : IUpdateHandler
|
||||
_callbackFunctions.Remove(item.Key);
|
||||
_logger.LogDebug("Removed expired callback function {Key}", item.Key);
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
|
||||
@ -251,8 +250,8 @@ public class BotHandler : IUpdateHandler
|
||||
|
||||
if (_subscribers.Count < 1) return;
|
||||
|
||||
var caches = response.Result.Select(x => (x as PhotoMessage).PhotoSet.LastOrDefault()?.Id).ToList();
|
||||
var media = caches.Select(x => new CachedPhoto(x)).ToList();
|
||||
var caches = response.Result.Select(x => (x as PhotoMessage)!.PhotoSet.LastOrDefault()?.Id).ToList();
|
||||
var media = caches.Select(x => new CachedPhoto(x!)).ToList();
|
||||
|
||||
//send to the rest of the subscribers
|
||||
foreach (var subscriber in _subscribers.Skip(1).ToList())
|
||||
@ -272,14 +271,6 @@ public class BotHandler : IUpdateHandler
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SendImageTest(TextMessage msg, BotCommand _)
|
||||
{
|
||||
await using var stream = File.OpenRead(@"C:\Users\GuillermoMarcel\Pictures\prueba.jpeg");
|
||||
|
||||
var send = new SendPhotoFile(msg.Chat.Id.ToString(), stream);
|
||||
await _bot.HandleAsync(send);
|
||||
}
|
||||
|
||||
public async Task SendPhoto(long chatId, string content, string caption)
|
||||
{
|
||||
await using var stream = File.OpenRead(content);
|
||||
@ -370,7 +361,15 @@ public class BotHandler : IUpdateHandler
|
||||
|
||||
private async Task OnMessage(TextMessage msg)
|
||||
{
|
||||
if(!_commands.TryGetValue(msg.Text, out var command))
|
||||
var cmd = msg.Text;
|
||||
//Deep link support
|
||||
// link format: https://t.me/your_bot?start=command
|
||||
// what we see: "/start command"
|
||||
if (cmd.StartsWith("/start "))
|
||||
{
|
||||
cmd = $"/{cmd[7..]}";
|
||||
}
|
||||
if(!_commands.TryGetValue(cmd, out var command))
|
||||
{
|
||||
if (msg.ReplyToMessage != null && OnReply is not null)
|
||||
{
|
||||
@ -381,12 +380,12 @@ public class BotHandler : IUpdateHandler
|
||||
return;
|
||||
}
|
||||
|
||||
if (command?.Action is null)
|
||||
if (command.Action is null)
|
||||
{
|
||||
_logger.LogError("Command {Command} has no action", msg.Text);
|
||||
}
|
||||
|
||||
await command!.Action!(msg, command);
|
||||
await command.Action!(msg, command);
|
||||
}
|
||||
|
||||
private async Task SendHelp(TextMessage msg)
|
||||
@ -411,7 +410,7 @@ public class BotHandler : IUpdateHandler
|
||||
|
||||
_subscribers.Add(msg.Chat);
|
||||
_logger.LogInformation("User {User} ({id}) registered to receive messages", msg.Chat.FirstName, msg.Chat.Id);
|
||||
await Respond(msg, "You are registered to receive messages every minute");
|
||||
await Respond(msg, "You are registered to receive non-alert messages (Nightly scans)");
|
||||
}
|
||||
private async Task RegisterUserAlarm(TextMessage msg, BotCommand _)
|
||||
{
|
||||
@ -434,6 +433,13 @@ public class BotHandler : IUpdateHandler
|
||||
_bot.HandleAsync(new SendPhotoFile(chat.Id.ToString(), path));
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Entry point for the bot
|
||||
/// </summary>
|
||||
/// <param name="bot">The bot client used to receive and send messages</param>
|
||||
/// <param name="update">Type of update and message info</param>
|
||||
/// <param name="cst"></param>
|
||||
/// <returns></returns>
|
||||
public Task HandleAsync(IBotClient bot, Update update, CancellationToken cst)
|
||||
{
|
||||
try
|
||||
|
Loading…
Reference in New Issue
Block a user