From 0aed956af719c369f4f42387420ede56906e1e7a Mon Sep 17 00:00:00 2001 From: herfost <133514023+sbadung@users.noreply.github.com> Date: Fri, 18 Aug 2023 11:14:03 +0200 Subject: [PATCH 01/20] Rewrite of business logic --- Moderation/Moderation/Lib_CSharp | 2 +- Moderation/Moderation/src/Program.cs | 91 ++++++++++------------------ 2 files changed, 34 insertions(+), 59 deletions(-) diff --git a/Moderation/Moderation/Lib_CSharp b/Moderation/Moderation/Lib_CSharp index f512d8b..5393de4 160000 --- a/Moderation/Moderation/Lib_CSharp +++ b/Moderation/Moderation/Lib_CSharp @@ -1 +1 @@ -Subproject commit f512d8ba2d933b9491dc55f39299413675a6cf53 +Subproject commit 5393de452a5794f14777d0441901539293ba21ef diff --git a/Moderation/Moderation/src/Program.cs b/Moderation/Moderation/src/Program.cs index 1adca04..ba3378b 100644 --- a/Moderation/Moderation/src/Program.cs +++ b/Moderation/Moderation/src/Program.cs @@ -1,81 +1,56 @@ -#region - -using PoliNetwork.Core.Data; +#region using PoliNetwork.Core.Utils; -using PoliNetwork.Core.Utils.LoggerNS; +using PoliNetwork.Telegram.Logger; using PoliNetwork.Db.Utils; -using PoliNetwork.Telegram.Objects.Bot; -using PoliNetwork.Telegram.Objects.Configuration; -using PoliNetwork.Telegram.Objects.Updates.Update; -using PoliNetwork.Telegram.Utils; -using PoliNetwork.Telegram.Utils.ConfigUtils; -using PoliNetwork.Telegram.Variables; - -#endregion +using PoliNetwork.Telegram.Bot; +using PoliNetwork.Telegram.Configuration; +using PoliNetwork.Telegram.ConfigurationLoader; +using PoliNetwork.Db.Objects; +using PoliNetwork.Telegram.Options; +using PoliNetwork.Telegram.Properties; +#endregion namespace Moderation; internal static class Program { - /// - /// Telegram bot - /// - private static TelegramBot? _telegramBot; - - /// - /// Default log config - /// - private static readonly LogConfig LogConfig = new(); - + private static ModerationBot? bot = null; + private static readonly string databaseConfigurationPath = ""; - public static void Main(string[] args) + public static void Main() { - GlobalVariables.DefaultLogger.SetLogConfing(LogConfig); - GlobalVariables.DefaultLogger.Info("Hello, starting Moderation bot!"); - var telegramConfig = TelegramConfigUtils.LoadOrInitializeConfig(Variables.DefaultConfigPath); - if (telegramConfig == null) + /* The PoliNetwork.Core.Utils.LoggerNS.Logger must extends the AbstractLogger so a sub class will be needed + The only dependency of the PoliNetwork.Core.Utils.LoggerNS.Logger resides here in the Program.cs */ + AbstractLogger? logger = new DefaultLogger(); + FileConfigurationLoader fileConfigurationLoader = new JSONFileConfigurationLoader(); + AbstractTelegramBotOptions? botConfiguration = fileConfigurationLoader.LoadOrInitializeConfig(Configuration.TELEGRAM_CONFIGURATION_PATH, logger); + + DbConfig? databaseConfiguration = DbConfigUtils.LoadOrInitializeConfig(databaseConfigurationPath); + if (botConfiguration == null) { - GlobalVariables.DefaultLogger.Emergency("Telegram Config is undefined when starting the bot."); + logger?.Emergency("Telegram Config is undefined when starting the bot."); return; } - telegramConfig.UpdateMethod = new UpdateMethod(UpdateAction); - - var dbConfig = DbConfigUtils.LoadOrInitializeConfig(PoliNetwork.Db.Variables.Variables.DefaultConfigPath); - if (dbConfig == null) + if (databaseConfiguration == null) { - GlobalVariables.DefaultLogger.Emergency("Database Config is undefined when starting the bot."); + logger?.Emergency("Database Config is undefined when starting the bot."); return; } - _telegramBot = new TelegramBot(telegramConfig, LogConfig); - _telegramBot.Start(new CancellationToken()); - Wait.WaitForever(); - } + logger?.Info("RUNNING MODERATION BOT"); + botConfiguration.UpdateMethod = new UpdateMethod(UpdateAction); - private static void UpdateAction(CancellationToken arg1, IUpdate arg2) - { - if (_telegramBot == null) - return; - - - // Only process Message updates: https://core.telegram.org/bots/api#message - if (arg2.Message is not { } message) - return; - - //Simply handle every message update with the "echo" method - Echo.EchoMethod( - message, - _telegramBot, //we actually pass our bot object, not the one received from the caller - arg1); + /* TelegramConfiguration should extends TelegramBotClientOptions */ + bot = new ModerationBot(options: botConfiguration, logger: logger); + bot.Start(new CancellationToken()); + Wait.WaitForever(); } -} -//to be removed -public class HelloWorld -{ - public string SayHello() + private static void UpdateAction(CancellationToken cancellationToken, IUpdate update) { - return "Hello, World!"; + /* Process Message updates only, see: https://core.telegram.org/bots/api#message */ + if (bot == null || update.Message is not { } message) return; + bot.Echo(message, cancellationToken); } } \ No newline at end of file From 1390eefe50f6b7e4cc128ace87c8a2280af69f2a Mon Sep 17 00:00:00 2001 From: user Date: Fri, 18 Aug 2023 12:07:43 +0200 Subject: [PATCH 02/20] Update .gitignore --- .gitignore | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index 57e1e8a..693cbd6 100644 --- a/.gitignore +++ b/.gitignore @@ -554,3 +554,7 @@ fabric.properties # Android studio 3.1+ serialized cache file .idea/caches/build_file_checksums.ser +Echo/.idea/.idea.Echo/.idea/.gitignore +Echo/.idea/.idea.Echo/.idea/encodings.xml +Echo/.idea/.idea.Echo/.idea/indexLayout.xml +Echo/.idea/.idea.Echo/.idea/vcs.xml From bfe05acc82ccb3b7be8fa01885eef59029666dfb Mon Sep 17 00:00:00 2001 From: user Date: Fri, 18 Aug 2023 12:07:50 +0200 Subject: [PATCH 03/20] Update .gitignore --- .gitignore | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index 693cbd6..5eb85ce 100644 --- a/.gitignore +++ b/.gitignore @@ -558,3 +558,7 @@ Echo/.idea/.idea.Echo/.idea/.gitignore Echo/.idea/.idea.Echo/.idea/encodings.xml Echo/.idea/.idea.Echo/.idea/indexLayout.xml Echo/.idea/.idea.Echo/.idea/vcs.xml +Moderation/.idea/.idea.Echo/.idea/.gitignore +Moderation/.idea/.idea.Echo/.idea/encodings.xml +Moderation/.idea/.idea.Echo/.idea/indexLayout.xml +Moderation/.idea/.idea.Echo/.idea/vcs.xml From e8b725acd4f13d95f94f4ce2cfcf3af7171a4e14 Mon Sep 17 00:00:00 2001 From: user Date: Fri, 18 Aug 2023 12:07:57 +0200 Subject: [PATCH 04/20] Update .gitignore --- .gitignore | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index 5eb85ce..e5affe7 100644 --- a/.gitignore +++ b/.gitignore @@ -562,3 +562,7 @@ Moderation/.idea/.idea.Echo/.idea/.gitignore Moderation/.idea/.idea.Echo/.idea/encodings.xml Moderation/.idea/.idea.Echo/.idea/indexLayout.xml Moderation/.idea/.idea.Echo/.idea/vcs.xml +Moderation/Main/.idea/.idea.Main.dir/.idea/.gitignore +Moderation/Main/.idea/.idea.Main.dir/.idea/encodings.xml +Moderation/Main/.idea/.idea.Main.dir/.idea/indexLayout.xml +Moderation/Main/.idea/.idea.Main.dir/.idea/vcs.xml From cb54616cf79fbb0756d06f16608305040e792202 Mon Sep 17 00:00:00 2001 From: user Date: Fri, 18 Aug 2023 12:18:58 +0200 Subject: [PATCH 05/20] Update vcs.xml --- Moderation/.idea/.idea.Moderation/.idea/vcs.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/Moderation/.idea/.idea.Moderation/.idea/vcs.xml b/Moderation/.idea/.idea.Moderation/.idea/vcs.xml index 6c0b863..4f569d3 100644 --- a/Moderation/.idea/.idea.Moderation/.idea/vcs.xml +++ b/Moderation/.idea/.idea.Moderation/.idea/vcs.xml @@ -2,5 +2,6 @@ + \ No newline at end of file From e8521e35a8bd3e9e05b3156efadc01ec32b8c3b6 Mon Sep 17 00:00:00 2001 From: user Date: Fri, 18 Aug 2023 12:19:48 +0200 Subject: [PATCH 06/20] Update Moderation.sln --- Moderation/Moderation.sln | 2 -- 1 file changed, 2 deletions(-) diff --git a/Moderation/Moderation.sln b/Moderation/Moderation.sln index f12b8d2..b718362 100644 --- a/Moderation/Moderation.sln +++ b/Moderation/Moderation.sln @@ -2,8 +2,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Moderation", "Moderation\Moderation.csproj", "{C28EF231-412A-4FE9-88C3-C47FC362BDFC}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Echo", "Echo", "{98A20692-9D53-4548-ADA5-3E4EF5AC78E0}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModerationTest", "ModerationTest\ModerationTest.csproj", "{904CB386-4B14-4A1F-A356-50380A4963A9}" EndProject Global From bc8435a89d6317ed9e4ca91212513ef385554e04 Mon Sep 17 00:00:00 2001 From: user Date: Fri, 18 Aug 2023 12:21:40 +0200 Subject: [PATCH 07/20] Update Moderation.sln --- Moderation/Moderation.sln | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Moderation/Moderation.sln b/Moderation/Moderation.sln index b718362..ca86e7a 100644 --- a/Moderation/Moderation.sln +++ b/Moderation/Moderation.sln @@ -4,6 +4,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Moderation", "Moderation\Mo EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModerationTest", "ModerationTest\ModerationTest.csproj", "{904CB386-4B14-4A1F-A356-50380A4963A9}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PoliNetwork.Core", "Moderation\Lib_CSharp\PoliNetwork.Core\src\PoliNetwork.Core.csproj", "{A987C703-A642-4D6D-9380-FBC140EB6A52}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PoliNetwork.Telegram", "Moderation\Lib_CSharp\PoliNetwork.Telegram\src\PoliNetwork.Telegram.csproj", "{38E88883-3571-4CF5-A7D3-8237B8588AAA}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PoliNetwork.Db", "Moderation\Lib_CSharp\PoliNetwork.Db\src\PoliNetwork.Db.csproj", "{E2A86DD9-3A27-474B-B16E-8E9139DD70E9}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -18,5 +24,17 @@ Global {904CB386-4B14-4A1F-A356-50380A4963A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {904CB386-4B14-4A1F-A356-50380A4963A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {904CB386-4B14-4A1F-A356-50380A4963A9}.Release|Any CPU.Build.0 = Release|Any CPU + {A987C703-A642-4D6D-9380-FBC140EB6A52}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A987C703-A642-4D6D-9380-FBC140EB6A52}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A987C703-A642-4D6D-9380-FBC140EB6A52}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A987C703-A642-4D6D-9380-FBC140EB6A52}.Release|Any CPU.Build.0 = Release|Any CPU + {38E88883-3571-4CF5-A7D3-8237B8588AAA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {38E88883-3571-4CF5-A7D3-8237B8588AAA}.Debug|Any CPU.Build.0 = Debug|Any CPU + {38E88883-3571-4CF5-A7D3-8237B8588AAA}.Release|Any CPU.ActiveCfg = Release|Any CPU + {38E88883-3571-4CF5-A7D3-8237B8588AAA}.Release|Any CPU.Build.0 = Release|Any CPU + {E2A86DD9-3A27-474B-B16E-8E9139DD70E9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E2A86DD9-3A27-474B-B16E-8E9139DD70E9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E2A86DD9-3A27-474B-B16E-8E9139DD70E9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E2A86DD9-3A27-474B-B16E-8E9139DD70E9}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection EndGlobal From d35e91de803e40dcbd765ab4939857b00c7cf3b5 Mon Sep 17 00:00:00 2001 From: user Date: Fri, 18 Aug 2023 12:23:19 +0200 Subject: [PATCH 08/20] Update Lib_CSharp --- Moderation/Moderation/Lib_CSharp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Moderation/Moderation/Lib_CSharp b/Moderation/Moderation/Lib_CSharp index 5393de4..94eb5e3 160000 --- a/Moderation/Moderation/Lib_CSharp +++ b/Moderation/Moderation/Lib_CSharp @@ -1 +1 @@ -Subproject commit 5393de452a5794f14777d0441901539293ba21ef +Subproject commit 94eb5e3c81bb187376b4ac69238a4f7de0103b10 From b91492d3d9576be23f886d1401c87e96c9c1a0a4 Mon Sep 17 00:00:00 2001 From: user Date: Fri, 18 Aug 2023 12:26:18 +0200 Subject: [PATCH 09/20] Update Lib_CSharp and Program.cs --- Moderation/Moderation/Lib_CSharp | 2 +- Moderation/Moderation/src/Program.cs | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Moderation/Moderation/Lib_CSharp b/Moderation/Moderation/Lib_CSharp index 94eb5e3..a693b73 160000 --- a/Moderation/Moderation/Lib_CSharp +++ b/Moderation/Moderation/Lib_CSharp @@ -1 +1 @@ -Subproject commit 94eb5e3c81bb187376b4ac69238a4f7de0103b10 +Subproject commit a693b7398af0c5eb915d5f03cd54a792de93b454 diff --git a/Moderation/Moderation/src/Program.cs b/Moderation/Moderation/src/Program.cs index ba3378b..87d172e 100644 --- a/Moderation/Moderation/src/Program.cs +++ b/Moderation/Moderation/src/Program.cs @@ -6,6 +6,7 @@ using PoliNetwork.Telegram.Configuration; using PoliNetwork.Telegram.ConfigurationLoader; using PoliNetwork.Db.Objects; +using PoliNetwork.Telegram.Bot.Bots; using PoliNetwork.Telegram.Options; using PoliNetwork.Telegram.Properties; #endregion From a73fc8869e0a37df69816d1671e9c059d5d9de7c Mon Sep 17 00:00:00 2001 From: user Date: Fri, 18 Aug 2023 12:29:16 +0200 Subject: [PATCH 10/20] Update Lib_CSharp and Common.cs --- Moderation/Moderation/Lib_CSharp | 2 +- Moderation/ModerationTest/Tests/Common.cs | 14 ++++++++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/Moderation/Moderation/Lib_CSharp b/Moderation/Moderation/Lib_CSharp index a693b73..79ab839 160000 --- a/Moderation/Moderation/Lib_CSharp +++ b/Moderation/Moderation/Lib_CSharp @@ -1 +1 @@ -Subproject commit a693b7398af0c5eb915d5f03cd54a792de93b454 +Subproject commit 79ab839a80ce276aefa314176e5f5397ab37f3ac diff --git a/Moderation/ModerationTest/Tests/Common.cs b/Moderation/ModerationTest/Tests/Common.cs index b659105..d2a2b8b 100644 --- a/Moderation/ModerationTest/Tests/Common.cs +++ b/Moderation/ModerationTest/Tests/Common.cs @@ -1,6 +1,8 @@ -using System.Threading; +using System; +using System.Threading; using Moderation; -using PoliNetwork.Telegram.Objects.Bot; +using PoliNetwork.Telegram.Bot.Bots; + namespace ModerationTest.Tests { @@ -37,4 +39,12 @@ public void TestSayHello() Assert.Equal("Hello, World!", result); } } + + public class HelloWorld + { + public string SayHello() + { + return "Hello, World!"; + } + } } \ No newline at end of file From 80b3e88ca1dcb29926893218e41ac116662c88af Mon Sep 17 00:00:00 2001 From: user Date: Fri, 18 Aug 2023 12:29:36 +0200 Subject: [PATCH 11/20] Update ModerationTest.csproj --- Moderation/ModerationTest/ModerationTest.csproj | 1 - 1 file changed, 1 deletion(-) diff --git a/Moderation/ModerationTest/ModerationTest.csproj b/Moderation/ModerationTest/ModerationTest.csproj index 5032947..2a41f07 100644 --- a/Moderation/ModerationTest/ModerationTest.csproj +++ b/Moderation/ModerationTest/ModerationTest.csproj @@ -24,7 +24,6 @@ - From 00c065edbdc9782ae1c33de9412ac33141f666d0 Mon Sep 17 00:00:00 2001 From: angeousta Date: Fri, 1 Sep 2023 08:23:30 +0200 Subject: [PATCH 12/20] Update Lib_CSharp --- Moderation/Moderation/Lib_CSharp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Moderation/Moderation/Lib_CSharp b/Moderation/Moderation/Lib_CSharp index 79ab839..0df6a01 160000 --- a/Moderation/Moderation/Lib_CSharp +++ b/Moderation/Moderation/Lib_CSharp @@ -1 +1 @@ -Subproject commit 79ab839a80ce276aefa314176e5f5397ab37f3ac +Subproject commit 0df6a015f09583e37fc744aa08bf28919bf364b4 From 1fa2c12c2ae1fa8841ab92c2e0974e23661c6b82 Mon Sep 17 00:00:00 2001 From: angeousta Date: Fri, 1 Sep 2023 10:36:58 +0200 Subject: [PATCH 13/20] Update Lib_CSharp, Program.cs, and Common.cs --- Moderation/Moderation/Lib_CSharp | 2 +- Moderation/Moderation/src/Program.cs | 15 +++++++-------- Moderation/ModerationTest/Tests/Common.cs | 4 +--- 3 files changed, 9 insertions(+), 12 deletions(-) diff --git a/Moderation/Moderation/Lib_CSharp b/Moderation/Moderation/Lib_CSharp index 0df6a01..270e908 160000 --- a/Moderation/Moderation/Lib_CSharp +++ b/Moderation/Moderation/Lib_CSharp @@ -1 +1 @@ -Subproject commit 0df6a015f09583e37fc744aa08bf28919bf364b4 +Subproject commit 270e908b700ad364d128f85eea74c7482ffb23d1 diff --git a/Moderation/Moderation/src/Program.cs b/Moderation/Moderation/src/Program.cs index 87d172e..2c0fc64 100644 --- a/Moderation/Moderation/src/Program.cs +++ b/Moderation/Moderation/src/Program.cs @@ -2,7 +2,6 @@ using PoliNetwork.Core.Utils; using PoliNetwork.Telegram.Logger; using PoliNetwork.Db.Utils; -using PoliNetwork.Telegram.Bot; using PoliNetwork.Telegram.Configuration; using PoliNetwork.Telegram.ConfigurationLoader; using PoliNetwork.Db.Objects; @@ -15,8 +14,8 @@ namespace Moderation; internal static class Program { - private static ModerationBot? bot = null; - private static readonly string databaseConfigurationPath = ""; + private static ModerationBot? _bot = null; + private const string DatabaseConfigurationPath = ""; public static void Main() { @@ -26,7 +25,7 @@ The only dependency of the PoliNetwork.Core.Utils.LoggerNS.Logger resides here i FileConfigurationLoader fileConfigurationLoader = new JSONFileConfigurationLoader(); AbstractTelegramBotOptions? botConfiguration = fileConfigurationLoader.LoadOrInitializeConfig(Configuration.TELEGRAM_CONFIGURATION_PATH, logger); - DbConfig? databaseConfiguration = DbConfigUtils.LoadOrInitializeConfig(databaseConfigurationPath); + DbConfig? databaseConfiguration = DbConfigUtils.LoadOrInitializeConfig(DatabaseConfigurationPath); if (botConfiguration == null) { logger?.Emergency("Telegram Config is undefined when starting the bot."); @@ -43,15 +42,15 @@ The only dependency of the PoliNetwork.Core.Utils.LoggerNS.Logger resides here i botConfiguration.UpdateMethod = new UpdateMethod(UpdateAction); /* TelegramConfiguration should extends TelegramBotClientOptions */ - bot = new ModerationBot(options: botConfiguration, logger: logger); - bot.Start(new CancellationToken()); + _bot = new ModerationBot(options: botConfiguration, logger: logger); + _bot.Start(new CancellationToken()); Wait.WaitForever(); } private static void UpdateAction(CancellationToken cancellationToken, IUpdate update) { /* Process Message updates only, see: https://core.telegram.org/bots/api#message */ - if (bot == null || update.Message is not { } message) return; - bot.Echo(message, cancellationToken); + if (_bot == null || update.Message is not { } message) return; + _bot.Echo(message, cancellationToken); } } \ No newline at end of file diff --git a/Moderation/ModerationTest/Tests/Common.cs b/Moderation/ModerationTest/Tests/Common.cs index d2a2b8b..f02f5e2 100644 --- a/Moderation/ModerationTest/Tests/Common.cs +++ b/Moderation/ModerationTest/Tests/Common.cs @@ -1,6 +1,4 @@ -using System; -using System.Threading; -using Moderation; +using System.Threading; using PoliNetwork.Telegram.Bot.Bots; From b52c38d5fe911dd04ccc21107049f0fc81165a80 Mon Sep 17 00:00:00 2001 From: joebiden <133514023+sbadung@users.noreply.github.com> Date: Thu, 7 Sep 2023 16:27:43 +0200 Subject: [PATCH 14/20] Fixing issue#14 actions and build --- Moderation/Moderation/Moderation.csproj | 25 ++++--- .../AbstractTelegramBotFunctionality.cs | 18 +++++ .../Example/ResponseOnMessageFunctionality.cs | 42 +++++++++++ .../ITelegramBotFunctionality.cs | 18 +++++ .../Default/DefaultPollingErrorHandler.cs | 21 ++++++ .../Handler/Default/DefaultUpdateHandler.cs | 25 +++++++ .../src/Bot/Handler/IPollingErrorHandler.cs | 22 ++++++ .../src/Bot/Handler/IUpdateHandler.cs | 21 ++++++ Moderation/Moderation/src/Bot/TelegramBot.cs | 53 ++++++++++++++ .../Moderation/src/Bot/TelegramBotOptions.cs | 19 +++++ Moderation/Moderation/src/Configuration.cs | 9 +++ Moderation/Moderation/src/Program.cs | 69 ++++++------------- .../ConfigurationLoad/IConfigurationLoader.cs | 17 +++++ .../JSONConfigurationLoader.cs | 50 ++++++++++++++ .../src/Utility/Converter/JSONConverter.cs | 16 +++++ .../ForbiddenWordsController.cs | 19 +++++ .../src/persistence/appsettings.json | 5 ++ .../src/persistence/forbidden_words.json | 3 + 18 files changed, 394 insertions(+), 58 deletions(-) create mode 100644 Moderation/Moderation/src/Bot/Functionality/AbstractTelegramBotFunctionality.cs create mode 100644 Moderation/Moderation/src/Bot/Functionality/Example/ResponseOnMessageFunctionality.cs create mode 100644 Moderation/Moderation/src/Bot/Functionality/ITelegramBotFunctionality.cs create mode 100644 Moderation/Moderation/src/Bot/Handler/Default/DefaultPollingErrorHandler.cs create mode 100644 Moderation/Moderation/src/Bot/Handler/Default/DefaultUpdateHandler.cs create mode 100644 Moderation/Moderation/src/Bot/Handler/IPollingErrorHandler.cs create mode 100644 Moderation/Moderation/src/Bot/Handler/IUpdateHandler.cs create mode 100644 Moderation/Moderation/src/Bot/TelegramBot.cs create mode 100644 Moderation/Moderation/src/Bot/TelegramBotOptions.cs create mode 100644 Moderation/Moderation/src/Configuration.cs create mode 100644 Moderation/Moderation/src/Utility/ConfigurationLoad/IConfigurationLoader.cs create mode 100644 Moderation/Moderation/src/Utility/ConfigurationLoad/JSONConfigurationLoader.cs create mode 100644 Moderation/Moderation/src/Utility/Converter/JSONConverter.cs create mode 100644 Moderation/Moderation/src/Utility/MessageContentControl/ForbiddenWordsController.cs create mode 100644 Moderation/Moderation/src/persistence/appsettings.json create mode 100644 Moderation/Moderation/src/persistence/forbidden_words.json diff --git a/Moderation/Moderation/Moderation.csproj b/Moderation/Moderation/Moderation.csproj index c5cd62a..ffa2d18 100644 --- a/Moderation/Moderation/Moderation.csproj +++ b/Moderation/Moderation/Moderation.csproj @@ -15,24 +15,29 @@ - - - + + + - - + + - - + + - - - + + + + + + + + diff --git a/Moderation/Moderation/src/Bot/Functionality/AbstractTelegramBotFunctionality.cs b/Moderation/Moderation/src/Bot/Functionality/AbstractTelegramBotFunctionality.cs new file mode 100644 index 0000000..93bf809 --- /dev/null +++ b/Moderation/Moderation/src/Bot/Functionality/AbstractTelegramBotFunctionality.cs @@ -0,0 +1,18 @@ +using Telegram.Bot; +using Telegram.Bot.Types; + +namespace PoliNetwork.Telegram.Bot.Functionality +{ + /// + /// Represents an abstract base class for defining the functionality of a Telegram bot. + /// + public abstract class AbstractTelegramBotFunctionality : ITelegramBotFunctionality + { + /// + /// Defines the behavior of the bot's functionality. This method must be implemented by derived classes. + /// + /// The instance representing the bot with which the functionality is associated. + /// A representing the asynchronous operation. + public abstract Task RunAsync(ITelegramBotClient bot, Update update, CancellationToken cancellationToken); + } +} diff --git a/Moderation/Moderation/src/Bot/Functionality/Example/ResponseOnMessageFunctionality.cs b/Moderation/Moderation/src/Bot/Functionality/Example/ResponseOnMessageFunctionality.cs new file mode 100644 index 0000000..7ad3d4c --- /dev/null +++ b/Moderation/Moderation/src/Bot/Functionality/Example/ResponseOnMessageFunctionality.cs @@ -0,0 +1,42 @@ +using PoliNetwork.Utility.Configuration; +using Telegram.Bot; +using Telegram.Bot.Types; +using PoliNetwork.Utility.MessageContentControl; + +namespace PoliNetwork.Telegram.Bot.Functionality.Example +{ + public class ResponseOnMessageFunctionality : AbstractTelegramBotFunctionality + { + private static string[] CreateForbiddenWordsArray() + { + var path = Config.FORBIDDEN_WORDS; + return JSONConverter.GetArrayFromFile(path) ?? Array.Empty(); + } + + public override async Task RunAsync(ITelegramBotClient bot, Update update, CancellationToken cancellationToken) + { + /* This way we only process the message text part */ + if (update.Message is not { } message) return; + if (message.Text is not { } messageText) return; + + var chatId = message.Chat.Id; + var username = message.Chat.Username; + + var forbiddenWords = CreateForbiddenWordsArray(); + var HasForbiddenWord = new ForbiddenWordsController(forbiddenWords).ContainsForbiddenWord(messageText); + + var serverPrompt = $"Received a '{messageText}' message in chat {chatId} ({username})."; + var responseText = HasForbiddenWord ? "Your massage contains a forbidden word" : "Your message is a valid one"; + Console.WriteLine(serverPrompt); + + var sentMessage = await bot.SendTextMessageAsync( + chatId: chatId, + text: responseText, + cancellationToken: cancellationToken + ); + + serverPrompt = $"Sent message: {sentMessage.Text}"; + Console.WriteLine(serverPrompt); + } + } +} \ No newline at end of file diff --git a/Moderation/Moderation/src/Bot/Functionality/ITelegramBotFunctionality.cs b/Moderation/Moderation/src/Bot/Functionality/ITelegramBotFunctionality.cs new file mode 100644 index 0000000..09f1e68 --- /dev/null +++ b/Moderation/Moderation/src/Bot/Functionality/ITelegramBotFunctionality.cs @@ -0,0 +1,18 @@ +using Telegram.Bot; +using Telegram.Bot.Types; + +namespace PoliNetwork.Telegram.Bot.Functionality +{ + /// + /// Represents an interface for defining the functionality of a Telegram bot. + /// + public interface ITelegramBotFunctionality + { + /// + /// Runs the defined functionality using the provided . + /// + /// The instance representing the bot with which the functionality is associated. + /// A representing the asynchronous operation. + Task RunAsync(ITelegramBotClient bot, Update update, CancellationToken cancellationToken); + } +} diff --git a/Moderation/Moderation/src/Bot/Handler/Default/DefaultPollingErrorHandler.cs b/Moderation/Moderation/src/Bot/Handler/Default/DefaultPollingErrorHandler.cs new file mode 100644 index 0000000..5427e57 --- /dev/null +++ b/Moderation/Moderation/src/Bot/Handler/Default/DefaultPollingErrorHandler.cs @@ -0,0 +1,21 @@ +using Telegram.Bot; +using Telegram.Bot.Exceptions; + +namespace PoliNetwork.Telegram.Bot.Handler +{ + public class DefaultPollingErrorHandler : IPollingErrorHandler + { + public Task HandlePollingErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken) + { + var ErrorMessage = exception switch + { + ApiRequestException apiRequestException + => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}", + _ => exception.ToString() + }; + + Console.WriteLine(ErrorMessage); + return Task.CompletedTask; + } + } +} \ No newline at end of file diff --git a/Moderation/Moderation/src/Bot/Handler/Default/DefaultUpdateHandler.cs b/Moderation/Moderation/src/Bot/Handler/Default/DefaultUpdateHandler.cs new file mode 100644 index 0000000..2e7c118 --- /dev/null +++ b/Moderation/Moderation/src/Bot/Handler/Default/DefaultUpdateHandler.cs @@ -0,0 +1,25 @@ +using PoliNetwork.Telegram.Bot.Functionality; +using Telegram.Bot; +using Telegram.Bot.Types; + +namespace PoliNetwork.Telegram.Bot.Handler +{ + public class DefaultUpdateHandler : IUpdateHandler + { + private readonly List Functionalities; + + public DefaultUpdateHandler(List functionalities) + { + Functionalities = functionalities; + } + + public async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) + { + /* Parallel.ForEach(_functionalities, functionalities => functionalities.Run(botClient, update, cancellationToken)); */ + foreach (var functionality in Functionalities) + { + await functionality.RunAsync(botClient, update, cancellationToken); + } + } + } +} \ No newline at end of file diff --git a/Moderation/Moderation/src/Bot/Handler/IPollingErrorHandler.cs b/Moderation/Moderation/src/Bot/Handler/IPollingErrorHandler.cs new file mode 100644 index 0000000..c53abc2 --- /dev/null +++ b/Moderation/Moderation/src/Bot/Handler/IPollingErrorHandler.cs @@ -0,0 +1,22 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Telegram.Bot; + +namespace PoliNetwork.Telegram.Bot.Handler +{ + /// + /// Represents an interface for handling errors that occur during the polling process of a Telegram bot. + /// + public interface IPollingErrorHandler + { + /// + /// Handles a polling error asynchronously. + /// + /// The instance used for interaction with the Telegram Bot API. + /// The that occurred during the polling process. + /// A that can be used to cancel the asynchronous operation. + /// A representing the asynchronous operation. + Task HandlePollingErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken); + } +} diff --git a/Moderation/Moderation/src/Bot/Handler/IUpdateHandler.cs b/Moderation/Moderation/src/Bot/Handler/IUpdateHandler.cs new file mode 100644 index 0000000..c4050a9 --- /dev/null +++ b/Moderation/Moderation/src/Bot/Handler/IUpdateHandler.cs @@ -0,0 +1,21 @@ + +using Telegram.Bot; +using Telegram.Bot.Types; + +namespace PoliNetwork.Telegram.Bot.Handler +{ + /// + /// Represents an interface for handling incoming Telegram updates. + /// + public interface IUpdateHandler + { + /// + /// Handles an incoming Telegram update asynchronously. + /// + /// The instance used for interaction with the Telegram Bot API. + /// The representing the incoming update to be handled. + /// A that can be used to cancel the asynchronous operation. + /// A representing the asynchronous operation. + Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken); + } +} diff --git a/Moderation/Moderation/src/Bot/TelegramBot.cs b/Moderation/Moderation/src/Bot/TelegramBot.cs new file mode 100644 index 0000000..a3c1da8 --- /dev/null +++ b/Moderation/Moderation/src/Bot/TelegramBot.cs @@ -0,0 +1,53 @@ +using PoliNetwork.Telegram.Bot.Handler; +using Telegram.Bot; +using Telegram.Bot.Polling; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; + +namespace PoliNetwork.Telegram.Bot +{ + /// + /// Represents a Telegram bot that can interact with the Telegram Bot API. + /// + public class TelegramBot : TelegramBotClient + { + /// + /// Initializes a new instance of the class with the provided options and an optional HttpClient. + /// + /// The options specifying bot settings. + /// Optional HttpClient to be used for API requests. + public TelegramBot(TelegramBotOptions options, HttpClient? httpClient = null) + : base(options, httpClient) { } + + /// + /// Initializes a new instance of the class with the provided bot token and an optional HttpClient. + /// + /// The authentication token of the bot. + /// Optional HttpClient to be used for API requests. + public TelegramBot(string token, HttpClient? httpClient = null) + : base(token, httpClient) { } + + public async Task RunAsync(Handler.IUpdateHandler updateHandler, IPollingErrorHandler pollingErrorHandler) + { + using CancellationTokenSource cts = new(); + + ReceiverOptions receiverOptions = new() + { + AllowedUpdates = Array.Empty() + }; + + this.StartReceiving( + updateHandler: updateHandler.HandleUpdateAsync, + pollingErrorHandler: pollingErrorHandler.HandlePollingErrorAsync, + receiverOptions: receiverOptions, + cancellationToken: cts.Token + ); + + var me = await this.GetMeAsync(); + Console.WriteLine($"Start listening for @{me.Username}\nExit via typing"); + Console.ReadLine(); + cts.Cancel(); + } + } +} + diff --git a/Moderation/Moderation/src/Bot/TelegramBotOptions.cs b/Moderation/Moderation/src/Bot/TelegramBotOptions.cs new file mode 100644 index 0000000..deb1c7f --- /dev/null +++ b/Moderation/Moderation/src/Bot/TelegramBotOptions.cs @@ -0,0 +1,19 @@ +using Telegram.Bot; + +namespace PoliNetwork.Telegram.Bot +{ + /// + /// Represents options for configuring a . + /// + public class TelegramBotOptions : TelegramBotClientOptions + { + /// + /// Initializes a new instance of the class with the provided token, base URL, and test environment settings. + /// + /// The authentication token of the bot. + /// Optional base URL for API requests. + /// Flag indicating whether to use the test environment. + protected TelegramBotOptions(string token, string? baseUrl = null, bool useTestEnvironment = false) + : base(token, baseUrl, useTestEnvironment) { } + } +} diff --git a/Moderation/Moderation/src/Configuration.cs b/Moderation/Moderation/src/Configuration.cs new file mode 100644 index 0000000..ab372b3 --- /dev/null +++ b/Moderation/Moderation/src/Configuration.cs @@ -0,0 +1,9 @@ +namespace PoliNetwork.Utility.Configuration +{ + public static class Config + { + private static readonly string? BASE_PATH = Directory.GetParent(Environment.CurrentDirectory)?.FullName; + public static readonly string FORBIDDEN_WORDS = BASE_PATH + @"\Moderation\src\persistence\forbidden_words.json"; + public static readonly string APP_SETTINGS = BASE_PATH + @"\Moderation\src\persistence\appsettings.json"; + } +} \ No newline at end of file diff --git a/Moderation/Moderation/src/Program.cs b/Moderation/Moderation/src/Program.cs index 2c0fc64..f6ca506 100644 --- a/Moderation/Moderation/src/Program.cs +++ b/Moderation/Moderation/src/Program.cs @@ -1,56 +1,29 @@ -#region -using PoliNetwork.Core.Utils; -using PoliNetwork.Telegram.Logger; -using PoliNetwork.Db.Utils; -using PoliNetwork.Telegram.Configuration; -using PoliNetwork.Telegram.ConfigurationLoader; -using PoliNetwork.Db.Objects; -using PoliNetwork.Telegram.Bot.Bots; -using PoliNetwork.Telegram.Options; -using PoliNetwork.Telegram.Properties; -#endregion - -namespace Moderation; - -internal static class Program +using PoliNetwork.Telegram.Bot; +using PoliNetwork.Telegram.Bot.Functionality; +using PoliNetwork.Telegram.Bot.Functionality.Example; +using PoliNetwork.Telegram.Bot.Handler; +using PoliNetwork.Utility.ConfigurationLoader; +using PoliNetwork.Utility.Configuration; + +namespace PoliNetwork.Moderation { - private static ModerationBot? _bot = null; - private const string DatabaseConfigurationPath = ""; - - public static void Main() + internal abstract class Program { - /* The PoliNetwork.Core.Utils.LoggerNS.Logger must extends the AbstractLogger so a sub class will be needed - The only dependency of the PoliNetwork.Core.Utils.LoggerNS.Logger resides here in the Program.cs */ - AbstractLogger? logger = new DefaultLogger(); - FileConfigurationLoader fileConfigurationLoader = new JSONFileConfigurationLoader(); - AbstractTelegramBotOptions? botConfiguration = fileConfigurationLoader.LoadOrInitializeConfig(Configuration.TELEGRAM_CONFIGURATION_PATH, logger); - - DbConfig? databaseConfiguration = DbConfigUtils.LoadOrInitializeConfig(DatabaseConfigurationPath); - if (botConfiguration == null) + private static async Task Main() { - logger?.Emergency("Telegram Config is undefined when starting the bot."); - return; - } + List telegramBotFunctionalities = new() + { + new ResponseOnMessageFunctionality() + }; - if (databaseConfiguration == null) - { - logger?.Emergency("Database Config is undefined when starting the bot."); - return; - } - - logger?.Info("RUNNING MODERATION BOT"); - botConfiguration.UpdateMethod = new UpdateMethod(UpdateAction); + IUpdateHandler updateHandler = new DefaultUpdateHandler(telegramBotFunctionalities); + IPollingErrorHandler pollingErrorHandler = new DefaultPollingErrorHandler(); - /* TelegramConfiguration should extends TelegramBotClientOptions */ - _bot = new ModerationBot(options: botConfiguration, logger: logger); - _bot.Start(new CancellationToken()); - Wait.WaitForever(); - } + var botToken = new JSONConfigurationLoader().LoadConfiguration(Config.APP_SETTINGS) + .GetSection("Secrets:BotToken").Value!; + TelegramBot bot = new(botToken); - private static void UpdateAction(CancellationToken cancellationToken, IUpdate update) - { - /* Process Message updates only, see: https://core.telegram.org/bots/api#message */ - if (_bot == null || update.Message is not { } message) return; - _bot.Echo(message, cancellationToken); + await bot.RunAsync(updateHandler, pollingErrorHandler); + } } } \ No newline at end of file diff --git a/Moderation/Moderation/src/Utility/ConfigurationLoad/IConfigurationLoader.cs b/Moderation/Moderation/src/Utility/ConfigurationLoad/IConfigurationLoader.cs new file mode 100644 index 0000000..7177325 --- /dev/null +++ b/Moderation/Moderation/src/Utility/ConfigurationLoad/IConfigurationLoader.cs @@ -0,0 +1,17 @@ +using Microsoft.Extensions.Configuration; + +namespace PoliNetwork.Utility.ConfigurationLoader +{ + /// + /// Represents an interface for loading configuration data from various sources. + /// + public interface IConfigurationLoader + { + /// + /// Loads configuration data from the specified path. + /// + /// The path to the configuration data. + /// An containing the loaded configuration data. + IConfigurationRoot LoadConfiguration(string path); + } +} diff --git a/Moderation/Moderation/src/Utility/ConfigurationLoad/JSONConfigurationLoader.cs b/Moderation/Moderation/src/Utility/ConfigurationLoad/JSONConfigurationLoader.cs new file mode 100644 index 0000000..639358b --- /dev/null +++ b/Moderation/Moderation/src/Utility/ConfigurationLoad/JSONConfigurationLoader.cs @@ -0,0 +1,50 @@ +using Microsoft.Extensions.Configuration; +using System.Text.Json; + +namespace PoliNetwork.Utility.ConfigurationLoader +{ + /// + /// Represents a configuration loader for loading JSON configuration data. + /// + public class JSONConfigurationLoader : IConfigurationLoader + { + /// + /// Loads configuration data from the specified JSON file. + /// + /// The path to the JSON configuration file. + /// An containing the loaded configuration data. + /// Thrown if the specified JSON file does not exist. + /// Thrown if the provided path is not a JSON file. + /// Thrown if the specified JSON file is not valid. + public IConfigurationRoot LoadConfiguration(string path) + { + bool notFound = !File.Exists(path); + bool notJson = !Path.HasExtension(path) || !Path.GetExtension(path).Equals(".json", StringComparison.OrdinalIgnoreCase); + + if (notFound) throw new FileNotFoundException("Unable to locate specified JSON file.", path); + if (notJson) throw new ArgumentException("Only JSON files are supported.", nameof(path)); + + try + { + return new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path) + .Build(); + } + catch (JsonException ex) + { + throw new JsonException("The specified JSON file is not valid.", ex); + } + catch (IOException ex) + { + throw new IOException("Could not open file.", ex); + } + + } + + /// + /// Initializes a new instance of the class. + /// + public JSONConfigurationLoader() : base() { } + } +} diff --git a/Moderation/Moderation/src/Utility/Converter/JSONConverter.cs b/Moderation/Moderation/src/Utility/Converter/JSONConverter.cs new file mode 100644 index 0000000..5440dbd --- /dev/null +++ b/Moderation/Moderation/src/Utility/Converter/JSONConverter.cs @@ -0,0 +1,16 @@ +using System.Runtime.InteropServices; +using Newtonsoft.Json; + +class JSONConverter +{ + public static string[]? GetArrayFromString(string json) + { + return JsonConvert.DeserializeObject(json)?.ToArray(); + } + + public static string[]? GetArrayFromFile(string path) + { + string json = File.ReadAllText(path); + return GetArrayFromString(json); + } +} \ No newline at end of file diff --git a/Moderation/Moderation/src/Utility/MessageContentControl/ForbiddenWordsController.cs b/Moderation/Moderation/src/Utility/MessageContentControl/ForbiddenWordsController.cs new file mode 100644 index 0000000..3e278a1 --- /dev/null +++ b/Moderation/Moderation/src/Utility/MessageContentControl/ForbiddenWordsController.cs @@ -0,0 +1,19 @@ +namespace PoliNetwork.Utility.MessageContentControl; + +public sealed class ForbiddenWordsController +{ + private string[] ForbiddenWords { get; set; } + + public ForbiddenWordsController(string[] forbiddenWords) + { + ForbiddenWords = forbiddenWords; + } + + public bool ContainsForbiddenWord(string line) => ForbiddenWords.Any(line.Contains); + + public string? GetFirstForbiddenWord(string line) => + ForbiddenWords.FirstOrDefault(word => line.Contains(word, StringComparison.OrdinalIgnoreCase)); + + + public bool HasForbiddenWord(string line) => ForbiddenWords.Any(); +} \ No newline at end of file diff --git a/Moderation/Moderation/src/persistence/appsettings.json b/Moderation/Moderation/src/persistence/appsettings.json new file mode 100644 index 0000000..7d0cf10 --- /dev/null +++ b/Moderation/Moderation/src/persistence/appsettings.json @@ -0,0 +1,5 @@ +{ + "Secrets": { + "BotToken": "6576423301:AAGZY8_D-QmDxFsWGp6D3z_CJ-odA8NLQSE" + } +} \ No newline at end of file diff --git a/Moderation/Moderation/src/persistence/forbidden_words.json b/Moderation/Moderation/src/persistence/forbidden_words.json new file mode 100644 index 0000000..f46c070 --- /dev/null +++ b/Moderation/Moderation/src/persistence/forbidden_words.json @@ -0,0 +1,3 @@ +[ + "forbidden" +] \ No newline at end of file From 2da4c7764a00444251c4ac8fc77a5f2412ce1037 Mon Sep 17 00:00:00 2001 From: joebiden <133514023+sbadung@users.noreply.github.com> Date: Thu, 7 Sep 2023 21:02:25 +0200 Subject: [PATCH 15/20] Merge conflict from main #1 --- Lib_CSharp | 1 - .../AbstractTelegramBotFunctionality.cs | 18 ------- .../Example/ResponseOnMessageFunctionality.cs | 51 ------------------ .../ITelegramBotFunctionality.cs | 18 ------- .../Default/DefaultPollingErrorHandler.cs | 21 -------- .../Handler/Default/DefaultUpdateHandler.cs | 27 ---------- .../Bot/Handler/IPollingErrorHandler.cs | 22 -------- .../Moderation/Bot/Handler/IUpdateHandler.cs | 24 --------- Moderation/Moderation/Bot/TelegramBot.cs | 52 ------------------- .../Moderation/Bot/TelegramBotOptions.cs | 19 ------- Moderation/Moderation/Configuration.cs | 9 ---- Moderation/Moderation/PoliNetwork.Bot.csproj | 16 ------ Moderation/Moderation/Program.cs | 34 ------------ .../Moderation/persistence/appsettings.json | 5 -- .../persistence/forbidden_words.json | 3 -- 15 files changed, 320 deletions(-) delete mode 160000 Lib_CSharp delete mode 100644 Moderation/Moderation/Bot/Functionality/AbstractTelegramBotFunctionality.cs delete mode 100644 Moderation/Moderation/Bot/Functionality/Example/ResponseOnMessageFunctionality.cs delete mode 100644 Moderation/Moderation/Bot/Functionality/ITelegramBotFunctionality.cs delete mode 100644 Moderation/Moderation/Bot/Handler/Default/DefaultPollingErrorHandler.cs delete mode 100644 Moderation/Moderation/Bot/Handler/Default/DefaultUpdateHandler.cs delete mode 100644 Moderation/Moderation/Bot/Handler/IPollingErrorHandler.cs delete mode 100644 Moderation/Moderation/Bot/Handler/IUpdateHandler.cs delete mode 100644 Moderation/Moderation/Bot/TelegramBot.cs delete mode 100644 Moderation/Moderation/Bot/TelegramBotOptions.cs delete mode 100644 Moderation/Moderation/Configuration.cs delete mode 100644 Moderation/Moderation/PoliNetwork.Bot.csproj delete mode 100644 Moderation/Moderation/Program.cs delete mode 100644 Moderation/Moderation/persistence/appsettings.json delete mode 100644 Moderation/Moderation/persistence/forbidden_words.json diff --git a/Lib_CSharp b/Lib_CSharp deleted file mode 160000 index 88742e7..0000000 --- a/Lib_CSharp +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 88742e75e88f8da0ce1be3f9bf59b723e6ebc443 diff --git a/Moderation/Moderation/Bot/Functionality/AbstractTelegramBotFunctionality.cs b/Moderation/Moderation/Bot/Functionality/AbstractTelegramBotFunctionality.cs deleted file mode 100644 index 93bf809..0000000 --- a/Moderation/Moderation/Bot/Functionality/AbstractTelegramBotFunctionality.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Telegram.Bot; -using Telegram.Bot.Types; - -namespace PoliNetwork.Telegram.Bot.Functionality -{ - /// - /// Represents an abstract base class for defining the functionality of a Telegram bot. - /// - public abstract class AbstractTelegramBotFunctionality : ITelegramBotFunctionality - { - /// - /// Defines the behavior of the bot's functionality. This method must be implemented by derived classes. - /// - /// The instance representing the bot with which the functionality is associated. - /// A representing the asynchronous operation. - public abstract Task RunAsync(ITelegramBotClient bot, Update update, CancellationToken cancellationToken); - } -} diff --git a/Moderation/Moderation/Bot/Functionality/Example/ResponseOnMessageFunctionality.cs b/Moderation/Moderation/Bot/Functionality/Example/ResponseOnMessageFunctionality.cs deleted file mode 100644 index c76ae65..0000000 --- a/Moderation/Moderation/Bot/Functionality/Example/ResponseOnMessageFunctionality.cs +++ /dev/null @@ -1,51 +0,0 @@ -using Configuration; -using PoliNetwork.Telegram.Bot.Functionality; -using Telegram.Bot; -using Telegram.Bot.Types; - -namespace PoliNetwork.Bot.Bot.Functionality.Example -{ - public class ResponseOnMessageFunctionality : AbstractTelegramBotFunctionality - { - private static string GetBasePath() - { - return "C:/Users/Joe Biden/RiderProjects/PoliNetworkBot/Moderation/Moderation/"; - } - - private static string[] CreateForbiddenWordsArray() - { - var path = GetBasePath() + Config.FORBIDDEN_WORDS; - return JSONConverter.GetArrayFromFile(path) ?? Array.Empty(); - } - - public override async Task RunAsync(ITelegramBotClient bot, Update update, - CancellationToken cancellationToken) - { - /* This way we only process the message text part */ - if (update.Message is not { } message) return Task.CompletedTask; - if (message.Text is not { } messageText) return Task.CompletedTask; - - var chatId = message.Chat.Id; - var username = message.Chat.Username; - - var forbiddenWords = CreateForbiddenWordsArray(); - var hasForbiddenWord = new ForbiddenWordsController(forbiddenWords).ContainsForbiddenWord(messageText); - - var serverPrompt = $"Received a '{messageText}' message in chat {chatId} ({username})."; - var responseText = - hasForbiddenWord ? "Your massage contains a forbidden word" : "Your message is a valid one"; - Console.WriteLine(serverPrompt); - - var sentMessage = await bot.SendTextMessageAsync( - chatId: chatId, - text: responseText, - cancellationToken: cancellationToken - ); - - serverPrompt = $"Sent message: {sentMessage.Text}"; - Console.WriteLine(serverPrompt); - - return Task.CompletedTask; - } - } -} \ No newline at end of file diff --git a/Moderation/Moderation/Bot/Functionality/ITelegramBotFunctionality.cs b/Moderation/Moderation/Bot/Functionality/ITelegramBotFunctionality.cs deleted file mode 100644 index 09f1e68..0000000 --- a/Moderation/Moderation/Bot/Functionality/ITelegramBotFunctionality.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Telegram.Bot; -using Telegram.Bot.Types; - -namespace PoliNetwork.Telegram.Bot.Functionality -{ - /// - /// Represents an interface for defining the functionality of a Telegram bot. - /// - public interface ITelegramBotFunctionality - { - /// - /// Runs the defined functionality using the provided . - /// - /// The instance representing the bot with which the functionality is associated. - /// A representing the asynchronous operation. - Task RunAsync(ITelegramBotClient bot, Update update, CancellationToken cancellationToken); - } -} diff --git a/Moderation/Moderation/Bot/Handler/Default/DefaultPollingErrorHandler.cs b/Moderation/Moderation/Bot/Handler/Default/DefaultPollingErrorHandler.cs deleted file mode 100644 index 5427e57..0000000 --- a/Moderation/Moderation/Bot/Handler/Default/DefaultPollingErrorHandler.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Telegram.Bot; -using Telegram.Bot.Exceptions; - -namespace PoliNetwork.Telegram.Bot.Handler -{ - public class DefaultPollingErrorHandler : IPollingErrorHandler - { - public Task HandlePollingErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken) - { - var ErrorMessage = exception switch - { - ApiRequestException apiRequestException - => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}", - _ => exception.ToString() - }; - - Console.WriteLine(ErrorMessage); - return Task.CompletedTask; - } - } -} \ No newline at end of file diff --git a/Moderation/Moderation/Bot/Handler/Default/DefaultUpdateHandler.cs b/Moderation/Moderation/Bot/Handler/Default/DefaultUpdateHandler.cs deleted file mode 100644 index d02954d..0000000 --- a/Moderation/Moderation/Bot/Handler/Default/DefaultUpdateHandler.cs +++ /dev/null @@ -1,27 +0,0 @@ -using PoliNetwork.Telegram.Bot.Functionality; -using Telegram.Bot; -using Telegram.Bot.Types; - -namespace PoliNetwork.Telegram.Bot.Handler -{ - public class DefaultUpdateHandler : IUpdateHandler - { - private readonly List _functionalities; - - public DefaultUpdateHandler(List functionalities) - { - _functionalities = functionalities; - } - - public async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) - { - /* Parallel.ForEach(_functionalities, functionalities => functionalities.Run(botClient, update, cancellationToken)); */ - foreach (var functionality in _functionalities) - { - await functionality.RunAsync(botClient, update, cancellationToken); - } - } - - public List GetFunctionalitisList() => _functionalities; - } -} \ No newline at end of file diff --git a/Moderation/Moderation/Bot/Handler/IPollingErrorHandler.cs b/Moderation/Moderation/Bot/Handler/IPollingErrorHandler.cs deleted file mode 100644 index c53abc2..0000000 --- a/Moderation/Moderation/Bot/Handler/IPollingErrorHandler.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using Telegram.Bot; - -namespace PoliNetwork.Telegram.Bot.Handler -{ - /// - /// Represents an interface for handling errors that occur during the polling process of a Telegram bot. - /// - public interface IPollingErrorHandler - { - /// - /// Handles a polling error asynchronously. - /// - /// The instance used for interaction with the Telegram Bot API. - /// The that occurred during the polling process. - /// A that can be used to cancel the asynchronous operation. - /// A representing the asynchronous operation. - Task HandlePollingErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken); - } -} diff --git a/Moderation/Moderation/Bot/Handler/IUpdateHandler.cs b/Moderation/Moderation/Bot/Handler/IUpdateHandler.cs deleted file mode 100644 index a76d18d..0000000 --- a/Moderation/Moderation/Bot/Handler/IUpdateHandler.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.Threading; -using System.Threading.Tasks; -using PoliNetwork.Telegram.Bot.Functionality; -using Telegram.Bot; -using Telegram.Bot.Types; - -namespace PoliNetwork.Telegram.Bot.Handler -{ - /// - /// Represents an interface for handling incoming Telegram updates. - /// - public interface IUpdateHandler - { - /// - /// Handles an incoming Telegram update asynchronously. - /// - /// The instance used for interaction with the Telegram Bot API. - /// The representing the incoming update to be handled. - /// A that can be used to cancel the asynchronous operation. - /// A representing the asynchronous operation. - Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken); - List GetFunctionalitisList(); - } -} diff --git a/Moderation/Moderation/Bot/TelegramBot.cs b/Moderation/Moderation/Bot/TelegramBot.cs deleted file mode 100644 index 559c913..0000000 --- a/Moderation/Moderation/Bot/TelegramBot.cs +++ /dev/null @@ -1,52 +0,0 @@ -using PoliNetwork.Telegram.Bot.Handler; -using Telegram.Bot; -using Telegram.Bot.Polling; -using Telegram.Bot.Types.Enums; - -namespace PoliNetwork.Telegram.Bot -{ - /// - /// Represents a Telegram bot that can interact with the Telegram Bot API. - /// - public class TelegramBot : TelegramBotClient - { - /// - /// Initializes a new instance of the class with the provided options and an optional HttpClient. - /// - /// The options specifying bot settings. - /// Optional HttpClient to be used for API requests. - public TelegramBot(TelegramBotOptions options, HttpClient? httpClient = null) - : base(options, httpClient) { } - - /// - /// Initializes a new instance of the class with the provided bot token and an optional HttpClient. - /// - /// The authentication token of the bot. - /// Optional HttpClient to be used for API requests. - public TelegramBot(string token, HttpClient? httpClient = null) - : base(token, httpClient) { } - - public async Task RunAsync(Handler.IUpdateHandler updateHandler, IPollingErrorHandler pollingErrorHandler) - { - using CancellationTokenSource cts = new(); - - ReceiverOptions receiverOptions = new() - { - AllowedUpdates = Array.Empty() - }; - - this.StartReceiving( - updateHandler: updateHandler.HandleUpdateAsync, - pollingErrorHandler: pollingErrorHandler.HandlePollingErrorAsync, - receiverOptions: receiverOptions, - cancellationToken: cts.Token - ); - - var me = await this.GetMeAsync(); - Console.WriteLine($"Start listening for @{me.Username}\nExit via typing"); - Console.ReadLine(); - cts.Cancel(); - } - } -} - diff --git a/Moderation/Moderation/Bot/TelegramBotOptions.cs b/Moderation/Moderation/Bot/TelegramBotOptions.cs deleted file mode 100644 index deb1c7f..0000000 --- a/Moderation/Moderation/Bot/TelegramBotOptions.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Telegram.Bot; - -namespace PoliNetwork.Telegram.Bot -{ - /// - /// Represents options for configuring a . - /// - public class TelegramBotOptions : TelegramBotClientOptions - { - /// - /// Initializes a new instance of the class with the provided token, base URL, and test environment settings. - /// - /// The authentication token of the bot. - /// Optional base URL for API requests. - /// Flag indicating whether to use the test environment. - protected TelegramBotOptions(string token, string? baseUrl = null, bool useTestEnvironment = false) - : base(token, baseUrl, useTestEnvironment) { } - } -} diff --git a/Moderation/Moderation/Configuration.cs b/Moderation/Moderation/Configuration.cs deleted file mode 100644 index f04a862..0000000 --- a/Moderation/Moderation/Configuration.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace Configuration -{ - public sealed class Config - { - public static readonly string FORBIDDEN_WORDS = @"\moderation\persistence\forbidden_words.json"; - public static readonly string APP_SETTIGNS = @"\moderation\persistence\appsettings.json"; - } - -} \ No newline at end of file diff --git a/Moderation/Moderation/PoliNetwork.Bot.csproj b/Moderation/Moderation/PoliNetwork.Bot.csproj deleted file mode 100644 index fccf78f..0000000 --- a/Moderation/Moderation/PoliNetwork.Bot.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - Exe - net7.0 - enable - enable - - - - - - - - - diff --git a/Moderation/Moderation/Program.cs b/Moderation/Moderation/Program.cs deleted file mode 100644 index c63e91d..0000000 --- a/Moderation/Moderation/Program.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Configuration; -using PoliNetwork.Bot.Bot.Functionality.Example; -using PoliNetwork.Telegram.Bot; -using PoliNetwork.Telegram.Bot.Functionality; -using PoliNetwork.Telegram.Bot.Handler; -using PoliNetwork.Utility.ConfigurationLoader; - -namespace PoliNetwork.Bot -{ - internal static class Program - { - private static async Task Main(string[] args) - { - List telegramBotFunctionalities = new() - { - new ResponseOnMessageFunctionality() - }; - - IUpdateHandler updateHandler = new DefaultUpdateHandler(telegramBotFunctionalities); - IPollingErrorHandler pollingErrorHandler = new DefaultPollingErrorHandler(); - - var botToken = new JSONConfigurationLoader().LoadConfiguration(GetBasePath() + Config.APP_SETTIGNS) - .GetSection("Secrets:BotToken").Value!; - TelegramBot bot = new(botToken); - - await bot.RunAsync(updateHandler, pollingErrorHandler); - } - - public static string GetBasePath() - { - return Directory.GetParent(Environment.CurrentDirectory).FullName; - } - } -} \ No newline at end of file diff --git a/Moderation/Moderation/persistence/appsettings.json b/Moderation/Moderation/persistence/appsettings.json deleted file mode 100644 index 7d0cf10..0000000 --- a/Moderation/Moderation/persistence/appsettings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "Secrets": { - "BotToken": "6576423301:AAGZY8_D-QmDxFsWGp6D3z_CJ-odA8NLQSE" - } -} \ No newline at end of file diff --git a/Moderation/Moderation/persistence/forbidden_words.json b/Moderation/Moderation/persistence/forbidden_words.json deleted file mode 100644 index f46c070..0000000 --- a/Moderation/Moderation/persistence/forbidden_words.json +++ /dev/null @@ -1,3 +0,0 @@ -[ - "forbidden" -] \ No newline at end of file From ecb03cf2afaa90cfd7bc1a98f308b2505430e563 Mon Sep 17 00:00:00 2001 From: joebiden <133514023+sbadung@users.noreply.github.com> Date: Thu, 7 Sep 2023 21:01:22 +0200 Subject: [PATCH 16/20] Revert "Merge conflic from main #1" This reverts commit 7caf06e5bf7fd6009258d0bb95541c053528b562. --- .gitignore | 2 - .gitmodules | 6 +- .../.idea/.idea.Moderation}/.idea/.gitignore | 4 +- .../.idea.Moderation}/.idea/encodings.xml | 0 .../.idea.Moderation}/.idea/indexLayout.xml | 0 .../.idea/projectSettingsUpdater.xml | 6 - .../.idea/.idea.Moderation}/.idea/vcs.xml | 1 + .../.idea.Moderation/.idea/workspace.xml | 117 ------------------ Moderation/Moderation/Dockerfile | 2 +- .../ConfigurationLoad/IConfigurationLoader.cs | 17 --- .../JSONConfigurationLoader.cs | 50 -------- .../Utility/Converter/JSONConverter.cs | 16 --- .../ForbiddenWordsController.cs | 29 ----- Moderation/Moderation/static/ssh-agent | 23 ++++ Moderation/ModerationTest/GlobalUsing.cs | 1 + PoliNetworkBot.sln | 34 ----- README.md | 34 ----- 17 files changed, 31 insertions(+), 311 deletions(-) rename {.idea/.idea.PoliNetworkBot => Moderation/.idea/.idea.Moderation}/.idea/.gitignore (90%) rename {.idea/.idea.PoliNetworkBot => Moderation/.idea/.idea.Moderation}/.idea/encodings.xml (100%) rename {.idea/.idea.PoliNetworkBot => Moderation/.idea/.idea.Moderation}/.idea/indexLayout.xml (100%) delete mode 100644 Moderation/.idea/.idea.Moderation/.idea/projectSettingsUpdater.xml rename {.idea/.idea.PoliNetworkBot => Moderation/.idea/.idea.Moderation}/.idea/vcs.xml (71%) delete mode 100644 Moderation/.idea/.idea.Moderation/.idea/workspace.xml delete mode 100644 Moderation/Moderation/Utility/ConfigurationLoad/IConfigurationLoader.cs delete mode 100644 Moderation/Moderation/Utility/ConfigurationLoad/JSONConfigurationLoader.cs delete mode 100644 Moderation/Moderation/Utility/Converter/JSONConverter.cs delete mode 100644 Moderation/Moderation/Utility/MessageContentControl/ForbiddenWordsController.cs create mode 100644 Moderation/Moderation/static/ssh-agent create mode 100644 Moderation/ModerationTest/GlobalUsing.cs delete mode 100644 PoliNetworkBot.sln diff --git a/.gitignore b/.gitignore index 509c522..e5affe7 100644 --- a/.gitignore +++ b/.gitignore @@ -566,5 +566,3 @@ Moderation/Main/.idea/.idea.Main.dir/.idea/.gitignore Moderation/Main/.idea/.idea.Main.dir/.idea/encodings.xml Moderation/Main/.idea/.idea.Main.dir/.idea/indexLayout.xml Moderation/Main/.idea/.idea.Main.dir/.idea/vcs.xml -.idea/.idea.PoliNetwork.Bot/.idea/ -.idea/.idea.Telegram/.idea/ \ No newline at end of file diff --git a/.gitmodules b/.gitmodules index 93899fa..201b1a7 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,3 @@ -[submodule "Lib_CSharp"] - path = Lib_CSharp - url = https://github.com/PoliNetworkOrg/Lib_CSharp.git +[submodule "Moderation/Moderation/Lib_CSharp"] + path = Moderation/Moderation/Lib_CSharp + url = https://github.com/PoliNetworkOrg/Lib_CSharp diff --git a/.idea/.idea.PoliNetworkBot/.idea/.gitignore b/Moderation/.idea/.idea.Moderation/.idea/.gitignore similarity index 90% rename from .idea/.idea.PoliNetworkBot/.idea/.gitignore rename to Moderation/.idea/.idea.Moderation/.idea/.gitignore index b55536b..41edf57 100644 --- a/.idea/.idea.PoliNetworkBot/.idea/.gitignore +++ b/Moderation/.idea/.idea.Moderation/.idea/.gitignore @@ -2,10 +2,10 @@ /shelf/ /workspace.xml # Rider ignored files +/projectSettingsUpdater.xml +/.idea.Moderation.iml /contentModel.xml /modules.xml -/.idea.PoliNetworkBot.iml -/projectSettingsUpdater.xml # Editor-based HTTP Client requests /httpRequests/ # Datasource local storage ignored files diff --git a/.idea/.idea.PoliNetworkBot/.idea/encodings.xml b/Moderation/.idea/.idea.Moderation/.idea/encodings.xml similarity index 100% rename from .idea/.idea.PoliNetworkBot/.idea/encodings.xml rename to Moderation/.idea/.idea.Moderation/.idea/encodings.xml diff --git a/.idea/.idea.PoliNetworkBot/.idea/indexLayout.xml b/Moderation/.idea/.idea.Moderation/.idea/indexLayout.xml similarity index 100% rename from .idea/.idea.PoliNetworkBot/.idea/indexLayout.xml rename to Moderation/.idea/.idea.Moderation/.idea/indexLayout.xml diff --git a/Moderation/.idea/.idea.Moderation/.idea/projectSettingsUpdater.xml b/Moderation/.idea/.idea.Moderation/.idea/projectSettingsUpdater.xml deleted file mode 100644 index 4bb9f4d..0000000 --- a/Moderation/.idea/.idea.Moderation/.idea/projectSettingsUpdater.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - \ No newline at end of file diff --git a/.idea/.idea.PoliNetworkBot/.idea/vcs.xml b/Moderation/.idea/.idea.Moderation/.idea/vcs.xml similarity index 71% rename from .idea/.idea.PoliNetworkBot/.idea/vcs.xml rename to Moderation/.idea/.idea.Moderation/.idea/vcs.xml index 6c0b863..4f569d3 100644 --- a/.idea/.idea.PoliNetworkBot/.idea/vcs.xml +++ b/Moderation/.idea/.idea.Moderation/.idea/vcs.xml @@ -2,5 +2,6 @@ + \ No newline at end of file diff --git a/Moderation/.idea/.idea.Moderation/.idea/workspace.xml b/Moderation/.idea/.idea.Moderation/.idea/workspace.xml deleted file mode 100644 index a803f68..0000000 --- a/Moderation/.idea/.idea.Moderation/.idea/workspace.xml +++ /dev/null @@ -1,117 +0,0 @@ - - - - Moderation/Moderation.csproj - - - - - - - - - - - - - - - - - - - - - - - - - - 1693580141369 - - - - - - - - - - - \ No newline at end of file diff --git a/Moderation/Moderation/Dockerfile b/Moderation/Moderation/Dockerfile index e789265..a83532a 100644 --- a/Moderation/Moderation/Dockerfile +++ b/Moderation/Moderation/Dockerfile @@ -1,4 +1,4 @@ -FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build-env +FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build-env WORKDIR /App # Copy everything diff --git a/Moderation/Moderation/Utility/ConfigurationLoad/IConfigurationLoader.cs b/Moderation/Moderation/Utility/ConfigurationLoad/IConfigurationLoader.cs deleted file mode 100644 index 7177325..0000000 --- a/Moderation/Moderation/Utility/ConfigurationLoad/IConfigurationLoader.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Microsoft.Extensions.Configuration; - -namespace PoliNetwork.Utility.ConfigurationLoader -{ - /// - /// Represents an interface for loading configuration data from various sources. - /// - public interface IConfigurationLoader - { - /// - /// Loads configuration data from the specified path. - /// - /// The path to the configuration data. - /// An containing the loaded configuration data. - IConfigurationRoot LoadConfiguration(string path); - } -} diff --git a/Moderation/Moderation/Utility/ConfigurationLoad/JSONConfigurationLoader.cs b/Moderation/Moderation/Utility/ConfigurationLoad/JSONConfigurationLoader.cs deleted file mode 100644 index 639358b..0000000 --- a/Moderation/Moderation/Utility/ConfigurationLoad/JSONConfigurationLoader.cs +++ /dev/null @@ -1,50 +0,0 @@ -using Microsoft.Extensions.Configuration; -using System.Text.Json; - -namespace PoliNetwork.Utility.ConfigurationLoader -{ - /// - /// Represents a configuration loader for loading JSON configuration data. - /// - public class JSONConfigurationLoader : IConfigurationLoader - { - /// - /// Loads configuration data from the specified JSON file. - /// - /// The path to the JSON configuration file. - /// An containing the loaded configuration data. - /// Thrown if the specified JSON file does not exist. - /// Thrown if the provided path is not a JSON file. - /// Thrown if the specified JSON file is not valid. - public IConfigurationRoot LoadConfiguration(string path) - { - bool notFound = !File.Exists(path); - bool notJson = !Path.HasExtension(path) || !Path.GetExtension(path).Equals(".json", StringComparison.OrdinalIgnoreCase); - - if (notFound) throw new FileNotFoundException("Unable to locate specified JSON file.", path); - if (notJson) throw new ArgumentException("Only JSON files are supported.", nameof(path)); - - try - { - return new ConfigurationBuilder() - .SetBasePath(Directory.GetCurrentDirectory()) - .AddJsonFile(path) - .Build(); - } - catch (JsonException ex) - { - throw new JsonException("The specified JSON file is not valid.", ex); - } - catch (IOException ex) - { - throw new IOException("Could not open file.", ex); - } - - } - - /// - /// Initializes a new instance of the class. - /// - public JSONConfigurationLoader() : base() { } - } -} diff --git a/Moderation/Moderation/Utility/Converter/JSONConverter.cs b/Moderation/Moderation/Utility/Converter/JSONConverter.cs deleted file mode 100644 index 5440dbd..0000000 --- a/Moderation/Moderation/Utility/Converter/JSONConverter.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System.Runtime.InteropServices; -using Newtonsoft.Json; - -class JSONConverter -{ - public static string[]? GetArrayFromString(string json) - { - return JsonConvert.DeserializeObject(json)?.ToArray(); - } - - public static string[]? GetArrayFromFile(string path) - { - string json = File.ReadAllText(path); - return GetArrayFromString(json); - } -} \ No newline at end of file diff --git a/Moderation/Moderation/Utility/MessageContentControl/ForbiddenWordsController.cs b/Moderation/Moderation/Utility/MessageContentControl/ForbiddenWordsController.cs deleted file mode 100644 index 8ed992c..0000000 --- a/Moderation/Moderation/Utility/MessageContentControl/ForbiddenWordsController.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System.Diagnostics; - -public sealed class ForbiddenWordsController -{ - private string[] ForbiddenWords { get; set; } - - public ForbiddenWordsController(string[] _forbiddenWords) - { - ForbiddenWords = _forbiddenWords; - } - - public bool ContainsForbiddenWord(string line) => ForbiddenWords.Any(word => line.Contains(word)); - public string? GetFirstForbiddenWord(string line) - { - string? _word = null; - foreach (string word in ForbiddenWords) - { - /* Todo: extend StringComparison to support other checkings */ - if (line.Contains(word, StringComparison.OrdinalIgnoreCase)) - { - _word = word; break; - } - } - - return _word; - } - - public bool HasForbiddenWord(string line) => ForbiddenWords.Any(); -} \ No newline at end of file diff --git a/Moderation/Moderation/static/ssh-agent b/Moderation/Moderation/static/ssh-agent new file mode 100644 index 0000000..1a1493a --- /dev/null +++ b/Moderation/Moderation/static/ssh-agent @@ -0,0 +1,23 @@ + +SSH_ENV="$HOME/.ssh/agent-environment" + +function start_agent { + echo "Initialising new SSH agent..." + /usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}" + echo succeeded + chmod 600 "${SSH_ENV}" + . "${SSH_ENV}" > /dev/null + /usr/bin/ssh-add; +} + +# Source SSH settings, if applicable + +if [ -f "${SSH_ENV}" ]; then + . "${SSH_ENV}" > /dev/null + #ps ${SSH_AGENT_PID} doesn't work under cywgin + ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || { + start_agent; + } +else + start_agent; +fi \ No newline at end of file diff --git a/Moderation/ModerationTest/GlobalUsing.cs b/Moderation/ModerationTest/GlobalUsing.cs new file mode 100644 index 0000000..a611174 --- /dev/null +++ b/Moderation/ModerationTest/GlobalUsing.cs @@ -0,0 +1 @@ +global using Xunit; \ No newline at end of file diff --git a/PoliNetworkBot.sln b/PoliNetworkBot.sln deleted file mode 100644 index e61807a..0000000 --- a/PoliNetworkBot.sln +++ /dev/null @@ -1,34 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PoliNetwork.Bot", "Moderation\Moderation\PoliNetwork.Bot.csproj", "{2F99A9EE-BDCD-4927-A4FA-35C3D3F06F2D}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PoliNetwork.Telegram", "Lib_CSharp\PoliNetwork.Telegram\src\PoliNetwork.Telegram.csproj", "{21D75B9B-F9E1-4D99-B054-0B5DDF790821}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PoliNetwork.Db", "Lib_CSharp\PoliNetwork.Db\src\PoliNetwork.Db.csproj", "{CEEB9629-B53D-482C-ABD8-96C7301242DB}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PoliNetwork.Core", "Lib_CSharp\PoliNetwork.Core\src\PoliNetwork.Core.csproj", "{2514676E-0FB4-431E-A690-76BBFD1F84CC}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {2F99A9EE-BDCD-4927-A4FA-35C3D3F06F2D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2F99A9EE-BDCD-4927-A4FA-35C3D3F06F2D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2F99A9EE-BDCD-4927-A4FA-35C3D3F06F2D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2F99A9EE-BDCD-4927-A4FA-35C3D3F06F2D}.Release|Any CPU.Build.0 = Release|Any CPU - {21D75B9B-F9E1-4D99-B054-0B5DDF790821}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {21D75B9B-F9E1-4D99-B054-0B5DDF790821}.Debug|Any CPU.Build.0 = Debug|Any CPU - {21D75B9B-F9E1-4D99-B054-0B5DDF790821}.Release|Any CPU.ActiveCfg = Release|Any CPU - {21D75B9B-F9E1-4D99-B054-0B5DDF790821}.Release|Any CPU.Build.0 = Release|Any CPU - {CEEB9629-B53D-482C-ABD8-96C7301242DB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CEEB9629-B53D-482C-ABD8-96C7301242DB}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CEEB9629-B53D-482C-ABD8-96C7301242DB}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CEEB9629-B53D-482C-ABD8-96C7301242DB}.Release|Any CPU.Build.0 = Release|Any CPU - {2514676E-0FB4-431E-A690-76BBFD1F84CC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2514676E-0FB4-431E-A690-76BBFD1F84CC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2514676E-0FB4-431E-A690-76BBFD1F84CC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2514676E-0FB4-431E-A690-76BBFD1F84CC}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection -EndGlobal diff --git a/README.md b/README.md index 8ac9e3b..8f787b5 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,3 @@ - # PoliNetworkBot [![codecov](https://codecov.io/github/PoliNetworkOrg/PoliNetworkBot/branch/main/graph/badge.svg?token=VOA14BM161)](https://codecov.io/github/PoliNetworkOrg/PoliNetworkBot) # PoliNetworkBot @@ -7,36 +6,3 @@ Repository for the new revision of https://github.com/PoliNetworkOrg/PoliNetwork ### Lib We are using this library https://github.com/PoliNetworkOrg/Lib_CSharp - -# PoliNetwork Telegram Bot -Codebase sperimentale per il refactoring del PoliNetwork Telegram Bot. - -## Da implementare -1. **Helper**: restituisce la lista dei possibili comandi con la relativa descrzione -Utilizzare un file JSON per inserire la descrizione e la stringa per chiamare il comando. All'interno dell'intera applicazione, accedere alle variabile attraverso il file JSON per ridurre l'hardcoding e non dover riscrivere le variabili in altri progetti o linguaggi di programmazione. Vedi [ConfigurationBuilder](https://learn.microsoft.com/it-it/dotnet/api/microsoft.extensions.configuration.configurationbuilder?view=dotnet-plat-ext-7.0#remarks) -2. **SendMessageInGroup**: inoltrare un dato messaggio in un dato gruppo -3. Le altre funzionalità presenti nel bot... -4. Handler delle funzionalità. -5. Policy per il controllo delle forbidden words: algoritmo per il confronto (rimuovere spazi, convertire cifre con lettere simili etc.) - -## Logistica ricezione messaggi: -1. Il messaggio viene inoltrato dall'utente. -2. Il messaggio viene letto dal bot. -3. Il messaggio viene esaminato. -4. In caso di spam, linguaggio scurrile e contenuti che violano le regole della comunity, il messaggio viene eliminato. -5. In caso di possibile messaggio duplicato, il bot inoltra un messaggio in chat privata all'utente soggetto. -6. In caso di comando, viene eseguito il comando richiesto. - -### Testing -Creare il file `appsettings.json` all'interno della root directory e specifiare il token del vostro bot come segue -```json -{ - "Secrets": { - "BotToken": "{YOUR_BOT_TOKEN}" - } -} -``` - -Vedi come creare un bot e ottenere il relativo token: https://core.telegram.org/bots/tutorial#obtain-your-bot-token - - From fc128d6e68f0e1f8410d552598f7a72ad3285096 Mon Sep 17 00:00:00 2001 From: joebiden <133514023+sbadung@users.noreply.github.com> Date: Thu, 7 Sep 2023 16:27:43 +0200 Subject: [PATCH 17/20] Revert "Fixing issue#14 actions and build" This reverts commit b52c38d5fe911dd04ccc21107049f0fc81165a80. --- Moderation/Moderation/Moderation.csproj | 25 +++---- .../AbstractTelegramBotFunctionality.cs | 18 ----- .../Example/ResponseOnMessageFunctionality.cs | 42 ----------- .../ITelegramBotFunctionality.cs | 18 ----- .../Default/DefaultPollingErrorHandler.cs | 21 ------ .../Handler/Default/DefaultUpdateHandler.cs | 25 ------- .../src/Bot/Handler/IPollingErrorHandler.cs | 22 ------ .../src/Bot/Handler/IUpdateHandler.cs | 21 ------ Moderation/Moderation/src/Bot/TelegramBot.cs | 53 -------------- .../Moderation/src/Bot/TelegramBotOptions.cs | 19 ----- Moderation/Moderation/src/Configuration.cs | 9 --- Moderation/Moderation/src/Program.cs | 69 +++++++++++++------ .../ConfigurationLoad/IConfigurationLoader.cs | 17 ----- .../JSONConfigurationLoader.cs | 50 -------------- .../src/Utility/Converter/JSONConverter.cs | 16 ----- .../ForbiddenWordsController.cs | 19 ----- .../src/persistence/appsettings.json | 5 -- .../src/persistence/forbidden_words.json | 3 - 18 files changed, 58 insertions(+), 394 deletions(-) delete mode 100644 Moderation/Moderation/src/Bot/Functionality/AbstractTelegramBotFunctionality.cs delete mode 100644 Moderation/Moderation/src/Bot/Functionality/Example/ResponseOnMessageFunctionality.cs delete mode 100644 Moderation/Moderation/src/Bot/Functionality/ITelegramBotFunctionality.cs delete mode 100644 Moderation/Moderation/src/Bot/Handler/Default/DefaultPollingErrorHandler.cs delete mode 100644 Moderation/Moderation/src/Bot/Handler/Default/DefaultUpdateHandler.cs delete mode 100644 Moderation/Moderation/src/Bot/Handler/IPollingErrorHandler.cs delete mode 100644 Moderation/Moderation/src/Bot/Handler/IUpdateHandler.cs delete mode 100644 Moderation/Moderation/src/Bot/TelegramBot.cs delete mode 100644 Moderation/Moderation/src/Bot/TelegramBotOptions.cs delete mode 100644 Moderation/Moderation/src/Configuration.cs delete mode 100644 Moderation/Moderation/src/Utility/ConfigurationLoad/IConfigurationLoader.cs delete mode 100644 Moderation/Moderation/src/Utility/ConfigurationLoad/JSONConfigurationLoader.cs delete mode 100644 Moderation/Moderation/src/Utility/Converter/JSONConverter.cs delete mode 100644 Moderation/Moderation/src/Utility/MessageContentControl/ForbiddenWordsController.cs delete mode 100644 Moderation/Moderation/src/persistence/appsettings.json delete mode 100644 Moderation/Moderation/src/persistence/forbidden_words.json diff --git a/Moderation/Moderation/Moderation.csproj b/Moderation/Moderation/Moderation.csproj index ffa2d18..c5cd62a 100644 --- a/Moderation/Moderation/Moderation.csproj +++ b/Moderation/Moderation/Moderation.csproj @@ -15,29 +15,24 @@ - - - + + + - - + + - - + + - - - - - - - - + + + diff --git a/Moderation/Moderation/src/Bot/Functionality/AbstractTelegramBotFunctionality.cs b/Moderation/Moderation/src/Bot/Functionality/AbstractTelegramBotFunctionality.cs deleted file mode 100644 index 93bf809..0000000 --- a/Moderation/Moderation/src/Bot/Functionality/AbstractTelegramBotFunctionality.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Telegram.Bot; -using Telegram.Bot.Types; - -namespace PoliNetwork.Telegram.Bot.Functionality -{ - /// - /// Represents an abstract base class for defining the functionality of a Telegram bot. - /// - public abstract class AbstractTelegramBotFunctionality : ITelegramBotFunctionality - { - /// - /// Defines the behavior of the bot's functionality. This method must be implemented by derived classes. - /// - /// The instance representing the bot with which the functionality is associated. - /// A representing the asynchronous operation. - public abstract Task RunAsync(ITelegramBotClient bot, Update update, CancellationToken cancellationToken); - } -} diff --git a/Moderation/Moderation/src/Bot/Functionality/Example/ResponseOnMessageFunctionality.cs b/Moderation/Moderation/src/Bot/Functionality/Example/ResponseOnMessageFunctionality.cs deleted file mode 100644 index 7ad3d4c..0000000 --- a/Moderation/Moderation/src/Bot/Functionality/Example/ResponseOnMessageFunctionality.cs +++ /dev/null @@ -1,42 +0,0 @@ -using PoliNetwork.Utility.Configuration; -using Telegram.Bot; -using Telegram.Bot.Types; -using PoliNetwork.Utility.MessageContentControl; - -namespace PoliNetwork.Telegram.Bot.Functionality.Example -{ - public class ResponseOnMessageFunctionality : AbstractTelegramBotFunctionality - { - private static string[] CreateForbiddenWordsArray() - { - var path = Config.FORBIDDEN_WORDS; - return JSONConverter.GetArrayFromFile(path) ?? Array.Empty(); - } - - public override async Task RunAsync(ITelegramBotClient bot, Update update, CancellationToken cancellationToken) - { - /* This way we only process the message text part */ - if (update.Message is not { } message) return; - if (message.Text is not { } messageText) return; - - var chatId = message.Chat.Id; - var username = message.Chat.Username; - - var forbiddenWords = CreateForbiddenWordsArray(); - var HasForbiddenWord = new ForbiddenWordsController(forbiddenWords).ContainsForbiddenWord(messageText); - - var serverPrompt = $"Received a '{messageText}' message in chat {chatId} ({username})."; - var responseText = HasForbiddenWord ? "Your massage contains a forbidden word" : "Your message is a valid one"; - Console.WriteLine(serverPrompt); - - var sentMessage = await bot.SendTextMessageAsync( - chatId: chatId, - text: responseText, - cancellationToken: cancellationToken - ); - - serverPrompt = $"Sent message: {sentMessage.Text}"; - Console.WriteLine(serverPrompt); - } - } -} \ No newline at end of file diff --git a/Moderation/Moderation/src/Bot/Functionality/ITelegramBotFunctionality.cs b/Moderation/Moderation/src/Bot/Functionality/ITelegramBotFunctionality.cs deleted file mode 100644 index 09f1e68..0000000 --- a/Moderation/Moderation/src/Bot/Functionality/ITelegramBotFunctionality.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Telegram.Bot; -using Telegram.Bot.Types; - -namespace PoliNetwork.Telegram.Bot.Functionality -{ - /// - /// Represents an interface for defining the functionality of a Telegram bot. - /// - public interface ITelegramBotFunctionality - { - /// - /// Runs the defined functionality using the provided . - /// - /// The instance representing the bot with which the functionality is associated. - /// A representing the asynchronous operation. - Task RunAsync(ITelegramBotClient bot, Update update, CancellationToken cancellationToken); - } -} diff --git a/Moderation/Moderation/src/Bot/Handler/Default/DefaultPollingErrorHandler.cs b/Moderation/Moderation/src/Bot/Handler/Default/DefaultPollingErrorHandler.cs deleted file mode 100644 index 5427e57..0000000 --- a/Moderation/Moderation/src/Bot/Handler/Default/DefaultPollingErrorHandler.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Telegram.Bot; -using Telegram.Bot.Exceptions; - -namespace PoliNetwork.Telegram.Bot.Handler -{ - public class DefaultPollingErrorHandler : IPollingErrorHandler - { - public Task HandlePollingErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken) - { - var ErrorMessage = exception switch - { - ApiRequestException apiRequestException - => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}", - _ => exception.ToString() - }; - - Console.WriteLine(ErrorMessage); - return Task.CompletedTask; - } - } -} \ No newline at end of file diff --git a/Moderation/Moderation/src/Bot/Handler/Default/DefaultUpdateHandler.cs b/Moderation/Moderation/src/Bot/Handler/Default/DefaultUpdateHandler.cs deleted file mode 100644 index 2e7c118..0000000 --- a/Moderation/Moderation/src/Bot/Handler/Default/DefaultUpdateHandler.cs +++ /dev/null @@ -1,25 +0,0 @@ -using PoliNetwork.Telegram.Bot.Functionality; -using Telegram.Bot; -using Telegram.Bot.Types; - -namespace PoliNetwork.Telegram.Bot.Handler -{ - public class DefaultUpdateHandler : IUpdateHandler - { - private readonly List Functionalities; - - public DefaultUpdateHandler(List functionalities) - { - Functionalities = functionalities; - } - - public async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) - { - /* Parallel.ForEach(_functionalities, functionalities => functionalities.Run(botClient, update, cancellationToken)); */ - foreach (var functionality in Functionalities) - { - await functionality.RunAsync(botClient, update, cancellationToken); - } - } - } -} \ No newline at end of file diff --git a/Moderation/Moderation/src/Bot/Handler/IPollingErrorHandler.cs b/Moderation/Moderation/src/Bot/Handler/IPollingErrorHandler.cs deleted file mode 100644 index c53abc2..0000000 --- a/Moderation/Moderation/src/Bot/Handler/IPollingErrorHandler.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using Telegram.Bot; - -namespace PoliNetwork.Telegram.Bot.Handler -{ - /// - /// Represents an interface for handling errors that occur during the polling process of a Telegram bot. - /// - public interface IPollingErrorHandler - { - /// - /// Handles a polling error asynchronously. - /// - /// The instance used for interaction with the Telegram Bot API. - /// The that occurred during the polling process. - /// A that can be used to cancel the asynchronous operation. - /// A representing the asynchronous operation. - Task HandlePollingErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken); - } -} diff --git a/Moderation/Moderation/src/Bot/Handler/IUpdateHandler.cs b/Moderation/Moderation/src/Bot/Handler/IUpdateHandler.cs deleted file mode 100644 index c4050a9..0000000 --- a/Moderation/Moderation/src/Bot/Handler/IUpdateHandler.cs +++ /dev/null @@ -1,21 +0,0 @@ - -using Telegram.Bot; -using Telegram.Bot.Types; - -namespace PoliNetwork.Telegram.Bot.Handler -{ - /// - /// Represents an interface for handling incoming Telegram updates. - /// - public interface IUpdateHandler - { - /// - /// Handles an incoming Telegram update asynchronously. - /// - /// The instance used for interaction with the Telegram Bot API. - /// The representing the incoming update to be handled. - /// A that can be used to cancel the asynchronous operation. - /// A representing the asynchronous operation. - Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken); - } -} diff --git a/Moderation/Moderation/src/Bot/TelegramBot.cs b/Moderation/Moderation/src/Bot/TelegramBot.cs deleted file mode 100644 index a3c1da8..0000000 --- a/Moderation/Moderation/src/Bot/TelegramBot.cs +++ /dev/null @@ -1,53 +0,0 @@ -using PoliNetwork.Telegram.Bot.Handler; -using Telegram.Bot; -using Telegram.Bot.Polling; -using Telegram.Bot.Types; -using Telegram.Bot.Types.Enums; - -namespace PoliNetwork.Telegram.Bot -{ - /// - /// Represents a Telegram bot that can interact with the Telegram Bot API. - /// - public class TelegramBot : TelegramBotClient - { - /// - /// Initializes a new instance of the class with the provided options and an optional HttpClient. - /// - /// The options specifying bot settings. - /// Optional HttpClient to be used for API requests. - public TelegramBot(TelegramBotOptions options, HttpClient? httpClient = null) - : base(options, httpClient) { } - - /// - /// Initializes a new instance of the class with the provided bot token and an optional HttpClient. - /// - /// The authentication token of the bot. - /// Optional HttpClient to be used for API requests. - public TelegramBot(string token, HttpClient? httpClient = null) - : base(token, httpClient) { } - - public async Task RunAsync(Handler.IUpdateHandler updateHandler, IPollingErrorHandler pollingErrorHandler) - { - using CancellationTokenSource cts = new(); - - ReceiverOptions receiverOptions = new() - { - AllowedUpdates = Array.Empty() - }; - - this.StartReceiving( - updateHandler: updateHandler.HandleUpdateAsync, - pollingErrorHandler: pollingErrorHandler.HandlePollingErrorAsync, - receiverOptions: receiverOptions, - cancellationToken: cts.Token - ); - - var me = await this.GetMeAsync(); - Console.WriteLine($"Start listening for @{me.Username}\nExit via typing"); - Console.ReadLine(); - cts.Cancel(); - } - } -} - diff --git a/Moderation/Moderation/src/Bot/TelegramBotOptions.cs b/Moderation/Moderation/src/Bot/TelegramBotOptions.cs deleted file mode 100644 index deb1c7f..0000000 --- a/Moderation/Moderation/src/Bot/TelegramBotOptions.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Telegram.Bot; - -namespace PoliNetwork.Telegram.Bot -{ - /// - /// Represents options for configuring a . - /// - public class TelegramBotOptions : TelegramBotClientOptions - { - /// - /// Initializes a new instance of the class with the provided token, base URL, and test environment settings. - /// - /// The authentication token of the bot. - /// Optional base URL for API requests. - /// Flag indicating whether to use the test environment. - protected TelegramBotOptions(string token, string? baseUrl = null, bool useTestEnvironment = false) - : base(token, baseUrl, useTestEnvironment) { } - } -} diff --git a/Moderation/Moderation/src/Configuration.cs b/Moderation/Moderation/src/Configuration.cs deleted file mode 100644 index ab372b3..0000000 --- a/Moderation/Moderation/src/Configuration.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace PoliNetwork.Utility.Configuration -{ - public static class Config - { - private static readonly string? BASE_PATH = Directory.GetParent(Environment.CurrentDirectory)?.FullName; - public static readonly string FORBIDDEN_WORDS = BASE_PATH + @"\Moderation\src\persistence\forbidden_words.json"; - public static readonly string APP_SETTINGS = BASE_PATH + @"\Moderation\src\persistence\appsettings.json"; - } -} \ No newline at end of file diff --git a/Moderation/Moderation/src/Program.cs b/Moderation/Moderation/src/Program.cs index f6ca506..2c0fc64 100644 --- a/Moderation/Moderation/src/Program.cs +++ b/Moderation/Moderation/src/Program.cs @@ -1,29 +1,56 @@ -using PoliNetwork.Telegram.Bot; -using PoliNetwork.Telegram.Bot.Functionality; -using PoliNetwork.Telegram.Bot.Functionality.Example; -using PoliNetwork.Telegram.Bot.Handler; -using PoliNetwork.Utility.ConfigurationLoader; -using PoliNetwork.Utility.Configuration; - -namespace PoliNetwork.Moderation +#region +using PoliNetwork.Core.Utils; +using PoliNetwork.Telegram.Logger; +using PoliNetwork.Db.Utils; +using PoliNetwork.Telegram.Configuration; +using PoliNetwork.Telegram.ConfigurationLoader; +using PoliNetwork.Db.Objects; +using PoliNetwork.Telegram.Bot.Bots; +using PoliNetwork.Telegram.Options; +using PoliNetwork.Telegram.Properties; +#endregion + +namespace Moderation; + +internal static class Program { - internal abstract class Program + private static ModerationBot? _bot = null; + private const string DatabaseConfigurationPath = ""; + + public static void Main() { - private static async Task Main() + /* The PoliNetwork.Core.Utils.LoggerNS.Logger must extends the AbstractLogger so a sub class will be needed + The only dependency of the PoliNetwork.Core.Utils.LoggerNS.Logger resides here in the Program.cs */ + AbstractLogger? logger = new DefaultLogger(); + FileConfigurationLoader fileConfigurationLoader = new JSONFileConfigurationLoader(); + AbstractTelegramBotOptions? botConfiguration = fileConfigurationLoader.LoadOrInitializeConfig(Configuration.TELEGRAM_CONFIGURATION_PATH, logger); + + DbConfig? databaseConfiguration = DbConfigUtils.LoadOrInitializeConfig(DatabaseConfigurationPath); + if (botConfiguration == null) { - List telegramBotFunctionalities = new() - { - new ResponseOnMessageFunctionality() - }; + logger?.Emergency("Telegram Config is undefined when starting the bot."); + return; + } - IUpdateHandler updateHandler = new DefaultUpdateHandler(telegramBotFunctionalities); - IPollingErrorHandler pollingErrorHandler = new DefaultPollingErrorHandler(); + if (databaseConfiguration == null) + { + logger?.Emergency("Database Config is undefined when starting the bot."); + return; + } - var botToken = new JSONConfigurationLoader().LoadConfiguration(Config.APP_SETTINGS) - .GetSection("Secrets:BotToken").Value!; - TelegramBot bot = new(botToken); + logger?.Info("RUNNING MODERATION BOT"); + botConfiguration.UpdateMethod = new UpdateMethod(UpdateAction); - await bot.RunAsync(updateHandler, pollingErrorHandler); - } + /* TelegramConfiguration should extends TelegramBotClientOptions */ + _bot = new ModerationBot(options: botConfiguration, logger: logger); + _bot.Start(new CancellationToken()); + Wait.WaitForever(); + } + + private static void UpdateAction(CancellationToken cancellationToken, IUpdate update) + { + /* Process Message updates only, see: https://core.telegram.org/bots/api#message */ + if (_bot == null || update.Message is not { } message) return; + _bot.Echo(message, cancellationToken); } } \ No newline at end of file diff --git a/Moderation/Moderation/src/Utility/ConfigurationLoad/IConfigurationLoader.cs b/Moderation/Moderation/src/Utility/ConfigurationLoad/IConfigurationLoader.cs deleted file mode 100644 index 7177325..0000000 --- a/Moderation/Moderation/src/Utility/ConfigurationLoad/IConfigurationLoader.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Microsoft.Extensions.Configuration; - -namespace PoliNetwork.Utility.ConfigurationLoader -{ - /// - /// Represents an interface for loading configuration data from various sources. - /// - public interface IConfigurationLoader - { - /// - /// Loads configuration data from the specified path. - /// - /// The path to the configuration data. - /// An containing the loaded configuration data. - IConfigurationRoot LoadConfiguration(string path); - } -} diff --git a/Moderation/Moderation/src/Utility/ConfigurationLoad/JSONConfigurationLoader.cs b/Moderation/Moderation/src/Utility/ConfigurationLoad/JSONConfigurationLoader.cs deleted file mode 100644 index 639358b..0000000 --- a/Moderation/Moderation/src/Utility/ConfigurationLoad/JSONConfigurationLoader.cs +++ /dev/null @@ -1,50 +0,0 @@ -using Microsoft.Extensions.Configuration; -using System.Text.Json; - -namespace PoliNetwork.Utility.ConfigurationLoader -{ - /// - /// Represents a configuration loader for loading JSON configuration data. - /// - public class JSONConfigurationLoader : IConfigurationLoader - { - /// - /// Loads configuration data from the specified JSON file. - /// - /// The path to the JSON configuration file. - /// An containing the loaded configuration data. - /// Thrown if the specified JSON file does not exist. - /// Thrown if the provided path is not a JSON file. - /// Thrown if the specified JSON file is not valid. - public IConfigurationRoot LoadConfiguration(string path) - { - bool notFound = !File.Exists(path); - bool notJson = !Path.HasExtension(path) || !Path.GetExtension(path).Equals(".json", StringComparison.OrdinalIgnoreCase); - - if (notFound) throw new FileNotFoundException("Unable to locate specified JSON file.", path); - if (notJson) throw new ArgumentException("Only JSON files are supported.", nameof(path)); - - try - { - return new ConfigurationBuilder() - .SetBasePath(Directory.GetCurrentDirectory()) - .AddJsonFile(path) - .Build(); - } - catch (JsonException ex) - { - throw new JsonException("The specified JSON file is not valid.", ex); - } - catch (IOException ex) - { - throw new IOException("Could not open file.", ex); - } - - } - - /// - /// Initializes a new instance of the class. - /// - public JSONConfigurationLoader() : base() { } - } -} diff --git a/Moderation/Moderation/src/Utility/Converter/JSONConverter.cs b/Moderation/Moderation/src/Utility/Converter/JSONConverter.cs deleted file mode 100644 index 5440dbd..0000000 --- a/Moderation/Moderation/src/Utility/Converter/JSONConverter.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System.Runtime.InteropServices; -using Newtonsoft.Json; - -class JSONConverter -{ - public static string[]? GetArrayFromString(string json) - { - return JsonConvert.DeserializeObject(json)?.ToArray(); - } - - public static string[]? GetArrayFromFile(string path) - { - string json = File.ReadAllText(path); - return GetArrayFromString(json); - } -} \ No newline at end of file diff --git a/Moderation/Moderation/src/Utility/MessageContentControl/ForbiddenWordsController.cs b/Moderation/Moderation/src/Utility/MessageContentControl/ForbiddenWordsController.cs deleted file mode 100644 index 3e278a1..0000000 --- a/Moderation/Moderation/src/Utility/MessageContentControl/ForbiddenWordsController.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace PoliNetwork.Utility.MessageContentControl; - -public sealed class ForbiddenWordsController -{ - private string[] ForbiddenWords { get; set; } - - public ForbiddenWordsController(string[] forbiddenWords) - { - ForbiddenWords = forbiddenWords; - } - - public bool ContainsForbiddenWord(string line) => ForbiddenWords.Any(line.Contains); - - public string? GetFirstForbiddenWord(string line) => - ForbiddenWords.FirstOrDefault(word => line.Contains(word, StringComparison.OrdinalIgnoreCase)); - - - public bool HasForbiddenWord(string line) => ForbiddenWords.Any(); -} \ No newline at end of file diff --git a/Moderation/Moderation/src/persistence/appsettings.json b/Moderation/Moderation/src/persistence/appsettings.json deleted file mode 100644 index 7d0cf10..0000000 --- a/Moderation/Moderation/src/persistence/appsettings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "Secrets": { - "BotToken": "6576423301:AAGZY8_D-QmDxFsWGp6D3z_CJ-odA8NLQSE" - } -} \ No newline at end of file diff --git a/Moderation/Moderation/src/persistence/forbidden_words.json b/Moderation/Moderation/src/persistence/forbidden_words.json deleted file mode 100644 index f46c070..0000000 --- a/Moderation/Moderation/src/persistence/forbidden_words.json +++ /dev/null @@ -1,3 +0,0 @@ -[ - "forbidden" -] \ No newline at end of file From 926f323ae6aabde127d93cecd1e31403a365dcfe Mon Sep 17 00:00:00 2001 From: joebiden <133514023+sbadung@users.noreply.github.com> Date: Thu, 7 Sep 2023 21:09:45 +0200 Subject: [PATCH 18/20] Revert "Revert "Fixing issue#14 actions and build"" This reverts commit fc128d6e68f0e1f8410d552598f7a72ad3285096. --- Moderation/Moderation/Moderation.csproj | 25 ++++--- .../AbstractTelegramBotFunctionality.cs | 18 +++++ .../Example/ResponseOnMessageFunctionality.cs | 42 +++++++++++ .../ITelegramBotFunctionality.cs | 18 +++++ .../Default/DefaultPollingErrorHandler.cs | 21 ++++++ .../Handler/Default/DefaultUpdateHandler.cs | 25 +++++++ .../src/Bot/Handler/IPollingErrorHandler.cs | 22 ++++++ .../src/Bot/Handler/IUpdateHandler.cs | 21 ++++++ Moderation/Moderation/src/Bot/TelegramBot.cs | 53 ++++++++++++++ .../Moderation/src/Bot/TelegramBotOptions.cs | 19 +++++ Moderation/Moderation/src/Configuration.cs | 9 +++ Moderation/Moderation/src/Program.cs | 69 ++++++------------- .../ConfigurationLoad/IConfigurationLoader.cs | 17 +++++ .../JSONConfigurationLoader.cs | 50 ++++++++++++++ .../src/Utility/Converter/JSONConverter.cs | 16 +++++ .../ForbiddenWordsController.cs | 19 +++++ .../src/persistence/appsettings.json | 5 ++ .../src/persistence/forbidden_words.json | 3 + 18 files changed, 394 insertions(+), 58 deletions(-) create mode 100644 Moderation/Moderation/src/Bot/Functionality/AbstractTelegramBotFunctionality.cs create mode 100644 Moderation/Moderation/src/Bot/Functionality/Example/ResponseOnMessageFunctionality.cs create mode 100644 Moderation/Moderation/src/Bot/Functionality/ITelegramBotFunctionality.cs create mode 100644 Moderation/Moderation/src/Bot/Handler/Default/DefaultPollingErrorHandler.cs create mode 100644 Moderation/Moderation/src/Bot/Handler/Default/DefaultUpdateHandler.cs create mode 100644 Moderation/Moderation/src/Bot/Handler/IPollingErrorHandler.cs create mode 100644 Moderation/Moderation/src/Bot/Handler/IUpdateHandler.cs create mode 100644 Moderation/Moderation/src/Bot/TelegramBot.cs create mode 100644 Moderation/Moderation/src/Bot/TelegramBotOptions.cs create mode 100644 Moderation/Moderation/src/Configuration.cs create mode 100644 Moderation/Moderation/src/Utility/ConfigurationLoad/IConfigurationLoader.cs create mode 100644 Moderation/Moderation/src/Utility/ConfigurationLoad/JSONConfigurationLoader.cs create mode 100644 Moderation/Moderation/src/Utility/Converter/JSONConverter.cs create mode 100644 Moderation/Moderation/src/Utility/MessageContentControl/ForbiddenWordsController.cs create mode 100644 Moderation/Moderation/src/persistence/appsettings.json create mode 100644 Moderation/Moderation/src/persistence/forbidden_words.json diff --git a/Moderation/Moderation/Moderation.csproj b/Moderation/Moderation/Moderation.csproj index c5cd62a..ffa2d18 100644 --- a/Moderation/Moderation/Moderation.csproj +++ b/Moderation/Moderation/Moderation.csproj @@ -15,24 +15,29 @@ - - - + + + - - + + - - + + - - - + + + + + + + + diff --git a/Moderation/Moderation/src/Bot/Functionality/AbstractTelegramBotFunctionality.cs b/Moderation/Moderation/src/Bot/Functionality/AbstractTelegramBotFunctionality.cs new file mode 100644 index 0000000..93bf809 --- /dev/null +++ b/Moderation/Moderation/src/Bot/Functionality/AbstractTelegramBotFunctionality.cs @@ -0,0 +1,18 @@ +using Telegram.Bot; +using Telegram.Bot.Types; + +namespace PoliNetwork.Telegram.Bot.Functionality +{ + /// + /// Represents an abstract base class for defining the functionality of a Telegram bot. + /// + public abstract class AbstractTelegramBotFunctionality : ITelegramBotFunctionality + { + /// + /// Defines the behavior of the bot's functionality. This method must be implemented by derived classes. + /// + /// The instance representing the bot with which the functionality is associated. + /// A representing the asynchronous operation. + public abstract Task RunAsync(ITelegramBotClient bot, Update update, CancellationToken cancellationToken); + } +} diff --git a/Moderation/Moderation/src/Bot/Functionality/Example/ResponseOnMessageFunctionality.cs b/Moderation/Moderation/src/Bot/Functionality/Example/ResponseOnMessageFunctionality.cs new file mode 100644 index 0000000..7ad3d4c --- /dev/null +++ b/Moderation/Moderation/src/Bot/Functionality/Example/ResponseOnMessageFunctionality.cs @@ -0,0 +1,42 @@ +using PoliNetwork.Utility.Configuration; +using Telegram.Bot; +using Telegram.Bot.Types; +using PoliNetwork.Utility.MessageContentControl; + +namespace PoliNetwork.Telegram.Bot.Functionality.Example +{ + public class ResponseOnMessageFunctionality : AbstractTelegramBotFunctionality + { + private static string[] CreateForbiddenWordsArray() + { + var path = Config.FORBIDDEN_WORDS; + return JSONConverter.GetArrayFromFile(path) ?? Array.Empty(); + } + + public override async Task RunAsync(ITelegramBotClient bot, Update update, CancellationToken cancellationToken) + { + /* This way we only process the message text part */ + if (update.Message is not { } message) return; + if (message.Text is not { } messageText) return; + + var chatId = message.Chat.Id; + var username = message.Chat.Username; + + var forbiddenWords = CreateForbiddenWordsArray(); + var HasForbiddenWord = new ForbiddenWordsController(forbiddenWords).ContainsForbiddenWord(messageText); + + var serverPrompt = $"Received a '{messageText}' message in chat {chatId} ({username})."; + var responseText = HasForbiddenWord ? "Your massage contains a forbidden word" : "Your message is a valid one"; + Console.WriteLine(serverPrompt); + + var sentMessage = await bot.SendTextMessageAsync( + chatId: chatId, + text: responseText, + cancellationToken: cancellationToken + ); + + serverPrompt = $"Sent message: {sentMessage.Text}"; + Console.WriteLine(serverPrompt); + } + } +} \ No newline at end of file diff --git a/Moderation/Moderation/src/Bot/Functionality/ITelegramBotFunctionality.cs b/Moderation/Moderation/src/Bot/Functionality/ITelegramBotFunctionality.cs new file mode 100644 index 0000000..09f1e68 --- /dev/null +++ b/Moderation/Moderation/src/Bot/Functionality/ITelegramBotFunctionality.cs @@ -0,0 +1,18 @@ +using Telegram.Bot; +using Telegram.Bot.Types; + +namespace PoliNetwork.Telegram.Bot.Functionality +{ + /// + /// Represents an interface for defining the functionality of a Telegram bot. + /// + public interface ITelegramBotFunctionality + { + /// + /// Runs the defined functionality using the provided . + /// + /// The instance representing the bot with which the functionality is associated. + /// A representing the asynchronous operation. + Task RunAsync(ITelegramBotClient bot, Update update, CancellationToken cancellationToken); + } +} diff --git a/Moderation/Moderation/src/Bot/Handler/Default/DefaultPollingErrorHandler.cs b/Moderation/Moderation/src/Bot/Handler/Default/DefaultPollingErrorHandler.cs new file mode 100644 index 0000000..5427e57 --- /dev/null +++ b/Moderation/Moderation/src/Bot/Handler/Default/DefaultPollingErrorHandler.cs @@ -0,0 +1,21 @@ +using Telegram.Bot; +using Telegram.Bot.Exceptions; + +namespace PoliNetwork.Telegram.Bot.Handler +{ + public class DefaultPollingErrorHandler : IPollingErrorHandler + { + public Task HandlePollingErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken) + { + var ErrorMessage = exception switch + { + ApiRequestException apiRequestException + => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}", + _ => exception.ToString() + }; + + Console.WriteLine(ErrorMessage); + return Task.CompletedTask; + } + } +} \ No newline at end of file diff --git a/Moderation/Moderation/src/Bot/Handler/Default/DefaultUpdateHandler.cs b/Moderation/Moderation/src/Bot/Handler/Default/DefaultUpdateHandler.cs new file mode 100644 index 0000000..2e7c118 --- /dev/null +++ b/Moderation/Moderation/src/Bot/Handler/Default/DefaultUpdateHandler.cs @@ -0,0 +1,25 @@ +using PoliNetwork.Telegram.Bot.Functionality; +using Telegram.Bot; +using Telegram.Bot.Types; + +namespace PoliNetwork.Telegram.Bot.Handler +{ + public class DefaultUpdateHandler : IUpdateHandler + { + private readonly List Functionalities; + + public DefaultUpdateHandler(List functionalities) + { + Functionalities = functionalities; + } + + public async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) + { + /* Parallel.ForEach(_functionalities, functionalities => functionalities.Run(botClient, update, cancellationToken)); */ + foreach (var functionality in Functionalities) + { + await functionality.RunAsync(botClient, update, cancellationToken); + } + } + } +} \ No newline at end of file diff --git a/Moderation/Moderation/src/Bot/Handler/IPollingErrorHandler.cs b/Moderation/Moderation/src/Bot/Handler/IPollingErrorHandler.cs new file mode 100644 index 0000000..c53abc2 --- /dev/null +++ b/Moderation/Moderation/src/Bot/Handler/IPollingErrorHandler.cs @@ -0,0 +1,22 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Telegram.Bot; + +namespace PoliNetwork.Telegram.Bot.Handler +{ + /// + /// Represents an interface for handling errors that occur during the polling process of a Telegram bot. + /// + public interface IPollingErrorHandler + { + /// + /// Handles a polling error asynchronously. + /// + /// The instance used for interaction with the Telegram Bot API. + /// The that occurred during the polling process. + /// A that can be used to cancel the asynchronous operation. + /// A representing the asynchronous operation. + Task HandlePollingErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken); + } +} diff --git a/Moderation/Moderation/src/Bot/Handler/IUpdateHandler.cs b/Moderation/Moderation/src/Bot/Handler/IUpdateHandler.cs new file mode 100644 index 0000000..c4050a9 --- /dev/null +++ b/Moderation/Moderation/src/Bot/Handler/IUpdateHandler.cs @@ -0,0 +1,21 @@ + +using Telegram.Bot; +using Telegram.Bot.Types; + +namespace PoliNetwork.Telegram.Bot.Handler +{ + /// + /// Represents an interface for handling incoming Telegram updates. + /// + public interface IUpdateHandler + { + /// + /// Handles an incoming Telegram update asynchronously. + /// + /// The instance used for interaction with the Telegram Bot API. + /// The representing the incoming update to be handled. + /// A that can be used to cancel the asynchronous operation. + /// A representing the asynchronous operation. + Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken); + } +} diff --git a/Moderation/Moderation/src/Bot/TelegramBot.cs b/Moderation/Moderation/src/Bot/TelegramBot.cs new file mode 100644 index 0000000..a3c1da8 --- /dev/null +++ b/Moderation/Moderation/src/Bot/TelegramBot.cs @@ -0,0 +1,53 @@ +using PoliNetwork.Telegram.Bot.Handler; +using Telegram.Bot; +using Telegram.Bot.Polling; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; + +namespace PoliNetwork.Telegram.Bot +{ + /// + /// Represents a Telegram bot that can interact with the Telegram Bot API. + /// + public class TelegramBot : TelegramBotClient + { + /// + /// Initializes a new instance of the class with the provided options and an optional HttpClient. + /// + /// The options specifying bot settings. + /// Optional HttpClient to be used for API requests. + public TelegramBot(TelegramBotOptions options, HttpClient? httpClient = null) + : base(options, httpClient) { } + + /// + /// Initializes a new instance of the class with the provided bot token and an optional HttpClient. + /// + /// The authentication token of the bot. + /// Optional HttpClient to be used for API requests. + public TelegramBot(string token, HttpClient? httpClient = null) + : base(token, httpClient) { } + + public async Task RunAsync(Handler.IUpdateHandler updateHandler, IPollingErrorHandler pollingErrorHandler) + { + using CancellationTokenSource cts = new(); + + ReceiverOptions receiverOptions = new() + { + AllowedUpdates = Array.Empty() + }; + + this.StartReceiving( + updateHandler: updateHandler.HandleUpdateAsync, + pollingErrorHandler: pollingErrorHandler.HandlePollingErrorAsync, + receiverOptions: receiverOptions, + cancellationToken: cts.Token + ); + + var me = await this.GetMeAsync(); + Console.WriteLine($"Start listening for @{me.Username}\nExit via typing"); + Console.ReadLine(); + cts.Cancel(); + } + } +} + diff --git a/Moderation/Moderation/src/Bot/TelegramBotOptions.cs b/Moderation/Moderation/src/Bot/TelegramBotOptions.cs new file mode 100644 index 0000000..deb1c7f --- /dev/null +++ b/Moderation/Moderation/src/Bot/TelegramBotOptions.cs @@ -0,0 +1,19 @@ +using Telegram.Bot; + +namespace PoliNetwork.Telegram.Bot +{ + /// + /// Represents options for configuring a . + /// + public class TelegramBotOptions : TelegramBotClientOptions + { + /// + /// Initializes a new instance of the class with the provided token, base URL, and test environment settings. + /// + /// The authentication token of the bot. + /// Optional base URL for API requests. + /// Flag indicating whether to use the test environment. + protected TelegramBotOptions(string token, string? baseUrl = null, bool useTestEnvironment = false) + : base(token, baseUrl, useTestEnvironment) { } + } +} diff --git a/Moderation/Moderation/src/Configuration.cs b/Moderation/Moderation/src/Configuration.cs new file mode 100644 index 0000000..ab372b3 --- /dev/null +++ b/Moderation/Moderation/src/Configuration.cs @@ -0,0 +1,9 @@ +namespace PoliNetwork.Utility.Configuration +{ + public static class Config + { + private static readonly string? BASE_PATH = Directory.GetParent(Environment.CurrentDirectory)?.FullName; + public static readonly string FORBIDDEN_WORDS = BASE_PATH + @"\Moderation\src\persistence\forbidden_words.json"; + public static readonly string APP_SETTINGS = BASE_PATH + @"\Moderation\src\persistence\appsettings.json"; + } +} \ No newline at end of file diff --git a/Moderation/Moderation/src/Program.cs b/Moderation/Moderation/src/Program.cs index 2c0fc64..f6ca506 100644 --- a/Moderation/Moderation/src/Program.cs +++ b/Moderation/Moderation/src/Program.cs @@ -1,56 +1,29 @@ -#region -using PoliNetwork.Core.Utils; -using PoliNetwork.Telegram.Logger; -using PoliNetwork.Db.Utils; -using PoliNetwork.Telegram.Configuration; -using PoliNetwork.Telegram.ConfigurationLoader; -using PoliNetwork.Db.Objects; -using PoliNetwork.Telegram.Bot.Bots; -using PoliNetwork.Telegram.Options; -using PoliNetwork.Telegram.Properties; -#endregion - -namespace Moderation; - -internal static class Program +using PoliNetwork.Telegram.Bot; +using PoliNetwork.Telegram.Bot.Functionality; +using PoliNetwork.Telegram.Bot.Functionality.Example; +using PoliNetwork.Telegram.Bot.Handler; +using PoliNetwork.Utility.ConfigurationLoader; +using PoliNetwork.Utility.Configuration; + +namespace PoliNetwork.Moderation { - private static ModerationBot? _bot = null; - private const string DatabaseConfigurationPath = ""; - - public static void Main() + internal abstract class Program { - /* The PoliNetwork.Core.Utils.LoggerNS.Logger must extends the AbstractLogger so a sub class will be needed - The only dependency of the PoliNetwork.Core.Utils.LoggerNS.Logger resides here in the Program.cs */ - AbstractLogger? logger = new DefaultLogger(); - FileConfigurationLoader fileConfigurationLoader = new JSONFileConfigurationLoader(); - AbstractTelegramBotOptions? botConfiguration = fileConfigurationLoader.LoadOrInitializeConfig(Configuration.TELEGRAM_CONFIGURATION_PATH, logger); - - DbConfig? databaseConfiguration = DbConfigUtils.LoadOrInitializeConfig(DatabaseConfigurationPath); - if (botConfiguration == null) + private static async Task Main() { - logger?.Emergency("Telegram Config is undefined when starting the bot."); - return; - } + List telegramBotFunctionalities = new() + { + new ResponseOnMessageFunctionality() + }; - if (databaseConfiguration == null) - { - logger?.Emergency("Database Config is undefined when starting the bot."); - return; - } - - logger?.Info("RUNNING MODERATION BOT"); - botConfiguration.UpdateMethod = new UpdateMethod(UpdateAction); + IUpdateHandler updateHandler = new DefaultUpdateHandler(telegramBotFunctionalities); + IPollingErrorHandler pollingErrorHandler = new DefaultPollingErrorHandler(); - /* TelegramConfiguration should extends TelegramBotClientOptions */ - _bot = new ModerationBot(options: botConfiguration, logger: logger); - _bot.Start(new CancellationToken()); - Wait.WaitForever(); - } + var botToken = new JSONConfigurationLoader().LoadConfiguration(Config.APP_SETTINGS) + .GetSection("Secrets:BotToken").Value!; + TelegramBot bot = new(botToken); - private static void UpdateAction(CancellationToken cancellationToken, IUpdate update) - { - /* Process Message updates only, see: https://core.telegram.org/bots/api#message */ - if (_bot == null || update.Message is not { } message) return; - _bot.Echo(message, cancellationToken); + await bot.RunAsync(updateHandler, pollingErrorHandler); + } } } \ No newline at end of file diff --git a/Moderation/Moderation/src/Utility/ConfigurationLoad/IConfigurationLoader.cs b/Moderation/Moderation/src/Utility/ConfigurationLoad/IConfigurationLoader.cs new file mode 100644 index 0000000..7177325 --- /dev/null +++ b/Moderation/Moderation/src/Utility/ConfigurationLoad/IConfigurationLoader.cs @@ -0,0 +1,17 @@ +using Microsoft.Extensions.Configuration; + +namespace PoliNetwork.Utility.ConfigurationLoader +{ + /// + /// Represents an interface for loading configuration data from various sources. + /// + public interface IConfigurationLoader + { + /// + /// Loads configuration data from the specified path. + /// + /// The path to the configuration data. + /// An containing the loaded configuration data. + IConfigurationRoot LoadConfiguration(string path); + } +} diff --git a/Moderation/Moderation/src/Utility/ConfigurationLoad/JSONConfigurationLoader.cs b/Moderation/Moderation/src/Utility/ConfigurationLoad/JSONConfigurationLoader.cs new file mode 100644 index 0000000..639358b --- /dev/null +++ b/Moderation/Moderation/src/Utility/ConfigurationLoad/JSONConfigurationLoader.cs @@ -0,0 +1,50 @@ +using Microsoft.Extensions.Configuration; +using System.Text.Json; + +namespace PoliNetwork.Utility.ConfigurationLoader +{ + /// + /// Represents a configuration loader for loading JSON configuration data. + /// + public class JSONConfigurationLoader : IConfigurationLoader + { + /// + /// Loads configuration data from the specified JSON file. + /// + /// The path to the JSON configuration file. + /// An containing the loaded configuration data. + /// Thrown if the specified JSON file does not exist. + /// Thrown if the provided path is not a JSON file. + /// Thrown if the specified JSON file is not valid. + public IConfigurationRoot LoadConfiguration(string path) + { + bool notFound = !File.Exists(path); + bool notJson = !Path.HasExtension(path) || !Path.GetExtension(path).Equals(".json", StringComparison.OrdinalIgnoreCase); + + if (notFound) throw new FileNotFoundException("Unable to locate specified JSON file.", path); + if (notJson) throw new ArgumentException("Only JSON files are supported.", nameof(path)); + + try + { + return new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path) + .Build(); + } + catch (JsonException ex) + { + throw new JsonException("The specified JSON file is not valid.", ex); + } + catch (IOException ex) + { + throw new IOException("Could not open file.", ex); + } + + } + + /// + /// Initializes a new instance of the class. + /// + public JSONConfigurationLoader() : base() { } + } +} diff --git a/Moderation/Moderation/src/Utility/Converter/JSONConverter.cs b/Moderation/Moderation/src/Utility/Converter/JSONConverter.cs new file mode 100644 index 0000000..5440dbd --- /dev/null +++ b/Moderation/Moderation/src/Utility/Converter/JSONConverter.cs @@ -0,0 +1,16 @@ +using System.Runtime.InteropServices; +using Newtonsoft.Json; + +class JSONConverter +{ + public static string[]? GetArrayFromString(string json) + { + return JsonConvert.DeserializeObject(json)?.ToArray(); + } + + public static string[]? GetArrayFromFile(string path) + { + string json = File.ReadAllText(path); + return GetArrayFromString(json); + } +} \ No newline at end of file diff --git a/Moderation/Moderation/src/Utility/MessageContentControl/ForbiddenWordsController.cs b/Moderation/Moderation/src/Utility/MessageContentControl/ForbiddenWordsController.cs new file mode 100644 index 0000000..3e278a1 --- /dev/null +++ b/Moderation/Moderation/src/Utility/MessageContentControl/ForbiddenWordsController.cs @@ -0,0 +1,19 @@ +namespace PoliNetwork.Utility.MessageContentControl; + +public sealed class ForbiddenWordsController +{ + private string[] ForbiddenWords { get; set; } + + public ForbiddenWordsController(string[] forbiddenWords) + { + ForbiddenWords = forbiddenWords; + } + + public bool ContainsForbiddenWord(string line) => ForbiddenWords.Any(line.Contains); + + public string? GetFirstForbiddenWord(string line) => + ForbiddenWords.FirstOrDefault(word => line.Contains(word, StringComparison.OrdinalIgnoreCase)); + + + public bool HasForbiddenWord(string line) => ForbiddenWords.Any(); +} \ No newline at end of file diff --git a/Moderation/Moderation/src/persistence/appsettings.json b/Moderation/Moderation/src/persistence/appsettings.json new file mode 100644 index 0000000..7d0cf10 --- /dev/null +++ b/Moderation/Moderation/src/persistence/appsettings.json @@ -0,0 +1,5 @@ +{ + "Secrets": { + "BotToken": "6576423301:AAGZY8_D-QmDxFsWGp6D3z_CJ-odA8NLQSE" + } +} \ No newline at end of file diff --git a/Moderation/Moderation/src/persistence/forbidden_words.json b/Moderation/Moderation/src/persistence/forbidden_words.json new file mode 100644 index 0000000..f46c070 --- /dev/null +++ b/Moderation/Moderation/src/persistence/forbidden_words.json @@ -0,0 +1,3 @@ +[ + "forbidden" +] \ No newline at end of file From d165ddbe27c1556925834e88965e497c7353ebb3 Mon Sep 17 00:00:00 2001 From: joebiden <133514023+sbadung@users.noreply.github.com> Date: Thu, 7 Sep 2023 21:10:52 +0200 Subject: [PATCH 19/20] Revert "Fixing issue#14 actions and build" This reverts commit b52c38d5fe911dd04ccc21107049f0fc81165a80. --- Moderation/Moderation/Moderation.csproj | 25 +++---- .../AbstractTelegramBotFunctionality.cs | 18 ----- .../Example/ResponseOnMessageFunctionality.cs | 42 ----------- .../ITelegramBotFunctionality.cs | 18 ----- .../Default/DefaultPollingErrorHandler.cs | 21 ------ .../Handler/Default/DefaultUpdateHandler.cs | 25 ------- .../src/Bot/Handler/IPollingErrorHandler.cs | 22 ------ .../src/Bot/Handler/IUpdateHandler.cs | 21 ------ Moderation/Moderation/src/Bot/TelegramBot.cs | 53 -------------- .../Moderation/src/Bot/TelegramBotOptions.cs | 19 ----- Moderation/Moderation/src/Configuration.cs | 9 --- Moderation/Moderation/src/Program.cs | 69 +++++++++++++------ .../ConfigurationLoad/IConfigurationLoader.cs | 17 ----- .../JSONConfigurationLoader.cs | 50 -------------- .../src/Utility/Converter/JSONConverter.cs | 16 ----- .../ForbiddenWordsController.cs | 19 ----- .../src/persistence/appsettings.json | 5 -- .../src/persistence/forbidden_words.json | 3 - 18 files changed, 58 insertions(+), 394 deletions(-) delete mode 100644 Moderation/Moderation/src/Bot/Functionality/AbstractTelegramBotFunctionality.cs delete mode 100644 Moderation/Moderation/src/Bot/Functionality/Example/ResponseOnMessageFunctionality.cs delete mode 100644 Moderation/Moderation/src/Bot/Functionality/ITelegramBotFunctionality.cs delete mode 100644 Moderation/Moderation/src/Bot/Handler/Default/DefaultPollingErrorHandler.cs delete mode 100644 Moderation/Moderation/src/Bot/Handler/Default/DefaultUpdateHandler.cs delete mode 100644 Moderation/Moderation/src/Bot/Handler/IPollingErrorHandler.cs delete mode 100644 Moderation/Moderation/src/Bot/Handler/IUpdateHandler.cs delete mode 100644 Moderation/Moderation/src/Bot/TelegramBot.cs delete mode 100644 Moderation/Moderation/src/Bot/TelegramBotOptions.cs delete mode 100644 Moderation/Moderation/src/Configuration.cs delete mode 100644 Moderation/Moderation/src/Utility/ConfigurationLoad/IConfigurationLoader.cs delete mode 100644 Moderation/Moderation/src/Utility/ConfigurationLoad/JSONConfigurationLoader.cs delete mode 100644 Moderation/Moderation/src/Utility/Converter/JSONConverter.cs delete mode 100644 Moderation/Moderation/src/Utility/MessageContentControl/ForbiddenWordsController.cs delete mode 100644 Moderation/Moderation/src/persistence/appsettings.json delete mode 100644 Moderation/Moderation/src/persistence/forbidden_words.json diff --git a/Moderation/Moderation/Moderation.csproj b/Moderation/Moderation/Moderation.csproj index ffa2d18..c5cd62a 100644 --- a/Moderation/Moderation/Moderation.csproj +++ b/Moderation/Moderation/Moderation.csproj @@ -15,29 +15,24 @@ - - - + + + - - + + - - + + - - - - - - - - + + + diff --git a/Moderation/Moderation/src/Bot/Functionality/AbstractTelegramBotFunctionality.cs b/Moderation/Moderation/src/Bot/Functionality/AbstractTelegramBotFunctionality.cs deleted file mode 100644 index 93bf809..0000000 --- a/Moderation/Moderation/src/Bot/Functionality/AbstractTelegramBotFunctionality.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Telegram.Bot; -using Telegram.Bot.Types; - -namespace PoliNetwork.Telegram.Bot.Functionality -{ - /// - /// Represents an abstract base class for defining the functionality of a Telegram bot. - /// - public abstract class AbstractTelegramBotFunctionality : ITelegramBotFunctionality - { - /// - /// Defines the behavior of the bot's functionality. This method must be implemented by derived classes. - /// - /// The instance representing the bot with which the functionality is associated. - /// A representing the asynchronous operation. - public abstract Task RunAsync(ITelegramBotClient bot, Update update, CancellationToken cancellationToken); - } -} diff --git a/Moderation/Moderation/src/Bot/Functionality/Example/ResponseOnMessageFunctionality.cs b/Moderation/Moderation/src/Bot/Functionality/Example/ResponseOnMessageFunctionality.cs deleted file mode 100644 index 7ad3d4c..0000000 --- a/Moderation/Moderation/src/Bot/Functionality/Example/ResponseOnMessageFunctionality.cs +++ /dev/null @@ -1,42 +0,0 @@ -using PoliNetwork.Utility.Configuration; -using Telegram.Bot; -using Telegram.Bot.Types; -using PoliNetwork.Utility.MessageContentControl; - -namespace PoliNetwork.Telegram.Bot.Functionality.Example -{ - public class ResponseOnMessageFunctionality : AbstractTelegramBotFunctionality - { - private static string[] CreateForbiddenWordsArray() - { - var path = Config.FORBIDDEN_WORDS; - return JSONConverter.GetArrayFromFile(path) ?? Array.Empty(); - } - - public override async Task RunAsync(ITelegramBotClient bot, Update update, CancellationToken cancellationToken) - { - /* This way we only process the message text part */ - if (update.Message is not { } message) return; - if (message.Text is not { } messageText) return; - - var chatId = message.Chat.Id; - var username = message.Chat.Username; - - var forbiddenWords = CreateForbiddenWordsArray(); - var HasForbiddenWord = new ForbiddenWordsController(forbiddenWords).ContainsForbiddenWord(messageText); - - var serverPrompt = $"Received a '{messageText}' message in chat {chatId} ({username})."; - var responseText = HasForbiddenWord ? "Your massage contains a forbidden word" : "Your message is a valid one"; - Console.WriteLine(serverPrompt); - - var sentMessage = await bot.SendTextMessageAsync( - chatId: chatId, - text: responseText, - cancellationToken: cancellationToken - ); - - serverPrompt = $"Sent message: {sentMessage.Text}"; - Console.WriteLine(serverPrompt); - } - } -} \ No newline at end of file diff --git a/Moderation/Moderation/src/Bot/Functionality/ITelegramBotFunctionality.cs b/Moderation/Moderation/src/Bot/Functionality/ITelegramBotFunctionality.cs deleted file mode 100644 index 09f1e68..0000000 --- a/Moderation/Moderation/src/Bot/Functionality/ITelegramBotFunctionality.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Telegram.Bot; -using Telegram.Bot.Types; - -namespace PoliNetwork.Telegram.Bot.Functionality -{ - /// - /// Represents an interface for defining the functionality of a Telegram bot. - /// - public interface ITelegramBotFunctionality - { - /// - /// Runs the defined functionality using the provided . - /// - /// The instance representing the bot with which the functionality is associated. - /// A representing the asynchronous operation. - Task RunAsync(ITelegramBotClient bot, Update update, CancellationToken cancellationToken); - } -} diff --git a/Moderation/Moderation/src/Bot/Handler/Default/DefaultPollingErrorHandler.cs b/Moderation/Moderation/src/Bot/Handler/Default/DefaultPollingErrorHandler.cs deleted file mode 100644 index 5427e57..0000000 --- a/Moderation/Moderation/src/Bot/Handler/Default/DefaultPollingErrorHandler.cs +++ /dev/null @@ -1,21 +0,0 @@ -using Telegram.Bot; -using Telegram.Bot.Exceptions; - -namespace PoliNetwork.Telegram.Bot.Handler -{ - public class DefaultPollingErrorHandler : IPollingErrorHandler - { - public Task HandlePollingErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken) - { - var ErrorMessage = exception switch - { - ApiRequestException apiRequestException - => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}", - _ => exception.ToString() - }; - - Console.WriteLine(ErrorMessage); - return Task.CompletedTask; - } - } -} \ No newline at end of file diff --git a/Moderation/Moderation/src/Bot/Handler/Default/DefaultUpdateHandler.cs b/Moderation/Moderation/src/Bot/Handler/Default/DefaultUpdateHandler.cs deleted file mode 100644 index 2e7c118..0000000 --- a/Moderation/Moderation/src/Bot/Handler/Default/DefaultUpdateHandler.cs +++ /dev/null @@ -1,25 +0,0 @@ -using PoliNetwork.Telegram.Bot.Functionality; -using Telegram.Bot; -using Telegram.Bot.Types; - -namespace PoliNetwork.Telegram.Bot.Handler -{ - public class DefaultUpdateHandler : IUpdateHandler - { - private readonly List Functionalities; - - public DefaultUpdateHandler(List functionalities) - { - Functionalities = functionalities; - } - - public async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) - { - /* Parallel.ForEach(_functionalities, functionalities => functionalities.Run(botClient, update, cancellationToken)); */ - foreach (var functionality in Functionalities) - { - await functionality.RunAsync(botClient, update, cancellationToken); - } - } - } -} \ No newline at end of file diff --git a/Moderation/Moderation/src/Bot/Handler/IPollingErrorHandler.cs b/Moderation/Moderation/src/Bot/Handler/IPollingErrorHandler.cs deleted file mode 100644 index c53abc2..0000000 --- a/Moderation/Moderation/src/Bot/Handler/IPollingErrorHandler.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using Telegram.Bot; - -namespace PoliNetwork.Telegram.Bot.Handler -{ - /// - /// Represents an interface for handling errors that occur during the polling process of a Telegram bot. - /// - public interface IPollingErrorHandler - { - /// - /// Handles a polling error asynchronously. - /// - /// The instance used for interaction with the Telegram Bot API. - /// The that occurred during the polling process. - /// A that can be used to cancel the asynchronous operation. - /// A representing the asynchronous operation. - Task HandlePollingErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken); - } -} diff --git a/Moderation/Moderation/src/Bot/Handler/IUpdateHandler.cs b/Moderation/Moderation/src/Bot/Handler/IUpdateHandler.cs deleted file mode 100644 index c4050a9..0000000 --- a/Moderation/Moderation/src/Bot/Handler/IUpdateHandler.cs +++ /dev/null @@ -1,21 +0,0 @@ - -using Telegram.Bot; -using Telegram.Bot.Types; - -namespace PoliNetwork.Telegram.Bot.Handler -{ - /// - /// Represents an interface for handling incoming Telegram updates. - /// - public interface IUpdateHandler - { - /// - /// Handles an incoming Telegram update asynchronously. - /// - /// The instance used for interaction with the Telegram Bot API. - /// The representing the incoming update to be handled. - /// A that can be used to cancel the asynchronous operation. - /// A representing the asynchronous operation. - Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken); - } -} diff --git a/Moderation/Moderation/src/Bot/TelegramBot.cs b/Moderation/Moderation/src/Bot/TelegramBot.cs deleted file mode 100644 index a3c1da8..0000000 --- a/Moderation/Moderation/src/Bot/TelegramBot.cs +++ /dev/null @@ -1,53 +0,0 @@ -using PoliNetwork.Telegram.Bot.Handler; -using Telegram.Bot; -using Telegram.Bot.Polling; -using Telegram.Bot.Types; -using Telegram.Bot.Types.Enums; - -namespace PoliNetwork.Telegram.Bot -{ - /// - /// Represents a Telegram bot that can interact with the Telegram Bot API. - /// - public class TelegramBot : TelegramBotClient - { - /// - /// Initializes a new instance of the class with the provided options and an optional HttpClient. - /// - /// The options specifying bot settings. - /// Optional HttpClient to be used for API requests. - public TelegramBot(TelegramBotOptions options, HttpClient? httpClient = null) - : base(options, httpClient) { } - - /// - /// Initializes a new instance of the class with the provided bot token and an optional HttpClient. - /// - /// The authentication token of the bot. - /// Optional HttpClient to be used for API requests. - public TelegramBot(string token, HttpClient? httpClient = null) - : base(token, httpClient) { } - - public async Task RunAsync(Handler.IUpdateHandler updateHandler, IPollingErrorHandler pollingErrorHandler) - { - using CancellationTokenSource cts = new(); - - ReceiverOptions receiverOptions = new() - { - AllowedUpdates = Array.Empty() - }; - - this.StartReceiving( - updateHandler: updateHandler.HandleUpdateAsync, - pollingErrorHandler: pollingErrorHandler.HandlePollingErrorAsync, - receiverOptions: receiverOptions, - cancellationToken: cts.Token - ); - - var me = await this.GetMeAsync(); - Console.WriteLine($"Start listening for @{me.Username}\nExit via typing"); - Console.ReadLine(); - cts.Cancel(); - } - } -} - diff --git a/Moderation/Moderation/src/Bot/TelegramBotOptions.cs b/Moderation/Moderation/src/Bot/TelegramBotOptions.cs deleted file mode 100644 index deb1c7f..0000000 --- a/Moderation/Moderation/src/Bot/TelegramBotOptions.cs +++ /dev/null @@ -1,19 +0,0 @@ -using Telegram.Bot; - -namespace PoliNetwork.Telegram.Bot -{ - /// - /// Represents options for configuring a . - /// - public class TelegramBotOptions : TelegramBotClientOptions - { - /// - /// Initializes a new instance of the class with the provided token, base URL, and test environment settings. - /// - /// The authentication token of the bot. - /// Optional base URL for API requests. - /// Flag indicating whether to use the test environment. - protected TelegramBotOptions(string token, string? baseUrl = null, bool useTestEnvironment = false) - : base(token, baseUrl, useTestEnvironment) { } - } -} diff --git a/Moderation/Moderation/src/Configuration.cs b/Moderation/Moderation/src/Configuration.cs deleted file mode 100644 index ab372b3..0000000 --- a/Moderation/Moderation/src/Configuration.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace PoliNetwork.Utility.Configuration -{ - public static class Config - { - private static readonly string? BASE_PATH = Directory.GetParent(Environment.CurrentDirectory)?.FullName; - public static readonly string FORBIDDEN_WORDS = BASE_PATH + @"\Moderation\src\persistence\forbidden_words.json"; - public static readonly string APP_SETTINGS = BASE_PATH + @"\Moderation\src\persistence\appsettings.json"; - } -} \ No newline at end of file diff --git a/Moderation/Moderation/src/Program.cs b/Moderation/Moderation/src/Program.cs index f6ca506..2c0fc64 100644 --- a/Moderation/Moderation/src/Program.cs +++ b/Moderation/Moderation/src/Program.cs @@ -1,29 +1,56 @@ -using PoliNetwork.Telegram.Bot; -using PoliNetwork.Telegram.Bot.Functionality; -using PoliNetwork.Telegram.Bot.Functionality.Example; -using PoliNetwork.Telegram.Bot.Handler; -using PoliNetwork.Utility.ConfigurationLoader; -using PoliNetwork.Utility.Configuration; - -namespace PoliNetwork.Moderation +#region +using PoliNetwork.Core.Utils; +using PoliNetwork.Telegram.Logger; +using PoliNetwork.Db.Utils; +using PoliNetwork.Telegram.Configuration; +using PoliNetwork.Telegram.ConfigurationLoader; +using PoliNetwork.Db.Objects; +using PoliNetwork.Telegram.Bot.Bots; +using PoliNetwork.Telegram.Options; +using PoliNetwork.Telegram.Properties; +#endregion + +namespace Moderation; + +internal static class Program { - internal abstract class Program + private static ModerationBot? _bot = null; + private const string DatabaseConfigurationPath = ""; + + public static void Main() { - private static async Task Main() + /* The PoliNetwork.Core.Utils.LoggerNS.Logger must extends the AbstractLogger so a sub class will be needed + The only dependency of the PoliNetwork.Core.Utils.LoggerNS.Logger resides here in the Program.cs */ + AbstractLogger? logger = new DefaultLogger(); + FileConfigurationLoader fileConfigurationLoader = new JSONFileConfigurationLoader(); + AbstractTelegramBotOptions? botConfiguration = fileConfigurationLoader.LoadOrInitializeConfig(Configuration.TELEGRAM_CONFIGURATION_PATH, logger); + + DbConfig? databaseConfiguration = DbConfigUtils.LoadOrInitializeConfig(DatabaseConfigurationPath); + if (botConfiguration == null) { - List telegramBotFunctionalities = new() - { - new ResponseOnMessageFunctionality() - }; + logger?.Emergency("Telegram Config is undefined when starting the bot."); + return; + } - IUpdateHandler updateHandler = new DefaultUpdateHandler(telegramBotFunctionalities); - IPollingErrorHandler pollingErrorHandler = new DefaultPollingErrorHandler(); + if (databaseConfiguration == null) + { + logger?.Emergency("Database Config is undefined when starting the bot."); + return; + } - var botToken = new JSONConfigurationLoader().LoadConfiguration(Config.APP_SETTINGS) - .GetSection("Secrets:BotToken").Value!; - TelegramBot bot = new(botToken); + logger?.Info("RUNNING MODERATION BOT"); + botConfiguration.UpdateMethod = new UpdateMethod(UpdateAction); - await bot.RunAsync(updateHandler, pollingErrorHandler); - } + /* TelegramConfiguration should extends TelegramBotClientOptions */ + _bot = new ModerationBot(options: botConfiguration, logger: logger); + _bot.Start(new CancellationToken()); + Wait.WaitForever(); + } + + private static void UpdateAction(CancellationToken cancellationToken, IUpdate update) + { + /* Process Message updates only, see: https://core.telegram.org/bots/api#message */ + if (_bot == null || update.Message is not { } message) return; + _bot.Echo(message, cancellationToken); } } \ No newline at end of file diff --git a/Moderation/Moderation/src/Utility/ConfigurationLoad/IConfigurationLoader.cs b/Moderation/Moderation/src/Utility/ConfigurationLoad/IConfigurationLoader.cs deleted file mode 100644 index 7177325..0000000 --- a/Moderation/Moderation/src/Utility/ConfigurationLoad/IConfigurationLoader.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Microsoft.Extensions.Configuration; - -namespace PoliNetwork.Utility.ConfigurationLoader -{ - /// - /// Represents an interface for loading configuration data from various sources. - /// - public interface IConfigurationLoader - { - /// - /// Loads configuration data from the specified path. - /// - /// The path to the configuration data. - /// An containing the loaded configuration data. - IConfigurationRoot LoadConfiguration(string path); - } -} diff --git a/Moderation/Moderation/src/Utility/ConfigurationLoad/JSONConfigurationLoader.cs b/Moderation/Moderation/src/Utility/ConfigurationLoad/JSONConfigurationLoader.cs deleted file mode 100644 index 639358b..0000000 --- a/Moderation/Moderation/src/Utility/ConfigurationLoad/JSONConfigurationLoader.cs +++ /dev/null @@ -1,50 +0,0 @@ -using Microsoft.Extensions.Configuration; -using System.Text.Json; - -namespace PoliNetwork.Utility.ConfigurationLoader -{ - /// - /// Represents a configuration loader for loading JSON configuration data. - /// - public class JSONConfigurationLoader : IConfigurationLoader - { - /// - /// Loads configuration data from the specified JSON file. - /// - /// The path to the JSON configuration file. - /// An containing the loaded configuration data. - /// Thrown if the specified JSON file does not exist. - /// Thrown if the provided path is not a JSON file. - /// Thrown if the specified JSON file is not valid. - public IConfigurationRoot LoadConfiguration(string path) - { - bool notFound = !File.Exists(path); - bool notJson = !Path.HasExtension(path) || !Path.GetExtension(path).Equals(".json", StringComparison.OrdinalIgnoreCase); - - if (notFound) throw new FileNotFoundException("Unable to locate specified JSON file.", path); - if (notJson) throw new ArgumentException("Only JSON files are supported.", nameof(path)); - - try - { - return new ConfigurationBuilder() - .SetBasePath(Directory.GetCurrentDirectory()) - .AddJsonFile(path) - .Build(); - } - catch (JsonException ex) - { - throw new JsonException("The specified JSON file is not valid.", ex); - } - catch (IOException ex) - { - throw new IOException("Could not open file.", ex); - } - - } - - /// - /// Initializes a new instance of the class. - /// - public JSONConfigurationLoader() : base() { } - } -} diff --git a/Moderation/Moderation/src/Utility/Converter/JSONConverter.cs b/Moderation/Moderation/src/Utility/Converter/JSONConverter.cs deleted file mode 100644 index 5440dbd..0000000 --- a/Moderation/Moderation/src/Utility/Converter/JSONConverter.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System.Runtime.InteropServices; -using Newtonsoft.Json; - -class JSONConverter -{ - public static string[]? GetArrayFromString(string json) - { - return JsonConvert.DeserializeObject(json)?.ToArray(); - } - - public static string[]? GetArrayFromFile(string path) - { - string json = File.ReadAllText(path); - return GetArrayFromString(json); - } -} \ No newline at end of file diff --git a/Moderation/Moderation/src/Utility/MessageContentControl/ForbiddenWordsController.cs b/Moderation/Moderation/src/Utility/MessageContentControl/ForbiddenWordsController.cs deleted file mode 100644 index 3e278a1..0000000 --- a/Moderation/Moderation/src/Utility/MessageContentControl/ForbiddenWordsController.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace PoliNetwork.Utility.MessageContentControl; - -public sealed class ForbiddenWordsController -{ - private string[] ForbiddenWords { get; set; } - - public ForbiddenWordsController(string[] forbiddenWords) - { - ForbiddenWords = forbiddenWords; - } - - public bool ContainsForbiddenWord(string line) => ForbiddenWords.Any(line.Contains); - - public string? GetFirstForbiddenWord(string line) => - ForbiddenWords.FirstOrDefault(word => line.Contains(word, StringComparison.OrdinalIgnoreCase)); - - - public bool HasForbiddenWord(string line) => ForbiddenWords.Any(); -} \ No newline at end of file diff --git a/Moderation/Moderation/src/persistence/appsettings.json b/Moderation/Moderation/src/persistence/appsettings.json deleted file mode 100644 index 7d0cf10..0000000 --- a/Moderation/Moderation/src/persistence/appsettings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "Secrets": { - "BotToken": "6576423301:AAGZY8_D-QmDxFsWGp6D3z_CJ-odA8NLQSE" - } -} \ No newline at end of file diff --git a/Moderation/Moderation/src/persistence/forbidden_words.json b/Moderation/Moderation/src/persistence/forbidden_words.json deleted file mode 100644 index f46c070..0000000 --- a/Moderation/Moderation/src/persistence/forbidden_words.json +++ /dev/null @@ -1,3 +0,0 @@ -[ - "forbidden" -] \ No newline at end of file From 86e1c2754138342b30cd172ba05582cff23fe8c2 Mon Sep 17 00:00:00 2001 From: angeousta <132761637+angeousta@users.noreply.github.com> Date: Sat, 9 Sep 2023 14:53:15 +0200 Subject: [PATCH 20/20] Test fix (#20) * Update .gitignore * Update Lib_CSharp --- .gitignore | 2 ++ Moderation/Moderation/Lib_CSharp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index e5affe7..5b5c9a8 100644 --- a/.gitignore +++ b/.gitignore @@ -566,3 +566,5 @@ Moderation/Main/.idea/.idea.Main.dir/.idea/.gitignore Moderation/Main/.idea/.idea.Main.dir/.idea/encodings.xml Moderation/Main/.idea/.idea.Main.dir/.idea/indexLayout.xml Moderation/Main/.idea/.idea.Main.dir/.idea/vcs.xml +.idea/.idea.PoliNetwork.Bot/.idea/projectSettingsUpdater.xml +.idea/.idea.Telegram/.idea/projectSettingsUpdater.xml diff --git a/Moderation/Moderation/Lib_CSharp b/Moderation/Moderation/Lib_CSharp index 270e908..7758928 160000 --- a/Moderation/Moderation/Lib_CSharp +++ b/Moderation/Moderation/Lib_CSharp @@ -1 +1 @@ -Subproject commit 270e908b700ad364d128f85eea74c7482ffb23d1 +Subproject commit 7758928e2b125dff2ba750c83009adddd054d2cf