Added DB backup command

Added automated backup every 1 hour
This commit is contained in:
mahdium committed 2024-10-31 15:16:42 +03:30
1 parent 4cb0ada1d0
commit d680ae818d
2 files changed
+35

No files matched your search

+11
View File
@@ -72,10 +72,21 @@ public class MastodonBot
{ {
await HandleStartMessage.HandleStartMessageAsync(message,bot, db, logger); await HandleStartMessage.HandleStartMessageAsync(message,bot, db, logger);
} }
else if (message.Text == "/backup")
{
await HandleDbBackup.HandleDbBackupAsync(bot, logger, config.DB_NAME, config.ADMIN_NUMID, db);
}
else
{
// Send a help message to prompt user to send /start and recieve their cat photo
await bot.SendTextMessageAsync(message.Chat.Id, "Send /start to get a random cat!");
}
} }
// 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, config.TAG, logger, config.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));
// Another timer to automatically backup the DB every 1 hour
_timer = new Timer(async _ => await HandleDbBackup.HandleDbBackupAsync(bot, logger, config.DB_NAME, config.ADMIN_NUMID, db), null, TimeSpan.Zero, TimeSpan.FromHours(1));
Console.ReadLine(); Console.ReadLine();
} }
+24
View File
@@ -0,0 +1,24 @@
using JsonFlatFileDataStore;
using Microsoft.Extensions.Logging;
using mstdnCats.Models;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
namespace mstdnCats.Services;
public class HandleDbBackup
{
public static async Task HandleDbBackupAsync(TelegramBotClient _bot, ILogger<MastodonBot>? logger, string dbname, string adminId,IDocumentCollection<Post> _db)
{
logger?.LogInformation("Backup requested");
await using Stream stream = System.IO.File.OpenRead("./" + dbname);
var message = await _bot.SendDocumentAsync(adminId, document: InputFile.FromStream(stream, dbname+".json"),
caption: "Backup of " + dbname + "\nCreated at " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss" + "\nCurrent post count: " + _db.AsQueryable().Count()), parseMode: ParseMode.Html);
logger?.LogInformation("Backup sent");
}
}