From 51747b3e3d2055adf379a63db67004a969a9b89b Mon Sep 17 00:00:00 2001 From: Mohammad Mahdi Mohammadi Date: Tue, 5 Nov 2024 17:25:29 +0330 Subject: [PATCH] Migrate to Telegram.Bot v22 and some minor improvements --- .../.idea/.gitignore | 13 +++++++++++++ .../.idea/indexLayout.xml | 8 ++++++++ .../.idea.CatsOfMastodonBot.dir/.idea/vcs.xml | 6 ++++++ Models/configData.cs | 2 +- Program.cs | 8 ++++---- Services/DbInitializer.cs | 7 ++----- Services/HandleDbBackup.cs | 2 +- Services/HandlePostAction.cs | 16 ++++++++-------- Services/HandleStartMessage.cs | 18 ++++++++---------- Services/ProcessPosts.cs | 2 +- mstdnCats.csproj | 2 +- 11 files changed, 53 insertions(+), 31 deletions(-) create mode 100755 .idea/.idea.CatsOfMastodonBot.dir/.idea/.gitignore create mode 100755 .idea/.idea.CatsOfMastodonBot.dir/.idea/indexLayout.xml create mode 100755 .idea/.idea.CatsOfMastodonBot.dir/.idea/vcs.xml diff --git a/.idea/.idea.CatsOfMastodonBot.dir/.idea/.gitignore b/.idea/.idea.CatsOfMastodonBot.dir/.idea/.gitignore new file mode 100755 index 0000000..7f08cb6 --- /dev/null +++ b/.idea/.idea.CatsOfMastodonBot.dir/.idea/.gitignore @@ -0,0 +1,13 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Rider ignored files +/modules.xml +/projectSettingsUpdater.xml +/.idea.CatsOfMastodonBot.iml +/contentModel.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/.idea.CatsOfMastodonBot.dir/.idea/indexLayout.xml b/.idea/.idea.CatsOfMastodonBot.dir/.idea/indexLayout.xml new file mode 100755 index 0000000..7b08163 --- /dev/null +++ b/.idea/.idea.CatsOfMastodonBot.dir/.idea/indexLayout.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/.idea.CatsOfMastodonBot.dir/.idea/vcs.xml b/.idea/.idea.CatsOfMastodonBot.dir/.idea/vcs.xml new file mode 100755 index 0000000..35eb1dd --- /dev/null +++ b/.idea/.idea.CatsOfMastodonBot.dir/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Models/configData.cs b/Models/configData.cs index b236a8c..9c4cdea 100755 --- a/Models/configData.cs +++ b/Models/configData.cs @@ -14,7 +14,7 @@ namespace CatsOfMastodonBot.Models 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"); + 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) diff --git a/Program.cs b/Program.cs index 02341aa..96654d2 100755 --- a/Program.cs +++ b/Program.cs @@ -42,8 +42,8 @@ public class MastodonBot var bot = new TelegramBotClient(config.BOT_TOKEN); - var me = await bot.GetMeAsync(); - await bot.DropPendingUpdatesAsync(); + var me = await bot.GetMe(); + await bot.DropPendingUpdates(); bot.OnMessage += OnMessage; bot.OnUpdate += OnUpdate; @@ -56,7 +56,7 @@ public class MastodonBot switch (update) { case { CallbackQuery: { } callbackQuery }: { - if(callbackQuery.Data == "new_random"){ await HandleStartMessage.HandleStartMessageAsync(callbackQuery.Message, bot, db, logger); break;} + if(callbackQuery.Data == "new_random"){ await HandleStartMessage.HandleStartMessageAsync(callbackQuery.Message, bot, db, logger,callbackQuery); break;} else {await HandlePostAction.HandleCallbackQuery(callbackQuery, db, bot, logger); break;} @@ -79,7 +79,7 @@ public class MastodonBot 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!"); + await bot.SendMessage(message.Chat.Id, "Send /start to get a random cat!"); } } diff --git a/Services/DbInitializer.cs b/Services/DbInitializer.cs index 0a7fc3c..fef44ef 100755 --- a/Services/DbInitializer.cs +++ b/Services/DbInitializer.cs @@ -9,12 +9,11 @@ namespace mstdnCats.Services { // Setup DB IDocumentCollection? collection = null; - if (_dbname != null) - { + try { // Initialize DB - var store = new DataStore($"{_dbname}.json", minifyJson: false); + var store = new DataStore($"{_dbname}.json", minifyJson: true); collection = store.GetCollection(); } catch @@ -24,8 +23,6 @@ namespace mstdnCats.Services // Return collection return Task.FromResult(collection); - } - return Task.FromResult(collection); } } } \ No newline at end of file diff --git a/Services/HandleDbBackup.cs b/Services/HandleDbBackup.cs index b04c4ca..e1033e5 100755 --- a/Services/HandleDbBackup.cs +++ b/Services/HandleDbBackup.cs @@ -14,7 +14,7 @@ public class HandleDbBackup logger?.LogInformation("Backup requested"); await using Stream stream = System.IO.File.OpenRead("./" + dbname+".json"); - var message = await _bot.SendDocumentAsync(adminId, document: InputFile.FromStream(stream, dbname+".json"), + var message = await _bot.SendDocument(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"); diff --git a/Services/HandlePostAction.cs b/Services/HandlePostAction.cs index 040c566..ebd438a 100755 --- a/Services/HandlePostAction.cs +++ b/Services/HandlePostAction.cs @@ -43,7 +43,7 @@ namespace mstdnCats.Services // Check if the media attachment is already approved bool isAlreadyApproved = mediaAttachment.Approved; if (isAlreadyApproved){ - await _bot.AnswerCallbackQueryAsync(callbackQuery.Id, "Media attachment is already approved.",true); + await _bot.AnswerCallbackQuery(callbackQuery.Id, "Media attachment is already approved.",true); return; } @@ -55,11 +55,11 @@ namespace mstdnCats.Services if (updated) { // Send the media attachment to the channel - await _bot.SendPhotoAsync(config.CHANNEL_NUMID, post.MediaAttachments.First().Url, caption: $"Post from " + $"" + post.Account.DisplayName + " ", parseMode: ParseMode.Html + await _bot.SendPhoto(config.CHANNEL_NUMID, post.MediaAttachments.First().Url, caption: $"Post from " + $"" + post.Account.DisplayName + " ", parseMode: ParseMode.Html , replyMarkup: new InlineKeyboardMarkup(InlineKeyboardButton.WithUrl("View on Mastodon", post.Url))); - await _bot.AnswerCallbackQueryAsync(callbackQuery.Id, "Media attachment approved and sent to channel."); - await _bot.DeleteMessageAsync(callbackQuery.Message.Chat.Id, callbackQuery.Message.MessageId); + await _bot.AnswerCallbackQuery(callbackQuery.Id, "Media attachment approved and sent to channel."); + await _bot.DeleteMessage(callbackQuery.Message.Chat.Id, callbackQuery.Message.MessageId); logger?.LogTrace($"Media attachment {mediaId} approved."); @@ -83,8 +83,8 @@ namespace mstdnCats.Services // Check if the post has only one attachment, if so, do not delete it, else delete the associated attachment if (post.MediaAttachments.Count == 1 && post.MediaAttachments.First().MediaId == mediaId) { - await _bot.AnswerCallbackQueryAsync(callbackQuery.Id, "Post has only one attachment. No deletion performed."); - await _bot.DeleteMessageAsync(callbackQuery.Message.Chat.Id, callbackQuery.Message.MessageId); + await _bot.AnswerCallbackQuery(callbackQuery.Id, "Post has only one attachment. No deletion performed."); + await _bot.DeleteMessage(callbackQuery.Message.Chat.Id, callbackQuery.Message.MessageId); logger?.LogTrace($"Post {post.mstdnPostId} has only one attachment. No deletion performed."); } @@ -92,8 +92,8 @@ namespace mstdnCats.Services { post.MediaAttachments.RemoveAll(m => m.MediaId == mediaId); await _db.UpdateOneAsync(p => p.mstdnPostId == post.mstdnPostId, post); - await _bot.AnswerCallbackQueryAsync(callbackQuery.Id, "Media attachment rejected."); - await _bot.DeleteMessageAsync(callbackQuery.Message.Chat.Id, callbackQuery.Message.MessageId); + await _bot.AnswerCallbackQuery(callbackQuery.Id, "Media attachment rejected."); + await _bot.DeleteMessage(callbackQuery.Message.Chat.Id, callbackQuery.Message.MessageId); logger?.LogTrace($"Media attachment {mediaId} removed from post {post.mstdnPostId}."); } diff --git a/Services/HandleStartMessage.cs b/Services/HandleStartMessage.cs index 20b50da..f069fe5 100755 --- a/Services/HandleStartMessage.cs +++ b/Services/HandleStartMessage.cs @@ -1,8 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.CompilerServices; -using System.Threading.Tasks; using JsonFlatFileDataStore; using Microsoft.Extensions.Logging; using mstdnCats.Models; @@ -15,10 +10,10 @@ namespace CatsOfMastodonBot.Services { public class HandleStartMessage { - public static async Task HandleStartMessageAsync(Message message, TelegramBotClient _bot, IDocumentCollection _db, ILogger? logger) + public static async Task HandleStartMessageAsync(Message message, TelegramBotClient _bot, IDocumentCollection _db, ILogger? logger, CallbackQuery callbackQuery = null) { logger?.LogInformation("Start message received"); - + // choose all media attachments that are approved var mediaAttachmentsToSelect = _db.AsQueryable() .Where(post => post.MediaAttachments.Any(media => media.Approved)) @@ -26,12 +21,15 @@ namespace CatsOfMastodonBot.Services // select random approved media attachment var selectedMediaAttachment = mediaAttachmentsToSelect[new Random().Next(mediaAttachmentsToSelect.Count)]; // send media attachment - await _bot.SendPhotoAsync(message.Chat.Id, selectedMediaAttachment.MediaAttachments.FirstOrDefault(m => m.Approved == true).Url, - caption: $"Here is your cat!🐈\n"+"" + $"View on Mastodon " + " ", parseMode: ParseMode.Html + await _bot.SendPhoto(callbackQuery.Message.Chat.Id, selectedMediaAttachment.MediaAttachments.FirstOrDefault(m => m.Approved == true).Url, + caption: $"Here is your cat!🐈\n" + "" + $"View on Mastodon " + " ", parseMode: ParseMode.Html , replyMarkup: new InlineKeyboardMarkup().AddButton(InlineKeyboardButton.WithUrl("Join channel 😺", "https://t.me/catsofmastodon")) .AddNewRow() .AddButton(InlineKeyboardButton.WithCallbackData("Send me another one!", $"new_random"))); - + if (callbackQuery != null) + { + await _bot.AnswerCallbackQuery(callbackQuery.Id, "Catch your cat!", url: selectedMediaAttachment.Url); + } logger?.LogInformation("Random cat sent!"); diff --git a/Services/ProcessPosts.cs b/Services/ProcessPosts.cs index d1eb7e5..26e6b9a 100755 --- a/Services/ProcessPosts.cs +++ b/Services/ProcessPosts.cs @@ -32,7 +32,7 @@ namespace mstdnCats.Services { try { - await _bot.SendPhotoAsync(config.ADMIN_NUMID, media.PreviewUrl, caption: $" Mastodon ", parseMode: ParseMode.Html + await _bot.SendPhoto(config.ADMIN_NUMID, media.PreviewUrl, caption: $" Mastodon ", parseMode: ParseMode.Html , replyMarkup: new InlineKeyboardMarkup().AddButton("Approve", $"approve-{media.MediaId}").AddButton("Reject", $"reject-{media.MediaId}")); // Insert post diff --git a/mstdnCats.csproj b/mstdnCats.csproj index 8485894..2b7e990 100755 --- a/mstdnCats.csproj +++ b/mstdnCats.csproj @@ -11,7 +11,7 @@ - +