diff --git a/src/CasaBot/CasaBotApp/TelegramBot/BotHandler.cs b/src/CasaBot/CasaBotApp/TelegramBot/BotHandler.cs index 9eb9013..802888b 100644 --- a/src/CasaBot/CasaBotApp/TelegramBot/BotHandler.cs +++ b/src/CasaBot/CasaBotApp/TelegramBot/BotHandler.cs @@ -16,22 +16,21 @@ namespace CasaBotApp.TelegramBot; public class BotHandler : IUpdateHandler { private readonly ILogger _logger; - private readonly TelegramOptions _telegramOptions; private readonly List _subscribers = []; private readonly List _subscribersAlarm = []; private readonly Dictionary _commands; - //TODO hacerlo mejor. + private readonly Dictionary _callbackFunctions = new(); private record CallbackQueueItem(DateTime inserted, Func> callback); - public Func? OnReply { get; set; } = null; + public Func? OnReply { get; set; } private readonly IBotClient _bot; public BotHandler(IBotClient bot, IOptions telegramConfiguration, ILogger 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 } /// - /// Send text message to all subscribers + /// Send a text message to all subscribers /// /// public Task UpdateText(string message) => UpdateTextInt(_subscribers, message); public Task AlertText(string message) => UpdateTextInt(_subscribersAlarm, message); - public async Task UpdateTextInt(List subscribers,string message) + + private async Task UpdateTextInt(List subscribers,string message) { if (subscribers.Count == 0) { @@ -137,7 +128,7 @@ public class BotHandler : IUpdateHandler /// - /// Send photo to all subscribers + /// Send a photo to all subscribers /// /// /// Optional message with photo @@ -145,6 +136,13 @@ public class BotHandler : IUpdateHandler public Task UpdatePhoto(string path, string? caption = null, IEnumerable? options = null) => UpdatePhotoInt(_subscribers, path, caption, options); + /// + /// Send a photo to all alert subscribers + /// + /// + /// + /// + /// public Task AlertPhoto(string path, string? caption = null, IEnumerable? 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)); + /// + /// Entry point for the bot + /// + /// The bot client used to receive and send messages + /// Type of update and message info + /// + /// public Task HandleAsync(IBotClient bot, Update update, CancellationToken cst) { try