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

74 lines
2.0 KiB
C#
Raw Normal View History

2025-02-12 19:15:20 -03:00
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);
}
}