Improved fetching config data, implemented envinronmet variable support alongside .env support

This commit is contained in:
2024-10-07 19:38:38 +03:30
parent c675824820
commit 6b3aab913c
5 changed files with 69 additions and 29 deletions

49
Models/configData.cs Executable file
View File

@@ -0,0 +1,49 @@
namespace CatsOfMastodonBot.Models
{
public class configData
{
public static Boolean fetchData()
{
// Load from .env file first
DotNetEnv.Env.Load();
// Fetch values from .env file or environment variables (fall back)
string dbName = DotNetEnv.Env.GetString("DB_NAME") ?? Environment.GetEnvironmentVariable("DB_NAME");
string botToken = DotNetEnv.Env.GetString("BOT_TOKEN") ?? Environment.GetEnvironmentVariable("BOT_TOKEN");
string tag = DotNetEnv.Env.GetString("TAG") ?? Environment.GetEnvironmentVariable("TAG");
string channelNumId = DotNetEnv.Env.GetString("CHANNEL_NUMID") ?? Environment.GetEnvironmentVariable("CHANNEL_NUMID");
string adminNumId = DotNetEnv.Env.GetString("ADMIN_NUMID") ?? Environment.GetEnvironmentVariable("ADMIN_NUMID");
string instance = DotNetEnv.Env.GetString("INSTANCE") ?? Environment.GetEnvironmentVariable("INSTANCE");
// Check if any of the values are still null or empty
if (string.IsNullOrEmpty(dbName) || string.IsNullOrEmpty(botToken) || string.IsNullOrEmpty(tag)
|| string.IsNullOrEmpty(channelNumId) || string.IsNullOrEmpty(adminNumId))
{
return false; // Failure if any are missing
}
// If all required variables are present, assign to the config
config config = new config
{
DB_NAME = dbName,
BOT_TOKEN = botToken,
TAG = tag,
CHANNEL_NUMID = channelNumId,
ADMIN_NUMID = adminNumId
};
return true; // Success
}
public class config
{
public string DB_NAME { get; set; }
public string BOT_TOKEN { get; set; }
public string TAG { get; set; }
public string CHANNEL_NUMID { get; set; }
public string ADMIN_NUMID { get; set; }
public string INSTANCE { get; set; }
}
}
}

View File

@@ -1,4 +1,5 @@
using CatsOfMastodonBot.Services; using CatsOfMastodonBot.Models;
using CatsOfMastodonBot.Services;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using mstdnCats.Services; using mstdnCats.Services;
using Telegram.Bot; using Telegram.Bot;
@@ -8,11 +9,12 @@ using Telegram.Bot.Types.Enums;
public class MastodonBot public class MastodonBot
{ {
private static Timer _timer; private static Timer _timer;
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 =>
@@ -21,13 +23,14 @@ public class MastodonBot
}); });
var logger = loggerFactory.CreateLogger<MastodonBot>(); var logger = loggerFactory.CreateLogger<MastodonBot>();
if (!CheckEnv.IsValid()) if (!configData.fetchData())
{ {
logger.LogCritical("Error reading envinonment variables, either some values are missing or no .env file was found"); 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"); throw new Exception("Error reading envinonment variables, either some values are missing or no .env file was found");
} }
var config = new configData.config();
// Setup DB // Setup DB
var db = await DbInitializer.SetupDb(DotNetEnv.Env.GetString("DB_NAME")); var db = await DbInitializer.SetupDb(config.DB_NAME);
if (db == null) if (db == null)
{ {
logger.LogCritical("Unable to setup DB"); logger.LogCritical("Unable to setup DB");
@@ -37,7 +40,7 @@ public class MastodonBot
// Setup bot // Setup bot
var bot = new TelegramBotClient(DotNetEnv.Env.GetString("BOT_TOKEN")); var bot = new TelegramBotClient(config.BOT_TOKEN);
var me = await bot.GetMeAsync(); var me = await bot.GetMeAsync();
await bot.DropPendingUpdatesAsync(); await bot.DropPendingUpdatesAsync();
@@ -72,8 +75,12 @@ 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, DotNetEnv.Env.GetString("TAG"), logger, DotNetEnv.Env.GetString("CUSTOM_INSTANCE")), null, TimeSpan.Zero, TimeSpan.FromMinutes(15)); _timer = new Timer(async _ => await RunCheck.runAsync(db, bot, config.TAG, logger, config.INSTANCE), null, TimeSpan.Zero, TimeSpan.FromMinutes(15));
Console.ReadLine(); Console.ReadLine();
} }
} }
internal class ConfigData
{
}

View File

@@ -1,21 +0,0 @@
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;
}
}
}

View File

@@ -1,3 +1,4 @@
using CatsOfMastodonBot.Models;
using JsonFlatFileDataStore; using JsonFlatFileDataStore;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using mstdnCats.Models; using mstdnCats.Models;
@@ -12,6 +13,8 @@ namespace mstdnCats.Services
{ {
public static async Task HandleCallbackQuery(CallbackQuery callbackQuery, IDocumentCollection<Post> _db, TelegramBotClient _bot, ILogger<MastodonBot>? logger) public static async Task HandleCallbackQuery(CallbackQuery callbackQuery, IDocumentCollection<Post> _db, TelegramBotClient _bot, ILogger<MastodonBot>? logger)
{ {
var config = new configData.config();
// Extract media ID from callback query data // Extract media ID from callback query data
string[] parts = callbackQuery.Data.Split('-'); string[] parts = callbackQuery.Data.Split('-');
if (parts.Length != 2) if (parts.Length != 2)
@@ -52,7 +55,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(DotNetEnv.Env.GetString("CHANNEL_NUMID"), post.MediaAttachments.First().Url, caption: $"Post from " + $"<a href=\"" + post.Account.Url + "\">" + post.Account.DisplayName + " </a>", parseMode: ParseMode.Html await _bot.SendPhotoAsync(config.ADMIN_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.");

View File

@@ -1,3 +1,4 @@
using CatsOfMastodonBot.Models;
using JsonFlatFileDataStore; using JsonFlatFileDataStore;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using mstdnCats.Models; using mstdnCats.Models;
@@ -11,6 +12,7 @@ namespace mstdnCats.Services
{ {
public static async Task<List<MediaAttachment>> checkAndInsertPostsAsync(IDocumentCollection<Post> _db, TelegramBotClient _bot, List<Post> fetchedPosts, ILogger<MastodonBot>? logger) public static async Task<List<MediaAttachment>> checkAndInsertPostsAsync(IDocumentCollection<Post> _db, TelegramBotClient _bot, List<Post> fetchedPosts, ILogger<MastodonBot>? logger)
{ {
var config = new configData.config();
// Get existing posts // Get existing posts
var existingPosts = _db.AsQueryable().Select(x => x.mstdnPostId).ToArray(); var existingPosts = _db.AsQueryable().Select(x => x.mstdnPostId).ToArray();
@@ -30,7 +32,7 @@ namespace mstdnCats.Services
{ {
try try
{ {
await _bot.SendPhotoAsync(DotNetEnv.Env.GetString("ADMIN_NUMID"), media.PreviewUrl, caption: $"<a href=\"" + post.Url + "\"> Mastodon </a>", parseMode: ParseMode.Html await _bot.SendPhotoAsync(config.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}"));
// Insert post // Insert post