Implemented MongoDb Basics

This commit is contained in:
2024-12-06 13:35:47 +03:30
parent 4495e6b605
commit e0cdcf1198
4 changed files with 50 additions and 26 deletions

View File

@@ -9,7 +9,7 @@ namespace CatsOfMastodonBot.Models
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 dbName = DotNetEnv.Env.GetString("DB_NAME") ?? Environment.GetEnvironmentVariable("DB_NAME") ?? "catsofmastodon";
string mongoDbConnectionString = DotNetEnv.Env.GetString("MONGODB_CONNECTION_STRING") ?? Environment.GetEnvironmentVariable("MONGODB_CONNECTION_STRING");
string botToken = DotNetEnv.Env.GetString("BOT_TOKEN") ?? Environment.GetEnvironmentVariable("BOT_TOKEN");
string tag = DotNetEnv.Env.GetString("TAG") ?? Environment.GetEnvironmentVariable("TAG");
@@ -18,7 +18,7 @@ namespace CatsOfMastodonBot.Models
string instance = DotNetEnv.Env.GetString("CUSTOM_INSTANCE") ?? Environment.GetEnvironmentVariable("CUSTOM_INSTANCE") ?? "https://haminoa.net";
// Check if any of the values are still null or empty
if (string.IsNullOrEmpty(dbName) || string.IsNullOrEmpty(botToken) || string.IsNullOrEmpty(tag)
if (string.IsNullOrEmpty(botToken) || string.IsNullOrEmpty(tag)
|| string.IsNullOrEmpty(channelNumId) || string.IsNullOrEmpty(adminNumId))
{
return null; // Failure if any are missing
@@ -28,6 +28,7 @@ namespace CatsOfMastodonBot.Models
config config = new config
{
DB_NAME = dbName,
MONGODB_CONNECTION_STRING = mongoDbConnectionString,
BOT_TOKEN = botToken,
TAG = tag,
CHANNEL_NUMID = channelNumId,
@@ -46,6 +47,7 @@ namespace CatsOfMastodonBot.Models
public string CHANNEL_NUMID { get; set; }
public string ADMIN_NUMID { get; set; }
public string INSTANCE { get; set; }
public string MONGODB_CONNECTION_STRING { get; set; }
}
}
}

View File

@@ -30,12 +30,13 @@ public class MastodonBot
// Setup DB
Console.WriteLine("DB name: " + config.DB_NAME);
var db = await DbInitializer.SetupDb(config.DB_NAME);
if (db == null)
var backupDb = await DbInitializer.SetupJsonDb(config.DB_NAME);
if (backupDb == null)
{
logger.LogCritical("Unable to setup DB");
throw new Exception("Unable to setup DB");
logger.LogCritical("Unable to setup json DB");
throw new Exception("Unable to setup json DB");
}
var db = await DbInitializer.SetupDb(config.MONGODB_CONNECTION_STRING, config.DB_NAME);
logger.LogInformation("DB setup done");
// Setup bot
@@ -56,9 +57,9 @@ public class MastodonBot
switch (update)
{
case { CallbackQuery: { } callbackQuery }: {
if(callbackQuery.Data == "new_random"){ await HandleStartMessage.HandleStartMessageAsync(callbackQuery.Message, bot, db, logger,callbackQuery); break;}
if(callbackQuery.Data == "new_random"){ await HandleStartMessage.HandleStartMessageAsync(callbackQuery.Message, bot, backupDb, logger,callbackQuery); break;}
else {await HandlePostAction.HandleCallbackQuery(callbackQuery, db, bot, logger); break;}
else {await HandlePostAction.HandleCallbackQuery(callbackQuery, backupDb, bot, logger); break;}
}
default: logger.LogInformation($"Received unhandled update {update.Type}"); break;
@@ -70,23 +71,23 @@ public class MastodonBot
{
if (message.Text == "/start")
{
await HandleStartMessage.HandleStartMessageAsync(message,bot, db, logger);
await HandleStartMessage.HandleStartMessageAsync(message,bot, backupDb, logger);
}
else if (message.Text == "/backup")
{
await HandleDbBackup.HandleDbBackupAsync(bot, logger, config.DB_NAME, config.ADMIN_NUMID, db);
await HandleDbBackup.HandleDbBackupAsync(bot, logger, config.DB_NAME, config.ADMIN_NUMID, backupDb);
}
// 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);
await HandleStartMessage.HandleStartMessageAsync(message, bot, backupDb, logger);
}
}
// Set a timer to fetch and process posts every 15 minutes
_postFetchTimer = new Timer(async _ => await RunCheck.runAsync(db, bot, config.TAG, logger, config.INSTANCE), null, TimeSpan.Zero, TimeSpan.FromMinutes(10));
_postFetchTimer = new Timer(async _ => await RunCheck.runAsync(backupDb, bot, config.TAG, logger, config.INSTANCE), null, TimeSpan.Zero, TimeSpan.FromMinutes(10));
// Another timer to automatically backup the DB every 1 hour
_backupTimer = new Timer(async _ => await HandleDbBackup.HandleDbBackupAsync(bot, logger, config.DB_NAME, config.ADMIN_NUMID, db), null, TimeSpan.Zero, TimeSpan.FromHours(6));
_backupTimer = new Timer(async _ => await HandleDbBackup.HandleDbBackupAsync(bot, logger, config.DB_NAME, config.ADMIN_NUMID, backupDb), null, TimeSpan.Zero, TimeSpan.FromHours(6));
// Keep the bot running
await Task.Delay(-1);
}

View File

@@ -1,28 +1,48 @@
using JsonFlatFileDataStore;
using MongoDB.Driver;
using mstdnCats.Models;
namespace mstdnCats.Services
{
public class DbInitializer
{
public static Task<IDocumentCollection<Post>> SetupDb(string _dbname)
public static Task<IDocumentCollection<Post>> SetupJsonDb(string _dbname)
{
// Setup DB
IDocumentCollection<Post>? collection = null;
try
{
// Initialize DB
var store = new DataStore($"{_dbname}.json", minifyJson: true);
collection = store.GetCollection<Post>();
}
catch
{
return Task.FromResult<IDocumentCollection<Post>>(null);
}
try
{
// Initialize Backup DB
var store = new DataStore($"{_dbname + "_BK"}.json", minifyJson: true);
collection = store.GetCollection<Post>();
}
catch
{
return Task.FromResult<IDocumentCollection<Post>>(null);
}
// Return collection
return Task.FromResult(collection);
// Return collection
return Task.FromResult(collection);
}
public static Task<IMongoDatabase> SetupDb(string mongoDbConnectionString, string dbName)
{
if (mongoDbConnectionString == null)
{
throw new Exception("MongoDb connection string is null");
}
try
{
var client = new MongoClient(mongoDbConnectionString);
var database = client.GetDatabase(dbName);
return Task.FromResult(database);
}
catch (Exception ex)
{
throw new Exception("Error while connecting to MongoDB: " + ex.Message);
}
}
}
}

View File

@@ -11,6 +11,7 @@
<ItemGroup>
<PackageReference Include="DotNetEnv" Version="3.1.1" />
<PackageReference Include="JsonFlatFileDataStore" Version="2.4.2" />
<PackageReference Include="MongoDB.Driver" Version="3.1.0" />
<PackageReference Include="Telegram.Bot" Version="22.0.2" />
</ItemGroup>