added support for .env file and improved validation

This commit is contained in:
mahdium committed 2024-09-14 21:34:21 +03:30
1 parent 2f2ab5f944
commit 77f1a931fd
6 files changed
+43 -7

No files matched your search

+15 -4
View File
@@ -10,6 +10,8 @@ public class MastodonBot
private static async Task Main() private static async Task Main()
{ {
DotNetEnv.Env.Load();
// Configure logging // Configure logging
using var loggerFactory = LoggerFactory.Create(builder => using var loggerFactory = LoggerFactory.Create(builder =>
{ {
@@ -17,8 +19,12 @@ public class MastodonBot
}); });
var logger = loggerFactory.CreateLogger<MastodonBot>(); var logger = loggerFactory.CreateLogger<MastodonBot>();
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 // Setup DB
var db = await DbInitializer.SetupDb(Environment.GetEnvironmentVariable("DB_NAME")); var db = await DbInitializer.SetupDb(DotNetEnv.Env.GetString("DB_NAME"));
if (db == null) if (db == null)
{ {
logger.LogCritical("Unable to setup DB"); logger.LogCritical("Unable to setup DB");
@@ -27,12 +33,16 @@ public class MastodonBot
logger.LogInformation("DB setup done"); logger.LogInformation("DB setup done");
// Setup bot // Setup bot
var bot = new TelegramBotClient(Environment.GetEnvironmentVariable("BOT_TOKEN"));
var bot = new TelegramBotClient(DotNetEnv.Env.GetString("BOT_TOKEN"));
var me = await bot.GetMeAsync(); var me = await bot.GetMeAsync();
await bot.DropPendingUpdatesAsync(); await bot.DropPendingUpdatesAsync();
bot.OnUpdate += OnUpdate;
logger.LogInformation($"Bot is running as {me.FirstName}."); logger.LogInformation($"Bot is running as {me.FirstName}.");
bot.OnUpdate += OnUpdate;
// Handle bot updates // Handle bot updates
async Task OnUpdate(Update update) async Task OnUpdate(Update update)
@@ -45,9 +55,10 @@ public class MastodonBot
} }
// Set a timer to fetch and process posts every 15 minutes // 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)); _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(); Console.ReadLine();
} }
} }
+21
View File
@@ -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;
}
}
}
+4 -1
View File
@@ -9,7 +9,8 @@ namespace mstdnCats.Services
{ {
// Setup DB // Setup DB
IDocumentCollection<Post>? collection = null; IDocumentCollection<Post>? collection = null;
if (_dbname != null)
{
try try
{ {
// Initialize DB // Initialize DB
@@ -24,5 +25,7 @@ namespace mstdnCats.Services
// Return collection // Return collection
return Task.FromResult(collection); return Task.FromResult(collection);
} }
return Task.FromResult(collection);
}
} }
} }
+1 -1
View File
@@ -44,7 +44,7 @@ namespace mstdnCats.Services
if (updated) if (updated)
{ {
// Send the media attachment to the channel // Send the media attachment to the channel
await _bot.SendPhotoAsync(Environment.GetEnvironmentVariable("CHANNEL_NUMID"), post.MediaAttachments.First().Url, caption: $"Post from " + $"<a href=\"" + post.Account.Url + "\">" + post.Account.DisplayName + " </a>", parseMode: ParseMode.Html await _bot.SendPhotoAsync(DotNetEnv.Env.GetString("CHANNEL_NUMID"), post.MediaAttachments.First().Url, caption: $"Post from " + $"<a href=\"" + post.Account.Url + "\">" + post.Account.DisplayName + " </a>", parseMode: ParseMode.Html
, replyMarkup: new InlineKeyboardMarkup(InlineKeyboardButton.WithUrl("View on Mastodon", post.Url))); , replyMarkup: new InlineKeyboardMarkup(InlineKeyboardButton.WithUrl("View on Mastodon", post.Url)));
await _bot.AnswerCallbackQueryAsync(callbackQuery.Id, "Media attachment approved and sent to channel."); await _bot.AnswerCallbackQueryAsync(callbackQuery.Id, "Media attachment approved and sent to channel.");
+1 -1
View File
@@ -24,7 +24,7 @@ namespace mstdnCats.Services
// Send approve or reject message to admin // Send approve or reject message to admin
foreach (var media in post.MediaAttachments) foreach (var media in post.MediaAttachments)
{ {
await _bot.SendPhotoAsync(Environment.GetEnvironmentVariable("ADMIN_NUMID"), media.PreviewUrl, caption: $"<a href=\"" + post.Url + "\"> Mastodon </a>", parseMode: ParseMode.Html await _bot.SendPhotoAsync(DotNetEnv.Env.GetString("ADMIN_NUMID"), media.PreviewUrl, caption: $"<a href=\"" + post.Url + "\"> Mastodon </a>", parseMode: ParseMode.Html
, replyMarkup: new InlineKeyboardMarkup().AddButton("Approve", $"approve-{media.MediaId}").AddButton("Reject", $"reject-{media.MediaId}")); , replyMarkup: new InlineKeyboardMarkup().AddButton("Approve", $"approve-{media.MediaId}").AddButton("Reject", $"reject-{media.MediaId}"));
} }
+1
View File
@@ -9,6 +9,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="DotNetEnv" Version="3.1.1" />
<PackageReference Include="JsonFlatFileDataStore" Version="2.4.2" /> <PackageReference Include="JsonFlatFileDataStore" Version="2.4.2" />
<PackageReference Include="Telegram.Bot" Version="21.11.0" /> <PackageReference Include="Telegram.Bot" Version="21.11.0" />
</ItemGroup> </ItemGroup>