From 77f1a931fdea1e8ee971000807915f2b7d1d49ec Mon Sep 17 00:00:00 2001 From: Mohammad Mahdi Mohammadi Date: Sat, 14 Sep 2024 21:34:21 +0330 Subject: [PATCH] added support for .env file and improved validation --- Program.cs | 47 ++++++++++++++++++++++-------------- Services/CheckEnv.cs | 21 ++++++++++++++++ Services/DbInitializer.cs | 25 ++++++++++--------- Services/HandlePostAction.cs | 2 +- Services/ProcessPosts.cs | 2 +- mstdnCats.csproj | 1 + 6 files changed, 67 insertions(+), 31 deletions(-) create mode 100644 Services/CheckEnv.cs diff --git a/Program.cs b/Program.cs index 06ec5ed..16c3471 100644 --- a/Program.cs +++ b/Program.cs @@ -7,9 +7,11 @@ public class MastodonBot { private static Timer _timer; - + private static async Task Main() { + DotNetEnv.Env.Load(); + // Configure logging using var loggerFactory = LoggerFactory.Create(builder => { @@ -17,8 +19,12 @@ public class MastodonBot }); var logger = loggerFactory.CreateLogger(); + if(!CheckEnv.IsValid()){ + logger.LogCritical("Error reading envinonment variables, either some values are missing or no .env file was found"); + throw new Exception("Error reading envinonment variables, either some values are missing or no .env file was found"); + } // Setup DB - var db = await DbInitializer.SetupDb(Environment.GetEnvironmentVariable("DB_NAME")); + var db = await DbInitializer.SetupDb(DotNetEnv.Env.GetString("DB_NAME")); if (db == null) { logger.LogCritical("Unable to setup DB"); @@ -27,26 +33,31 @@ public class MastodonBot logger.LogInformation("DB setup done"); // Setup bot - var bot = new TelegramBotClient(Environment.GetEnvironmentVariable("BOT_TOKEN")); - var me = await bot.GetMeAsync(); - await bot.DropPendingUpdatesAsync(); - logger.LogInformation($"Bot is running as {me.FirstName}."); - bot.OnUpdate += OnUpdate; + var bot = new TelegramBotClient(DotNetEnv.Env.GetString("BOT_TOKEN")); - // Handle bot updates - async Task OnUpdate(Update update) - { - switch (update) + var me = await bot.GetMeAsync(); + await bot.DropPendingUpdatesAsync(); + bot.OnUpdate += OnUpdate; + + logger.LogInformation($"Bot is running as {me.FirstName}."); + + + + // Handle bot updates + async Task OnUpdate(Update update) { - case { CallbackQuery: { } callbackQuery }: await HandlePostAction.HandleCallbackQuery(callbackQuery,db,bot, logger); break; - default: logger.LogInformation($"Received unhandled update {update.Type}"); break; - }; - } + switch (update) + { + case { CallbackQuery: { } callbackQuery }: await HandlePostAction.HandleCallbackQuery(callbackQuery, db, bot, logger); break; + default: logger.LogInformation($"Received unhandled update {update.Type}"); break; + }; + } - // Set a timer to fetch and process posts every 15 minutes - _timer = new Timer(async _ => await RunCheck.runAsync(db, bot, Environment.GetEnvironmentVariable("TAG"),logger,Environment.GetEnvironmentVariable("CUSTOM_INSTANCE")), null, TimeSpan.Zero, TimeSpan.FromMinutes(15)); - Console.ReadLine(); + // Set a timer to fetch and process posts every 15 minutes + _timer = new Timer(async _ => await RunCheck.runAsync(db, bot, DotNetEnv.Env.GetString("TAG"), logger, DotNetEnv.Env.GetString("CUSTOM_INSTANCE")), null, TimeSpan.Zero, TimeSpan.FromMinutes(15)); + Console.ReadLine(); + } diff --git a/Services/CheckEnv.cs b/Services/CheckEnv.cs new file mode 100644 index 0000000..dc5d70f --- /dev/null +++ b/Services/CheckEnv.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace mstdnCats.Services +{ + public class CheckEnv + { + public static Boolean IsValid(){ + if (DotNetEnv.Env.GetString("DB_NAME") == null || + DotNetEnv.Env.GetString("BOT_TOKEN") == null || + DotNetEnv.Env.GetString("TAG") == null || + DotNetEnv.Env.GetString("CHANNEL_NUMID") == null || + DotNetEnv.Env.GetString("ADMIN_NUMID") == null ){ + return false; + } + return true; + } + } +} \ No newline at end of file diff --git a/Services/DbInitializer.cs b/Services/DbInitializer.cs index f73bf30..0a7fc3c 100644 --- a/Services/DbInitializer.cs +++ b/Services/DbInitializer.cs @@ -9,19 +9,22 @@ namespace mstdnCats.Services { // Setup DB IDocumentCollection? collection = null; - - try + if (_dbname != null) { - // Initialize DB - var store = new DataStore($"{_dbname}.json", minifyJson: false); - collection = store.GetCollection(); - } - catch - { - return Task.FromResult>(null); - } + try + { + // Initialize DB + var store = new DataStore($"{_dbname}.json", minifyJson: false); + collection = store.GetCollection(); + } + catch + { + return Task.FromResult>(null); + } - // Return collection + // Return collection + return Task.FromResult(collection); + } return Task.FromResult(collection); } } diff --git a/Services/HandlePostAction.cs b/Services/HandlePostAction.cs index 7b0076b..291ec42 100644 --- a/Services/HandlePostAction.cs +++ b/Services/HandlePostAction.cs @@ -44,7 +44,7 @@ namespace mstdnCats.Services if (updated) { // Send the media attachment to the channel - await _bot.SendPhotoAsync(Environment.GetEnvironmentVariable("CHANNEL_NUMID"), post.MediaAttachments.First().Url, caption: $"Post from " + $"" + post.Account.DisplayName + " ", parseMode: ParseMode.Html + await _bot.SendPhotoAsync(DotNetEnv.Env.GetString("CHANNEL_NUMID"), post.MediaAttachments.First().Url, caption: $"Post from " + $"" + post.Account.DisplayName + " ", parseMode: ParseMode.Html , replyMarkup: new InlineKeyboardMarkup(InlineKeyboardButton.WithUrl("View on Mastodon", post.Url))); await _bot.AnswerCallbackQueryAsync(callbackQuery.Id, "Media attachment approved and sent to channel."); diff --git a/Services/ProcessPosts.cs b/Services/ProcessPosts.cs index f6dbb34..3a334f6 100644 --- a/Services/ProcessPosts.cs +++ b/Services/ProcessPosts.cs @@ -24,7 +24,7 @@ namespace mstdnCats.Services // Send approve or reject message to admin foreach (var media in post.MediaAttachments) { - await _bot.SendPhotoAsync(Environment.GetEnvironmentVariable("ADMIN_NUMID"), media.PreviewUrl, caption: $" Mastodon ", parseMode: ParseMode.Html + await _bot.SendPhotoAsync(DotNetEnv.Env.GetString("ADMIN_NUMID"), media.PreviewUrl, caption: $" Mastodon ", parseMode: ParseMode.Html , replyMarkup: new InlineKeyboardMarkup().AddButton("Approve", $"approve-{media.MediaId}").AddButton("Reject", $"reject-{media.MediaId}")); } diff --git a/mstdnCats.csproj b/mstdnCats.csproj index 817f94d..8485894 100644 --- a/mstdnCats.csproj +++ b/mstdnCats.csproj @@ -9,6 +9,7 @@ +