using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Telegram.Bots; using Telegram.Bots.Extensions.Polling; using Telegram.Bots.Requests.Usernames; using Telegram.Bots.Types; using File = System.IO.File; namespace CasaBotApp; public class BotHandler : IUpdateHandler { private readonly ILogger _logger; private readonly TelegramOptions _telegramOptions; private readonly List _subscribers = []; private readonly IBotClient _bot; public BotHandler(IBotClient bot, IOptions telegramConfiguration, ILogger logger) { _logger = logger; _telegramOptions = telegramConfiguration.Value; _bot = bot; } public void Start(CancellationToken cancellationToken) { foreach (var subs in _telegramOptions.SubscribedChatIds) { Subscribe(subs); } } public void Subscribe(long id) { if (_subscribers.Any(x => x.Id == id)) { _logger.LogWarning("User {Id} is already subscribed", id); return; } _subscribers.Add(new Chat() { Id = id }); _logger.LogInformation("User {Id} subscribed to receive messages", id); } public async Task Update(string message) { if (_subscribers.Count == 0) { _logger.LogWarning("No subscribers to send message to"); return; } var replacement = new List<(Chat from, Chat to)>(); foreach (var subscriber in _subscribers) { var response = await SndTxt(subscriber, message); if (subscriber.FirstName is null) { replacement.Add((subscriber, response.Result.Chat)); } } foreach (var rep in replacement) { _subscribers.Remove(rep.from); _subscribers.Add(rep.to); } } public async Task UpdatePhoto(string path) { if (_subscribers.Count == 0) { _logger.LogWarning("No subscribers to send message to"); return; } foreach (var subscriber in _subscribers) { await using var stream = File.OpenRead(path); await SndPhoto(subscriber, stream); } } private async Task SendImageTest(long id) { await using var stream = File.OpenRead(@"C:\Users\GuillermoMarcel\Pictures\prueba.jpeg"); var send = new SendPhotoFile(id.ToString(), stream); await _bot.HandleAsync(send); } private async Task OnMessage(TextMessage msg) { switch (msg.Text) { case "/register": if (_subscribers.Any(c => c.Id == msg.Chat.Id)) { await Respond(msg, "You are already registered to receive messages"); return; } _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"); return; case "/photo": await SendImageTest(msg.Chat.Id); return; case "/soyandre": await Respond(msg, "Hola vida, te amo mucho ❤️"); return; default: _logger.LogInformation("Received '{Text}' in {Chat}", msg.Text, msg.Chat); const string commands = "Commands: \n/help to show the commands \n/register to get messages every minute \n/photo to get a photo \n/soyandre por si sos andre"; await Respond(msg, commands); break; } } private Task> SndTxt(long id, string txt) => _bot.HandleAsync(new SendText(id.ToString(), txt)); private Task> SndTxt(Chat chat, string txt) => SndTxt(chat.Id, txt); private Task> Respond(Message msg, string txt) => SndTxt(msg.Chat.Id, txt); private Task> SndPhoto(Chat chat, FileStream path) => _bot.HandleAsync(new SendPhotoFile(chat.Id.ToString(), path)); public Task HandleAsync(IBotClient bot, Update update, CancellationToken cst) { try { return update switch { MessageUpdate u when u.Data is TextMessage message => OnMessage(message), EditedMessageUpdate u when u.Data is TextMessage message => bot.HandleAsync(new SendText(message.Chat.Id.ToString(), message.Text) { ReplyToMessageId = message.Id }, cst), _ => Task.CompletedTask }; }catch (Exception e) { _logger.LogError(e, "Error handling update"); return Task.CompletedTask; } } }