casa-bot/src/CasaBot/CasaBotApp/BotHandler.cs

172 lines
5.3 KiB
C#
Raw Normal View History

2025-02-12 19:15:20 -03:00
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
2025-02-12 19:15:20 -03:00
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<BotHandler> _logger;
private readonly TelegramOptions _telegramOptions;
2025-02-12 19:15:20 -03:00
private readonly List<ChatId> _subscribers = [];
private TelegramBotClient? _bot;
public BotHandler(IOptions<TelegramOptions> telegramConfiguration, ILogger<BotHandler> logger)
2025-02-12 19:15:20 -03:00
{
_logger = logger;
if (string.IsNullOrEmpty(telegramConfiguration.Value.BotToken))
2025-02-12 19:15:20 -03:00
{
_logger.LogError("Bot token is not provided");
throw new ArgumentException("Bot token is required", nameof(telegramConfiguration));
2025-02-12 19:15:20 -03:00
}
_telegramOptions = telegramConfiguration.Value;
2025-02-12 19:15:20 -03:00
}
public void Start(CancellationToken cancellationToken)
{
_logger.LogInformation("Starting bot...");
_bot = new TelegramBotClient(_telegramOptions.BotToken, cancellationToken: cancellationToken);
2025-02-12 19:22:18 -03:00
2025-02-12 19:15:20 -03:00
_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;
}
2025-02-12 19:15:20 -03:00
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");
}
}
2025-02-12 19:15:20 -03:00
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");
2025-02-12 19:22:18 -03:00
2025-02-12 19:15:20 -03:00
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;
}
2025-02-12 19:22:18 -03:00
2025-02-12 19:15:20 -03:00
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}");
}
}
}