Added DB backup command

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

View File

@@ -72,10 +72,21 @@ public class MastodonBot
{
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
_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();
}

24
Services/HandleDbBackup.cs Executable file
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");
}
}