New feature: Web api and a custom webpage to show a random cat.

This commit is contained in:
2024-12-29 15:57:10 +03:30
parent 340192d7f0
commit d02d5744ff
5 changed files with 391 additions and 5 deletions

View File

@@ -1,5 +1,7 @@
using CatsOfMastodonBot.Models;
using CatsOfMastodonBot.Services;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using mstdnCats.Services;
using Telegram.Bot;
@@ -30,6 +32,21 @@ public class MastodonBot
var db = await DbInitializer.SetupDb(config.MONGODB_CONNECTION_STRING, config.DB_NAME);
logger.LogInformation("DB setup done");
// Web server setup
var host = Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseKestrel(options =>
{
options.ListenAnyIP(5005); // Listen on port 5005
});
ServerStartup.Serverstartup(db);
webBuilder.UseStartup<ServerStartup>();
})
.Build();
await host.RunAsync();
// Setup bot
var bot = new TelegramBotClient(config.BOT_TOKEN);
@@ -41,13 +58,14 @@ public class MastodonBot
logger.LogInformation("Setup complete");
logger.LogInformation($"Bot is running as {me.FirstName} - instance: {config.INSTANCE}");
// Handle bot updates
// Handle bot updates - For glass buttons functionality
async Task OnUpdate(Update update)
{
switch (update)
{
case { CallbackQuery: { } callbackQuery }:
{
// Send a new cat picture
if (callbackQuery.Data == "new_random")
{
await HandleStartMessage.HandleStartMessageAsync(callbackQuery.Message, bot, db, logger,
@@ -55,11 +73,14 @@ public class MastodonBot
break;
}
else
// Approve or reject a post
else if (callbackQuery.Data.Contains("approve-") || callbackQuery.Data.Contains("reject-"))
{
await HandlePostAction.HandleCallbackQuery(callbackQuery, db, bot, logger);
break;
}
break;
}
default: logger.LogInformation($"Received unhandled update {update.Type}"); break;
}
@@ -72,14 +93,16 @@ public class MastodonBot
{
if (message.Text == "/start" && message.Chat.Type == ChatType.Private)
await HandleStartMessage.HandleStartMessageAsync(message, bot, db, logger);
else if (message.Text == "/backup")
else if (message.Text == "/backup" && message.Chat.Type == ChatType.Private)
await HandleDbBackup.HandleDbBackupAsync(bot, logger, config.DB_NAME, config.ADMIN_NUMID, db);
// Send a message to prompt user to send /start and recieve their cat photo only if its from a telegram user and not a channel
else if (message.Chat.Type == ChatType.Private)
await HandleStartMessage.HandleStartMessageAsync(message, bot, db, logger);
}
// Set a timer to fetch and process posts every 15 minutes
// Set a timer to fetch and process posts every 10 minutes
_postFetchTimer = new Timer(async _ => await RunCheck.runAsync(db, bot, config.TAG, logger, config.INSTANCE),
null, TimeSpan.Zero, TimeSpan.FromMinutes(10));
// Another timer to automatically backup the DB every 6 hour