Implemented MongoDb Basics
This commit is contained in:
1 parent
4495e6b605
commit
e0cdcf1198
4 files changed
+50
-26
No files matched your search
@@ -9,7 +9,7 @@ namespace CatsOfMastodonBot.Models
|
|||||||
DotNetEnv.Env.Load();
|
DotNetEnv.Env.Load();
|
||||||
|
|
||||||
// Fetch values from .env file or environment variables (fall back)
|
// 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 mongoDbConnectionString = DotNetEnv.Env.GetString("MONGODB_CONNECTION_STRING") ?? Environment.GetEnvironmentVariable("MONGODB_CONNECTION_STRING");
|
||||||
string botToken = DotNetEnv.Env.GetString("BOT_TOKEN") ?? Environment.GetEnvironmentVariable("BOT_TOKEN");
|
string botToken = DotNetEnv.Env.GetString("BOT_TOKEN") ?? Environment.GetEnvironmentVariable("BOT_TOKEN");
|
||||||
string tag = DotNetEnv.Env.GetString("TAG") ?? Environment.GetEnvironmentVariable("TAG");
|
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";
|
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
|
// 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))
|
|| string.IsNullOrEmpty(channelNumId) || string.IsNullOrEmpty(adminNumId))
|
||||||
{
|
{
|
||||||
return null; // Failure if any are missing
|
return null; // Failure if any are missing
|
||||||
@@ -28,6 +28,7 @@ namespace CatsOfMastodonBot.Models
|
|||||||
config config = new config
|
config config = new config
|
||||||
{
|
{
|
||||||
DB_NAME = dbName,
|
DB_NAME = dbName,
|
||||||
|
MONGODB_CONNECTION_STRING = mongoDbConnectionString,
|
||||||
BOT_TOKEN = botToken,
|
BOT_TOKEN = botToken,
|
||||||
TAG = tag,
|
TAG = tag,
|
||||||
CHANNEL_NUMID = channelNumId,
|
CHANNEL_NUMID = channelNumId,
|
||||||
@@ -46,6 +47,7 @@ namespace CatsOfMastodonBot.Models
|
|||||||
public string CHANNEL_NUMID { get; set; }
|
public string CHANNEL_NUMID { get; set; }
|
||||||
public string ADMIN_NUMID { get; set; }
|
public string ADMIN_NUMID { get; set; }
|
||||||
public string INSTANCE { get; set; }
|
public string INSTANCE { get; set; }
|
||||||
|
public string MONGODB_CONNECTION_STRING { get; set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+12
-11
@@ -30,12 +30,13 @@ public class MastodonBot
|
|||||||
|
|
||||||
// Setup DB
|
// Setup DB
|
||||||
Console.WriteLine("DB name: " + config.DB_NAME);
|
Console.WriteLine("DB name: " + config.DB_NAME);
|
||||||
var db = await DbInitializer.SetupDb(config.DB_NAME);
|
var backupDb = await DbInitializer.SetupJsonDb(config.DB_NAME);
|
||||||
if (db == null)
|
if (backupDb == null)
|
||||||
{
|
{
|
||||||
logger.LogCritical("Unable to setup DB");
|
logger.LogCritical("Unable to setup json DB");
|
||||||
throw new Exception("Unable to setup 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");
|
logger.LogInformation("DB setup done");
|
||||||
|
|
||||||
// Setup bot
|
// Setup bot
|
||||||
@@ -56,9 +57,9 @@ public class MastodonBot
|
|||||||
switch (update)
|
switch (update)
|
||||||
{
|
{
|
||||||
case { CallbackQuery: { } callbackQuery }: {
|
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;
|
default: logger.LogInformation($"Received unhandled update {update.Type}"); break;
|
||||||
@@ -70,23 +71,23 @@ public class MastodonBot
|
|||||||
{
|
{
|
||||||
if (message.Text == "/start")
|
if (message.Text == "/start")
|
||||||
{
|
{
|
||||||
await HandleStartMessage.HandleStartMessageAsync(message,bot, db, logger);
|
await HandleStartMessage.HandleStartMessageAsync(message,bot, backupDb, logger);
|
||||||
}
|
}
|
||||||
else if (message.Text == "/backup")
|
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
|
// 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)
|
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
|
// 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
|
// 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
|
// Keep the bot running
|
||||||
await Task.Delay(-1);
|
await Task.Delay(-1);
|
||||||
}
|
}
|
||||||
|
|||||||
+33
-13
@@ -1,28 +1,48 @@
|
|||||||
using JsonFlatFileDataStore;
|
using JsonFlatFileDataStore;
|
||||||
|
using MongoDB.Driver;
|
||||||
using mstdnCats.Models;
|
using mstdnCats.Models;
|
||||||
|
|
||||||
namespace mstdnCats.Services
|
namespace mstdnCats.Services
|
||||||
{
|
{
|
||||||
public class DbInitializer
|
public class DbInitializer
|
||||||
{
|
{
|
||||||
public static Task<IDocumentCollection<Post>> SetupDb(string _dbname)
|
public static Task<IDocumentCollection<Post>> SetupJsonDb(string _dbname)
|
||||||
{
|
{
|
||||||
// Setup DB
|
// Setup DB
|
||||||
IDocumentCollection<Post>? collection = null;
|
IDocumentCollection<Post>? collection = null;
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
// Initialize DB
|
// Initialize Backup DB
|
||||||
var store = new DataStore($"{_dbname}.json", minifyJson: true);
|
var store = new DataStore($"{_dbname + "_BK"}.json", minifyJson: true);
|
||||||
collection = store.GetCollection<Post>();
|
collection = store.GetCollection<Post>();
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
return Task.FromResult<IDocumentCollection<Post>>(null);
|
return Task.FromResult<IDocumentCollection<Post>>(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return collection
|
// Return collection
|
||||||
return Task.FromResult(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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -11,6 +11,7 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="DotNetEnv" Version="3.1.1" />
|
<PackageReference Include="DotNetEnv" Version="3.1.1" />
|
||||||
<PackageReference Include="JsonFlatFileDataStore" Version="2.4.2" />
|
<PackageReference Include="JsonFlatFileDataStore" Version="2.4.2" />
|
||||||
|
<PackageReference Include="MongoDB.Driver" Version="3.1.0" />
|
||||||
<PackageReference Include="Telegram.Bot" Version="22.0.2" />
|
<PackageReference Include="Telegram.Bot" Version="22.0.2" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user