feat: initial version of working bot

This commit is contained in:
Guillermo Marcel 2025-02-12 19:15:20 -03:00
parent 7348178d56
commit 37f987d244
7 changed files with 304 additions and 0 deletions

25
src/CasaBot/.dockerignore Normal file
View File

@ -0,0 +1,25 @@
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/.idea
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md

16
src/CasaBot/CasaBot.sln Normal file
View File

@ -0,0 +1,16 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CasaBotApp", "CasaBotApp\CasaBotApp.csproj", "{FF1AF6E7-88E4-488B-B6FB-BDAC126DD94E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{FF1AF6E7-88E4-488B-B6FB-BDAC126DD94E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FF1AF6E7-88E4-488B-B6FB-BDAC126DD94E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FF1AF6E7-88E4-488B-B6FB-BDAC126DD94E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FF1AF6E7-88E4-488B-B6FB-BDAC126DD94E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,6 @@
namespace CasaBotApp;
public class BotConfiguration
{
public required string Token { get; set; }
}

View File

@ -0,0 +1,142 @@
using Microsoft.Extensions.Logging;
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 BotConfiguration _botConfiguration;
private readonly List<ChatId> _subscribers = [];
private TelegramBotClient? _bot;
public BotHandler(BotConfiguration botConfiguration, ILogger<BotHandler> logger)
{
_logger = logger;
if (string.IsNullOrEmpty(botConfiguration.Token))
{
_logger.LogError("Bot token is not provided");
throw new ArgumentException("Bot token is required", nameof(botConfiguration));
}
_botConfiguration = botConfiguration;
}
public void Start(CancellationToken cancellationToken)
{
_logger.LogInformation("Starting bot...");
_bot = new TelegramBotClient(_botConfiguration.Token, cancellationToken: cancellationToken);
// var me = await _bot.GetMe();
_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);
}
}
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");
// var message = await _bot.SendPhotoAsync(new ChatId(id), new InputOnlineFile(stream, "prueba.jpeg"));
// await _bot.SendDocument(new ChatId(id), document: inputFile, caption: "imagen de prueba");
// await _bot.SendPhoto(new ChatId(id),
// "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/6.png", "Wild charizard");
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;
}
// method that handle messages received by the bot:
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}");
}
}
}

View File

@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<Content Include="..\.dockerignore">
<Link>.dockerignore</Link>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Telegram.Bot" Version="22.3.0" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,21 @@
FROM mcr.microsoft.com/dotnet/runtime:9.0 AS base
USER $APP_UID
WORKDIR /app
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["CasaBotApp/CasaBotApp.csproj", "CasaBotApp/"]
RUN dotnet restore "CasaBotApp/CasaBotApp.csproj"
COPY . .
WORKDIR "/src/CasaBotApp"
RUN dotnet build "CasaBotApp.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "CasaBotApp.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "CasaBotApp.dll"]

View File

@ -0,0 +1,73 @@
using CasaBotApp;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
// See https://aka.ms/new-console-template for more information
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddJsonFile($"appsettings.json", true, true)
.AddJsonFile($"appsettings.{environment}.json", true, true)
.AddEnvironmentVariables()
.Build();
var serviceCollection = new ServiceCollection();
serviceCollection.AddLogging(builder =>
{
builder.AddConsole();
});
serviceCollection.AddSingleton(new BotConfiguration()
{
Token = configuration.GetValue<string>("TelegramToken") ?? ""
});
serviceCollection.AddSingleton<BotHandler>();
var serviceProvider = serviceCollection.BuildServiceProvider();
// var url = "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getMe";
// var token = ;
var botHandler = serviceProvider.GetService<BotHandler>();
if (botHandler is null)
{
Console.WriteLine("Bot is not initialized");
return;
}
using var cts = new CancellationTokenSource();
botHandler.Start(cts.Token);
// call the bot handler to send a message every minute to the subscribers
_ = SendMessageToSubscribers(cts.Token);
// var bot = new TelegramBotClient(token, cancellationToken: cts.Token);
// var me = await bot.GetMe();
//
// bot.OnError += OnError;
// bot.OnMessage += OnMessage;
// bot.OnUpdate += OnUpdate;
//
Console.WriteLine($"bot is running... Press Enter to terminate");
Console.ReadLine();
cts.Cancel(); // stop the bot
return;
//async method to send a message to the subscribers every two minutes with the current time
async Task SendMessageToSubscribers(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
await Task.Delay(TimeSpan.FromMinutes(1), cancellationToken);
botHandler.Update("Hello from CasaBot! at " + DateTime.Now);
}
}