using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Telegram.Bot; using Telegram.Bot.Polling; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.ReplyMarkups; namespace CasaBotApp; public class BotHandler { private readonly ILogger _logger; private readonly TelegramOptions _telegramOptions; private readonly List _subscribers = []; private TelegramBotClient? _bot; public BotHandler(IOptions telegramConfiguration, ILogger logger) { _logger = logger; if (string.IsNullOrEmpty(telegramConfiguration.Value.BotToken)) { _logger.LogError("Bot token is not provided"); throw new ArgumentException("Bot token is required", nameof(telegramConfiguration)); } _telegramOptions = telegramConfiguration.Value; } public void Start(CancellationToken cancellationToken) { _logger.LogInformation("Starting bot..."); _bot = new TelegramBotClient(_telegramOptions.BotToken, cancellationToken: cancellationToken); _bot.OnError += OnError; _bot.OnMessage += OnMessage; _bot.OnUpdate += OnUpdate; } public void Update(string message) { if (_bot is null) { _logger.LogWarning("Bot is not initialized yet"); return; } if (_subscribers.Count == 0) { _logger.LogWarning("No subscribers to send message to"); return; } foreach (var subscriber in _subscribers) { _bot.SendMessage(subscriber, message); } } public void Subscribe(long id) { if (_subscribers.Any(s => s.Identifier == id)) { _logger.LogWarning("User {Id} is already subscribed", id); return; } _subscribers.Add(new ChatId(id)); _logger.LogInformation("User {Id} subscribed to receive messages", id); } public async Task UpdatePhoto(string path) { if (_bot is null) { _logger.LogWarning("Bot is not initialized yet"); return; } 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); var inputFile = InputFile.FromStream(stream, Path.GetFileName(path)); await _bot.SendPhoto(subscriber, inputFile, "Detected object"); } } private async Task SendImageTest(long id) { if (_bot is null) { _logger.LogWarning("Bot is not initialized yet"); return; } await using var stream = File.OpenRead(@"C:\Users\GuillermoMarcel\Pictures\prueba.jpeg"); var inputFile = InputFile.FromStream(stream, "gorda.jpeg"); await _bot.SendPhoto(new ChatId(id), inputFile, "mi gorda"); } // method to handle errors in polling or in your OnMessage/OnUpdate code private Task OnError(Exception exception, HandleErrorSource source) { _logger.LogError(exception, "Error in {Source}", source); return Task.CompletedTask; } private async Task OnMessage(Message msg, UpdateType type) { if (_bot is null) { _logger.LogWarning("Bot is not initialized yet"); return; } switch (msg.Text) { case "/start": await _bot.SendMessage(msg.Chat, "Welcome! Pick one direction", replyMarkup: new InlineKeyboardMarkup().AddButtons("Left", "Right")); return; case "/register": if (_subscribers.Any(s => s.Identifier == msg.Chat.Id)) { await _bot.SendMessage(msg.Chat, "You are already registered to receive messages"); return; } _subscribers.Add(msg.Chat); _logger.LogInformation("User {User} registered to receive messages", msg.Chat); await _bot.SendMessage(msg.Chat, "You are registered to receive messages every minute"); return; case "/photo": await SendImageTest(msg.Chat.Id); return; default: _logger.LogInformation("Received {Type} '{Text}' in {Chat}", type, msg.Text, msg.Chat); await _bot.SendMessage(msg.Chat, "Commands: \n/start to start over \n/register to get messages every minute \n/photo to get a photo"); // await _bot.SendMessage(msg.Chat, "Hola vida te amo mucho ❤️"); break; } } // method that handle other types of updates received by the bot: private async Task OnUpdate(Update update) { if (_bot is null) { _logger.LogWarning("Bot is not initialized yet"); return; } if (update is { CallbackQuery: { } query }) // non-null CallbackQuery { await _bot.AnswerCallbackQuery(query.Id, $"You picked {query.Data}"); await _bot.SendMessage(query.Message!.Chat, $"User {query.From} clicked on {query.Data}"); } } }