From 3f0d109fe2f66505411c46936a7357bd095ff2ac Mon Sep 17 00:00:00 2001 From: ZavaruKitsu Date: Sat, 8 Oct 2022 18:39:22 +0300 Subject: [PATCH 01/22] fix(readme): missing spaces and semicolon --- README.md | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index e83b588..7f067ad 100644 --- a/README.md +++ b/README.md @@ -91,8 +91,7 @@ var bot = BotBaseBuilder .NoProxy() .CustomCommands(a => { - a.Start("Starts the bot") - + a.Start("Starts the bot"); }) .NoSerialization() .UseEnglish() @@ -206,9 +205,9 @@ var bot = BotBaseBuilder .CustomCommands(a => { a.Start("Starts the bot"); - a.Add("form1","Opens test form 1" ); - a.Add("form2", "Opens test form 2" ); - a.Add("params", "Returns all send parameters as a message." ); + a.Add("form1","Opens test form 1"); + a.Add("form2", "Opens test form 2"); + a.Add("params", "Returns all send parameters as a message."); }) .NoSerialization() .UseEnglish() @@ -219,19 +218,19 @@ bot.BotCommand += async (s, en) => switch (en.Command) { case "/form1": - var form1 = new TestForm(); - await en.Device.ActiveForm.NavigateTo(form1); - break; + var form1 = new TestForm(); + await en.Device.ActiveForm.NavigateTo(form1); + break; case "/form2": - var form2 = new TestForm2(); - await en.Device.ActiveForm.NavigateTo(form2); - break; + var form2 = new TestForm2(); + await en.Device.ActiveForm.NavigateTo(form2); + break; case "/params": - string m = en.Parameters.DefaultIfEmpty("").Aggregate((a, b) => a + " and " + b); - await en.Device.Send("Your parameters are " + m, replyTo: en.Device.LastMessage); - break; + string m = en.Parameters.DefaultIfEmpty("").Aggregate((a, b) => a + " and " + b); + await en.Device.Send("Your parameters are " + m, replyTo: en.Device.LastMessage); + break; } }; @@ -1027,6 +1026,7 @@ Will delete Join and Leave messages automatically in groups. - [Examples/JoinHiderBot](Examples/JoinHiderBot) -When you want to update forms async without any user interaction (message/action) before. Use the new InvokeMessageLoop method of BotBase. +When you want to update forms async without any user interaction (message/action) before. Use the new InvokeMessageLoop +method of BotBase. - [Examples/AsyncFormUpdates](Examples/AsyncFormUpdates) From a731e2a8d089c40ec88eba0f7512e3c43381b071 Mon Sep 17 00:00:00 2001 From: ZavaruKitsu Date: Sat, 8 Oct 2022 19:15:51 +0300 Subject: [PATCH 02/22] fix: some build & linter warnings --- Examples/AsyncFormUpdates/Program.cs | 28 +- .../Properties/AssemblyInfo.cs | 1 - .../AsyncFormUpdates/forms/AsyncFormEdit.cs | 26 +- .../AsyncFormUpdates/forms/AsyncFormUpdate.cs | 18 +- Examples/AsyncFormUpdates/forms/Start.cs | 8 +- Examples/JoinHiderBot/Program.cs | 9 +- .../JoinHiderBot/forms/GroupManageForm.cs | 10 +- Examples/JoinHiderBot/forms/Start.cs | 9 +- Examples/SystemCommandsBot/Program.cs | 12 +- .../SystemCommandsBot/commands/Commando.cs | 17 +- Examples/SystemCommandsBot/config/Config.cs | 43 +- Examples/SystemCommandsBot/forms/CmdForm.cs | 62 +-- Examples/SystemCommandsBot/forms/StartForm.cs | 21 +- .../ImageExtensions.cs | 17 +- .../BotBaseBuilderExtensions.cs | 36 +- .../MSSQLSerializer.cs | 113 +++-- TelegramBotBase.Test/Program.cs | 25 +- .../Properties/AssemblyInfo.cs | 1 - TelegramBotBase.Test/Tests/ButtonTestForm.cs | 21 +- .../Tests/Controls/ButtonGridForm.cs | 54 +-- .../Tests/Controls/ButtonGridPagingForm.cs | 46 +- .../Tests/Controls/ButtonGridTagForm.cs | 48 +- .../Tests/Controls/CalendarPickerForm.cs | 52 +-- .../Tests/Controls/CheckedButtonListForm.cs | 64 ++- .../Tests/Controls/MonthPickerForm.cs | 48 +- .../Tests/Controls/MultiToggleButtons.cs | 30 +- .../Tests/Controls/MultiViewForm.cs | 41 +- .../Tests/Controls/Subclass/MultiViewTest.cs | 18 +- .../Tests/Controls/ToggleButtons.cs | 39 +- .../Tests/Controls/TreeViewForms.cs | 50 +- TelegramBotBase.Test/Tests/DataForm.cs | 49 +- .../Tests/Datasources/CustomDataSource.cs | 56 +-- .../Tests/Datasources/List.cs | 37 +- .../Tests/Groups/GroupChange.cs | 18 +- .../Tests/Groups/LinkReplaceTest.cs | 47 +- .../Tests/Groups/WelcomeUser.cs | 27 +- TelegramBotBase.Test/Tests/Menu.cs | 70 +-- .../Tests/Navigation/CustomController.cs | 10 +- .../Tests/Navigation/Form1.cs | 14 +- .../Tests/Navigation/Start.cs | 30 +- .../Tests/Notifications/Start.cs | 14 +- TelegramBotBase.Test/Tests/ProgressTest.cs | 62 +-- .../Tests/Register/PerForm.cs | 65 ++- .../Tests/Register/PerStep.cs | 21 +- TelegramBotBase.Test/Tests/Register/Start.cs | 27 +- .../Tests/Register/Steps/Data.cs | 14 +- .../Tests/Register/Steps/Step1.cs | 37 +- .../Tests/Register/Steps/Step2.cs | 30 +- .../Tests/Register/Steps/Step3.cs | 42 +- TelegramBotBase.Test/Tests/SimpleForm.cs | 20 +- TelegramBotBase.Test/Tests/Start.cs | 12 +- TelegramBotBase.Test/Tests/TestForm.cs | 22 +- TelegramBotBase.Test/Tests/TestForm2.cs | 43 +- TelegramBotBase/Args/BotCommandEventArgs.cs | 19 +- .../Args/ButtonClickedEventArgs.cs | 22 +- .../Args/CheckedChangedEventArgs.cs | 13 +- TelegramBotBase/Args/GroupChangedEventArgs.cs | 6 +- TelegramBotBase/Args/InitEventArgs.cs | 6 +- TelegramBotBase/Args/LoadStateEventArgs.cs | 28 +- TelegramBotBase/Args/MemberChangeEventArgs.cs | 9 +- .../Args/MessageDeletedEventArgs.cs | 11 +- .../Args/MessageIncomeEventArgs.cs | 12 +- .../Args/MessageReceivedEventArgs.cs | 17 +- TelegramBotBase/Args/MessageSentEventArgs.cs | 18 +- .../Args/PromptDialogCompletedEventArgs.cs | 8 +- TelegramBotBase/Args/RenderViewEventArgs.cs | 6 +- TelegramBotBase/Args/SaveStateEventArgs.cs | 16 +- TelegramBotBase/Args/SaveStatesEventArgs.cs | 9 +- TelegramBotBase/Args/SessionBeginEventArgs.cs | 10 +- .../Args/SystemExceptionEventArgs.cs | 16 +- .../Args/UnhandledCallEventArgs.cs | 24 +- TelegramBotBase/Attributes/IgnoreState.cs | 2 - TelegramBotBase/Attributes/SaveState.cs | 4 +- TelegramBotBase/Base/Async.cs | 1 - TelegramBotBase/Base/ControlBase.cs | 47 +- TelegramBotBase/Base/DataResult.cs | 146 ++---- TelegramBotBase/Base/FormBase.cs | 148 +++--- TelegramBotBase/Base/MessageClient.cs | 88 ++-- TelegramBotBase/Base/MessageResult.cs | 122 ++--- TelegramBotBase/Base/ResultBase.cs | 18 +- TelegramBotBase/Base/StateContainer.cs | 8 +- TelegramBotBase/Base/StateEntry.cs | 15 +- TelegramBotBase/Base/UpdateResult.cs | 50 +- TelegramBotBase/BotBase.cs | 187 ++++---- TelegramBotBase/Builder/BotBaseBuilder.cs | 134 +++--- .../Interfaces/IAPIKeySelectionStage.cs | 10 +- .../Builder/Interfaces/IBotCommandsStage.cs | 1 - .../Builder/Interfaces/IBuildingStage.cs | 6 +- .../Interfaces/ILanguageSelectionStage.cs | 5 +- .../Interfaces/IMessageLoopSelectionStage.cs | 6 +- .../Interfaces/INetworkingSelectionStage.cs | 9 +- .../Interfaces/ISessionSerializationStage.cs | 11 +- .../Interfaces/IStartFormSelectionStage.cs | 2 - TelegramBotBase/Commands/Extensions.cs | 29 +- TelegramBotBase/Constants/Telegram.cs | 8 +- TelegramBotBase/Controls/Hybrid/ButtonGrid.cs | 311 ++++++------- TelegramBotBase/Controls/Hybrid/ButtonRow.cs | 46 +- .../Controls/Hybrid/CheckedButtonList.cs | 335 ++++++-------- TelegramBotBase/Controls/Hybrid/MultiView.cs | 56 +-- .../Controls/Hybrid/TaggedButtonGrid.cs | 431 ++++++++---------- .../Controls/Inline/CalendarPicker.cs | 162 +++---- .../Controls/Inline/MonthPicker.cs | 14 +- .../Controls/Inline/MultiToggleButton.cs | 67 ++- .../Controls/Inline/ProgressBar.cs | 209 ++++----- .../Controls/Inline/ToggleButton.cs | 78 ++-- TelegramBotBase/Controls/Inline/TreeView.cs | 45 +- .../Controls/Inline/TreeViewNode.cs | 31 +- .../ButtonFormDataSource.cs | 35 +- .../StaticDataSource.cs | 21 +- TelegramBotBase/Enums/eDeleteMode.cs | 10 +- TelegramBotBase/Enums/eDeleteSide.cs | 10 +- TelegramBotBase/Enums/eKeyboardType.cs | 10 +- TelegramBotBase/Enums/eMonthPickerMode.cs | 10 +- .../Enums/eNavigationBarVisibility.cs | 8 +- TelegramBotBase/Enums/eSettings.cs | 8 +- .../Exceptions/MaxLengthException.cs | 4 - .../Exceptions/MaximumColsException.cs | 10 +- .../Exceptions/MaximumRowsException.cs | 10 +- .../Factories/DefaultStartFormFactory.cs | 5 +- .../Factories/LambdaStartFormFactory.cs | 8 +- TelegramBotBase/Form/AlertDialog.cs | 17 +- TelegramBotBase/Form/ArrayPromptDialog.cs | 47 +- TelegramBotBase/Form/AutoCleanForm.cs | 67 +-- TelegramBotBase/Form/ButtonBase.cs | 38 +- TelegramBotBase/Form/ButtonForm.cs | 122 +++-- TelegramBotBase/Form/CallbackData.cs | 30 +- TelegramBotBase/Form/ConfirmDialog.cs | 43 +- TelegramBotBase/Form/DynamicButton.cs | 32 +- TelegramBotBase/Form/GroupForm.cs | 57 +-- TelegramBotBase/Form/ModalDialog.cs | 8 +- .../Form/Navigation/NavigationController.cs | 67 ++- TelegramBotBase/Form/PromptDialog.cs | 54 +-- TelegramBotBase/Form/SplitterForm.cs | 30 +- TelegramBotBase/Form/TagButtonBase.cs | 23 +- TelegramBotBase/Interfaces/IDataSource.cs | 5 +- TelegramBotBase/Interfaces/IDeviceSession.cs | 6 +- .../Interfaces/IMessageLoopFactory.cs | 5 +- .../Interfaces/IStartFormFactory.cs | 5 +- TelegramBotBase/Interfaces/IStateForm.cs | 6 +- TelegramBotBase/Interfaces/IStateMachine.cs | 3 - TelegramBotBase/Localizations/Default.cs | 6 +- TelegramBotBase/Localizations/English.cs | 8 +- TelegramBotBase/Localizations/German.cs | 8 +- TelegramBotBase/Localizations/Localization.cs | 21 +- TelegramBotBase/Markdown/Generator.cs | 117 ++--- .../MessageLoops/FormBaseMessageLoop.cs | 53 +-- .../MessageLoops/FullMessageLoop.cs | 47 +- .../MessageLoops/MinimalMessageLoop.cs | 28 +- TelegramBotBase/Properties/AssemblyInfo.cs | 1 - TelegramBotBase/SessionBase.cs | 101 ++-- TelegramBotBase/Sessions/DeviceSession.cs | 257 +++++------ TelegramBotBase/States/JSONStateMachine.cs | 43 +- .../States/SimpleJSONStateMachine.cs | 41 +- TelegramBotBase/States/XMLStateMachine.cs | 36 +- TelegramBotBase/TelegramBotBase.csproj | 7 +- TelegramBotBase/Tools/Arrays.cs | 9 +- TelegramBotBase/Tools/Console.cs | 36 +- TelegramBotBase/Tools/Conversion.cs | 15 +- TelegramBotBase/Tools/Time.cs | 6 +- 159 files changed, 2738 insertions(+), 3742 deletions(-) rename TelegramBotBase/{Datasources => DataSources}/ButtonFormDataSource.cs (78%) rename TelegramBotBase/{Datasources => DataSources}/StaticDataSource.cs (56%) diff --git a/Examples/AsyncFormUpdates/Program.cs b/Examples/AsyncFormUpdates/Program.cs index b12cb83..27283f7 100644 --- a/Examples/AsyncFormUpdates/Program.cs +++ b/Examples/AsyncFormUpdates/Program.cs @@ -1,26 +1,24 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Timers; +using AsyncFormUpdates.forms; +using TelegramBotBase; using TelegramBotBase.Builder; namespace AsyncFormUpdates { - class Program + internal class Program { - static TelegramBotBase.BotBase bot = null; + private static BotBase __bot; - static void Main(string[] args) + private static void Main(string[] args) { - String apiKey = "APIKey"; + var apiKey = "APIKey"; - bot = BotBaseBuilder.Create() - .QuickStart(apiKey) + __bot = BotBaseBuilder.Create() + .QuickStart(apiKey) .Build(); - bot.Start(); + __bot.Start(); var timer = new Timer(5000); @@ -30,19 +28,19 @@ namespace AsyncFormUpdates Console.ReadLine(); timer.Stop(); - bot.Stop(); + __bot.Stop(); } private static async void Timer_Elapsed(object sender, ElapsedEventArgs e) { - foreach(var s in bot.Sessions.SessionList) + foreach(var s in __bot.Sessions.SessionList) { //Only for AsyncUpdateForm - if (s.Value.ActiveForm.GetType() != typeof(forms.AsyncFormUpdate) && s.Value.ActiveForm.GetType() != typeof(forms.AsyncFormEdit)) + if (s.Value.ActiveForm.GetType() != typeof(AsyncFormUpdate) && s.Value.ActiveForm.GetType() != typeof(AsyncFormEdit)) continue; - await bot.InvokeMessageLoop(s.Key); + await __bot.InvokeMessageLoop(s.Key); } diff --git a/Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs b/Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs index 216bef4..7703157 100644 --- a/Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs +++ b/Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs @@ -1,5 +1,4 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden diff --git a/Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs b/Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs index 1e176d7..c24b8c2 100644 --- a/Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs +++ b/Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TelegramBotBase.Attributes; using TelegramBotBase.Base; using TelegramBotBase.Form; @@ -11,19 +7,19 @@ namespace AsyncFormUpdates.forms { public class AsyncFormEdit : FormBase { - [SaveState] - int counter = 0; + [SaveState] private int _counter; - int MessageId = 0; + private int _messageId; - public override async Task Load(MessageResult message) + public override Task Load(MessageResult message) { - counter++; + _counter++; + return Task.CompletedTask; } public override async Task Action(MessageResult message) { - await message.ConfirmAction(""); + await message.ConfirmAction(); switch (message.RawData ?? "") { @@ -41,14 +37,14 @@ namespace AsyncFormUpdates.forms var bf = new ButtonForm(); bf.AddButtonRow("Back", "back"); - if (MessageId != 0) + if (_messageId != 0) { - await Device.Edit(MessageId, $"Your current count is at: {counter}", bf); + await Device.Edit(_messageId, $"Your current count is at: {_counter}", bf); } else { - var m = await Device.Send($"Your current count is at: {counter}", bf, disableNotification: true); - MessageId = m.MessageId; + var m = await Device.Send($"Your current count is at: {_counter}", bf, disableNotification: true); + _messageId = m.MessageId; } } diff --git a/Examples/AsyncFormUpdates/forms/AsyncFormUpdate.cs b/Examples/AsyncFormUpdates/forms/AsyncFormUpdate.cs index 4a4b4c7..9e888a5 100644 --- a/Examples/AsyncFormUpdates/forms/AsyncFormUpdate.cs +++ b/Examples/AsyncFormUpdates/forms/AsyncFormUpdate.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TelegramBotBase.Attributes; using TelegramBotBase.Base; using TelegramBotBase.Form; @@ -11,18 +7,18 @@ namespace AsyncFormUpdates.forms { public class AsyncFormUpdate : AutoCleanForm { - [SaveState] - int counter = 0; + [SaveState] private int _counter; - public override async Task Load(MessageResult message) + public override Task Load(MessageResult message) { - counter++; + _counter++; + return Task.CompletedTask; } public override async Task Action(MessageResult message) { - await message.ConfirmAction(""); + await message.ConfirmAction(); switch (message.RawData ?? "") { @@ -40,7 +36,7 @@ namespace AsyncFormUpdates.forms var bf = new ButtonForm(); bf.AddButtonRow("Back", "back"); - await Device.Send($"Your current count is at: {counter}", bf, disableNotification: true); + await Device.Send($"Your current count is at: {_counter}", bf, disableNotification: true); } diff --git a/Examples/AsyncFormUpdates/forms/Start.cs b/Examples/AsyncFormUpdates/forms/Start.cs index c69fa4a..a8a726d 100644 --- a/Examples/AsyncFormUpdates/forms/Start.cs +++ b/Examples/AsyncFormUpdates/forms/Start.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; @@ -14,7 +10,7 @@ namespace AsyncFormUpdates.forms public override async Task Action(MessageResult message) { - await message.ConfirmAction(""); + await message.ConfirmAction(); switch (message.RawData ?? "") { diff --git a/Examples/JoinHiderBot/Program.cs b/Examples/JoinHiderBot/Program.cs index d2d05fe..369b758 100644 --- a/Examples/JoinHiderBot/Program.cs +++ b/Examples/JoinHiderBot/Program.cs @@ -1,17 +1,18 @@ using System; +using JoinHiderBot.forms; using TelegramBotBase.Builder; namespace JoinHiderBot { - class Program + internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { - String apiKey = ""; + var apiKey = ""; var bot = BotBaseBuilder.Create() - .QuickStart(apiKey) + .QuickStart(apiKey) .Build(); bot.Start(); diff --git a/Examples/JoinHiderBot/forms/GroupManageForm.cs b/Examples/JoinHiderBot/forms/GroupManageForm.cs index 3e6cc2a..61fdadc 100644 --- a/Examples/JoinHiderBot/forms/GroupManageForm.cs +++ b/Examples/JoinHiderBot/forms/GroupManageForm.cs @@ -1,7 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; +using Telegram.Bot.Types.Enums; using TelegramBotBase.Args; using TelegramBotBase.Form; @@ -12,13 +10,13 @@ namespace JoinHiderBot.forms public override async Task OnMemberChanges(MemberChangeEventArgs e) { - if (e.Type != Telegram.Bot.Types.Enums.MessageType.ChatMembersAdded && e.Type != Telegram.Bot.Types.Enums.MessageType.ChatMemberLeft) + if (e.Type != MessageType.ChatMembersAdded && e.Type != MessageType.ChatMemberLeft) return; var m = e.Result.Message; - await this.Device.DeleteMessage(m); + await Device.DeleteMessage(m); } } diff --git a/Examples/JoinHiderBot/forms/Start.cs b/Examples/JoinHiderBot/forms/Start.cs index aef4c7d..f506451 100644 --- a/Examples/JoinHiderBot/forms/Start.cs +++ b/Examples/JoinHiderBot/forms/Start.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; @@ -11,7 +8,7 @@ namespace JoinHiderBot.forms { public override async Task Open(MessageResult e) { - await this.Device.Send("This bot works only in groups."); + await Device.Send("This bot works only in groups."); return true; } @@ -20,7 +17,7 @@ namespace JoinHiderBot.forms { var gmf = new GroupManageForm(); - await this.NavigateTo(gmf); + await NavigateTo(gmf); return true; } diff --git a/Examples/SystemCommandsBot/Program.cs b/Examples/SystemCommandsBot/Program.cs index 17ff8b7..d0131f9 100644 --- a/Examples/SystemCommandsBot/Program.cs +++ b/Examples/SystemCommandsBot/Program.cs @@ -1,17 +1,19 @@ using System; +using SystemCommandsBot.config; +using SystemCommandsBot.forms; using TelegramBotBase.Builder; namespace SystemCommandsBot { - class Program + internal class Program { - public static config.Config BotConfig { get; set; } + public static Config BotConfig { get; set; } - static void Main(string[] args) + private static void Main(string[] args) { - BotConfig = config.Config.load(); + BotConfig = Config.Load(); if (BotConfig.ApiKey == null || BotConfig.ApiKey.Trim() == "") { @@ -21,7 +23,7 @@ namespace SystemCommandsBot } var bot = BotBaseBuilder.Create() - .QuickStart(BotConfig.ApiKey) + .QuickStart(BotConfig.ApiKey) .Build(); bot.Start(); diff --git a/Examples/SystemCommandsBot/commands/Commando.cs b/Examples/SystemCommandsBot/commands/Commando.cs index 97d6554..d93eb81 100644 --- a/Examples/SystemCommandsBot/commands/Commando.cs +++ b/Examples/SystemCommandsBot/commands/Commando.cs @@ -1,28 +1,23 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; - -namespace SystemCommandsBot.commands +namespace SystemCommandsBot.commands { public class Commando { - public int ID { get; set; } + public int Id { get; set; } - public String Title { get; set; } + public string Title { get; set; } - public String ShellCmd { get; set; } + public string ShellCmd { get; set; } public bool Enabled { get; set; } = true; - public String Action { get; set; } + public string Action { get; set; } public bool UseShell { get; set; } = true; public int? MaxInstances { get; set; } - public String ProcName + public string ProcName { get;set; } diff --git a/Examples/SystemCommandsBot/config/Config.cs b/Examples/SystemCommandsBot/config/Config.cs index 8300806..f63b8fc 100644 --- a/Examples/SystemCommandsBot/config/Config.cs +++ b/Examples/SystemCommandsBot/config/Config.cs @@ -1,36 +1,37 @@ using System; using System.Collections.Generic; using System.IO; -using System.Text; +using Newtonsoft.Json; +using SystemCommandsBot.commands; namespace SystemCommandsBot.config { public class Config { - public String Password { get; set; } + public string Password { get; set; } - public String ApiKey { get; set; } + public string ApiKey { get; set; } - public List Commandos { get; set; } + public List Commandos { get; set; } public Config() { - this.Commandos = new List(); + Commandos = new List(); } - public void loadDefaultValues() + public void LoadDefaultValues() { - this.ApiKey = ""; - this.Commandos.Add(new commands.Commando() { ID = 0, Enabled = true, Title = "Test Befehl", ShellCmd = "explorer.exe", Action = "start", MaxInstances = 2 }); + ApiKey = ""; + Commandos.Add(new Commando { Id = 0, Enabled = true, Title = "Test Befehl", ShellCmd = "explorer.exe", Action = "start", MaxInstances = 2 }); } - public static Config load() + public static Config Load() { try { - return load(AppContext.BaseDirectory + "config\\default.cfg"); + return Load(AppContext.BaseDirectory + "config\\default.cfg"); } @@ -42,16 +43,16 @@ namespace SystemCommandsBot.config } - public static Config load(String path) + public static Config Load(string path) { try { - var cfg = Newtonsoft.Json.JsonConvert.DeserializeObject(File.ReadAllText(path)) as Config; + var cfg = JsonConvert.DeserializeObject(File.ReadAllText(path)); return cfg; } - catch (DirectoryNotFoundException ex) + catch (DirectoryNotFoundException) { - DirectoryInfo di = new DirectoryInfo(path); + var di = new DirectoryInfo(path); if (!Directory.Exists(di.Parent.FullName)) { @@ -59,15 +60,15 @@ namespace SystemCommandsBot.config } var cfg = new Config(); - cfg.loadDefaultValues(); - cfg.save(path); + cfg.LoadDefaultValues(); + cfg.Save(path); return cfg; } - catch (FileNotFoundException ex) + catch (FileNotFoundException) { var cfg = new Config(); - cfg.loadDefaultValues(); - cfg.save(path); + cfg.LoadDefaultValues(); + cfg.Save(path); return cfg; } catch(Exception ex) @@ -77,11 +78,11 @@ namespace SystemCommandsBot.config return null; } - public void save(String path) + public void Save(string path) { try { - File.WriteAllText(path, Newtonsoft.Json.JsonConvert.SerializeObject(this)); + File.WriteAllText(path, JsonConvert.SerializeObject(this)); } catch { diff --git a/Examples/SystemCommandsBot/forms/CmdForm.cs b/Examples/SystemCommandsBot/forms/CmdForm.cs index 85a90ce..d42e713 100644 --- a/Examples/SystemCommandsBot/forms/CmdForm.cs +++ b/Examples/SystemCommandsBot/forms/CmdForm.cs @@ -1,31 +1,29 @@ using System; -using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; -using System.Text; using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; namespace SystemCommandsBot.forms { - public class CmdForm : TelegramBotBase.Form.AutoCleanForm + public class CmdForm : AutoCleanForm { public DateTime ExpiresAt { get; set; } public int? MessageId { get; set; } - public override async Task Load(MessageResult message) + public override Task Load(MessageResult message) { - + return Task.CompletedTask; } public override async Task Action(MessageResult message) { var btn = message.RawData; - int id = -1; + var id = -1; if (!int.TryParse(btn, out id)) { @@ -33,10 +31,10 @@ namespace SystemCommandsBot.forms return; } - var cmd = Program.BotConfig.Commandos.Where(a => a.Enabled && a.ID == id).FirstOrDefault(); + var cmd = Program.BotConfig.Commandos.Where(a => a.Enabled && a.Id == id).FirstOrDefault(); if (cmd == null) { - await this.Device.Send("Cmd nicht verfügbar."); + await Device.Send("Cmd nicht verfügbar."); return; } @@ -46,14 +44,14 @@ namespace SystemCommandsBot.forms { case "start": - FileInfo fi = new FileInfo(cmd.ShellCmd); + var fi = new FileInfo(cmd.ShellCmd); if (cmd.MaxInstances != null && cmd.MaxInstances >= 0) { if (Process.GetProcessesByName(cmd.ProcName).Count() >= cmd.MaxInstances) { - await this.Device.Send("Anwendung läuft bereits."); + await Device.Send("Anwendung läuft bereits."); await message.ConfirmAction("Anwendung läuft bereits."); return; @@ -61,14 +59,16 @@ namespace SystemCommandsBot.forms } - ProcessStartInfo psi = new ProcessStartInfo(); - psi.FileName = cmd.ShellCmd; - psi.WorkingDirectory = fi.DirectoryName; - psi.UseShellExecute = cmd.UseShell; + var psi = new ProcessStartInfo + { + FileName = cmd.ShellCmd, + WorkingDirectory = fi.DirectoryName, + UseShellExecute = cmd.UseShell + }; Process.Start(psi); - await this.Device.Send(fi.Name + " wurde gestarted."); + await Device.Send(fi.Name + " wurde gestarted."); await message.ConfirmAction(fi.Name + " wurde gestarted."); @@ -76,9 +76,9 @@ namespace SystemCommandsBot.forms case "kill": - FileInfo fi2 = new FileInfo(cmd.ShellCmd); + var fi2 = new FileInfo(cmd.ShellCmd); - String pros = fi2.Name.Replace(fi2.Extension, ""); + var pros = fi2.Name.Replace(fi2.Extension, ""); var proc = Process.GetProcessesByName(pros).ToList(); @@ -94,7 +94,7 @@ namespace SystemCommandsBot.forms } } - await this.Device.Send(fi2.Name + " wurde beendet."); + await Device.Send(fi2.Name + " wurde beendet."); await message.ConfirmAction(fi2.Name + " wurde beendet."); @@ -102,9 +102,9 @@ namespace SystemCommandsBot.forms case "restart": - FileInfo fi3 = new FileInfo(cmd.ShellCmd); + var fi3 = new FileInfo(cmd.ShellCmd); - String pros2 = fi3.Name.Replace(fi3.Extension, ""); + var pros2 = fi3.Name.Replace(fi3.Extension, ""); var proc2 = Process.GetProcessesByName(pros2).ToList(); @@ -120,17 +120,19 @@ namespace SystemCommandsBot.forms } } - FileInfo fi4 = new FileInfo(cmd.ShellCmd); + var fi4 = new FileInfo(cmd.ShellCmd); - ProcessStartInfo psi2 = new ProcessStartInfo(); - psi2.FileName = cmd.ShellCmd; - psi2.WorkingDirectory = fi4.DirectoryName; + var psi2 = new ProcessStartInfo + { + FileName = cmd.ShellCmd, + WorkingDirectory = fi4.DirectoryName + }; psi2.FileName = cmd.ShellCmd; psi2.UseShellExecute = cmd.UseShell; Process.Start(psi2); - await this.Device.Send(fi3.Name + " wurde neugestarted."); + await Device.Send(fi3.Name + " wurde neugestarted."); await message.ConfirmAction(fi3.Name + " wurde neugestarted."); @@ -151,15 +153,13 @@ namespace SystemCommandsBot.forms public override async Task Render(MessageResult message) { - if (this.MessageId == null) + if (MessageId == null) { - var buttons = Program.BotConfig.Commandos.Where(a => a.Enabled).Select(a => new ButtonBase(a.Title, a.ID.ToString())); + var buttons = Program.BotConfig.Commandos.Where(a => a.Enabled).Select(a => new ButtonBase(a.Title, a.Id.ToString())); - ButtonForm bf = new ButtonForm(); + var bf = new ButtonForm(); bf.AddSplitted(buttons, 1); - await this.Device.Send("Deine Optionen", bf); - - return; + await Device.Send("Deine Optionen", bf); } diff --git a/Examples/SystemCommandsBot/forms/StartForm.cs b/Examples/SystemCommandsBot/forms/StartForm.cs index c5e6597..ede4203 100644 --- a/Examples/SystemCommandsBot/forms/StartForm.cs +++ b/Examples/SystemCommandsBot/forms/StartForm.cs @@ -1,40 +1,39 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Threading.Tasks; using TelegramBotBase.Base; +using TelegramBotBase.Form; namespace SystemCommandsBot.forms { - public class StartForm : TelegramBotBase.Form.FormBase + public class StartForm : FormBase { - public String Password { get; set; } + public string Password { get; set; } - public override async Task Load(MessageResult message) + public override Task Load(MessageResult message) { var inp = message.MessageText; if (Program.BotConfig.Password == inp) { - this.Password = inp; + Password = inp; } - + return Task.CompletedTask; } public override async Task Render(MessageResult message) { - if (this.Password == null || this.Password.Trim() == "") + if (Password == null || Password.Trim() == "") { - await this.Device.Send("Bitte gib dein Passwort an."); + await Device.Send("Bitte gib dein Passwort an."); return; } - var cmd = new forms.CmdForm(); + var cmd = new CmdForm(); cmd.ExpiresAt = DateTime.Now.AddDays(14); - await this.NavigateTo(cmd); + await NavigateTo(cmd); } diff --git a/TelegramBotBase.Extensions.Images/ImageExtensions.cs b/TelegramBotBase.Extensions.Images/ImageExtensions.cs index 55ddbb2..314679c 100644 --- a/TelegramBotBase.Extensions.Images/ImageExtensions.cs +++ b/TelegramBotBase.Extensions.Images/ImageExtensions.cs @@ -1,12 +1,11 @@ -using System; -using System.Drawing; +using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Threading.Tasks; -using Telegram.Bot.Types.InputFiles; using Telegram.Bot.Types; -using TelegramBotBase.Sessions; +using Telegram.Bot.Types.InputFiles; using TelegramBotBase.Form; +using TelegramBotBase.Sessions; namespace TelegramBotBase.Extensions.Images { @@ -14,7 +13,7 @@ namespace TelegramBotBase.Extensions.Images { public static Stream ToStream(this Image image, ImageFormat format) { - var stream = new System.IO.MemoryStream(); + var stream = new MemoryStream(); image.Save(stream, format); stream.Position = 0; return stream; @@ -29,11 +28,11 @@ namespace TelegramBotBase.Extensions.Images /// /// /// - public static async Task SendPhoto(this DeviceSession session, Image image, String name, String caption, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) + public static async Task SendPhoto(this DeviceSession session, Image image, string name, string caption, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) { using (var fileStream = ToStream(image, ImageFormat.Png)) { - InputOnlineFile fts = new InputOnlineFile(fileStream, name); + var fts = new InputOnlineFile(fileStream, name); return await session.SendPhoto(fts, caption: caption, buttons, replyTo, disableNotification); } @@ -48,11 +47,11 @@ namespace TelegramBotBase.Extensions.Images /// /// /// - public static async Task SendPhoto(this DeviceSession session, Bitmap image, String name, String caption, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) + public static async Task SendPhoto(this DeviceSession session, Bitmap image, string name, string caption, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) { using (var fileStream = ToStream(image, ImageFormat.Png)) { - InputOnlineFile fts = new InputOnlineFile(fileStream, name); + var fts = new InputOnlineFile(fileStream, name); return await session.SendPhoto(fts, caption: caption, buttons, replyTo, disableNotification); } diff --git a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/BotBaseBuilderExtensions.cs b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/BotBaseBuilderExtensions.cs index fbf22db..06e1611 100644 --- a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/BotBaseBuilderExtensions.cs +++ b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/BotBaseBuilderExtensions.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using TelegramBotBase.Builder; using TelegramBotBase.Builder.Interfaces; @@ -15,13 +11,13 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL /// Uses an Microsoft SQL Server Database to save and restore sessions. /// /// - /// + /// /// /// /// - public static ILanguageSelectionStage UseSQLDatabase(this ISessionSerializationStage builder, String ConnectionString, Type fallbackForm = null, String tablePrefix = "tgb_") + public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string connectionString, Type fallbackForm = null, string tablePrefix = "tgb_") { - var serializer = new MSSQLSerializer(ConnectionString, tablePrefix, fallbackForm); + var serializer = new MssqlSerializer(connectionString, tablePrefix, fallbackForm); builder.UseSerialization(serializer); @@ -33,18 +29,18 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL /// Uses an Microsoft SQL Server Database to save and restore sessions. /// /// - /// - /// - /// - /// + /// + /// + /// + /// /// /// /// - public static ILanguageSelectionStage UseSQLDatabase(this ISessionSerializationStage builder, String HostOrIP, String DatabaseName, String UserId, String Password, Type fallbackForm = null, String tablePrefix = "tgb_") + public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string hostOrIP, string databaseName, string userId, string password, Type fallbackForm = null, string tablePrefix = "tgb_") { - var connectionString = $"Server={HostOrIP}; Database={DatabaseName}; User Id={UserId}; Password={Password}; TrustServerCertificate=true;"; + var connectionString = $"Server={hostOrIP}; Database={databaseName}; User Id={userId}; Password={password}; TrustServerCertificate=true;"; - var serializer = new MSSQLSerializer(connectionString, tablePrefix, fallbackForm); + var serializer = new MssqlSerializer(connectionString, tablePrefix, fallbackForm); builder.UseSerialization(serializer); @@ -55,19 +51,19 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL /// Uses an Microsoft SQL Server Database with Windows Authentication to save and restore sessions. /// /// - /// - /// + /// + /// /// /// /// - public static ILanguageSelectionStage UseSQLDatabase(this ISessionSerializationStage builder, String HostOrIP, String DatabaseName, bool IntegratedSecurity = true, Type fallbackForm = null, String tablePrefix = "tgb_") + public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string hostOrIP, string databaseName, bool integratedSecurity = true, Type fallbackForm = null, string tablePrefix = "tgb_") { - if (!IntegratedSecurity) + if (!integratedSecurity) throw new ArgumentOutOfRangeException(); - var connectionString = $"Server={HostOrIP}; Database={DatabaseName}; Integrated Security=true; TrustServerCertificate=true;"; + var connectionString = $"Server={hostOrIP}; Database={databaseName}; Integrated Security=true; TrustServerCertificate=true;"; - var serializer = new MSSQLSerializer(connectionString, tablePrefix, fallbackForm); + var serializer = new MssqlSerializer(connectionString, tablePrefix, fallbackForm); builder.UseSerialization(serializer); diff --git a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/MSSQLSerializer.cs b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/MSSQLSerializer.cs index 5aca6e4..fe271e0 100644 --- a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/MSSQLSerializer.cs +++ b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/MSSQLSerializer.cs @@ -1,19 +1,19 @@ -using TelegramBotBase.Interfaces; -using TelegramBotBase.Builder.Interfaces; -using System; -using TelegramBotBase.Base; -using TelegramBotBase.Args; -using TelegramBotBase.Form; -using Microsoft.Data.SqlClient; +using System; using System.Data; +using Microsoft.Data.SqlClient; +using Newtonsoft.Json; +using TelegramBotBase.Args; +using TelegramBotBase.Base; +using TelegramBotBase.Form; +using TelegramBotBase.Interfaces; namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL { - public class MSSQLSerializer : IStateMachine + public class MssqlSerializer : IStateMachine { public Type FallbackStateForm { get; set; } public string ConnectionString { get; } - public String TablePrefix { get; set; } + public string TablePrefix { get; set; } /// /// Will initialize the state machine. @@ -21,20 +21,15 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL /// Path of the file and name where to save the session details. /// Type of Form which will be saved instead of Form which has attribute declared. Needs to be subclass of . /// Declares of the file could be overwritten. - public MSSQLSerializer(String ConnectionString, String tablePrefix = "tgb_", Type fallbackStateForm = null) + public MssqlSerializer(string connectionString, string tablePrefix = "tgb_", Type fallbackStateForm = null) { - if (ConnectionString is null) - { - throw new ArgumentNullException(nameof(ConnectionString)); - } + this.ConnectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString)); - this.ConnectionString = ConnectionString; + TablePrefix = tablePrefix; - this.TablePrefix = tablePrefix; + FallbackStateForm = fallbackStateForm; - this.FallbackStateForm = fallbackStateForm; - - if (this.FallbackStateForm != null && !this.FallbackStateForm.IsSubclassOf(typeof(FormBase))) + if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase))) { throw new ArgumentException("FallbackStateForm is not a subclass of FormBase"); } @@ -58,7 +53,7 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL foreach (DataRow r in dataTable.Rows) { - var se = new StateEntry() + var se = new StateEntry { DeviceId = (long)r["deviceId"], ChatTitle = r["deviceTitle"].ToString(), @@ -77,21 +72,21 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL sc.GroupIds.Add(se.DeviceId); } - var data_command = connection.CreateCommand(); - data_command.CommandText = "SELECT [key], value, type FROM " + TablePrefix + "devices_sessions_data WHERE deviceId = @deviceId"; - data_command.Parameters.Add(new SqlParameter("@deviceId", r["deviceId"])); + var command2 = connection.CreateCommand(); + command2.CommandText = "SELECT [key], value, type FROM " + TablePrefix + "devices_sessions_data WHERE deviceId = @deviceId"; + command2.Parameters.Add(new SqlParameter("@deviceId", r["deviceId"])); - var data_table = new DataTable(); - using (var dataAdapter2 = new SqlDataAdapter(data_command)) + var dataTable2 = new DataTable(); + using (var dataAdapter2 = new SqlDataAdapter(command2)) { - dataAdapter2.Fill(data_table); + dataAdapter2.Fill(dataTable2); - foreach (DataRow r2 in data_table.Rows) + foreach (DataRow r2 in dataTable2.Rows) { var key = r2["key"].ToString(); var type = Type.GetType(r2["type"].ToString()); - var value = Newtonsoft.Json.JsonConvert.DeserializeObject(r2["value"].ToString(), type); + var value = JsonConvert.DeserializeObject(r2["value"].ToString(), type); se.Values.Add(key, value); } @@ -118,61 +113,61 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL connection.Open(); //Cleanup old Session data - var clear_command = connection.CreateCommand(); + var clearCommand = connection.CreateCommand(); - clear_command.CommandText = $"DELETE FROM {TablePrefix}devices_sessions_data"; + clearCommand.CommandText = $"DELETE FROM {TablePrefix}devices_sessions_data"; - clear_command.ExecuteNonQuery(); + clearCommand.ExecuteNonQuery(); - clear_command.CommandText = $"DELETE FROM {TablePrefix}devices_sessions"; + clearCommand.CommandText = $"DELETE FROM {TablePrefix}devices_sessions"; - clear_command.ExecuteNonQuery(); + clearCommand.ExecuteNonQuery(); //Prepare new session commands - var session_command = connection.CreateCommand(); - var data_command = connection.CreateCommand(); + var sessionCommand = connection.CreateCommand(); + var dataCommand = connection.CreateCommand(); - session_command.CommandText = "INSERT INTO " + TablePrefix + "devices_sessions (deviceId, deviceTitle, FormUri, QualifiedName) VALUES (@deviceId, @deviceTitle, @FormUri, @QualifiedName)"; - session_command.Parameters.Add(new SqlParameter("@deviceId", "")); - session_command.Parameters.Add(new SqlParameter("@deviceTitle", "")); - session_command.Parameters.Add(new SqlParameter("@FormUri", "")); - session_command.Parameters.Add(new SqlParameter("@QualifiedName", "")); + sessionCommand.CommandText = "INSERT INTO " + TablePrefix + "devices_sessions (deviceId, deviceTitle, FormUri, QualifiedName) VALUES (@deviceId, @deviceTitle, @FormUri, @QualifiedName)"; + sessionCommand.Parameters.Add(new SqlParameter("@deviceId", "")); + sessionCommand.Parameters.Add(new SqlParameter("@deviceTitle", "")); + sessionCommand.Parameters.Add(new SqlParameter("@FormUri", "")); + sessionCommand.Parameters.Add(new SqlParameter("@QualifiedName", "")); - data_command.CommandText = "INSERT INTO " + TablePrefix + "devices_sessions_data (deviceId, [key], value, type) VALUES (@deviceId, @key, @value, @type)"; - data_command.Parameters.Add(new SqlParameter("@deviceId", "")); - data_command.Parameters.Add(new SqlParameter("@key", "")); - data_command.Parameters.Add(new SqlParameter("@value", "")); - data_command.Parameters.Add(new SqlParameter("@type", "")); + dataCommand.CommandText = "INSERT INTO " + TablePrefix + "devices_sessions_data (deviceId, [key], value, type) VALUES (@deviceId, @key, @value, @type)"; + dataCommand.Parameters.Add(new SqlParameter("@deviceId", "")); + dataCommand.Parameters.Add(new SqlParameter("@key", "")); + dataCommand.Parameters.Add(new SqlParameter("@value", "")); + dataCommand.Parameters.Add(new SqlParameter("@type", "")); //Store session data in database foreach (var state in container.States) { - session_command.Parameters["@deviceId"].Value = state.DeviceId; - session_command.Parameters["@deviceTitle"].Value = state.ChatTitle ?? ""; - session_command.Parameters["@FormUri"].Value = state.FormUri; - session_command.Parameters["@QualifiedName"].Value = state.QualifiedName; + sessionCommand.Parameters["@deviceId"].Value = state.DeviceId; + sessionCommand.Parameters["@deviceTitle"].Value = state.ChatTitle ?? ""; + sessionCommand.Parameters["@FormUri"].Value = state.FormUri; + sessionCommand.Parameters["@QualifiedName"].Value = state.QualifiedName; - session_command.ExecuteNonQuery(); + sessionCommand.ExecuteNonQuery(); foreach (var data in state.Values) { - data_command.Parameters["@deviceId"].Value = state.DeviceId; - data_command.Parameters["@key"].Value = data.Key; + dataCommand.Parameters["@deviceId"].Value = state.DeviceId; + dataCommand.Parameters["@key"].Value = data.Key; var type = data.Value.GetType(); - + if (type.IsPrimitive || type.Equals(typeof(string))) { - data_command.Parameters["@value"].Value = data.Value; + dataCommand.Parameters["@value"].Value = data.Value; } else { - data_command.Parameters["@value"].Value = Newtonsoft.Json.JsonConvert.SerializeObject(data.Value); + dataCommand.Parameters["@value"].Value = JsonConvert.SerializeObject(data.Value); } - - data_command.Parameters["@type"].Value = type.AssemblyQualifiedName; - data_command.ExecuteNonQuery(); + dataCommand.Parameters["@type"].Value = type.AssemblyQualifiedName; + + dataCommand.ExecuteNonQuery(); } } @@ -183,4 +178,4 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL } } -} \ No newline at end of file +} diff --git a/TelegramBotBase.Test/Program.cs b/TelegramBotBase.Test/Program.cs index 8b76b97..a1d4b31 100644 --- a/TelegramBotBase.Test/Program.cs +++ b/TelegramBotBase.Test/Program.cs @@ -1,27 +1,24 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading.Tasks; -using Telegram.Bot.Types; -using TelegramBotBase; -using TelegramBotBase.Form; -using TelegramBotBaseTest.Tests; -using TelegramBotBase.Commands; +using TelegramBotBase.Args; using TelegramBotBase.Builder; +using TelegramBotBase.Commands; +using TelegramBotBase.Enums; +using TelegramBotBaseTest.Tests; namespace TelegramBotBaseTest { - class Program + internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { - String APIKey = ""; + var apiKey = ""; var bb = BotBaseBuilder .Create() - .WithAPIKey(APIKey) + .WithAPIKey(apiKey) .DefaultMessageLoop() .WithStartForm() .NoProxy() @@ -45,7 +42,7 @@ namespace TelegramBotBaseTest //Update Bot commands to botfather bb.UploadBotCommands().Wait(); - bb.SetSetting(TelegramBotBase.Enums.eSettings.LogAllMessages, true); + bb.SetSetting(ESettings.LogAllMessages, true); bb.Message += (s, en) => { @@ -65,7 +62,7 @@ namespace TelegramBotBaseTest } - private static async Task Bb_BotCommand(object sender, TelegramBotBase.Args.BotCommandEventArgs en) + private static async Task Bb_BotCommand(object sender, BotCommandEventArgs en) { switch (en.Command) { @@ -105,7 +102,7 @@ namespace TelegramBotBaseTest case "/params": - String m = en.Parameters.DefaultIfEmpty("").Aggregate((a, b) => a + " and " + b); + var m = en.Parameters.DefaultIfEmpty("").Aggregate((a, b) => a + " and " + b); await en.Device.Send("Your parameters are: " + m, replyTo: en.Device.LastMessageId); diff --git a/TelegramBotBase.Test/Properties/AssemblyInfo.cs b/TelegramBotBase.Test/Properties/AssemblyInfo.cs index e9d23b8..53a2683 100644 --- a/TelegramBotBase.Test/Properties/AssemblyInfo.cs +++ b/TelegramBotBase.Test/Properties/AssemblyInfo.cs @@ -1,5 +1,4 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden diff --git a/TelegramBotBase.Test/Tests/ButtonTestForm.cs b/TelegramBotBase.Test/Tests/ButtonTestForm.cs index ca41320..8f89af6 100644 --- a/TelegramBotBase.Test/Tests/ButtonTestForm.cs +++ b/TelegramBotBase.Test/Tests/ButtonTestForm.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; @@ -13,12 +10,12 @@ namespace TelegramBotBaseTest.Tests public ButtonTestForm() { - this.Opened += ButtonTestForm_Opened; + Opened += ButtonTestForm_Opened; } private async Task ButtonTestForm_Opened(object sender, EventArgs e) { - await this.Device.Send("Hello world! (Click 'back' to get back to Start)"); + await Device.Send("Hello world! (Click 'back' to get back to Start)"); } public override async Task Action(MessageResult message) @@ -38,25 +35,25 @@ namespace TelegramBotBaseTest.Tests { case "button1": - await this.Device.Send("Button 1 pressed"); + await Device.Send("Button 1 pressed"); break; case "button2": - await this.Device.Send("Button 2 pressed"); + await Device.Send("Button 2 pressed"); break; case "button3": - await this.Device.Send("Button 3 pressed"); + await Device.Send("Button 3 pressed"); break; case "button4": - await this.Device.Send("Button 4 pressed"); + await Device.Send("Button 4 pressed"); break; @@ -64,7 +61,7 @@ namespace TelegramBotBaseTest.Tests var st = new Menu(); - await this.NavigateTo(st); + await NavigateTo(st); break; @@ -82,7 +79,7 @@ namespace TelegramBotBaseTest.Tests public override async Task Render(MessageResult message) { - ButtonForm btn = new ButtonForm(); + var btn = new ButtonForm(); btn.AddButtonRow(new ButtonBase("Button 1", new CallbackData("a", "button1").Serialize()), new ButtonBase("Button 2", new CallbackData("a", "button2").Serialize())); @@ -92,7 +89,7 @@ namespace TelegramBotBaseTest.Tests btn.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "back").Serialize())); - await this.Device.Send("Click a button", btn); + await Device.Send("Click a button", btn); } diff --git a/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs b/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs index 01da851..3a7bdd9 100644 --- a/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs @@ -1,34 +1,30 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TelegramBotBase.Args; -using TelegramBotBase.Controls; using TelegramBotBase.Controls.Hybrid; +using TelegramBotBase.Enums; using TelegramBotBase.Form; namespace TelegramBotBaseTest.Tests.Controls { public class ButtonGridForm : AutoCleanForm { - - ButtonGrid m_Buttons = null; + private ButtonGrid _mButtons; public ButtonGridForm() { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; + DeleteMode = EDeleteMode.OnLeavingForm; - this.Init += ButtonGridForm_Init; + Init += ButtonGridForm_Init; } - private async Task ButtonGridForm_Init(object sender, InitEventArgs e) + private Task ButtonGridForm_Init(object sender, InitEventArgs e) { - m_Buttons = new ButtonGrid(); + _mButtons = new ButtonGrid + { + KeyboardType = EKeyboardType.InlineKeyBoard + }; - m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.InlineKeyBoard; - - ButtonForm bf = new ButtonForm(); + var bf = new ButtonForm(); bf.AddButtonRow(new ButtonBase("Back", "back"), new ButtonBase("Switch Keyboard", "switch")); @@ -36,13 +32,12 @@ namespace TelegramBotBaseTest.Tests.Controls bf.AddButtonRow(new ButtonBase("Button3", "b3"), new ButtonBase("Button4", "b4")); - m_Buttons.ButtonsForm = bf; - - m_Buttons.ButtonClicked += Bg_ButtonClicked; - - this.AddControl(m_Buttons); + _mButtons.ButtonsForm = bf; + _mButtons.ButtonClicked += Bg_ButtonClicked; + AddControl(_mButtons); + return Task.CompletedTask; } private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) @@ -53,26 +48,21 @@ namespace TelegramBotBaseTest.Tests.Controls if (e.Button.Value == "back") { var start = new Menu(); - await this.NavigateTo(start); + await NavigateTo(start); } else if (e.Button.Value == "switch") { - switch (m_Buttons.KeyboardType) + _mButtons.KeyboardType = _mButtons.KeyboardType switch { - case TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard: - m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.InlineKeyBoard; - break; - case TelegramBotBase.Enums.eKeyboardType.InlineKeyBoard: - m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard; - break; - } - - + EKeyboardType.ReplyKeyboard => EKeyboardType.InlineKeyBoard, + EKeyboardType.InlineKeyBoard => EKeyboardType.ReplyKeyboard, + _ => _mButtons.KeyboardType + }; } else { - await this.Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); + await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); } diff --git a/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs b/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs index 49239cd..cc62321 100644 --- a/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs @@ -1,55 +1,49 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Globalization; -using System.Linq; -using System.Text; using System.Threading.Tasks; using TelegramBotBase.Args; -using TelegramBotBase.Controls; using TelegramBotBase.Controls.Hybrid; +using TelegramBotBase.Enums; using TelegramBotBase.Form; namespace TelegramBotBaseTest.Tests.Controls { public class ButtonGridPagingForm : AutoCleanForm { - - ButtonGrid m_Buttons = null; + private ButtonGrid _mButtons; public ButtonGridPagingForm() { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; + DeleteMode = EDeleteMode.OnLeavingForm; - this.Init += ButtonGridForm_Init; + Init += ButtonGridForm_Init; } - private async Task ButtonGridForm_Init(object sender, InitEventArgs e) + private Task ButtonGridForm_Init(object sender, InitEventArgs e) { - m_Buttons = new ButtonGrid(); - - m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard; - - m_Buttons.EnablePaging = true; - m_Buttons.EnableSearch = true; - - m_Buttons.HeadLayoutButtonRow = new List() { new ButtonBase("Back", "back") }; + _mButtons = new ButtonGrid + { + KeyboardType = EKeyboardType.ReplyKeyboard, + EnablePaging = true, + EnableSearch = true, + HeadLayoutButtonRow = new List { new ButtonBase("Back", "back") } + }; var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures); - ButtonForm bf = new ButtonForm(); + var bf = new ButtonForm(); foreach (var c in countries) { bf.AddButtonRow(new ButtonBase(c.EnglishName, c.EnglishName)); } - m_Buttons.ButtonsForm = bf; - - m_Buttons.ButtonClicked += Bg_ButtonClicked; - - this.AddControl(m_Buttons); + _mButtons.ButtonsForm = bf; + _mButtons.ButtonClicked += Bg_ButtonClicked; + AddControl(_mButtons); + return Task.CompletedTask; } private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) @@ -60,12 +54,12 @@ namespace TelegramBotBaseTest.Tests.Controls if (e.Button.Value == "back") { var start = new Menu(); - await this.NavigateTo(start); + await NavigateTo(start); } else { - await this.Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); + await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); } diff --git a/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs b/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs index c737d10..510f208 100644 --- a/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs @@ -1,58 +1,56 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Globalization; using System.Linq; -using System.Text; using System.Threading.Tasks; using TelegramBotBase.Args; -using TelegramBotBase.Controls; using TelegramBotBase.Controls.Hybrid; +using TelegramBotBase.DataSources; +using TelegramBotBase.Enums; using TelegramBotBase.Form; namespace TelegramBotBaseTest.Tests.Controls { public class ButtonGridTagForm : AutoCleanForm { - - TaggedButtonGrid m_Buttons = null; + private TaggedButtonGrid _mButtons; public ButtonGridTagForm() { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; + DeleteMode = EDeleteMode.OnLeavingForm; - this.Init += ButtonGridTagForm_Init; + Init += ButtonGridTagForm_Init; } - private async Task ButtonGridTagForm_Init(object sender, InitEventArgs e) + private Task ButtonGridTagForm_Init(object sender, InitEventArgs e) { - m_Buttons = new TaggedButtonGrid(); + _mButtons = new TaggedButtonGrid + { + KeyboardType = EKeyboardType.ReplyKeyboard, + EnablePaging = true, + HeadLayoutButtonRow = new List { new ButtonBase("Back", "back") } + }; - m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard; - - m_Buttons.EnablePaging = true; - - m_Buttons.HeadLayoutButtonRow = new List() { new ButtonBase("Back", "back") }; - var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures); - ButtonForm bf = new ButtonForm(); + var bf = new ButtonForm(); foreach (var c in countries) { bf.AddButtonRow(new TagButtonBase(c.EnglishName, c.EnglishName, c.Parent.EnglishName)); } - m_Buttons.Tags = countries.Select(a => a.Parent.EnglishName).Distinct().OrderBy(a => a).ToList(); - m_Buttons.SelectedTags = countries.Select(a => a.Parent.EnglishName).Distinct().OrderBy(a => a).ToList(); + _mButtons.Tags = countries.Select(a => a.Parent.EnglishName).Distinct().OrderBy(a => a).ToList(); + _mButtons.SelectedTags = countries.Select(a => a.Parent.EnglishName).Distinct().OrderBy(a => a).ToList(); - m_Buttons.EnableCheckAllTools = true; + _mButtons.EnableCheckAllTools = true; - m_Buttons.DataSource = new TelegramBotBase.Datasources.ButtonFormDataSource(bf); + _mButtons.DataSource = new ButtonFormDataSource(bf); - m_Buttons.ButtonClicked += Bg_ButtonClicked; + _mButtons.ButtonClicked += Bg_ButtonClicked; - this.AddControl(m_Buttons); + AddControl(_mButtons); + return Task.CompletedTask; } private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) @@ -65,13 +63,13 @@ namespace TelegramBotBaseTest.Tests.Controls case "back": var start = new Menu(); - await this.NavigateTo(start); + await NavigateTo(start); return; } - await this.Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); + await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); } } } diff --git a/TelegramBotBase.Test/Tests/Controls/CalendarPickerForm.cs b/TelegramBotBase.Test/Tests/Controls/CalendarPickerForm.cs index 261cda8..4d1eaac 100644 --- a/TelegramBotBase.Test/Tests/Controls/CalendarPickerForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/CalendarPickerForm.cs @@ -1,14 +1,9 @@ -using System; - -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using TelegramBotBase.Base; -using TelegramBotBase.Form; -using TelegramBotBase.Controls; +using System.Threading.Tasks; using TelegramBotBase.Args; +using TelegramBotBase.Base; using TelegramBotBase.Controls.Inline; +using TelegramBotBase.Enums; +using TelegramBotBase.Form; namespace TelegramBotBaseTest.Tests.Controls { @@ -17,20 +12,23 @@ namespace TelegramBotBaseTest.Tests.Controls public CalendarPicker Picker { get; set; } - int? selectedDateMessage { get; set; } + private int? SelectedDateMessage { get; set; } public CalendarPickerForm() { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; - this.Init += CalendarPickerForm_Init; + DeleteMode = EDeleteMode.OnLeavingForm; + Init += CalendarPickerForm_Init; } - private async Task CalendarPickerForm_Init(object sender, InitEventArgs e) + private Task CalendarPickerForm_Init(object sender, InitEventArgs e) { - this.Picker = new CalendarPicker(); - this.Picker.Title = "Datum auswählen / Pick date"; - - this.AddControl(Picker); + Picker = new CalendarPicker + { + Title = "Datum auswählen / Pick date" + }; + + AddControl(Picker); + return Task.CompletedTask; } @@ -43,7 +41,7 @@ namespace TelegramBotBaseTest.Tests.Controls var s = new Menu(); - await this.NavigateTo(s); + await NavigateTo(s); break; } @@ -52,23 +50,23 @@ namespace TelegramBotBaseTest.Tests.Controls public override async Task Render(MessageResult message) { - String s = ""; + var s = ""; - s = "Selected date is " + this.Picker.SelectedDate.ToShortDateString() + "\r\n"; - s += "Selected month is " + this.Picker.Culture.DateTimeFormat.MonthNames[this.Picker.VisibleMonth.Month - 1] + "\r\n"; - s += "Selected year is " + this.Picker.VisibleMonth.Year.ToString(); + s = "Selected date is " + Picker.SelectedDate.ToShortDateString() + "\r\n"; + s += "Selected month is " + Picker.Culture.DateTimeFormat.MonthNames[Picker.VisibleMonth.Month - 1] + "\r\n"; + s += "Selected year is " + Picker.VisibleMonth.Year; - ButtonForm bf = new ButtonForm(); + var bf = new ButtonForm(); bf.AddButtonRow(new ButtonBase("Back","back")); - if (selectedDateMessage != null) + if (SelectedDateMessage != null) { - await this.Device.Edit(this.selectedDateMessage.Value, s, bf); + await Device.Edit(SelectedDateMessage.Value, s, bf); } else { - var m = await this.Device.Send(s, bf); - this.selectedDateMessage = m.MessageId; + var m = await Device.Send(s, bf); + SelectedDateMessage = m.MessageId; } diff --git a/TelegramBotBase.Test/Tests/Controls/CheckedButtonListForm.cs b/TelegramBotBase.Test/Tests/Controls/CheckedButtonListForm.cs index eeeae3a..6906c4f 100644 --- a/TelegramBotBase.Test/Tests/Controls/CheckedButtonListForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/CheckedButtonListForm.cs @@ -1,56 +1,54 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System.Collections.Generic; using System.Threading.Tasks; using TelegramBotBase.Args; -using TelegramBotBase.Controls; using TelegramBotBase.Controls.Hybrid; +using TelegramBotBase.DataSources; +using TelegramBotBase.Enums; using TelegramBotBase.Form; namespace TelegramBotBaseTest.Tests.Controls { public class CheckedButtonListForm : AutoCleanForm { - - CheckedButtonList m_Buttons = null; + private CheckedButtonList _mButtons; public CheckedButtonListForm() { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; + DeleteMode = EDeleteMode.OnLeavingForm; - this.Init += CheckedButtonListForm_Init; + Init += CheckedButtonListForm_Init; } - private async Task CheckedButtonListForm_Init(object sender, InitEventArgs e) + private Task CheckedButtonListForm_Init(object sender, InitEventArgs e) { - m_Buttons = new CheckedButtonList(); + _mButtons = new CheckedButtonList + { + KeyboardType = EKeyboardType.InlineKeyBoard, + EnablePaging = true, + HeadLayoutButtonRow = new List { new ButtonBase("Back", "back"), new ButtonBase("Switch Keyboard", "switch") }, + SubHeadLayoutButtonRow = new List { new ButtonBase("No checked items", "$") } + }; - m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.InlineKeyBoard; - m_Buttons.EnablePaging = true; + var bf = new ButtonForm(); - m_Buttons.HeadLayoutButtonRow = new List() { new ButtonBase("Back", "back"), new ButtonBase("Switch Keyboard", "switch") }; - - m_Buttons.SubHeadLayoutButtonRow = new List() { new ButtonBase("No checked items", "$") }; - - ButtonForm bf = new ButtonForm(); - - for (int i = 0; i < 30; i++) + for (var i = 0; i < 30; i++) { bf.AddButtonRow($"{i + 1}. Item", i.ToString()); } - m_Buttons.DataSource = new TelegramBotBase.Datasources.ButtonFormDataSource(bf); + _mButtons.DataSource = new ButtonFormDataSource(bf); - m_Buttons.ButtonClicked += Bg_ButtonClicked; - m_Buttons.CheckedChanged += M_Buttons_CheckedChanged; + _mButtons.ButtonClicked += Bg_ButtonClicked; + _mButtons.CheckedChanged += M_Buttons_CheckedChanged; - this.AddControl(m_Buttons); + AddControl(_mButtons); + return Task.CompletedTask; } - private async Task M_Buttons_CheckedChanged(object sender, CheckedChangedEventArgs e) + private Task M_Buttons_CheckedChanged(object sender, CheckedChangedEventArgs e) { - m_Buttons.SubHeadLayoutButtonRow = new List() { new ButtonBase($"{m_Buttons.CheckedItems.Count} checked items", "$") }; + _mButtons.SubHeadLayoutButtonRow = new List { new ButtonBase($"{_mButtons.CheckedItems.Count} checked items", "$") }; + return Task.CompletedTask; } private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) @@ -68,16 +66,12 @@ namespace TelegramBotBaseTest.Tests.Controls case "switch": - switch (m_Buttons.KeyboardType) + _mButtons.KeyboardType = _mButtons.KeyboardType switch { - case TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard: - m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.InlineKeyBoard; - break; - case TelegramBotBase.Enums.eKeyboardType.InlineKeyBoard: - m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard; - break; - } - + EKeyboardType.ReplyKeyboard => EKeyboardType.InlineKeyBoard, + EKeyboardType.InlineKeyBoard => EKeyboardType.ReplyKeyboard, + _ => _mButtons.KeyboardType + }; break; diff --git a/TelegramBotBase.Test/Tests/Controls/MonthPickerForm.cs b/TelegramBotBase.Test/Tests/Controls/MonthPickerForm.cs index a5973e0..3774430 100644 --- a/TelegramBotBase.Test/Tests/Controls/MonthPickerForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/MonthPickerForm.cs @@ -1,14 +1,9 @@ -using System; - -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using TelegramBotBase.Base; -using TelegramBotBase.Form; -using TelegramBotBase.Controls; +using System.Threading.Tasks; using TelegramBotBase.Args; +using TelegramBotBase.Base; using TelegramBotBase.Controls.Inline; +using TelegramBotBase.Enums; +using TelegramBotBase.Form; namespace TelegramBotBaseTest.Tests.Controls { @@ -17,19 +12,22 @@ namespace TelegramBotBaseTest.Tests.Controls public MonthPicker Picker { get; set; } - int? selectedDateMessage { get; set; } + private int? SelectedDateMessage { get; set; } public MonthPickerForm() { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; - this.Init += MonthPickerForm_Init; + DeleteMode = EDeleteMode.OnLeavingForm; + Init += MonthPickerForm_Init; } - private async Task MonthPickerForm_Init(object sender, InitEventArgs e) + private Task MonthPickerForm_Init(object sender, InitEventArgs e) { - this.Picker = new MonthPicker(); - this.Picker.Title = "Monat auswählen / Pick month"; - this.AddControl(Picker); + Picker = new MonthPicker + { + Title = "Monat auswählen / Pick month" + }; + AddControl(Picker); + return Task.CompletedTask; } @@ -42,7 +40,7 @@ namespace TelegramBotBaseTest.Tests.Controls var s = new Menu(); - await this.NavigateTo(s); + await NavigateTo(s); break; } @@ -51,22 +49,22 @@ namespace TelegramBotBaseTest.Tests.Controls public override async Task Render(MessageResult message) { - String s = ""; + var s = ""; - s += "Selected month is " + this.Picker.Culture.DateTimeFormat.MonthNames[this.Picker.SelectedDate.Month - 1] + "\r\n"; - s += "Selected year is " + this.Picker.VisibleMonth.Year.ToString(); + s += "Selected month is " + Picker.Culture.DateTimeFormat.MonthNames[Picker.SelectedDate.Month - 1] + "\r\n"; + s += "Selected year is " + Picker.VisibleMonth.Year; - ButtonForm bf = new ButtonForm(); + var bf = new ButtonForm(); bf.AddButtonRow(new ButtonBase("Back","back")); - if (selectedDateMessage != null) + if (SelectedDateMessage != null) { - await this.Device.Edit(this.selectedDateMessage.Value, s, bf); + await Device.Edit(SelectedDateMessage.Value, s, bf); } else { - var m = await this.Device.Send(s, bf); - this.selectedDateMessage = m.MessageId; + var m = await Device.Send(s, bf); + SelectedDateMessage = m.MessageId; } diff --git a/TelegramBotBase.Test/Tests/Controls/MultiToggleButtons.cs b/TelegramBotBase.Test/Tests/Controls/MultiToggleButtons.cs index b38abb4..dfa774f 100644 --- a/TelegramBotBase.Test/Tests/Controls/MultiToggleButtons.cs +++ b/TelegramBotBase.Test/Tests/Controls/MultiToggleButtons.cs @@ -1,11 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading.Tasks; using TelegramBotBase.Args; -using TelegramBotBase.Controls; using TelegramBotBase.Controls.Inline; +using TelegramBotBase.Enums; using TelegramBotBase.Form; namespace TelegramBotBaseTest.Tests.Controls @@ -14,28 +13,33 @@ namespace TelegramBotBaseTest.Tests.Controls { public MultiToggleButtons() { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; + DeleteMode = EDeleteMode.OnLeavingForm; - this.Init += ToggleButtons_Init; + Init += ToggleButtons_Init; } - private async Task ToggleButtons_Init(object sender, InitEventArgs e) + private Task ToggleButtons_Init(object sender, InitEventArgs e) { - var mtb = new MultiToggleButton(); + var mtb = new MultiToggleButton + { + Options = new List { new ButtonBase("Option 1", "1"), new ButtonBase("Option 2", "2"), new ButtonBase("Option 3", "3") } + }; - mtb.Options = new List() { new ButtonBase("Option 1", "1"), new ButtonBase("Option 2", "2"), new ButtonBase("Option 3", "3") }; mtb.SelectedOption = mtb.Options.FirstOrDefault(); mtb.Toggled += Tb_Toggled; - this.AddControl(mtb); + AddControl(mtb); - mtb = new MultiToggleButton(); + mtb = new MultiToggleButton + { + Options = new List { new ButtonBase("Option 4", "4"), new ButtonBase("Option 5", "5"), new ButtonBase("Option 6", "6") } + }; - mtb.Options = new List() { new ButtonBase("Option 4", "4"), new ButtonBase("Option 5", "5"), new ButtonBase("Option 6", "6") }; mtb.SelectedOption = mtb.Options.FirstOrDefault(); mtb.AllowEmptySelection = false; mtb.Toggled += Tb_Toggled; - this.AddControl(mtb); + AddControl(mtb); + return Task.CompletedTask; } private void Tb_Toggled(object sender, EventArgs e) @@ -43,11 +47,11 @@ namespace TelegramBotBaseTest.Tests.Controls var tb = sender as MultiToggleButton; if (tb.SelectedOption != null) { - Console.WriteLine(tb.ID.ToString() + " was pressed, and toggled to " + tb.SelectedOption.Value); + Console.WriteLine(tb.Id + " was pressed, and toggled to " + tb.SelectedOption.Value); return; } - Console.WriteLine("Selection for " + tb.ID.ToString() + " has been removed."); + Console.WriteLine("Selection for " + tb.Id + " has been removed."); } } } diff --git a/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs b/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs index fccdfcb..e5f6431 100644 --- a/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs @@ -1,41 +1,42 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using TelegramBotBase.Base; +using System.Threading.Tasks; +using TelegramBotBase.Args; using TelegramBotBase.Controls.Hybrid; +using TelegramBotBase.Enums; using TelegramBotBase.Form; +using TelegramBotBaseTest.Tests.Controls.Subclass; namespace TelegramBotBaseTest.Tests.Controls { public class MultiViewForm : AutoCleanForm { + private MultiViewTest _mvt; - Subclass.MultiViewTest mvt = null; - - ButtonGrid bg = null; + private ButtonGrid _bg; public MultiViewForm() { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; - this.Init += MultiViewForm_Init; + DeleteMode = EDeleteMode.OnLeavingForm; + Init += MultiViewForm_Init; } - private async Task MultiViewForm_Init(object sender, TelegramBotBase.Args.InitEventArgs e) + private Task MultiViewForm_Init(object sender, InitEventArgs e) { - mvt = new Subclass.MultiViewTest(); + _mvt = new MultiViewTest(); - AddControl(mvt); + AddControl(_mvt); - bg = new ButtonGrid(); - bg.ButtonsForm = new ButtonForm(); - bg.ButtonsForm.AddButtonRow("Back", "$back$"); - bg.ButtonClicked += Bg_ButtonClicked; - bg.KeyboardType = TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard; - AddControl(bg); + _bg = new ButtonGrid + { + ButtonsForm = new ButtonForm() + }; + _bg.ButtonsForm.AddButtonRow("Back", "$back$"); + _bg.ButtonClicked += Bg_ButtonClicked; + _bg.KeyboardType = EKeyboardType.ReplyKeyboard; + AddControl(_bg); + return Task.CompletedTask; } - private async Task Bg_ButtonClicked(object sender, TelegramBotBase.Args.ButtonClickedEventArgs e) + private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) { switch(e.Button.Value) { diff --git a/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs b/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs index f376903..79dfeab 100644 --- a/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs +++ b/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs @@ -1,40 +1,38 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TelegramBotBase.Args; using TelegramBotBase.Base; +using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Form; namespace TelegramBotBaseTest.Tests.Controls.Subclass { - public class MultiViewTest : TelegramBotBase.Controls.Hybrid.MultiView + public class MultiViewTest : MultiView { - public override async Task Action(MessageResult result, string value = null) + public override Task Action(MessageResult result, string value = null) { - switch (result.RawData) { case "back": - this.SelectedViewIndex--; + SelectedViewIndex--; break; case "next": - this.SelectedViewIndex++; + SelectedViewIndex++; break; } + return Task.CompletedTask; } public override async Task RenderView(RenderViewEventArgs e) { - ButtonForm bf = new ButtonForm(); + var bf = new ButtonForm(); bf.AddButtonRow(new ButtonBase("Back", "back"), new ButtonBase("Next", "next")); switch (e.CurrentView) diff --git a/TelegramBotBase.Test/Tests/Controls/ToggleButtons.cs b/TelegramBotBase.Test/Tests/Controls/ToggleButtons.cs index 55b88e9..cb46305 100644 --- a/TelegramBotBase.Test/Tests/Controls/ToggleButtons.cs +++ b/TelegramBotBase.Test/Tests/Controls/ToggleButtons.cs @@ -1,11 +1,8 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading.Tasks; using TelegramBotBase.Args; -using TelegramBotBase.Controls; using TelegramBotBase.Controls.Inline; +using TelegramBotBase.Enums; using TelegramBotBase.Form; namespace TelegramBotBaseTest.Tests.Controls @@ -14,38 +11,44 @@ namespace TelegramBotBaseTest.Tests.Controls { public ToggleButtons() { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; + DeleteMode = EDeleteMode.OnLeavingForm; - this.Init += ToggleButtons_Init; + Init += ToggleButtons_Init; } - private async Task ToggleButtons_Init(object sender, InitEventArgs e) + private Task ToggleButtons_Init(object sender, InitEventArgs e) { - var tb = new ToggleButton(); - tb.Checked = true; + var tb = new ToggleButton + { + Checked = true + }; tb.Toggled += Tb_Toggled; - this.AddControl(tb); + AddControl(tb); - tb = new ToggleButton(); - tb.Checked = false; + tb = new ToggleButton + { + Checked = false + }; tb.Toggled += Tb_Toggled; - this.AddControl(tb); + AddControl(tb); - tb = new ToggleButton(); - tb.Checked = true; + tb = new ToggleButton + { + Checked = true + }; tb.Toggled += Tb_Toggled; - this.AddControl(tb); - + AddControl(tb); + return Task.CompletedTask; } private void Tb_Toggled(object sender, EventArgs e) { var tb = sender as ToggleButton; - Console.WriteLine(tb.ID.ToString() + " was pressed, and toggled to " + (tb.Checked ? "Checked" : "Unchecked")); + Console.WriteLine(tb.Id + " was pressed, and toggled to " + (tb.Checked ? "Checked" : "Unchecked")); } } } diff --git a/TelegramBotBase.Test/Tests/Controls/TreeViewForms.cs b/TelegramBotBase.Test/Tests/Controls/TreeViewForms.cs index 6c9dd41..4a41460 100644 --- a/TelegramBotBase.Test/Tests/Controls/TreeViewForms.cs +++ b/TelegramBotBase.Test/Tests/Controls/TreeViewForms.cs @@ -1,31 +1,27 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using TelegramBotBase.Form; -using TelegramBotBase.Controls; -using TelegramBotBase.Base; +using System.Threading.Tasks; using TelegramBotBase.Args; +using TelegramBotBase.Base; using TelegramBotBase.Controls.Inline; +using TelegramBotBase.Enums; +using TelegramBotBase.Form; namespace TelegramBotBaseTest.Tests.Controls { public class TreeViewForms : AutoCleanForm { - public TreeView view { get; set; } + public TreeView View { get; set; } private int? MessageId { get; set; } public TreeViewForms() { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; - this.Init += TreeViewForms_Init; + DeleteMode = EDeleteMode.OnLeavingForm; + Init += TreeViewForms_Init; } - private async Task TreeViewForms_Init(object sender, InitEventArgs e) + private Task TreeViewForms_Init(object sender, InitEventArgs e) { - view = new TreeView(); + View = new TreeView(); var tvn = new TreeViewNode("Cars", "cars"); @@ -35,7 +31,7 @@ namespace TelegramBotBaseTest.Tests.Controls tvn.AddNode(new TreeViewNode("VW", "vw")); tvn.AddNode(new TreeViewNode("Lamborghini", "lamborghini")); - view.Nodes.Add(tvn); + View.Nodes.Add(tvn); tvn = new TreeViewNode("Fruits", "fruits"); @@ -43,10 +39,10 @@ namespace TelegramBotBaseTest.Tests.Controls tvn.AddNode(new TreeViewNode("Orange", "orange")); tvn.AddNode(new TreeViewNode("Lemon", "lemon")); - view.Nodes.Add(tvn); - - this.AddControl(view); + View.Nodes.Add(tvn); + AddControl(View); + return Task.CompletedTask; } public override async Task Action(MessageResult message) @@ -64,7 +60,7 @@ namespace TelegramBotBaseTest.Tests.Controls var start = new Menu(); - await this.NavigateTo(start); + await NavigateTo(start); break; @@ -74,26 +70,26 @@ namespace TelegramBotBaseTest.Tests.Controls public override async Task Render(MessageResult message) { - String s = ""; + var s = ""; - s += "Selected Node: " + (this.view.SelectedNode?.Text ?? "(null)") + "\r\n"; + s += "Selected Node: " + (View.SelectedNode?.Text ?? "(null)") + "\r\n"; - s += "Visible Node: " + (this.view.VisibleNode?.Text ?? "(top)") + "\r\n"; + s += "Visible Node: " + (View.VisibleNode?.Text ?? "(top)") + "\r\n"; - s += "Visible Path: " + this.view.GetPath() + "\r\n"; - s += "Selected Path: " + (this.view.SelectedNode?.GetPath() ?? "(null)") + "\r\n"; + s += "Visible Path: " + View.GetPath() + "\r\n"; + s += "Selected Path: " + (View.SelectedNode?.GetPath() ?? "(null)") + "\r\n"; - ButtonForm bf = new ButtonForm(); + var bf = new ButtonForm(); bf.AddButtonRow(new ButtonBase("Back", "back")); if (MessageId != null) { - await this.Device.Edit(this.MessageId.Value, s, bf); + await Device.Edit(MessageId.Value, s, bf); } else { - var m = await this.Device.Send(s, bf); - this.MessageId = m.MessageId; + var m = await Device.Send(s, bf); + MessageId = m.MessageId; } } diff --git a/TelegramBotBase.Test/Tests/DataForm.cs b/TelegramBotBase.Test/Tests/DataForm.cs index 4a6edec..509e58b 100644 --- a/TelegramBotBase.Test/Tests/DataForm.cs +++ b/TelegramBotBase.Test/Tests/DataForm.cs @@ -1,10 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System.Linq; using System.Threading.Tasks; using Telegram.Bot; -using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.InputFiles; using Telegram.Bot.Types.ReplyMarkups; using TelegramBotBase.Base; @@ -18,68 +15,68 @@ namespace TelegramBotBaseTest.Tests public override async Task SentData(DataResult data) { - String tmp = ""; + var tmp = ""; InputOnlineFile file; switch (data.Type) { - case Telegram.Bot.Types.Enums.MessageType.Contact: + case MessageType.Contact: tmp += "Firstname: " + data.Contact.FirstName + "\r\n"; tmp += "Lastname: " + data.Contact.LastName + "\r\n"; tmp += "Phonenumber: " + data.Contact.PhoneNumber + "\r\n"; tmp += "UserId: " + data.Contact.UserId + "\r\n"; - await this.Device.Send("Your contact: \r\n" + tmp, replyTo: data.MessageId); + await Device.Send("Your contact: \r\n" + tmp, replyTo: data.MessageId); break; - case Telegram.Bot.Types.Enums.MessageType.Document: + case MessageType.Document: file = new InputOnlineFile(data.Document.FileId); - await this.Device.SendDocument(file, "Your uploaded document"); + await Device.SendDocument(file, "Your uploaded document"); break; - case Telegram.Bot.Types.Enums.MessageType.Video: + case MessageType.Video: file = new InputOnlineFile(data.Document.FileId); - await this.Device.SendDocument(file, "Your uploaded video"); + await Device.SendDocument(file, "Your uploaded video"); break; - case Telegram.Bot.Types.Enums.MessageType.Audio: + case MessageType.Audio: file = new InputOnlineFile(data.Document.FileId); - await this.Device.SendDocument(file, "Your uploaded audio"); + await Device.SendDocument(file, "Your uploaded audio"); break; - case Telegram.Bot.Types.Enums.MessageType.Location: + case MessageType.Location: tmp += "Lat: " + data.Location.Latitude + "\r\n"; tmp += "Lng: " + data.Location.Longitude + "\r\n"; - await this.Device.Send("Your location: \r\n" + tmp, replyTo: data.MessageId); + await Device.Send("Your location: \r\n" + tmp, replyTo: data.MessageId); break; - case Telegram.Bot.Types.Enums.MessageType.Photo: + case MessageType.Photo: - InputOnlineFile photo = new InputOnlineFile(data.Photos.Last().FileId); + var photo = new InputOnlineFile(data.Photos.Last().FileId); - await this.Device.Send("Your image: ", replyTo: data.MessageId); - await this.Client.TelegramClient.SendPhotoAsync(this.Device.DeviceId, photo); + await Device.Send("Your image: ", replyTo: data.MessageId); + await Client.TelegramClient.SendPhotoAsync(Device.DeviceId, photo); break; default: - await this.Device.Send("Unknown response"); + await Device.Send("Unknown response"); break; } @@ -97,13 +94,13 @@ namespace TelegramBotBaseTest.Tests { case "contact": - await this.Device.RequestContact(); + await Device.RequestContact(); break; case "location": - await this.Device.RequestLocation(); + await Device.RequestLocation(); break; @@ -113,7 +110,7 @@ namespace TelegramBotBaseTest.Tests var start = new Menu(); - await this.NavigateTo(start); + await NavigateTo(start); break; } @@ -123,7 +120,7 @@ namespace TelegramBotBaseTest.Tests public override async Task Render(MessageResult message) { - ButtonForm bf = new ButtonForm(); + var bf = new ButtonForm(); bf.AddButtonRow(new ButtonBase("Request User contact", "contact")); @@ -133,7 +130,7 @@ namespace TelegramBotBaseTest.Tests InlineKeyboardMarkup ikv = bf; - await this.Device.Send("Please upload a contact, photo, video, audio, document or location.", bf); + await Device.Send("Please upload a contact, photo, video, audio, document or location.", bf); diff --git a/TelegramBotBase.Test/Tests/Datasources/CustomDataSource.cs b/TelegramBotBase.Test/Tests/Datasources/CustomDataSource.cs index 3187968..1e418e8 100644 --- a/TelegramBotBase.Test/Tests/Datasources/CustomDataSource.cs +++ b/TelegramBotBase.Test/Tests/Datasources/CustomDataSource.cs @@ -3,9 +3,9 @@ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; -using System.Text; +using Newtonsoft.Json; using TelegramBotBase.Controls.Hybrid; -using TelegramBotBase.Datasources; +using TelegramBotBase.DataSources; using TelegramBotBase.Form; namespace TelegramBotBaseTest.Tests.Datasources @@ -13,28 +13,28 @@ namespace TelegramBotBaseTest.Tests.Datasources public class CustomDataSource : ButtonFormDataSource { - public List Countries = new List() { "Country 1", "Country 2", "Country 3" }; + public List Countries = new List { "Country 1", "Country 2", "Country 3" }; public CustomDataSource() { - loadData(); + LoadData(); } /// /// This method has the example purpose of creating and loading some example data. /// When using a database you do not need this kind of method. /// - private void loadData() + private void LoadData() { //Exists data source? Read it if (File.Exists(AppContext.BaseDirectory + "countries.json")) { try { - var List = Newtonsoft.Json.JsonConvert.DeserializeObject>(File.ReadAllText("countries.json")); + var list = JsonConvert.DeserializeObject>(File.ReadAllText("countries.json")); - Countries = List; + Countries = list; } catch { @@ -52,7 +52,7 @@ namespace TelegramBotBaseTest.Tests.Datasources Countries = countries; - var tmp = Newtonsoft.Json.JsonConvert.SerializeObject(countries); + var tmp = JsonConvert.SerializeObject(countries); File.WriteAllText( AppContext.BaseDirectory + "countries.json", tmp); } @@ -76,7 +76,7 @@ namespace TelegramBotBaseTest.Tests.Datasources { var items = Countries.Skip(start).Take(count); - List lst = new List(); + var lst = new List(); foreach (var c in items) { lst.Add(Render(c)); @@ -87,7 +87,7 @@ namespace TelegramBotBaseTest.Tests.Datasources public override List AllItems() { - List lst = new List(); + var lst = new List(); foreach (var c in Countries) { lst.Add(Render(c)); @@ -97,9 +97,9 @@ namespace TelegramBotBaseTest.Tests.Datasources public override ButtonForm PickItems(int start, int count, string filter = null) { - List rows = ItemRange(start, count); + var rows = ItemRange(start, count); - ButtonForm lst = new ButtonForm(); + var lst = new ButtonForm(); foreach (var c in rows) { lst.AddButtonRow(c); @@ -109,9 +109,9 @@ namespace TelegramBotBaseTest.Tests.Datasources public override ButtonForm PickAllItems(string filter = null) { - List rows = AllItems(); + var rows = AllItems(); - ButtonForm bf = new ButtonForm(); + var bf = new ButtonForm(); bf.AddButtonRows(rows); @@ -128,36 +128,16 @@ namespace TelegramBotBaseTest.Tests.Datasources public override ButtonRow Render(object data) { - var s = data as String; - if (s == null) + if (!(data is string s)) return new ButtonRow(new ButtonBase("Empty", "zero")); return new ButtonRow(new ButtonBase(s, s)); } - public override int Count - { - get - { - return Countries.Count; - } - } + public override int Count => Countries.Count; - public override int ColumnCount - { - get - { - return 1; - } - } - - public override int RowCount - { - get - { - return this.Count; - } - } + public override int ColumnCount => 1; + public override int RowCount => Count; } } diff --git a/TelegramBotBase.Test/Tests/Datasources/List.cs b/TelegramBotBase.Test/Tests/Datasources/List.cs index c352384..d73d92a 100644 --- a/TelegramBotBase.Test/Tests/Datasources/List.cs +++ b/TelegramBotBase.Test/Tests/Datasources/List.cs @@ -1,42 +1,43 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using TelegramBotBase.Base; +using System.Threading.Tasks; +using TelegramBotBase.Args; using TelegramBotBase.Controls.Hybrid; +using TelegramBotBase.Enums; using TelegramBotBase.Form; namespace TelegramBotBaseTest.Tests.Datasources { public class List : FormBase { - ButtonGrid __buttons = null; + private ButtonGrid _buttons; public List() { - this.Init += List_Init; + Init += List_Init; } - private async Task List_Init(object sender, TelegramBotBase.Args.InitEventArgs e) + private Task List_Init(object sender, InitEventArgs e) { - __buttons = new ButtonGrid(); + _buttons = new ButtonGrid + { + EnablePaging = true, + EnableSearch = false + }; - __buttons.EnablePaging = true; - __buttons.EnableSearch = false; - __buttons.ButtonClicked += __buttons_ButtonClicked; - __buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard; - __buttons.DeleteReplyMessage = true; + _buttons.ButtonClicked += __buttons_ButtonClicked; + _buttons.KeyboardType = EKeyboardType.ReplyKeyboard; + _buttons.DeleteReplyMessage = true; - __buttons.HeadLayoutButtonRow = new ButtonRow(new ButtonBase("Back", "back")); + _buttons.HeadLayoutButtonRow = new ButtonRow(new ButtonBase("Back", "back")); var cds = new CustomDataSource(); - __buttons.DataSource = cds; + _buttons.DataSource = cds; - AddControl(__buttons); + AddControl(_buttons); + return Task.CompletedTask; } - private async Task __buttons_ButtonClicked(object sender, TelegramBotBase.Args.ButtonClickedEventArgs e) + private async Task __buttons_ButtonClicked(object sender, ButtonClickedEventArgs e) { switch(e.Button.Value) { diff --git a/TelegramBotBase.Test/Tests/Groups/GroupChange.cs b/TelegramBotBase.Test/Tests/Groups/GroupChange.cs index 2322b9f..1d75ccf 100644 --- a/TelegramBotBase.Test/Tests/Groups/GroupChange.cs +++ b/TelegramBotBase.Test/Tests/Groups/GroupChange.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Threading.Tasks; using TelegramBotBase.Args; using TelegramBotBase.Base; @@ -8,24 +6,24 @@ using TelegramBotBase.Form; namespace TelegramBotBaseTest.Tests.Groups { - public class GroupChange : TelegramBotBase.Form.GroupForm + public class GroupChange : GroupForm { public GroupChange() { - this.Opened += GroupChange_Opened; + Opened += GroupChange_Opened; } private async Task GroupChange_Opened(object sender, EventArgs e) { - ButtonForm bf = new ButtonForm(); + var bf = new ButtonForm(); bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange")); bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser")); bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace")); - await this.Device.Send("GroupChange started, click to switch", bf); + await Device.Send("GroupChange started, click to switch", bf); } @@ -46,21 +44,21 @@ namespace TelegramBotBaseTest.Tests.Groups var gc = new GroupChange(); - await this.NavigateTo(gc); + await NavigateTo(gc); break; case "welcomeuser": var wu = new WelcomeUser(); - await this.NavigateTo(wu); + await NavigateTo(wu); break; case "linkreplace": var lr = new LinkReplaceTest(); - await this.NavigateTo(lr); + await NavigateTo(lr); break; } @@ -69,7 +67,7 @@ namespace TelegramBotBaseTest.Tests.Groups public override async Task OnGroupChanged(GroupChangedEventArgs e) { - await this.Device.Send("Group has been changed by " + e.OriginalMessage.Message.From.FirstName + " " + e.OriginalMessage.Message.From.LastName); + await Device.Send("Group has been changed by " + e.OriginalMessage.Message.From.FirstName + " " + e.OriginalMessage.Message.From.LastName); } } diff --git a/TelegramBotBase.Test/Tests/Groups/LinkReplaceTest.cs b/TelegramBotBase.Test/Tests/Groups/LinkReplaceTest.cs index d132303..243d7d4 100644 --- a/TelegramBotBase.Test/Tests/Groups/LinkReplaceTest.cs +++ b/TelegramBotBase.Test/Tests/Groups/LinkReplaceTest.cs @@ -1,37 +1,36 @@ using System; using System.Collections.Generic; -using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; using TelegramBotBase.Base; using TelegramBotBase.Form; namespace TelegramBotBaseTest.Tests.Groups { - public class LinkReplaceTest : TelegramBotBase.Form.GroupForm + public class LinkReplaceTest : GroupForm { - - Dictionary Counter { get; set; } = new Dictionary(); + private Dictionary Counter { get; set; } = new Dictionary(); private const int Maximum = 3; public LinkReplaceTest() { - this.Opened += LinkReplaceTest_Opened; + Opened += LinkReplaceTest_Opened; } private async Task LinkReplaceTest_Opened(object sender, EventArgs e) { - ButtonForm bf = new ButtonForm(); + var bf = new ButtonForm(); bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange")); bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser")); bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace")); - await this.Device.Send("LinkReplaceTest started, click to switch", bf); + await Device.Send("LinkReplaceTest started, click to switch", bf); } @@ -51,21 +50,21 @@ namespace TelegramBotBaseTest.Tests.Groups var gc = new GroupChange(); - await this.NavigateTo(gc); + await NavigateTo(gc); break; case "welcomeuser": var wu = new WelcomeUser(); - await this.NavigateTo(wu); + await NavigateTo(wu); break; case "linkreplace": var lr = new LinkReplaceTest(); - await this.NavigateTo(lr); + await NavigateTo(lr); break; } @@ -86,23 +85,25 @@ namespace TelegramBotBaseTest.Tests.Groups var u = await Device.GetChatUser(from); //Don't kick Admins or Creators - if (u.Status == Telegram.Bot.Types.Enums.ChatMemberStatus.Administrator | u.Status == Telegram.Bot.Types.Enums.ChatMemberStatus.Creator) + if (u.Status == ChatMemberStatus.Administrator | u.Status == ChatMemberStatus.Creator) { - await this.Device.Send("You won't get kicked,...not this time."); + await Device.Send("You won't get kicked,...not this time."); return; } await e.Device.DeleteMessage(e.MessageId); - var cp = new ChatPermissions(); - cp.CanAddWebPagePreviews = false; - cp.CanChangeInfo = false; - cp.CanInviteUsers = false; - cp.CanPinMessages = false; - cp.CanSendMediaMessages = false; - cp.CanSendMessages = false; - cp.CanSendOtherMessages = false; - cp.CanSendPolls = false; + var cp = new ChatPermissions + { + CanAddWebPagePreviews = false, + CanChangeInfo = false, + CanInviteUsers = false, + CanPinMessages = false, + CanSendMediaMessages = false, + CanSendMessages = false, + CanSendOtherMessages = false, + CanSendPolls = false + }; //Collect user "mistakes" with sending url, after 3 he gets kicked out. if (Counter.ContainsKey(from)) @@ -147,12 +148,12 @@ namespace TelegramBotBaseTest.Tests.Groups /// /// /// - private bool HasLinks(String str) + private bool HasLinks(string str) { var tmp = str; var pattern = @"^(http|https|ftp|)\://|[a-zA-Z0-9\-\.]+\.[a-zA-Z](:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*[^\.\,\)\(\s]$"; - Regex r = new Regex(pattern); + var r = new Regex(pattern); var matches = r.Matches(tmp); diff --git a/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs b/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs index c90a3b9..c700f85 100644 --- a/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs +++ b/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs @@ -1,33 +1,32 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Linq; using System.Threading.Tasks; +using Telegram.Bot.Types.Enums; +using TelegramBotBase.Args; using TelegramBotBase.Base; using TelegramBotBase.Form; -using TelegramBotBase.Args; namespace TelegramBotBaseTest.Tests.Groups { - public class WelcomeUser : TelegramBotBase.Form.GroupForm + public class WelcomeUser : GroupForm { public WelcomeUser() { - this.Opened += WelcomeUser_Opened; + Opened += WelcomeUser_Opened; } private async Task WelcomeUser_Opened(object sender, EventArgs e) { - ButtonForm bf = new ButtonForm(); + var bf = new ButtonForm(); bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange")); bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser")); bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace")); - await this.Device.Send("WelcomeUser started, click to switch", bf); + await Device.Send("WelcomeUser started, click to switch", bf); } @@ -47,21 +46,21 @@ namespace TelegramBotBaseTest.Tests.Groups var gc = new GroupChange(); - await this.NavigateTo(gc); + await NavigateTo(gc); break; case "welcomeuser": var wu = new WelcomeUser(); - await this.NavigateTo(wu); + await NavigateTo(wu); break; case "linkreplace": var lr = new LinkReplaceTest(); - await this.NavigateTo(lr); + await NavigateTo(lr); break; } @@ -71,15 +70,15 @@ namespace TelegramBotBaseTest.Tests.Groups public override async Task OnMemberChanges(MemberChangeEventArgs e) { - if (e.Type == Telegram.Bot.Types.Enums.MessageType.ChatMembersAdded) + if (e.Type == MessageType.ChatMembersAdded) { - await this.Device.Send("Welcome you new members!\r\n\r\n" + e.Members.Select(a => a.FirstName + " " + a.LastName).Aggregate((a, b) => a + "\r\n" + b)); + await Device.Send("Welcome you new members!\r\n\r\n" + e.Members.Select(a => a.FirstName + " " + a.LastName).Aggregate((a, b) => a + "\r\n" + b)); } - else if (e.Type == Telegram.Bot.Types.Enums.MessageType.ChatMemberLeft) + else if (e.Type == MessageType.ChatMemberLeft) { - await this.Device.Send(e.Members.Select(a => a.FirstName + " " + a.LastName).Aggregate((a, b) => a + " and " + b) + " has left the group"); + await Device.Send(e.Members.Select(a => a.FirstName + " " + a.LastName).Aggregate((a, b) => a + " and " + b) + " has left the group"); } diff --git a/TelegramBotBase.Test/Tests/Menu.cs b/TelegramBotBase.Test/Tests/Menu.cs index 6f14fec..3f9d04d 100644 --- a/TelegramBotBase.Test/Tests/Menu.cs +++ b/TelegramBotBase.Test/Tests/Menu.cs @@ -1,11 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; +using Telegram.Bot.Types.Enums; using TelegramBotBase.Base; +using TelegramBotBase.Enums; using TelegramBotBase.Form; using TelegramBotBaseTest.Tests.Controls; +using TelegramBotBaseTest.Tests.Datasources; +using TelegramBotBaseTest.Tests.Groups; namespace TelegramBotBaseTest.Tests { @@ -13,18 +13,18 @@ namespace TelegramBotBaseTest.Tests { public Menu() { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; + DeleteMode = EDeleteMode.OnLeavingForm; } public override async Task Load(MessageResult message) { - if (message.Message.Chat.Type == Telegram.Bot.Types.Enums.ChatType.Group | message.Message.Chat.Type == Telegram.Bot.Types.Enums.ChatType.Supergroup) + if (message.Message.Chat.Type == ChatType.Group | message.Message.Chat.Type == ChatType.Supergroup) { - var sf = new TelegramBotBaseTest.Tests.Groups.WelcomeUser(); + var sf = new WelcomeUser(); - await this.NavigateTo(sf); + await NavigateTo(sf); } @@ -49,7 +49,7 @@ namespace TelegramBotBaseTest.Tests var sf = new SimpleForm(); - await this.NavigateTo(sf); + await NavigateTo(sf); break; @@ -57,7 +57,7 @@ namespace TelegramBotBaseTest.Tests var bf = new ButtonTestForm(); - await this.NavigateTo(bf); + await NavigateTo(bf); break; @@ -65,7 +65,7 @@ namespace TelegramBotBaseTest.Tests var pf = new ProgressTest(); - await this.NavigateTo(pf); + await NavigateTo(pf); break; @@ -73,7 +73,7 @@ namespace TelegramBotBaseTest.Tests var reg = new Register.Start(); - await this.NavigateTo(reg); + await NavigateTo(reg); break; @@ -81,7 +81,7 @@ namespace TelegramBotBaseTest.Tests var form1 = new TestForm(); - await this.NavigateTo(form1); + await NavigateTo(form1); break; @@ -89,7 +89,7 @@ namespace TelegramBotBaseTest.Tests var form2 = new TestForm2(); - await this.NavigateTo(form2); + await NavigateTo(form2); break; @@ -97,71 +97,71 @@ namespace TelegramBotBaseTest.Tests var data = new DataForm(); - await this.NavigateTo(data); + await NavigateTo(data); break; case "calendar": - var calendar = new Controls.CalendarPickerForm(); + var calendar = new CalendarPickerForm(); - await this.NavigateTo(calendar); + await NavigateTo(calendar); break; case "month": - var month = new Controls.MonthPickerForm(); + var month = new MonthPickerForm(); - await this.NavigateTo(month); + await NavigateTo(month); break; case "treeview": - var tree = new Controls.TreeViewForms(); + var tree = new TreeViewForms(); - await this.NavigateTo(tree); + await NavigateTo(tree); break; case "togglebuttons": - var tb = new Controls.ToggleButtons(); + var tb = new ToggleButtons(); - await this.NavigateTo(tb); + await NavigateTo(tb); break; case "multitogglebuttons": - var mtb = new Controls.MultiToggleButtons(); + var mtb = new MultiToggleButtons(); - await this.NavigateTo(mtb); + await NavigateTo(mtb); break; case "buttongrid": - var bg = new Controls.ButtonGridForm(); + var bg = new ButtonGridForm(); - await this.NavigateTo(bg); + await NavigateTo(bg); break; case "buttongridfilter": - var bg2 = new Controls.ButtonGridPagingForm(); + var bg2 = new ButtonGridPagingForm(); - await this.NavigateTo(bg2); + await NavigateTo(bg2); break; case "buttongridtags": - var bg3 = new Controls.ButtonGridTagForm(); + var bg3 = new ButtonGridTagForm(); - await this.NavigateTo(bg3); + await NavigateTo(bg3); break; @@ -194,7 +194,7 @@ namespace TelegramBotBaseTest.Tests case "dynamicbuttongrid": - var dg = new Datasources.List(); + var dg = new List(); await NavigateTo(dg); @@ -220,7 +220,7 @@ namespace TelegramBotBaseTest.Tests public override async Task Render(MessageResult message) { - ButtonForm btn = new ButtonForm(); + var btn = new ButtonForm(); btn.AddButtonRow(new ButtonBase("#1 Simple Text", new CallbackData("a", "text").Serialize()), new ButtonBase("#2 Button Test", new CallbackData("a", "buttons").Serialize())); btn.AddButtonRow(new ButtonBase("#3 Progress Bar", new CallbackData("a", "progress").Serialize())); @@ -256,7 +256,7 @@ namespace TelegramBotBaseTest.Tests btn.AddButtonRow(new ButtonBase("#19 Notifications", new CallbackData("a", "notifications").Serialize())); - await this.Device.Send("Choose your test:", btn); + await Device.Send("Choose your test:", btn); } diff --git a/TelegramBotBase.Test/Tests/Navigation/CustomController.cs b/TelegramBotBase.Test/Tests/Navigation/CustomController.cs index e5b7205..5dff6fd 100644 --- a/TelegramBotBase.Test/Tests/Navigation/CustomController.cs +++ b/TelegramBotBase.Test/Tests/Navigation/CustomController.cs @@ -1,13 +1,11 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Threading.Tasks; using TelegramBotBase.Form; using TelegramBotBase.Form.Navigation; namespace TelegramBotBaseTest.Tests.Navigation { - class CustomController : NavigationController + internal class CustomController : NavigationController { public CustomController(FormBase form) : base(form) { @@ -17,7 +15,7 @@ namespace TelegramBotBaseTest.Tests.Navigation public override Task PushAsync(FormBase form, params object[] args) { - Console.WriteLine($"Pushes form (Count on stack {this.Index + 1})"); + Console.WriteLine($"Pushes form (Count on stack {Index + 1})"); //Device.Send($"Pushes form (Count on stack {this.Index + 1})"); return base.PushAsync(form, args); @@ -26,7 +24,7 @@ namespace TelegramBotBaseTest.Tests.Navigation public override Task PopAsync() { - Console.WriteLine($"Pops one form (Count on stack {this.Index + 1})"); + Console.WriteLine($"Pops one form (Count on stack {Index + 1})"); //Device.Send($"Pops one form (Count on stack {this.Index + 1})"); return base.PopAsync(); @@ -34,7 +32,7 @@ namespace TelegramBotBaseTest.Tests.Navigation public override Task PopToRootAsync() { - Console.WriteLine($"Moved back to root (Count on stack {this.Index + 1})"); + Console.WriteLine($"Moved back to root (Count on stack {Index + 1})"); //Device.Send($"Moved back to root (Count on stack {this.Index + 1})"); return base.PopToRootAsync(); diff --git a/TelegramBotBase.Test/Tests/Navigation/Form1.cs b/TelegramBotBase.Test/Tests/Navigation/Form1.cs index 29e37fc..b7270a6 100644 --- a/TelegramBotBase.Test/Tests/Navigation/Form1.cs +++ b/TelegramBotBase.Test/Tests/Navigation/Form1.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Threading.Tasks; using Telegram.Bot.Types; using TelegramBotBase.Base; @@ -10,19 +8,19 @@ namespace TelegramBotBaseTest.Tests.Navigation { public class Form1 : FormBase { - Message msg = null; + private Message _msg; public Form1() { - this.Closed += Form1_Closed; + Closed += Form1_Closed; } private async Task Form1_Closed(object sender, EventArgs e) { - if (msg == null) + if (_msg == null) return; - await Device.DeleteMessage(msg); + await Device.DeleteMessage(_msg); } public override async Task Action(MessageResult message) @@ -71,7 +69,7 @@ namespace TelegramBotBaseTest.Tests.Navigation public override async Task Render(MessageResult message) { - if (msg != null) + if (_msg != null) return; var bf = new ButtonForm(); @@ -79,7 +77,7 @@ namespace TelegramBotBaseTest.Tests.Navigation bf.AddButtonRow("Previous page", "previous"); bf.AddButtonRow("Back to root", "root"); - msg = await Device.Send($"Choose your options (Count on stack {NavigationController.Index + 1})", bf); + _msg = await Device.Send($"Choose your options (Count on stack {NavigationController.Index + 1})", bf); } diff --git a/TelegramBotBase.Test/Tests/Navigation/Start.cs b/TelegramBotBase.Test/Tests/Navigation/Start.cs index 1f70b5c..2599ff3 100644 --- a/TelegramBotBase.Test/Tests/Navigation/Start.cs +++ b/TelegramBotBase.Test/Tests/Navigation/Start.cs @@ -1,30 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using Telegram.Bot.Types; using TelegramBotBase.Base; using TelegramBotBase.Form; -using TelegramBotBase.Form.Navigation; namespace TelegramBotBaseTest.Tests.Navigation { public class Start : FormBase { + private Message _msg; - Message msg = null; - public Start() + public override Task Load(MessageResult message) { - - } - - - public override async Task Load(MessageResult message) - { - - - + return Task.CompletedTask; } public override async Task Action(MessageResult message) @@ -50,10 +38,10 @@ namespace TelegramBotBaseTest.Tests.Navigation await NavigateTo(nc); - if (msg == null) + if (_msg == null) return; - await Device.DeleteMessage(msg); + await Device.DeleteMessage(_msg); break; @@ -65,10 +53,10 @@ namespace TelegramBotBaseTest.Tests.Navigation await NavigateTo(mn); - if (msg == null) + if (_msg == null) return; - await Device.DeleteMessage(msg); + await Device.DeleteMessage(_msg); break; } @@ -82,7 +70,7 @@ namespace TelegramBotBaseTest.Tests.Navigation bf.AddButtonRow("Yes", "yes"); bf.AddButtonRow("No", "no"); - msg = await Device.Send("Open controller?", bf); + _msg = await Device.Send("Open controller?", bf); } diff --git a/TelegramBotBase.Test/Tests/Notifications/Start.cs b/TelegramBotBase.Test/Tests/Notifications/Start.cs index 9fb96f1..702a9e7 100644 --- a/TelegramBotBase.Test/Tests/Notifications/Start.cs +++ b/TelegramBotBase.Test/Tests/Notifications/Start.cs @@ -1,19 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TelegramBotBase.Base; +using TelegramBotBase.Enums; using TelegramBotBase.Form; namespace TelegramBotBaseTest.Tests.Notifications { public class Start : AutoCleanForm { - bool sent = false; + private bool _sent; public Start() { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; + DeleteMode = EDeleteMode.OnLeavingForm; } public override async Task Action(MessageResult message) @@ -46,7 +44,7 @@ namespace TelegramBotBaseTest.Tests.Notifications public override async Task Render(MessageResult message) { - if (sent) + if (_sent) return; var bf = new ButtonForm(); @@ -56,7 +54,7 @@ namespace TelegramBotBaseTest.Tests.Notifications await Device.Send("Choose your test", bf); - sent = true; + _sent = true; } } diff --git a/TelegramBotBase.Test/Tests/ProgressTest.cs b/TelegramBotBase.Test/Tests/ProgressTest.cs index 8b0ea16..0657c82 100644 --- a/TelegramBotBase.Test/Tests/ProgressTest.cs +++ b/TelegramBotBase.Test/Tests/ProgressTest.cs @@ -1,11 +1,9 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading; using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Controls.Inline; +using TelegramBotBase.Enums; using TelegramBotBase.Form; namespace TelegramBotBaseTest.Tests @@ -15,15 +13,15 @@ namespace TelegramBotBaseTest.Tests public ProgressTest() { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; - this.Opened += ProgressTest_Opened; - this.Closed += ProgressTest_Closed; + DeleteMode = EDeleteMode.OnLeavingForm; + Opened += ProgressTest_Opened; + Closed += ProgressTest_Closed; } private async Task ProgressTest_Opened(object sender, EventArgs e) { - await this.Device.Send("Welcome to ProgressTest"); + await Device.Send("Welcome to ProgressTest"); } public override async Task Action(MessageResult message) @@ -36,42 +34,52 @@ namespace TelegramBotBaseTest.Tests if (call == null) return; - ProgressBar Bar = null; + ProgressBar bar = null; switch (call.Value) { case "standard": - Bar = new ProgressBar(0, 100, ProgressBar.eProgressStyle.standard); - Bar.Device = this.Device; + bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.standard) + { + Device = Device + }; break; case "squares": - Bar = new ProgressBar(0, 100, ProgressBar.eProgressStyle.squares); - Bar.Device = this.Device; + bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.squares) + { + Device = Device + }; break; case "circles": - Bar = new ProgressBar(0, 100, ProgressBar.eProgressStyle.circles); - Bar.Device = this.Device; + bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.circles) + { + Device = Device + }; break; case "lines": - Bar = new ProgressBar(0, 100, ProgressBar.eProgressStyle.lines); - Bar.Device = this.Device; + bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.lines) + { + Device = Device + }; break; case "squaredlines": - Bar = new ProgressBar(0, 100, ProgressBar.eProgressStyle.squaredLines); - Bar.Device = this.Device; + bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.squaredLines) + { + Device = Device + }; break; @@ -79,7 +87,7 @@ namespace TelegramBotBaseTest.Tests var sf = new Menu(); - await this.NavigateTo(sf); + await NavigateTo(sf); return; @@ -91,14 +99,14 @@ namespace TelegramBotBaseTest.Tests //Render Progress bar and show some "example" progress - await Bar.Render(message); + await bar.Render(message); - this.Controls.Add(Bar); + Controls.Add(bar); - for (int i = 0; i <= 100; i++) + for (var i = 0; i <= 100; i++) { - Bar.Value++; - await Bar.Render(message); + bar.Value++; + await bar.Render(message); Thread.Sleep(250); } @@ -109,7 +117,7 @@ namespace TelegramBotBaseTest.Tests public override async Task Render(MessageResult message) { - ButtonForm btn = new ButtonForm(); + var btn = new ButtonForm(); btn.AddButtonRow(new ButtonBase("Standard", new CallbackData("a", "standard").Serialize()), new ButtonBase("Squares", new CallbackData("a", "squares").Serialize())); btn.AddButtonRow(new ButtonBase("Circles", new CallbackData("a", "circles").Serialize()), new ButtonBase("Lines", new CallbackData("a", "lines").Serialize())); @@ -118,12 +126,12 @@ namespace TelegramBotBaseTest.Tests btn.AddButtonRow(new ButtonBase("Back to start", new CallbackData("a", "start").Serialize())); - await this.Device.Send("Choose your progress bar:", btn); + await Device.Send("Choose your progress bar:", btn); } private async Task ProgressTest_Closed(object sender, EventArgs e) { - await this.Device.Send("Ciao from ProgressTest"); + await Device.Send("Ciao from ProgressTest"); } } diff --git a/TelegramBotBase.Test/Tests/Register/PerForm.cs b/TelegramBotBase.Test/Tests/Register/PerForm.cs index b66334c..ab703f7 100644 --- a/TelegramBotBase.Test/Tests/Register/PerForm.cs +++ b/TelegramBotBase.Test/Tests/Register/PerForm.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; @@ -10,38 +6,39 @@ namespace TelegramBotBaseTest.Tests.Register { public class PerForm : AutoCleanForm { - public String EMail { get; set; } + public string EMail { get; set; } - public String Firstname { get; set; } + public string Firstname { get; set; } - public String Lastname { get; set; } + public string Lastname { get; set; } - public async override Task Load(MessageResult message) + public override Task Load(MessageResult message) { if (message.MessageText.Trim() == "") - return; + return Task.CompletedTask; - if (this.Firstname == null) + if (Firstname == null) { - this.Firstname = message.MessageText; - return; + Firstname = message.MessageText; + return Task.CompletedTask; } - if (this.Lastname == null) + if (Lastname == null) { - this.Lastname = message.MessageText; - return; + Lastname = message.MessageText; + return Task.CompletedTask; } - if (this.EMail == null) + if (EMail == null) { - this.EMail = message.MessageText; - return; + EMail = message.MessageText; + return Task.CompletedTask; } + return Task.CompletedTask; } - public async override Task Action(MessageResult message) + public override async Task Action(MessageResult message) { var call = message.GetData(); @@ -56,7 +53,7 @@ namespace TelegramBotBaseTest.Tests.Register var start = new Start(); - await this.NavigateTo(start); + await NavigateTo(start); break; @@ -65,37 +62,37 @@ namespace TelegramBotBaseTest.Tests.Register } - public async override Task Render(MessageResult message) + public override async Task Render(MessageResult message) { - if (this.Firstname == null) + if (Firstname == null) { - await this.Device.Send("Please sent your firstname:"); + await Device.Send("Please sent your firstname:"); return; } - if (this.Lastname == null) + if (Lastname == null) { - await this.Device.Send("Please sent your lastname:"); + await Device.Send("Please sent your lastname:"); return; } - if (this.EMail == null) + if (EMail == null) { - await this.Device.Send("Please sent your email address:"); + await Device.Send("Please sent your email address:"); return; } - String s = ""; + var s = ""; - s += "Firstname: " + this.Firstname + "\r\n"; - s += "Lastname: " + this.Lastname + "\r\n"; - s += "E-Mail: " + this.EMail + "\r\n"; + s += "Firstname: " + Firstname + "\r\n"; + s += "Lastname: " + Lastname + "\r\n"; + s += "E-Mail: " + EMail + "\r\n"; - ButtonForm bf = new ButtonForm(); + var bf = new ButtonForm(); bf.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "back").Serialize())); - await this.Device.Send("Your details:\r\n" + s, bf); + await Device.Send("Your details:\r\n" + s, bf); } diff --git a/TelegramBotBase.Test/Tests/Register/PerStep.cs b/TelegramBotBase.Test/Tests/Register/PerStep.cs index afc709a..b31779a 100644 --- a/TelegramBotBase.Test/Tests/Register/PerStep.cs +++ b/TelegramBotBase.Test/Tests/Register/PerStep.cs @@ -1,17 +1,14 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; +using TelegramBotBaseTest.Tests.Register.Steps; namespace TelegramBotBaseTest.Tests.Register { public class PerStep: AutoCleanForm { - public async override Task Action(MessageResult message) + public override async Task Action(MessageResult message) { await message.ConfirmAction(); @@ -19,29 +16,29 @@ namespace TelegramBotBaseTest.Tests.Register { case "start": - var step1 = new Steps.Step1(); + var step1 = new Step1(); - await this.NavigateTo(step1); + await NavigateTo(step1); break; case "back": var start = new Start(); - await this.NavigateTo(start); + await NavigateTo(start); break; } } - public async override Task Render(MessageResult message) + public override async Task Render(MessageResult message) { - ButtonForm bf = new ButtonForm(); + var bf = new ButtonForm(); bf.AddButtonRow(new ButtonBase("Goto Step 1", "start")); bf.AddButtonRow(new ButtonBase("Back", "back")); - await this.Device.Send("Register Steps", bf); + await Device.Send("Register Steps", bf); } } } diff --git a/TelegramBotBase.Test/Tests/Register/Start.cs b/TelegramBotBase.Test/Tests/Register/Start.cs index 73ed856..a37c5c7 100644 --- a/TelegramBotBase.Test/Tests/Register/Start.cs +++ b/TelegramBotBase.Test/Tests/Register/Start.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; @@ -10,12 +6,7 @@ namespace TelegramBotBaseTest.Tests.Register { public class Start : AutoCleanForm { - public Start() - { - - } - - public async override Task Action(MessageResult message) + public override async Task Action(MessageResult message) { var call = message.GetData(); @@ -31,21 +22,21 @@ namespace TelegramBotBaseTest.Tests.Register var form = new PerForm(); - await this.NavigateTo(form); + await NavigateTo(form); break; case "step": var step = new PerStep(); - await this.NavigateTo(step); + await NavigateTo(step); break; case "backtodashboard": - var start = new Tests.Menu(); + var start = new Menu(); - await this.NavigateTo(start); + await NavigateTo(start); break; } @@ -53,16 +44,16 @@ namespace TelegramBotBaseTest.Tests.Register } - public async override Task Render(MessageResult message) + public override async Task Render(MessageResult message) { - ButtonForm btn = new ButtonForm(); + var btn = new ButtonForm(); btn.AddButtonRow(new ButtonBase("#4.1 Per Form", new CallbackData("a", "form").Serialize())); btn.AddButtonRow(new ButtonBase("#4.2 Per Step", new CallbackData("a", "step").Serialize())); btn.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "backtodashboard").Serialize())); - await this.Device.Send("Choose your test:", btn); + await Device.Send("Choose your test:", btn); } diff --git a/TelegramBotBase.Test/Tests/Register/Steps/Data.cs b/TelegramBotBase.Test/Tests/Register/Steps/Data.cs index 1fe077b..fab243b 100644 --- a/TelegramBotBase.Test/Tests/Register/Steps/Data.cs +++ b/TelegramBotBase.Test/Tests/Register/Steps/Data.cs @@ -1,18 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TelegramBotBaseTest.Tests.Register.Steps +namespace TelegramBotBaseTest.Tests.Register.Steps { public class Data { - public String EMail { get; set; } + public string EMail { get; set; } - public String Firstname { get; set; } + public string Firstname { get; set; } - public String Lastname { get; set; } + public string Lastname { get; set; } } } diff --git a/TelegramBotBase.Test/Tests/Register/Steps/Step1.cs b/TelegramBotBase.Test/Tests/Register/Steps/Step1.cs index 1952a1b..0b0616d 100644 --- a/TelegramBotBase.Test/Tests/Register/Steps/Step1.cs +++ b/TelegramBotBase.Test/Tests/Register/Steps/Step1.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TelegramBotBase.Args; using TelegramBotBase.Base; using TelegramBotBase.Form; @@ -15,35 +11,38 @@ namespace TelegramBotBaseTest.Tests.Register.Steps public Step1() { - this.Init += Step1_Init; + Init += Step1_Init; } - private async Task Step1_Init(object sender, InitEventArgs e) + private Task Step1_Init(object sender, InitEventArgs e) { - this.UserData = new Data(); + UserData = new Data(); + return Task.CompletedTask; } - public async override Task Load(MessageResult message) + public override Task Load(MessageResult message) { if (message.Handled) - return; + return Task.CompletedTask; if (message.MessageText.Trim() == "") - return; + return Task.CompletedTask; - if (this.UserData.Firstname == null) + if (UserData.Firstname == null) { - this.UserData.Firstname = message.MessageText; - return; + UserData.Firstname = message.MessageText; + return Task.CompletedTask; } + + return Task.CompletedTask; } - public async override Task Render(MessageResult message) + public override async Task Render(MessageResult message) { - if (this.UserData.Firstname == null) + if (UserData.Firstname == null) { - await this.Device.Send("Please sent your firstname:"); + await Device.Send("Please sent your firstname:"); return; } @@ -51,9 +50,9 @@ namespace TelegramBotBaseTest.Tests.Register.Steps var step2 = new Step2(); - step2.UserData = this.UserData; + step2.UserData = UserData; - await this.NavigateTo(step2); + await NavigateTo(step2); } } diff --git a/TelegramBotBase.Test/Tests/Register/Steps/Step2.cs b/TelegramBotBase.Test/Tests/Register/Steps/Step2.cs index 6ca2362..5a954f4 100644 --- a/TelegramBotBase.Test/Tests/Register/Steps/Step2.cs +++ b/TelegramBotBase.Test/Tests/Register/Steps/Step2.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; @@ -13,27 +9,29 @@ namespace TelegramBotBaseTest.Tests.Register.Steps public Data UserData { get; set; } - public async override Task Load(MessageResult message) + public override Task Load(MessageResult message) { if (message.Handled) - return; + return Task.CompletedTask; if (message.MessageText.Trim() == "") - return; + return Task.CompletedTask; - if (this.UserData.Lastname == null) + if (UserData.Lastname == null) { - this.UserData.Lastname = message.MessageText; - return; + UserData.Lastname = message.MessageText; + return Task.CompletedTask; } + + return Task.CompletedTask; } - public async override Task Render(MessageResult message) + public override async Task Render(MessageResult message) { - if (this.UserData.Lastname == null) + if (UserData.Lastname == null) { - await this.Device.Send("Please sent your lastname:"); + await Device.Send("Please sent your lastname:"); return; } @@ -41,9 +39,9 @@ namespace TelegramBotBaseTest.Tests.Register.Steps var step3 = new Step3(); - step3.UserData = this.UserData; + step3.UserData = UserData; - await this.NavigateTo(step3); + await NavigateTo(step3); } } diff --git a/TelegramBotBase.Test/Tests/Register/Steps/Step3.cs b/TelegramBotBase.Test/Tests/Register/Steps/Step3.cs index 038a9a2..1f22924 100644 --- a/TelegramBotBase.Test/Tests/Register/Steps/Step3.cs +++ b/TelegramBotBase.Test/Tests/Register/Steps/Step3.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; @@ -12,22 +8,24 @@ namespace TelegramBotBaseTest.Tests.Register.Steps { public Data UserData { get; set; } - public async override Task Load(MessageResult message) + public override Task Load(MessageResult message) { if (message.Handled) - return; + return Task.CompletedTask; if (message.MessageText.Trim() == "") - return; + return Task.CompletedTask; - if (this.UserData.EMail == null) + if (UserData.EMail == null) { - this.UserData.EMail = message.MessageText; - return; + UserData.EMail = message.MessageText; + return Task.CompletedTask; } + + return Task.CompletedTask; } - public async override Task Action(MessageResult message) + public override async Task Action(MessageResult message) { await message.ConfirmAction(); @@ -37,7 +35,7 @@ namespace TelegramBotBaseTest.Tests.Register.Steps var start = new Start(); - await this.NavigateTo(start); + await NavigateTo(start); break; @@ -45,26 +43,26 @@ namespace TelegramBotBaseTest.Tests.Register.Steps } - public async override Task Render(MessageResult message) + public override async Task Render(MessageResult message) { - if (this.UserData.EMail == null) + if (UserData.EMail == null) { - await this.Device.Send("Please sent your email:"); + await Device.Send("Please sent your email:"); return; } message.Handled = true; - String s = ""; + var s = ""; - s += "Firstname: " + this.UserData.Firstname + "\r\n"; - s += "Lastname: " + this.UserData.Lastname + "\r\n"; - s += "E-Mail: " + this.UserData.EMail + "\r\n"; + s += "Firstname: " + UserData.Firstname + "\r\n"; + s += "Lastname: " + UserData.Lastname + "\r\n"; + s += "E-Mail: " + UserData.EMail + "\r\n"; - ButtonForm bf = new ButtonForm(); + var bf = new ButtonForm(); bf.AddButtonRow(new ButtonBase("Back", "back")); - await this.Device.Send("Your details:\r\n" + s, bf); + await Device.Send("Your details:\r\n" + s, bf); } } diff --git a/TelegramBotBase.Test/Tests/SimpleForm.cs b/TelegramBotBase.Test/Tests/SimpleForm.cs index 0830cda..4f5c5fa 100644 --- a/TelegramBotBase.Test/Tests/SimpleForm.cs +++ b/TelegramBotBase.Test/Tests/SimpleForm.cs @@ -1,9 +1,7 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading.Tasks; using TelegramBotBase.Base; +using TelegramBotBase.Enums; using TelegramBotBase.Form; namespace TelegramBotBaseTest.Tests @@ -13,15 +11,15 @@ namespace TelegramBotBaseTest.Tests public SimpleForm() { - this.DeleteSide = TelegramBotBase.Enums.eDeleteSide.Both; - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; + DeleteSide = EDeleteSide.Both; + DeleteMode = EDeleteMode.OnLeavingForm; - this.Opened += SimpleForm_Opened; + Opened += SimpleForm_Opened; } private async Task SimpleForm_Opened(object sender, EventArgs e) { - await this.Device.Send("Hello world! (send 'back' to get back to Start)\r\nOr\r\nhi, hello, maybe, bye and ciao"); + await Device.Send("Hello world! (send 'back' to get back to Start)\r\nOr\r\nhi, hello, maybe, bye and ciao"); } public override async Task Load(MessageResult message) @@ -36,13 +34,13 @@ namespace TelegramBotBaseTest.Tests case "hi": //Send him a simple message - await this.Device.Send("Hello you there !"); + await Device.Send("Hello you there !"); break; case "maybe": //Send him a simple message and reply to the one of himself - await this.Device.Send("Maybe what?", replyTo: messageId); + await Device.Send("Maybe what?", replyTo: messageId); break; @@ -50,14 +48,14 @@ namespace TelegramBotBaseTest.Tests case "ciao": //Send him a simple message - await this.Device.Send("Ok, take care !"); + await Device.Send("Ok, take care !"); break; case "back": var st = new Menu(); - await this.NavigateTo(st); + await NavigateTo(st); break; } diff --git a/TelegramBotBase.Test/Tests/Start.cs b/TelegramBotBase.Test/Tests/Start.cs index e56642f..5933011 100644 --- a/TelegramBotBase.Test/Tests/Start.cs +++ b/TelegramBotBase.Test/Tests/Start.cs @@ -1,9 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; +using TelegramBotBaseTest.Tests.Groups; namespace TelegramBotBaseTest.Tests { @@ -12,7 +10,7 @@ namespace TelegramBotBaseTest.Tests public override async Task Open(MessageResult e) { var st = new Menu(); - await this.NavigateTo(st); + await NavigateTo(st); return true; } @@ -20,8 +18,8 @@ namespace TelegramBotBaseTest.Tests public override async Task OpenGroup(MessageResult e) { - var st = new Groups.LinkReplaceTest(); - await this.NavigateTo(st); + var st = new LinkReplaceTest(); + await NavigateTo(st); return true; } diff --git a/TelegramBotBase.Test/Tests/TestForm.cs b/TelegramBotBase.Test/Tests/TestForm.cs index 8994465..e248414 100644 --- a/TelegramBotBase.Test/Tests/TestForm.cs +++ b/TelegramBotBase.Test/Tests/TestForm.cs @@ -1,9 +1,5 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading.Tasks; -using Telegram.Bot.Types; using TelegramBotBase.Base; using TelegramBotBase.Form; @@ -11,24 +7,22 @@ namespace TelegramBotBaseTest.Tests { public class TestForm : FormBase { - - - String LastMessage { get; set; } + private string LastMessage { get; set; } public TestForm() { - this.Opened += TestForm_Opened; - this.Closed += TestForm_Closed; + Opened += TestForm_Opened; + Closed += TestForm_Closed; } private async Task TestForm_Opened(object sender, EventArgs e) { - await this.Device.Send("Welcome to Form 1"); + await Device.Send("Welcome to Form 1"); } private async Task TestForm_Closed(object sender, EventArgs e) { - await this.Device.Send("Ciao from Form 1"); + await Device.Send("Ciao from Form 1"); } @@ -45,7 +39,7 @@ namespace TelegramBotBaseTest.Tests var tf = new TestForm2(); - await this.NavigateTo(tf); + await NavigateTo(tf); break; @@ -54,7 +48,7 @@ namespace TelegramBotBaseTest.Tests if (message.UpdateData == null) return; - this.LastMessage = message.Message.Text; + LastMessage = message.Message.Text; break; } @@ -68,7 +62,7 @@ namespace TelegramBotBaseTest.Tests if (message.Command == "reply") { - await this.Device.Send("Last message: " + this.LastMessage); + await Device.Send("Last message: " + LastMessage); } diff --git a/TelegramBotBase.Test/Tests/TestForm2.cs b/TelegramBotBase.Test/Tests/TestForm2.cs index 089430e..93cced0 100644 --- a/TelegramBotBase.Test/Tests/TestForm2.cs +++ b/TelegramBotBase.Test/Tests/TestForm2.cs @@ -1,12 +1,7 @@ using System; -using System.Collections.Generic; using System.Drawing; -using System.Drawing.Imaging; -using System.Linq; -using System.Text; using System.Threading.Tasks; -using Telegram.Bot.Types; -using Telegram.Bot.Types.ReplyMarkups; +using Telegram.Bot.Types.Enums; using TelegramBotBase.Base; using TelegramBotBase.Extensions.Images; using TelegramBotBase.Form; @@ -19,18 +14,18 @@ namespace TelegramBotBaseTest.Tests public TestForm2() { - this.Opened += TestForm2_Opened; - this.Closed += TestForm2_Closed; + Opened += TestForm2_Opened; + Closed += TestForm2_Closed; } private async Task TestForm2_Opened(object sender, EventArgs e) { - await this.Device.Send("Welcome to Form 2"); + await Device.Send("Welcome to Form 2"); } private async Task TestForm2_Closed(object sender, EventArgs e) { - await this.Device.Send("Ciao from Form 2"); + await Device.Send("Ciao from Form 2"); } @@ -51,23 +46,23 @@ namespace TelegramBotBaseTest.Tests var tf = new TestForm(); - await this.NavigateTo(tf); + await NavigateTo(tf); } else if (call.Value == "alert") { - AlertDialog ad = new AlertDialog("This is a message", "Ok"); + var ad = new AlertDialog("This is a message", "Ok"); ad.ButtonClicked += async (s, en) => { var fto = new TestForm2(); - await this.NavigateTo(fto); + await NavigateTo(fto); }; - await this.NavigateTo(ad); + await NavigateTo(ad); } else if (call.Value == "confirm") { - ConfirmDialog pd = new ConfirmDialog("Please confirm", new ButtonBase("Ok", "ok"), new ButtonBase("Cancel", "cancel")); + var pd = new ConfirmDialog("Please confirm", new ButtonBase("Ok", "ok"), new ButtonBase("Cancel", "cancel")); pd.ButtonClicked += async (s, en) => { @@ -76,18 +71,18 @@ namespace TelegramBotBaseTest.Tests await pd.NavigateTo(tf); }; - await this.NavigateTo(pd); + await NavigateTo(pd); } else if (call.Value == "prompt") { - PromptDialog pd = new PromptDialog("Please tell me your name ?"); + var pd = new PromptDialog("Please tell me your name ?"); pd.Completed += async (s, en) => { - await this.Device.Send("Hello " + pd.Value); + await Device.Send("Hello " + pd.Value); }; - await this.OpenModal(pd); + await OpenModal(pd); } @@ -96,8 +91,8 @@ namespace TelegramBotBaseTest.Tests public override async Task Render(MessageResult message) { - Bitmap bmp = new Bitmap(800, 600); - using (Graphics g = Graphics.FromImage(bmp)) + var bmp = new Bitmap(800, 600); + using (var g = Graphics.FromImage(bmp)) { g.FillRectangle(Brushes.White, 0, 0, bmp.Width, bmp.Height); @@ -106,9 +101,9 @@ namespace TelegramBotBaseTest.Tests } - await this.Device.SetAction(Telegram.Bot.Types.Enums.ChatAction.UploadPhoto); + await Device.SetAction(ChatAction.UploadPhoto); - ButtonForm btn = new ButtonForm(); + var btn = new ButtonForm(); //btn.AddButtonRow(new ButtonBase("Zum Testformular 1", CallbackData.Create("navigate", "testform1")), new ButtonBase("Zum Testformular 1", CallbackData.Create("navigate", "testform1"))); @@ -119,7 +114,7 @@ namespace TelegramBotBaseTest.Tests btn.AddButtonRow(new ButtonBase("Request Prompt", CallbackData.Create("navigate", "prompt"))); - await this.Device.SendPhoto(bmp, "Test", "", btn); + await Device.SendPhoto(bmp, "Test", "", btn); } diff --git a/TelegramBotBase/Args/BotCommandEventArgs.cs b/TelegramBotBase/Args/BotCommandEventArgs.cs index ed9e62c..3f3d545 100644 --- a/TelegramBotBase/Args/BotCommandEventArgs.cs +++ b/TelegramBotBase/Args/BotCommandEventArgs.cs @@ -1,8 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using Telegram.Bot.Types; using TelegramBotBase.Sessions; @@ -13,9 +10,9 @@ namespace TelegramBotBase.Args /// public class BotCommandEventArgs : EventArgs { - public String Command { get; set; } + public string Command { get; set; } - public List Parameters { get; set; } + public List Parameters { get; set; } public long DeviceId { get; set; } @@ -32,13 +29,13 @@ namespace TelegramBotBase.Args } - public BotCommandEventArgs(String Command, List Parameters, Message Message, long DeviceId, DeviceSession Device) + public BotCommandEventArgs(string command, List parameters, Message message, long deviceId, DeviceSession device) { - this.Command = Command; - this.Parameters = Parameters; - this.OriginalMessage = Message; - this.DeviceId = DeviceId; - this.Device = Device; + this.Command = command; + this.Parameters = parameters; + OriginalMessage = message; + this.DeviceId = deviceId; + this.Device = device; } } diff --git a/TelegramBotBase/Args/ButtonClickedEventArgs.cs b/TelegramBotBase/Args/ButtonClickedEventArgs.cs index ef9ef71..2227abd 100644 --- a/TelegramBotBase/Args/ButtonClickedEventArgs.cs +++ b/TelegramBotBase/Args/ButtonClickedEventArgs.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Form; @@ -29,21 +25,21 @@ namespace TelegramBotBase.Args public ButtonClickedEventArgs(ButtonBase button) { - this.Button = button; - this.Index = -1; + Button = button; + Index = -1; } - public ButtonClickedEventArgs(ButtonBase button, int Index) + public ButtonClickedEventArgs(ButtonBase button, int index) { - this.Button = button; - this.Index = Index; + Button = button; + this.Index = index; } - public ButtonClickedEventArgs(ButtonBase button, int Index, ButtonRow row) + public ButtonClickedEventArgs(ButtonBase button, int index, ButtonRow row) { - this.Button = button; - this.Index = Index; - this.Row = row; + Button = button; + this.Index = index; + Row = row; } } } diff --git a/TelegramBotBase/Args/CheckedChangedEventArgs.cs b/TelegramBotBase/Args/CheckedChangedEventArgs.cs index 4750334..5ec61d3 100644 --- a/TelegramBotBase/Args/CheckedChangedEventArgs.cs +++ b/TelegramBotBase/Args/CheckedChangedEventArgs.cs @@ -1,15 +1,12 @@ using System; -using System.Collections.Generic; -using System.Text; using TelegramBotBase.Controls.Hybrid; -using TelegramBotBase.Form; namespace TelegramBotBase.Args { public class CheckedChangedEventArgs : EventArgs { /// - /// Contains the index of the row where the button is inside. + /// Contains the index of the row where the button is inside. /// Contains -1 when it is a layout button or not found. /// public int Index { get; set; } @@ -32,11 +29,11 @@ namespace TelegramBotBase.Args } - public CheckedChangedEventArgs(ButtonRow row, int Index, bool Checked) + public CheckedChangedEventArgs(ButtonRow row, int index, bool @checked) { - this.Row = row; - this.Index = Index; - this.Checked = Checked; + Row = row; + this.Index = index; + this.Checked = @checked; } diff --git a/TelegramBotBase/Args/GroupChangedEventArgs.cs b/TelegramBotBase/Args/GroupChangedEventArgs.cs index c1668a0..5493f9d 100644 --- a/TelegramBotBase/Args/GroupChangedEventArgs.cs +++ b/TelegramBotBase/Args/GroupChangedEventArgs.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using Telegram.Bot.Types.Enums; using TelegramBotBase.Base; @@ -14,8 +12,8 @@ namespace TelegramBotBase.Args public GroupChangedEventArgs(MessageType type, MessageResult message) { - this.Type = type; - this.OriginalMessage = message; + Type = type; + OriginalMessage = message; } diff --git a/TelegramBotBase/Args/InitEventArgs.cs b/TelegramBotBase/Args/InitEventArgs.cs index ec30db8..360aaa1 100644 --- a/TelegramBotBase/Args/InitEventArgs.cs +++ b/TelegramBotBase/Args/InitEventArgs.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace TelegramBotBase.Args { @@ -12,7 +8,7 @@ namespace TelegramBotBase.Args public InitEventArgs(params object[] args) { - this.Args = args; + Args = args; } } } diff --git a/TelegramBotBase/Args/LoadStateEventArgs.cs b/TelegramBotBase/Args/LoadStateEventArgs.cs index 7e79cb8..06834c7 100644 --- a/TelegramBotBase/Args/LoadStateEventArgs.cs +++ b/TelegramBotBase/Args/LoadStateEventArgs.cs @@ -1,42 +1,34 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; -using System.Text; namespace TelegramBotBase.Args { public class LoadStateEventArgs { - public Dictionary Values { get; set; } + public Dictionary Values { get; set; } public LoadStateEventArgs() { Values = new Dictionary(); } - public List Keys - { - get - { - return Values.Keys.ToList(); - } - } + public List Keys => Values.Keys.ToList(); - public String Get(String key) + public string Get(string key) { return Values[key].ToString(); } - public int GetInt(String key) + public int GetInt(string key) { - int i = 0; + var i = 0; if (int.TryParse(Values[key].ToString(), out i)) return i; return 0; } - public double GetDouble(String key) + public double GetDouble(string key) { double d = 0; if (double.TryParse(Values[key].ToString(), out d)) @@ -45,16 +37,16 @@ namespace TelegramBotBase.Args return 0; } - public bool GetBool(String key) + public bool GetBool(string key) { - bool b = false; + var b = false; if (bool.TryParse(Values[key].ToString(), out b)) return b; return false; } - public object GetObject(String key) + public object GetObject(string key) { return Values[key]; } diff --git a/TelegramBotBase/Args/MemberChangeEventArgs.cs b/TelegramBotBase/Args/MemberChangeEventArgs.cs index bc07add..34519a9 100644 --- a/TelegramBotBase/Args/MemberChangeEventArgs.cs +++ b/TelegramBotBase/Args/MemberChangeEventArgs.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using TelegramBotBase.Base; @@ -18,15 +17,15 @@ namespace TelegramBotBase.Args public MemberChangeEventArgs() { - this.Members = new List(); + Members = new List(); } public MemberChangeEventArgs(MessageType type, MessageResult result, params User[] members) { - this.Type = type; - this.Result = result; - this.Members = members.ToList(); + Type = type; + Result = result; + Members = members.ToList(); } diff --git a/TelegramBotBase/Args/MessageDeletedEventArgs.cs b/TelegramBotBase/Args/MessageDeletedEventArgs.cs index 69d262b..bab0af6 100644 --- a/TelegramBotBase/Args/MessageDeletedEventArgs.cs +++ b/TelegramBotBase/Args/MessageDeletedEventArgs.cs @@ -1,11 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Telegram.Bot.Types; - -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args { public class MessageDeletedEventArgs { @@ -16,7 +9,7 @@ namespace TelegramBotBase.Args public MessageDeletedEventArgs(int messageId) { - this.MessageId = messageId; + MessageId = messageId; } } diff --git a/TelegramBotBase/Args/MessageIncomeEventArgs.cs b/TelegramBotBase/Args/MessageIncomeEventArgs.cs index 38bad2a..5e6de76 100644 --- a/TelegramBotBase/Args/MessageIncomeEventArgs.cs +++ b/TelegramBotBase/Args/MessageIncomeEventArgs.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using TelegramBotBase.Sessions; namespace TelegramBotBase.Base @@ -16,11 +12,11 @@ namespace TelegramBotBase.Base public MessageResult Message { get; set; } - public MessageIncomeEventArgs(long DeviceId, DeviceSession Device, MessageResult message) + public MessageIncomeEventArgs(long deviceId, DeviceSession device, MessageResult message) { - this.DeviceId = DeviceId; - this.Device = Device; - this.Message = message; + this.DeviceId = deviceId; + this.Device = device; + Message = message; } diff --git a/TelegramBotBase/Args/MessageReceivedEventArgs.cs b/TelegramBotBase/Args/MessageReceivedEventArgs.cs index 397c6af..497782f 100644 --- a/TelegramBotBase/Args/MessageReceivedEventArgs.cs +++ b/TelegramBotBase/Args/MessageReceivedEventArgs.cs @@ -1,27 +1,16 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Telegram.Bot.Types; +using Telegram.Bot.Types; namespace TelegramBotBase.Args { public class MessageReceivedEventArgs { - public int MessageId - { - get - { - return this.Message.MessageId; - } - } + public int MessageId => Message.MessageId; public Message Message { get; set; } public MessageReceivedEventArgs(Message m) { - this.Message = m; + Message = m; } } diff --git a/TelegramBotBase/Args/MessageSentEventArgs.cs b/TelegramBotBase/Args/MessageSentEventArgs.cs index 9cfe651..a776207 100644 --- a/TelegramBotBase/Args/MessageSentEventArgs.cs +++ b/TelegramBotBase/Args/MessageSentEventArgs.cs @@ -1,21 +1,11 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using Telegram.Bot.Types; namespace TelegramBotBase.Args { public class MessageSentEventArgs : EventArgs { - public int MessageId - { - get - { - return this.Message.MessageId; - } - } + public int MessageId => Message.MessageId; public Message Message { get; set; } @@ -25,10 +15,10 @@ namespace TelegramBotBase.Args public Type Origin { get; set; } - public MessageSentEventArgs(Message message, Type Origin) + public MessageSentEventArgs(Message message, Type origin) { - this.Message = message; - this.Origin = Origin; + Message = message; + this.Origin = origin; } diff --git a/TelegramBotBase/Args/PromptDialogCompletedEventArgs.cs b/TelegramBotBase/Args/PromptDialogCompletedEventArgs.cs index 14f9cf8..b0b7e04 100644 --- a/TelegramBotBase/Args/PromptDialogCompletedEventArgs.cs +++ b/TelegramBotBase/Args/PromptDialogCompletedEventArgs.cs @@ -1,14 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args { public class PromptDialogCompletedEventArgs { public object Tag { get; set; } - public String Value { get; set; } + public string Value { get; set; } } } diff --git a/TelegramBotBase/Args/RenderViewEventArgs.cs b/TelegramBotBase/Args/RenderViewEventArgs.cs index a733291..82df8e5 100644 --- a/TelegramBotBase/Args/RenderViewEventArgs.cs +++ b/TelegramBotBase/Args/RenderViewEventArgs.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; namespace TelegramBotBase.Args { @@ -9,10 +7,10 @@ namespace TelegramBotBase.Args public int CurrentView { get; set; } - public RenderViewEventArgs(int ViewIndex) + public RenderViewEventArgs(int viewIndex) { - CurrentView = ViewIndex; + CurrentView = viewIndex; } diff --git a/TelegramBotBase/Args/SaveStateEventArgs.cs b/TelegramBotBase/Args/SaveStateEventArgs.cs index 4b26dea..bfc3984 100644 --- a/TelegramBotBase/Args/SaveStateEventArgs.cs +++ b/TelegramBotBase/Args/SaveStateEventArgs.cs @@ -1,38 +1,36 @@ -using System; -using System.Collections.Generic; -using System.Text; +using System.Collections.Generic; namespace TelegramBotBase.Args { public class SaveStateEventArgs { - public Dictionary Values { get; set; } + public Dictionary Values { get; set; } public SaveStateEventArgs() { Values = new Dictionary(); } - public void Set(String key, String value) + public void Set(string key, string value) { Values[key] = value; } - public void SetInt(String key, int value) + public void SetInt(string key, int value) { Values[key] = value; } - public void SetBool(String key, bool value) + public void SetBool(string key, bool value) { Values[key] = value; } - public void SetDouble(String key, double value) + public void SetDouble(string key, double value) { Values[key] = value; } - public void SetObject(String key, object value) + public void SetObject(string key, object value) { Values[key] = value; } diff --git a/TelegramBotBase/Args/SaveStatesEventArgs.cs b/TelegramBotBase/Args/SaveStatesEventArgs.cs index 2d6a3e5..e2d44f6 100644 --- a/TelegramBotBase/Args/SaveStatesEventArgs.cs +++ b/TelegramBotBase/Args/SaveStatesEventArgs.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using TelegramBotBase.Base; -using TelegramBotBase.Sessions; +using TelegramBotBase.Base; namespace TelegramBotBase.Args { @@ -14,7 +9,7 @@ namespace TelegramBotBase.Args public SaveStatesEventArgs(StateContainer states) { - this.States = states; + States = states; } } } diff --git a/TelegramBotBase/Args/SessionBeginEventArgs.cs b/TelegramBotBase/Args/SessionBeginEventArgs.cs index 778b5df..9187f0b 100644 --- a/TelegramBotBase/Args/SessionBeginEventArgs.cs +++ b/TelegramBotBase/Args/SessionBeginEventArgs.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using TelegramBotBase.Sessions; namespace TelegramBotBase.Base @@ -13,10 +9,10 @@ namespace TelegramBotBase.Base public DeviceSession Device { get; set; } - public SessionBeginEventArgs(long DeviceId, DeviceSession Device) + public SessionBeginEventArgs(long deviceId, DeviceSession device) { - this.DeviceId = DeviceId; - this.Device = Device; + this.DeviceId = deviceId; + this.Device = device; } } } diff --git a/TelegramBotBase/Args/SystemExceptionEventArgs.cs b/TelegramBotBase/Args/SystemExceptionEventArgs.cs index 229fa91..cc19a62 100644 --- a/TelegramBotBase/Args/SystemExceptionEventArgs.cs +++ b/TelegramBotBase/Args/SystemExceptionEventArgs.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using TelegramBotBase.Sessions; namespace TelegramBotBase.Args @@ -10,7 +6,7 @@ namespace TelegramBotBase.Args public class SystemExceptionEventArgs : EventArgs { - public String Command { get; set; } + public string Command { get; set; } public long DeviceId { get; set; } @@ -24,12 +20,12 @@ namespace TelegramBotBase.Args } - public SystemExceptionEventArgs(String Command, long DeviceId, DeviceSession Device, Exception error) + public SystemExceptionEventArgs(string command, long deviceId, DeviceSession device, Exception error) { - this.Command = Command; - this.DeviceId = DeviceId; - this.Device = Device; - this.Error = error; + this.Command = command; + this.DeviceId = deviceId; + this.Device = device; + Error = error; } } diff --git a/TelegramBotBase/Args/UnhandledCallEventArgs.cs b/TelegramBotBase/Args/UnhandledCallEventArgs.cs index e839e2d..279170f 100644 --- a/TelegramBotBase/Args/UnhandledCallEventArgs.cs +++ b/TelegramBotBase/Args/UnhandledCallEventArgs.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using Telegram.Bot.Types; using TelegramBotBase.Sessions; @@ -10,13 +6,13 @@ namespace TelegramBotBase.Args { public class UnhandledCallEventArgs : EventArgs { - public String Command { get; set; } + public string Command { get; set; } public long DeviceId { get; set; } public DeviceSession Device {get;set;} - public String RawData { get; set; } + public string RawData { get; set; } public int MessageId { get; set; } @@ -27,18 +23,18 @@ namespace TelegramBotBase.Args public UnhandledCallEventArgs() { - this.Handled = false; + Handled = false; } - public UnhandledCallEventArgs(String Command,String RawData, long DeviceId, int MessageId, Message message, DeviceSession Device) : this() + public UnhandledCallEventArgs(string command,string rawData, long deviceId, int messageId, Message message, DeviceSession device) : this() { - this.Command = Command; - this.RawData = RawData; - this.DeviceId = DeviceId; - this.MessageId = MessageId; - this.Message = message; - this.Device = Device; + this.Command = command; + this.RawData = rawData; + this.DeviceId = deviceId; + this.MessageId = messageId; + Message = message; + this.Device = device; } } diff --git a/TelegramBotBase/Attributes/IgnoreState.cs b/TelegramBotBase/Attributes/IgnoreState.cs index e1c5543..72c4381 100644 --- a/TelegramBotBase/Attributes/IgnoreState.cs +++ b/TelegramBotBase/Attributes/IgnoreState.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; namespace TelegramBotBase.Attributes { diff --git a/TelegramBotBase/Attributes/SaveState.cs b/TelegramBotBase/Attributes/SaveState.cs index a07fe6b..9b9190b 100644 --- a/TelegramBotBase/Attributes/SaveState.cs +++ b/TelegramBotBase/Attributes/SaveState.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; namespace TelegramBotBase.Attributes { @@ -9,7 +7,7 @@ namespace TelegramBotBase.Attributes /// public class SaveState : Attribute { - public String Key { get; set; } + public string Key { get; set; } } } diff --git a/TelegramBotBase/Base/Async.cs b/TelegramBotBase/Base/Async.cs index ac190c7..9eff287 100644 --- a/TelegramBotBase/Base/Async.cs +++ b/TelegramBotBase/Base/Async.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading.Tasks; namespace TelegramBotBase.Base diff --git a/TelegramBotBase/Base/ControlBase.cs b/TelegramBotBase/Base/ControlBase.cs index 234554f..b06b2d3 100644 --- a/TelegramBotBase/Base/ControlBase.cs +++ b/TelegramBotBase/Base/ControlBase.cs @@ -1,8 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; +using TelegramBotBase.Sessions; namespace TelegramBotBase.Base { @@ -11,17 +8,11 @@ namespace TelegramBotBase.Base /// public class ControlBase { - public Sessions.DeviceSession Device { get; set; } + public DeviceSession Device { get; set; } - public int ID { get; set; } + public int Id { get; set; } - public String ControlID - { - get - { - return "#c" + this.ID.ToString(); - } - } + public string ControlId => "#c" + Id; /// /// Defines if the control should be rendered and invoked with actions @@ -37,43 +28,35 @@ namespace TelegramBotBase.Base } - public virtual async Task Load(MessageResult result) + public virtual Task Load(MessageResult result) { - - - + return Task.CompletedTask; } - public virtual async Task Action(MessageResult result, String value = null) + public virtual Task Action(MessageResult result, string value = null) { - - - + return Task.CompletedTask; } - public virtual async Task Render(MessageResult result) + public virtual Task Render(MessageResult result) { - - - - + return Task.CompletedTask; } - public virtual async Task Hidden(bool FormClose) + public virtual Task Hidden(bool formClose) { - - + return Task.CompletedTask; } /// /// Will be called on a cleanup. /// /// - public virtual async Task Cleanup() + public virtual Task Cleanup() { - + return Task.CompletedTask; } } diff --git a/TelegramBotBase/Base/DataResult.cs b/TelegramBotBase/Base/DataResult.cs index fb87df0..bebef80 100644 --- a/TelegramBotBase/Base/DataResult.cs +++ b/TelegramBotBase/Base/DataResult.cs @@ -1,11 +1,10 @@ -using System; -using System.Collections.Generic; -using System.IO; +using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Telegram.Bot; using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.InputFiles; namespace TelegramBotBase.Base @@ -21,98 +20,45 @@ namespace TelegramBotBase.Base public UpdateResult UpdateData { get; set; } - public Contact Contact - { - get - { - return this.Message.Contact; - } - } + public Contact Contact => Message.Contact; - public Location Location - { - get - { - return this.Message.Location; - } - } + public Location Location => Message.Location; - public Document Document - { - get - { - return this.Message.Document; - } - } + public Document Document => Message.Document; - public Audio Audio - { - get - { - return this.Message.Audio; - } - } + public Audio Audio => Message.Audio; - public Video Video - { - get - { - return this.Message.Video; - } - } + public Video Video => Message.Video; - public PhotoSize[] Photos - { - get - { - return this.Message.Photo; - } - } + public PhotoSize[] Photos => Message.Photo; - public Telegram.Bot.Types.Enums.MessageType Type - { - get - { - return this.Message?.Type ?? Telegram.Bot.Types.Enums.MessageType.Unknown; - } - } + public MessageType Type => Message?.Type ?? MessageType.Unknown; - public override Message Message - { - get - { - return this.UpdateData?.Message; - } - } + public override Message Message => UpdateData?.Message; /// /// Returns the FileId of the first reachable element. /// - public String FileId - { - get - { - return (this.Document?.FileId ?? - this.Audio?.FileId ?? - this.Video?.FileId ?? - this.Photos.FirstOrDefault()?.FileId); - } - } + public string FileId => + (Document?.FileId ?? + Audio?.FileId ?? + Video?.FileId ?? + Photos.FirstOrDefault()?.FileId); public DataResult(UpdateResult update) { - this.UpdateData = update; + UpdateData = update; } public async Task DownloadDocument() { - var encryptedContent = new System.IO.MemoryStream(); - encryptedContent.SetLength(this.Document.FileSize.Value); - var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Document.FileId, encryptedContent); + var encryptedContent = new MemoryStream(); + encryptedContent.SetLength(Document.FileSize.Value); + var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, encryptedContent); - return new InputOnlineFile(encryptedContent, this.Document.FileName); + return new InputOnlineFile(encryptedContent, Document.FileName); } @@ -121,10 +67,10 @@ namespace TelegramBotBase.Base /// /// /// - public async Task DownloadDocument(String path) + public async Task DownloadDocument(string path) { - var file = await Device.Client.TelegramClient.GetFileAsync(this.Document.FileId); - FileStream fs = new FileStream(path, FileMode.Create); + var file = await Device.Client.TelegramClient.GetFileAsync(Document.FileId); + var fs = new FileStream(path, FileMode.Create); await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); fs.Close(); fs.Dispose(); @@ -136,8 +82,8 @@ namespace TelegramBotBase.Base /// public async Task DownloadRawDocument() { - MemoryStream ms = new MemoryStream(); - await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Document.FileId, ms); + var ms = new MemoryStream(); + await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, ms); return ms.ToArray(); } @@ -145,7 +91,7 @@ namespace TelegramBotBase.Base /// Downloads a document and returns it as string. (txt,csv,etc) Default encoding ist UTF8. /// /// - public async Task DownloadRawTextDocument() + public async Task DownloadRawTextDocument() { return await DownloadRawTextDocument(Encoding.UTF8); } @@ -154,10 +100,10 @@ namespace TelegramBotBase.Base /// Downloads a document and returns it as string. (txt,csv,etc) /// /// - public async Task DownloadRawTextDocument(Encoding encoding) + public async Task DownloadRawTextDocument(Encoding encoding) { - MemoryStream ms = new MemoryStream(); - await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Document.FileId, ms); + var ms = new MemoryStream(); + await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, ms); ms.Position = 0; @@ -168,17 +114,17 @@ namespace TelegramBotBase.Base public async Task DownloadVideo() { - var encryptedContent = new System.IO.MemoryStream(); - encryptedContent.SetLength(this.Video.FileSize.Value); - var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Video.FileId, encryptedContent); + var encryptedContent = new MemoryStream(); + encryptedContent.SetLength(Video.FileSize.Value); + var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Video.FileId, encryptedContent); return new InputOnlineFile(encryptedContent, ""); } - public async Task DownloadVideo(String path) + public async Task DownloadVideo(string path) { - var file = await Device.Client.TelegramClient.GetFileAsync(this.Video.FileId); - FileStream fs = new FileStream(path, FileMode.Create); + var file = await Device.Client.TelegramClient.GetFileAsync(Video.FileId); + var fs = new FileStream(path, FileMode.Create); await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); fs.Close(); fs.Dispose(); @@ -186,17 +132,17 @@ namespace TelegramBotBase.Base public async Task DownloadAudio() { - var encryptedContent = new System.IO.MemoryStream(); - encryptedContent.SetLength(this.Audio.FileSize.Value); - var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Audio.FileId, encryptedContent); + var encryptedContent = new MemoryStream(); + encryptedContent.SetLength(Audio.FileSize.Value); + var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Audio.FileId, encryptedContent); return new InputOnlineFile(encryptedContent, ""); } - public async Task DownloadAudio(String path) + public async Task DownloadAudio(string path) { - var file = await Device.Client.TelegramClient.GetFileAsync(this.Audio.FileId); - FileStream fs = new FileStream(path, FileMode.Create); + var file = await Device.Client.TelegramClient.GetFileAsync(Audio.FileId); + var fs = new FileStream(path, FileMode.Create); await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); fs.Close(); fs.Dispose(); @@ -204,19 +150,19 @@ namespace TelegramBotBase.Base public async Task DownloadPhoto(int index) { - var photo = this.Photos[index]; - var encryptedContent = new System.IO.MemoryStream(); + var photo = Photos[index]; + var encryptedContent = new MemoryStream(); encryptedContent.SetLength(photo.FileSize.Value); var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(photo.FileId, encryptedContent); return new InputOnlineFile(encryptedContent, ""); } - public async Task DownloadPhoto(int index, String path) + public async Task DownloadPhoto(int index, string path) { - var photo = this.Photos[index]; + var photo = Photos[index]; var file = await Device.Client.TelegramClient.GetFileAsync(photo.FileId); - FileStream fs = new FileStream(path, FileMode.Create); + var fs = new FileStream(path, FileMode.Create); await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); fs.Close(); fs.Dispose(); diff --git a/TelegramBotBase/Base/FormBase.cs b/TelegramBotBase/Base/FormBase.cs index 291e733..583eabe 100644 --- a/TelegramBotBase/Base/FormBase.cs +++ b/TelegramBotBase/Base/FormBase.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.ComponentModel; using System.Linq; -using System.Text; using System.Threading.Tasks; using TelegramBotBase.Args; using TelegramBotBase.Base; @@ -27,7 +26,7 @@ namespace TelegramBotBase.Form /// /// has this formular already been disposed ? /// - public bool IsDisposed { get; set; } = false; + public bool IsDisposed { get; set; } public List Controls { get; set; } @@ -35,33 +34,33 @@ namespace TelegramBotBase.Form public EventHandlerList Events = new EventHandlerList(); - private static object __evInit = new object(); + private static readonly object EvInit = new object(); - private static object __evOpened = new object(); + private static readonly object EvOpened = new object(); - private static object __evClosed = new object(); + private static readonly object EvClosed = new object(); public FormBase() { - this.Controls = new List(); + Controls = new List(); } - public FormBase(MessageClient Client) : this() + public FormBase(MessageClient client) : this() { - this.Client = Client; + this.Client = client; } public async Task OnInit(InitEventArgs e) { - var handler = this.Events[__evInit]?.GetInvocationList().Cast>(); + var handler = Events[EvInit]?.GetInvocationList().Cast>(); if (handler == null) return; foreach (var h in handler) { - await Async.InvokeAllAsync(h, this, e); + await h.InvokeAllAsync(this, e); } } @@ -70,27 +69,21 @@ namespace TelegramBotBase.Form ///// public event AsyncEventHandler Init { - add - { - this.Events.AddHandler(__evInit, value); - } - remove - { - this.Events.RemoveHandler(__evInit, value); - } + add => Events.AddHandler(EvInit, value); + remove => Events.RemoveHandler(EvInit, value); } public async Task OnOpened(EventArgs e) { - var handler = this.Events[__evOpened]?.GetInvocationList().Cast>(); + var handler = Events[EvOpened]?.GetInvocationList().Cast>(); if (handler == null) return; foreach (var h in handler) { - await Async.InvokeAllAsync(h, this, e); + await h.InvokeAllAsync(this, e); } } @@ -100,27 +93,21 @@ namespace TelegramBotBase.Form /// public event AsyncEventHandler Opened { - add - { - this.Events.AddHandler(__evOpened, value); - } - remove - { - this.Events.RemoveHandler(__evOpened, value); - } + add => Events.AddHandler(EvOpened, value); + remove => Events.RemoveHandler(EvOpened, value); } public async Task OnClosed(EventArgs e) { - var handler = this.Events[__evClosed]?.GetInvocationList().Cast>(); + var handler = Events[EvClosed]?.GetInvocationList().Cast>(); if (handler == null) return; foreach (var h in handler) { - await Async.InvokeAllAsync(h, this, e); + await h.InvokeAllAsync(this, e); } } @@ -131,14 +118,8 @@ namespace TelegramBotBase.Form /// public event AsyncEventHandler Closed { - add - { - this.Events.AddHandler(__evClosed, value); - } - remove - { - this.Events.RemoveHandler(__evClosed, value); - } + add => Events.AddHandler(EvClosed, value); + remove => Events.RemoveHandler(EvClosed, value); } /// @@ -146,9 +127,9 @@ namespace TelegramBotBase.Form /// /// /// - public virtual async Task ReturnFromModal(ModalDialog modal) + public virtual Task ReturnFromModal(ModalDialog modal) { - + return Task.CompletedTask; } @@ -156,17 +137,19 @@ namespace TelegramBotBase.Form /// Pre to form close, cleanup all controls /// /// - public async Task CloseControls() + public Task CloseControls() { - foreach (var b in this.Controls) + foreach (var b in Controls) { b.Cleanup().Wait(); } + + return Task.CompletedTask; } - public virtual async Task PreLoad(MessageResult message) + public virtual Task PreLoad(MessageResult message) { - + return Task.CompletedTask; } /// @@ -179,7 +162,7 @@ namespace TelegramBotBase.Form //Looking for the control by id, if not listened, raise event for all if (message.RawData?.StartsWith("#c") ?? false) { - var c = this.Controls.FirstOrDefault(a => a.ControlID == message.RawData.Split('_')[0]); + var c = Controls.FirstOrDefault(a => a.ControlId == message.RawData.Split('_')[0]); if (c != null) { await c.Load(message); @@ -187,7 +170,7 @@ namespace TelegramBotBase.Form } } - foreach (var b in this.Controls) + foreach (var b in Controls) { if (!b.Enabled) continue; @@ -201,9 +184,9 @@ namespace TelegramBotBase.Form /// /// /// - public virtual async Task Load(MessageResult message) + public virtual Task Load(MessageResult message) { - + return Task.CompletedTask; } /// @@ -211,9 +194,9 @@ namespace TelegramBotBase.Form /// /// /// - public virtual async Task Edited(MessageResult message) + public virtual Task Edited(MessageResult message) { - + return Task.CompletedTask; } @@ -227,7 +210,7 @@ namespace TelegramBotBase.Form //Looking for the control by id, if not listened, raise event for all if (message.RawData.StartsWith("#c")) { - var c = this.Controls.FirstOrDefault(a => a.ControlID == message.RawData.Split('_')[0]); + var c = Controls.FirstOrDefault(a => a.ControlId == message.RawData.Split('_')[0]); if (c != null) { await c.Action(message, message.RawData.Split('_')[1]); @@ -235,7 +218,7 @@ namespace TelegramBotBase.Form } } - foreach (var b in this.Controls) + foreach (var b in Controls) { if (!b.Enabled) continue; @@ -252,9 +235,9 @@ namespace TelegramBotBase.Form /// /// /// - public virtual async Task Action(MessageResult message) + public virtual Task Action(MessageResult message) { - + return Task.CompletedTask; } /// @@ -262,9 +245,9 @@ namespace TelegramBotBase.Form /// /// /// - public virtual async Task SentData(DataResult message) + public virtual Task SentData(DataResult message) { - + return Task.CompletedTask; } /// @@ -274,7 +257,7 @@ namespace TelegramBotBase.Form /// public virtual async Task RenderControls(MessageResult message) { - foreach (var b in this.Controls) + foreach (var b in Controls) { if (!b.Enabled) continue; @@ -288,9 +271,9 @@ namespace TelegramBotBase.Form /// /// /// - public virtual async Task Render(MessageResult message) + public virtual Task Render(MessageResult message) { - + return Task.CompletedTask; } @@ -302,7 +285,7 @@ namespace TelegramBotBase.Form /// public virtual async Task NavigateTo(FormBase newForm, params object[] args) { - DeviceSession ds = this.Device; + var ds = Device; if (ds == null) return; @@ -311,11 +294,11 @@ namespace TelegramBotBase.Form ds.PreviousForm = ds.ActiveForm; ds.ActiveForm = newForm; - newForm.Client = this.Client; + newForm.Client = Client; newForm.Device = ds; //Notify prior to close - foreach (var b in this.Controls) + foreach (var b in Controls) { if (!b.Enabled) continue; @@ -323,13 +306,13 @@ namespace TelegramBotBase.Form await b.Hidden(true); } - this.CloseControls().Wait(); + CloseControls().Wait(); - await this.OnClosed(new EventArgs()); + await OnClosed(EventArgs.Empty); await newForm.OnInit(new InitEventArgs(args)); - await newForm.OnOpened(new EventArgs()); + await newForm.OnOpened(EventArgs.Empty); } /// @@ -339,7 +322,7 @@ namespace TelegramBotBase.Form /// public virtual async Task OpenModal(ModalDialog newForm, params object[] args) { - DeviceSession ds = this.Device; + var ds = Device; if (ds == null) return; @@ -359,7 +342,7 @@ namespace TelegramBotBase.Form await CloseModal(newForm, parentForm); }; - foreach (var b in this.Controls) + foreach (var b in Controls) { if (!b.Enabled) continue; @@ -369,14 +352,14 @@ namespace TelegramBotBase.Form await newForm.OnInit(new InitEventArgs(args)); - await newForm.OnOpened(new EventArgs()); + await newForm.OnOpened(EventArgs.Empty); } - public async Task CloseModal(ModalDialog modalForm, FormBase oldForm) + public Task CloseModal(ModalDialog modalForm, FormBase oldForm) { - DeviceSession ds = this.Device; + var ds = Device; if (ds == null) - return; + return Task.CompletedTask; if (modalForm == null) throw new Exception("No modal form"); @@ -386,6 +369,7 @@ namespace TelegramBotBase.Form ds.PreviousForm = ds.ActiveForm; ds.ActiveForm = oldForm; + return Task.CompletedTask; } /// @@ -395,12 +379,12 @@ namespace TelegramBotBase.Form public void AddControl(ControlBase control) { //Duplicate check - if (this.Controls.Contains(control)) + if (Controls.Contains(control)) throw new ArgumentException("Control has been already added."); - control.ID = this.Controls.Count + 1; - control.Device = this.Device; - this.Controls.Add(control); + control.Id = Controls.Count + 1; + control.Device = Device; + Controls.Add(control); control.Init(); } @@ -411,12 +395,12 @@ namespace TelegramBotBase.Form /// public void RemoveControl(ControlBase control) { - if (!this.Controls.Contains(control)) + if (!Controls.Contains(control)) return; control.Cleanup().Wait(); - this.Controls.Remove(control); + Controls.Remove(control); } /// @@ -424,11 +408,11 @@ namespace TelegramBotBase.Form /// public void RemoveAllControls() { - foreach(var c in this.Controls) + foreach(var c in Controls) { c.Cleanup().Wait(); - this.Controls.Remove(c); + Controls.Remove(c); } } @@ -437,9 +421,9 @@ namespace TelegramBotBase.Form /// public void Dispose() { - this.Client = null; - this.Device = null; - this.IsDisposed = true; + Client = null; + Device = null; + IsDisposed = true; } } } diff --git a/TelegramBotBase/Base/MessageClient.cs b/TelegramBotBase/Base/MessageClient.cs index 85195f9..4813d86 100644 --- a/TelegramBotBase/Base/MessageClient.cs +++ b/TelegramBotBase/Base/MessageClient.cs @@ -1,17 +1,14 @@ using System; using System.Collections.Generic; using System.ComponentModel; -using System.Linq; using System.Net; using System.Net.Http; -using System.Text; using System.Threading; using System.Threading.Tasks; -using Telegram.Bot.Exceptions; using Telegram.Bot; -using Telegram.Bot.Types; -using Telegram.Bot.Types.Enums; +using Telegram.Bot.Exceptions; using Telegram.Bot.Extensions.Polling; +using Telegram.Bot.Types; namespace TelegramBotBase.Base { @@ -22,13 +19,13 @@ namespace TelegramBotBase.Base { - public String APIKey { get; set; } + public string ApiKey { get; set; } public ITelegramBotClient TelegramClient { get; set; } - private EventHandlerList __Events { get; set; } = new EventHandlerList(); + private EventHandlerList Events { get; set; } = new EventHandlerList(); - private static object __evOnMessageLoop = new object(); + private static readonly object EvOnMessageLoop = new object(); private static object __evOnMessage = new object(); @@ -36,21 +33,21 @@ namespace TelegramBotBase.Base private static object __evCallbackQuery = new object(); - CancellationTokenSource __cancellationTokenSource; + private CancellationTokenSource _cancellationTokenSource; - public MessageClient(String APIKey) + public MessageClient(string apiKey) { - this.APIKey = APIKey; - this.TelegramClient = new Telegram.Bot.TelegramBotClient(APIKey); + this.ApiKey = apiKey; + TelegramClient = new TelegramBotClient(apiKey); Prepare(); } - public MessageClient(String APIKey, HttpClient proxy) + public MessageClient(string apiKey, HttpClient proxy) { - this.APIKey = APIKey; - this.TelegramClient = new Telegram.Bot.TelegramBotClient(APIKey, proxy); + this.ApiKey = apiKey; + TelegramClient = new TelegramBotClient(apiKey, proxy); Prepare(); @@ -58,9 +55,9 @@ namespace TelegramBotBase.Base - public MessageClient(String APIKey, Uri proxyUrl, NetworkCredential credential = null) + public MessageClient(string apiKey, Uri proxyUrl, NetworkCredential credential = null) { - this.APIKey = APIKey; + this.ApiKey = apiKey; var proxy = new WebProxy(proxyUrl) { @@ -71,7 +68,7 @@ namespace TelegramBotBase.Base new HttpClientHandler { Proxy = proxy, UseProxy = true } ); - this.TelegramClient = new Telegram.Bot.TelegramBotClient(APIKey, httpClient); + TelegramClient = new TelegramBotClient(apiKey, httpClient); Prepare(); } @@ -79,12 +76,12 @@ namespace TelegramBotBase.Base /// /// Initializes the client with a proxy /// - /// + /// /// i.e. 127.0.0.1 /// i.e. 10000 - public MessageClient(String APIKey, String proxyHost, int proxyPort) + public MessageClient(string apiKey, string proxyHost, int proxyPort) { - this.APIKey = APIKey; + this.ApiKey = apiKey; var proxy = new WebProxy(proxyHost, proxyPort); @@ -92,17 +89,17 @@ namespace TelegramBotBase.Base new HttpClientHandler { Proxy = proxy, UseProxy = true } ); - this.TelegramClient = new Telegram.Bot.TelegramBotClient(APIKey, httpClient); + TelegramClient = new TelegramBotClient(apiKey, httpClient); Prepare(); } - public MessageClient(String APIKey, Telegram.Bot.TelegramBotClient Client) + public MessageClient(string apiKey, TelegramBotClient client) { - this.APIKey = APIKey; - this.TelegramClient = Client; + this.ApiKey = apiKey; + TelegramClient = client; Prepare(); } @@ -110,7 +107,7 @@ namespace TelegramBotBase.Base public void Prepare() { - this.TelegramClient.Timeout = new TimeSpan(0, 0, 30); + TelegramClient.Timeout = new TimeSpan(0, 0, 30); } @@ -118,19 +115,16 @@ namespace TelegramBotBase.Base public void StartReceiving() { - __cancellationTokenSource = new CancellationTokenSource(); + _cancellationTokenSource = new CancellationTokenSource(); - var receiverOptions = new ReceiverOptions - { - AllowedUpdates = { } // receive all update types - }; + var receiverOptions = new ReceiverOptions(); - this.TelegramClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, receiverOptions, __cancellationTokenSource.Token); + TelegramClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, receiverOptions, _cancellationTokenSource.Token); } public void StopReceiving() { - __cancellationTokenSource.Cancel(); + _cancellationTokenSource.Cancel(); } @@ -143,9 +137,9 @@ namespace TelegramBotBase.Base public Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken) { - if (exception is ApiRequestException exAPI) + if (exception is ApiRequestException exApi) { - Console.WriteLine($"Telegram API Error:\n[{exAPI.ErrorCode}]\n{exAPI.Message}"); + Console.WriteLine($"Telegram API Error:\n[{exApi.ErrorCode}]\n{exApi.Message}"); } else { @@ -159,9 +153,9 @@ namespace TelegramBotBase.Base /// This will return the current list of bot commands. /// /// - public async Task GetBotCommands(BotCommandScope scope = null, String languageCode = null) + public async Task GetBotCommands(BotCommandScope scope = null, string languageCode = null) { - return await this.TelegramClient.GetMyCommandsAsync(scope, languageCode); + return await TelegramClient.GetMyCommandsAsync(scope, languageCode); } @@ -170,18 +164,18 @@ namespace TelegramBotBase.Base /// /// /// - public async Task SetBotCommands(List botcommands, BotCommandScope scope = null, String languageCode = null) + public async Task SetBotCommands(List botcommands, BotCommandScope scope = null, string languageCode = null) { - await this.TelegramClient.SetMyCommandsAsync(botcommands, scope, languageCode); + await TelegramClient.SetMyCommandsAsync(botcommands, scope, languageCode); } /// /// This will delete the current list of bot commands. /// /// - public async Task DeleteBotCommands(BotCommandScope scope = null, String languageCode = null) + public async Task DeleteBotCommands(BotCommandScope scope = null, string languageCode = null) { - await this.TelegramClient.DeleteMyCommandsAsync(scope, languageCode); + await TelegramClient.DeleteMyCommandsAsync(scope, languageCode); } @@ -191,19 +185,13 @@ namespace TelegramBotBase.Base public event Async.AsyncEventHandler MessageLoop { - add - { - this.__Events.AddHandler(__evOnMessageLoop, value); - } - remove - { - this.__Events.RemoveHandler(__evOnMessageLoop, value); - } + add => Events.AddHandler(EvOnMessageLoop, value); + remove => Events.RemoveHandler(EvOnMessageLoop, value); } public void OnMessageLoop(UpdateResult update) { - (this.__Events[__evOnMessageLoop] as Async.AsyncEventHandler)?.Invoke(this, update); + (Events[EvOnMessageLoop] as Async.AsyncEventHandler)?.Invoke(this, update); } diff --git a/TelegramBotBase/Base/MessageResult.cs b/TelegramBotBase/Base/MessageResult.cs index 2e6148b..7d39fe7 100644 --- a/TelegramBotBase/Base/MessageResult.cs +++ b/TelegramBotBase/Base/MessageResult.cs @@ -1,110 +1,56 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading.Tasks; -using Telegram.Bot; +using Newtonsoft.Json; using Telegram.Bot.Types; -using TelegramBotBase.Sessions; +using Telegram.Bot.Types.Enums; namespace TelegramBotBase.Base { public class MessageResult : ResultBase { - public Telegram.Bot.Types.Update UpdateData { get; set; } + public Update UpdateData { get; set; } /// /// Returns the Device/ChatId /// - public override long DeviceId - { - get - { - return this.UpdateData?.Message?.Chat?.Id - ?? this.UpdateData?.EditedMessage?.Chat.Id - ?? this.UpdateData?.CallbackQuery.Message?.Chat.Id - ?? Device?.DeviceId - ?? 0; - } - } + public override long DeviceId => + UpdateData?.Message?.Chat?.Id + ?? UpdateData?.EditedMessage?.Chat.Id + ?? UpdateData?.CallbackQuery.Message?.Chat.Id + ?? Device?.DeviceId + ?? 0; /// /// The message id /// - public new int MessageId - { - get - { - return this.UpdateData?.Message?.MessageId - ?? this.Message?.MessageId - ?? this.UpdateData?.CallbackQuery?.Message?.MessageId - ?? 0; - } - } + public new int MessageId => + UpdateData?.Message?.MessageId + ?? Message?.MessageId + ?? UpdateData?.CallbackQuery?.Message?.MessageId + ?? 0; - public String Command - { - get - { - return this.UpdateData?.Message?.Text ?? ""; - } - } + public string Command => UpdateData?.Message?.Text ?? ""; - public String MessageText - { - get - { - return this.UpdateData?.Message?.Text ?? ""; - } - } + public string MessageText => UpdateData?.Message?.Text ?? ""; - public Telegram.Bot.Types.Enums.MessageType MessageType - { - get - { - return Message?.Type ?? Telegram.Bot.Types.Enums.MessageType.Unknown; - } - } - - public Message Message - { - get - { - return this.UpdateData?.Message - ?? this.UpdateData?.EditedMessage - ?? this.UpdateData?.ChannelPost - ?? this.UpdateData?.EditedChannelPost - ?? this.UpdateData?.CallbackQuery?.Message; - } - } + public MessageType MessageType => Message?.Type ?? MessageType.Unknown; /// /// Is this an action ? (i.e. button click) /// - public bool IsAction - { - get - { - return (this.UpdateData.CallbackQuery != null); - } - } + public bool IsAction => (UpdateData.CallbackQuery != null); /// /// Is this a command ? Starts with a slash '/' and a command /// - public bool IsBotCommand - { - get - { - return (this.MessageText.StartsWith("/")); - } - } + public bool IsBotCommand => (MessageText.StartsWith("/")); /// /// Returns a List of all parameters which has been sent with the command itself (i.e. /start 123 456 789 => 123,456,789) /// - public List BotCommandParameters + public List BotCommandParameters { get { @@ -112,21 +58,21 @@ namespace TelegramBotBase.Base return new List(); //Split by empty space and skip first entry (command itself), return as list - return this.MessageText.Split(' ').Skip(1).ToList(); + return MessageText.Split(' ').Skip(1).ToList(); } } /// /// Returns just the command (i.e. /start 1 2 3 => /start) /// - public String BotCommand + public string BotCommand { get { if (!IsBotCommand) return null; - return this.MessageText.Split(' ')[0]; + return MessageText.Split(' ')[0]; } } @@ -137,13 +83,7 @@ namespace TelegramBotBase.Base public bool Handled { get; set; } = false; - public String RawData - { - get - { - return this.UpdateData?.CallbackQuery?.Data; - } - } + public string RawData => UpdateData?.CallbackQuery?.Data; public T GetData() where T : class @@ -151,7 +91,7 @@ namespace TelegramBotBase.Base T cd = null; try { - cd = Newtonsoft.Json.JsonConvert.DeserializeObject(this.RawData); + cd = JsonConvert.DeserializeObject(RawData); return cd; } @@ -168,16 +108,16 @@ namespace TelegramBotBase.Base /// /// /// - public async Task ConfirmAction(String message = "", bool showAlert = false, String urlToOpen = null) + public async Task ConfirmAction(string message = "", bool showAlert = false, string urlToOpen = null) { - await this.Device.ConfirmAction(this.UpdateData.CallbackQuery.Id, message, showAlert, urlToOpen); + await Device.ConfirmAction(UpdateData.CallbackQuery.Id, message, showAlert, urlToOpen); } public override async Task DeleteMessage() { try { - await base.DeleteMessage(this.MessageId); + await base.DeleteMessage(MessageId); } catch { @@ -190,9 +130,9 @@ namespace TelegramBotBase.Base } - public MessageResult(Telegram.Bot.Types.Update update) + public MessageResult(Update update) { - this.UpdateData = update; + UpdateData = update; } diff --git a/TelegramBotBase/Base/ResultBase.cs b/TelegramBotBase/Base/ResultBase.cs index adf8ecc..59a130f 100644 --- a/TelegramBotBase/Base/ResultBase.cs +++ b/TelegramBotBase/Base/ResultBase.cs @@ -1,9 +1,7 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading.Tasks; using Telegram.Bot; +using Telegram.Bot.Types; using TelegramBotBase.Sessions; namespace TelegramBotBase.Base @@ -18,15 +16,9 @@ namespace TelegramBotBase.Base public virtual long DeviceId { get; set; } - public int MessageId - { - get - { - return this.Message.MessageId; - } - } + public int MessageId => Message.MessageId; - public virtual Telegram.Bot.Types.Message Message { get; set; } + public virtual Message Message { get; set; } /// /// Deletes the current message @@ -35,7 +27,7 @@ namespace TelegramBotBase.Base /// public virtual async Task DeleteMessage() { - await DeleteMessage(this.MessageId); + await DeleteMessage(MessageId); } /// @@ -47,7 +39,7 @@ namespace TelegramBotBase.Base { try { - await Device.Client.TelegramClient.DeleteMessageAsync(this.DeviceId, (messageId == -1 ? this.MessageId : messageId)); + await Device.Client.TelegramClient.DeleteMessageAsync(DeviceId, (messageId == -1 ? MessageId : messageId)); } catch { diff --git a/TelegramBotBase/Base/StateContainer.cs b/TelegramBotBase/Base/StateContainer.cs index d4a12f0..7e74cc6 100644 --- a/TelegramBotBase/Base/StateContainer.cs +++ b/TelegramBotBase/Base/StateContainer.cs @@ -1,11 +1,9 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; -using System.Text; namespace TelegramBotBase.Base { - public partial class StateContainer + public class StateContainer { public List States { get; set; } @@ -27,7 +25,7 @@ namespace TelegramBotBase.Base public StateContainer() { - this.States = new List(); + States = new List(); } } diff --git a/TelegramBotBase/Base/StateEntry.cs b/TelegramBotBase/Base/StateEntry.cs index 9a7e0c1..13e272f 100644 --- a/TelegramBotBase/Base/StateEntry.cs +++ b/TelegramBotBase/Base/StateEntry.cs @@ -1,8 +1,5 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Diagnostics; -using System.Runtime.Serialization; -using System.Text; namespace TelegramBotBase.Base { @@ -18,26 +15,26 @@ namespace TelegramBotBase.Base /// /// Contains the Username (on privat chats) or Group title on groups/channels. /// - public String ChatTitle { get; set; } + public string ChatTitle { get; set; } /// /// Contains additional values to save. /// - public Dictionary Values { get; set; } + public Dictionary Values { get; set; } /// /// Contains the full qualified namespace of the form to used for reload it via reflection. /// - public String FormUri {get;set;} + public string FormUri {get;set;} /// /// Contains the assembly, where to find that form. /// - public String QualifiedName { get; set; } + public string QualifiedName { get; set; } public StateEntry() { - this.Values = new Dictionary(); + Values = new Dictionary(); } } diff --git a/TelegramBotBase/Base/UpdateResult.cs b/TelegramBotBase/Base/UpdateResult.cs index f2341dd..4d8e430 100644 --- a/TelegramBotBase/Base/UpdateResult.cs +++ b/TelegramBotBase/Base/UpdateResult.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using Telegram.Bot.Types; +using Telegram.Bot.Types; using TelegramBotBase.Sessions; namespace TelegramBotBase.Base @@ -14,46 +10,26 @@ namespace TelegramBotBase.Base RawData = rawData; Device = device; - + } /// /// Returns the Device/ChatId /// - public override long DeviceId - { - get - { - return this.RawData?.Message?.Chat?.Id - ?? this.RawData?.CallbackQuery?.Message?.Chat?.Id - ?? Device?.DeviceId - ?? 0; - } - } + public override long DeviceId => + RawData?.Message?.Chat?.Id + ?? RawData?.CallbackQuery?.Message?.Chat?.Id + ?? Device?.DeviceId + ?? 0; public Update RawData { get; set; } - public override Message Message - { - get - { - return RawData?.Message - ?? RawData?.EditedMessage - ?? RawData?.ChannelPost - ?? RawData?.EditedChannelPost - ?? RawData?.CallbackQuery?.Message; - } - } - - - - public DeviceSession Device - { - get; - set; - } - - + public override Message Message => + RawData?.Message + ?? RawData?.EditedMessage + ?? RawData?.ChannelPost + ?? RawData?.EditedChannelPost + ?? RawData?.CallbackQuery?.Message; } } diff --git a/TelegramBotBase/BotBase.cs b/TelegramBotBase/BotBase.cs index b5ebd84..45b8a92 100644 --- a/TelegramBotBase/BotBase.cs +++ b/TelegramBotBase/BotBase.cs @@ -31,7 +31,7 @@ namespace TelegramBotBase /// /// Your TelegramBot APIKey /// - public String APIKey { get; set; } = ""; + public string ApiKey { get; set; } = ""; /// /// List of all running/active sessions @@ -46,19 +46,19 @@ namespace TelegramBotBase #region "Events" - private EventHandlerList __Events = new EventHandlerList(); + private readonly EventHandlerList _events = new EventHandlerList(); - private static object __evSessionBegins = new object(); + private static readonly object EvSessionBegins = new object(); - private static object __evMessage = new object(); + private static readonly object EvMessage = new object(); private static object __evSystemCall = new object(); public delegate Task BotCommandEventHandler(object sender, BotCommandEventArgs e); - private static object __evException = new object(); + private static readonly object EvException = new object(); - private static object __evUnhandledCall = new object(); + private static readonly object EvUnhandledCall = new object(); #endregion @@ -81,22 +81,24 @@ namespace TelegramBotBase /// /// All internal used settings. /// - public Dictionary SystemSettings { get; private set; } + public Dictionary SystemSettings { get; private set; } public BotBase() { - this.SystemSettings = new Dictionary(); + SystemSettings = new Dictionary(); - SetSetting(eSettings.MaxNumberOfRetries, 5); - SetSetting(eSettings.NavigationMaximum, 10); - SetSetting(eSettings.LogAllMessages, false); - SetSetting(eSettings.SkipAllMessages, false); - SetSetting(eSettings.SaveSessionsOnConsoleExit, false); + SetSetting(ESettings.MaxNumberOfRetries, 5); + SetSetting(ESettings.NavigationMaximum, 10); + SetSetting(ESettings.LogAllMessages, false); + SetSetting(ESettings.SkipAllMessages, false); + SetSetting(ESettings.SaveSessionsOnConsoleExit, false); - this.BotCommandScopes = new Dictionary>(); + BotCommandScopes = new Dictionary>(); - this.Sessions = new SessionBase(); - this.Sessions.BotBase = this; + Sessions = new SessionBase + { + BotBase = this + }; } @@ -106,38 +108,38 @@ namespace TelegramBotBase /// public void Start() { - if (this.Client == null) + if (Client == null) return; - this.Client.MessageLoop += Client_MessageLoop; + Client.MessageLoop += Client_MessageLoop; - if (this.StateMachine != null) + if (StateMachine != null) { - this.Sessions.LoadSessionStates(this.StateMachine); + Sessions.LoadSessionStates(StateMachine); } //Enable auto session saving - if (this.GetSetting(eSettings.SaveSessionsOnConsoleExit, false)) + if (GetSetting(ESettings.SaveSessionsOnConsoleExit, false)) { - TelegramBotBase.Tools.Console.SetHandler(() => + Tools.Console.SetHandler(() => { - this.Sessions.SaveSessionStates(); + Sessions.SaveSessionStates(); }); } - DeviceSession.MaxNumberOfRetries = this.GetSetting(eSettings.MaxNumberOfRetries, 5); + DeviceSession.MaxNumberOfRetries = GetSetting(ESettings.MaxNumberOfRetries, 5); - this.Client.StartReceiving(); + Client.StartReceiving(); } private async Task Client_MessageLoop(object sender, UpdateResult e) { - DeviceSession ds = this.Sessions.GetSession(e.DeviceId); + var ds = Sessions.GetSession(e.DeviceId); if (ds == null) { - ds = this.Sessions.StartSession(e.DeviceId).GetAwaiter().GetResult(); + ds = Sessions.StartSession(e.DeviceId).GetAwaiter().GetResult(); e.Device = ds; ds.LastMessage = e.RawData.Message; @@ -146,7 +148,7 @@ namespace TelegramBotBase var mr = new MessageResult(e.RawData); - int i = 0; + var i = 0; //Should formulars get navigated (allow maximum of 10, to dont get loops) do @@ -160,7 +162,7 @@ namespace TelegramBotBase mr.IsFirstHandler = false; - } while (ds.FormSwitched && i < this.GetSetting(eSettings.NavigationMaximum, 10)); + } while (ds.FormSwitched && i < GetSetting(ESettings.NavigationMaximum, 10)); } @@ -169,15 +171,15 @@ namespace TelegramBotBase /// public void Stop() { - if (this.Client == null) + if (Client == null) return; - this.Client.MessageLoop -= Client_MessageLoop; + Client.MessageLoop -= Client_MessageLoop; - this.Client.StopReceiving(); + Client.StopReceiving(); - this.Sessions.SaveSessionStates(); + Sessions.SaveSessionStates(); } /// @@ -185,14 +187,14 @@ namespace TelegramBotBase /// /// /// - public async Task SentToAll(String message) + public async Task SentToAll(string message) { - if (this.Client == null) + if (Client == null) return; - foreach (var s in this.Sessions.SessionList) + foreach (var s in Sessions.SessionList) { - await this.Client.TelegramClient.SendTextMessageAsync(s.Key, message); + await Client.TelegramClient.SendTextMessageAsync(s.Key, message); } } @@ -201,29 +203,30 @@ namespace TelegramBotBase /// /// This will invoke the full message loop for the device even when no "userevent" like message or action has been raised. /// - /// Contains the device/chat id of the device to update. - public async Task InvokeMessageLoop(long DeviceId) + /// Contains the device/chat id of the device to update. + public async Task InvokeMessageLoop(long deviceId) { - var mr = new MessageResult(); - - mr.UpdateData = new Update() + var mr = new MessageResult { - Message = new Message() + UpdateData = new Update() + { + Message = new Message() + } }; - await InvokeMessageLoop(DeviceId, mr); + await InvokeMessageLoop(deviceId, mr); } /// /// This will invoke the full message loop for the device even when no "userevent" like message or action has been raised. /// - /// Contains the device/chat id of the device to update. + /// Contains the device/chat id of the device to update. /// - public async Task InvokeMessageLoop(long DeviceId, MessageResult e) + public async Task InvokeMessageLoop(long deviceId, MessageResult e) { try { - DeviceSession ds = this.Sessions.GetSession(DeviceId); + var ds = Sessions.GetSession(deviceId); e.Device = ds; await MessageLoopFactory.MessageLoop(this, ds, new UpdateResult(e.UpdateData, ds), e); @@ -231,8 +234,8 @@ namespace TelegramBotBase } catch (Exception ex) { - DeviceSession ds = this.Sessions.GetSession(DeviceId); - OnException(new SystemExceptionEventArgs(e.Message.Text, DeviceId, ds, ex)); + var ds = Sessions.GetSession(deviceId); + OnException(new SystemExceptionEventArgs(e.Message.Text, deviceId, ds, ex)); } } @@ -252,17 +255,17 @@ namespace TelegramBotBase /// public async Task UploadBotCommands() { - foreach (var bs in this.BotCommandScopes) + foreach (var bs in BotCommandScopes) { if(bs.Value !=null) { - await this.Client.SetBotCommands(bs.Value, bs.Key); + await Client.SetBotCommands(bs.Value, bs.Key); } else { - await this.Client.DeleteBotCommands(bs.Key); + await Client.DeleteBotCommands(bs.Key); } - + } } @@ -271,9 +274,9 @@ namespace TelegramBotBase /// /// /// - public bool IsKnownBotCommand(String command) + public bool IsKnownBotCommand(string command) { - foreach (var scope in this.BotCommandScopes) + foreach (var scope in BotCommandScopes) { if (scope.Value.Any(a => "/" + a.Command == command)) return true; @@ -286,20 +289,20 @@ namespace TelegramBotBase /// Could set a variety of settings to improve the bot handling. /// /// - /// - public void SetSetting(eSettings set, uint Value) + /// + public void SetSetting(ESettings set, uint value) { - this.SystemSettings[set] = Value; + SystemSettings[set] = value; } /// /// Could set a variety of settings to improve the bot handling. /// /// - /// - public void SetSetting(eSettings set, bool Value) + /// + public void SetSetting(ESettings set, bool value) { - this.SystemSettings[set] = (Value ? 1u : 0u); + SystemSettings[set] = (value ? 1u : 0u); } /// @@ -308,12 +311,12 @@ namespace TelegramBotBase /// /// /// - public uint GetSetting(eSettings set, uint defaultValue) + public uint GetSetting(ESettings set, uint defaultValue) { - if (!this.SystemSettings.ContainsKey(set)) + if (!SystemSettings.ContainsKey(set)) return defaultValue; - return this.SystemSettings[set]; + return SystemSettings[set]; } /// @@ -322,12 +325,12 @@ namespace TelegramBotBase /// /// /// - public bool GetSetting(eSettings set, bool defaultValue) + public bool GetSetting(ESettings set, bool defaultValue) { - if (!this.SystemSettings.ContainsKey(set)) + if (!SystemSettings.ContainsKey(set)) return defaultValue; - return this.SystemSettings[set] == 0u ? false : true; + return SystemSettings[set] == 0u ? false : true; } #region "Events" @@ -338,19 +341,13 @@ namespace TelegramBotBase public event EventHandler SessionBegins { - add - { - this.__Events.AddHandler(__evSessionBegins, value); - } - remove - { - this.__Events.RemoveHandler(__evSessionBegins, value); - } + add => _events.AddHandler(EvSessionBegins, value); + remove => _events.RemoveHandler(EvSessionBegins, value); } public void OnSessionBegins(SessionBeginEventArgs e) { - (this.__Events[__evSessionBegins] as EventHandler)?.Invoke(this, e); + (_events[EvSessionBegins] as EventHandler)?.Invoke(this, e); } @@ -359,19 +356,13 @@ namespace TelegramBotBase /// public event EventHandler Message { - add - { - this.__Events.AddHandler(__evMessage, value); - } - remove - { - this.__Events.RemoveHandler(__evMessage, value); - } + add => _events.AddHandler(EvMessage, value); + remove => _events.RemoveHandler(EvMessage, value); } public void OnMessage(MessageIncomeEventArgs e) { - (this.__Events[__evMessage] as EventHandler)?.Invoke(this, e); + (_events[EvMessage] as EventHandler)?.Invoke(this, e); } @@ -383,7 +374,7 @@ namespace TelegramBotBase public async Task OnBotCommand(BotCommandEventArgs e) { - if (this.BotCommand != null) + if (BotCommand != null) await BotCommand(this, e); } @@ -392,19 +383,13 @@ namespace TelegramBotBase /// public event EventHandler Exception { - add - { - this.__Events.AddHandler(__evException, value); - } - remove - { - this.__Events.RemoveHandler(__evException, value); - } + add => _events.AddHandler(EvException, value); + remove => _events.RemoveHandler(EvException, value); } public void OnException(SystemExceptionEventArgs e) { - (this.__Events[__evException] as EventHandler)?.Invoke(this, e); + (_events[EvException] as EventHandler)?.Invoke(this, e); } @@ -413,19 +398,13 @@ namespace TelegramBotBase /// public event EventHandler UnhandledCall { - add - { - this.__Events.AddHandler(__evUnhandledCall, value); - } - remove - { - this.__Events.RemoveHandler(__evUnhandledCall, value); - } + add => _events.AddHandler(EvUnhandledCall, value); + remove => _events.RemoveHandler(EvUnhandledCall, value); } public void OnUnhandledCall(UnhandledCallEventArgs e) { - (this.__Events[__evUnhandledCall] as EventHandler)?.Invoke(this, e); + (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); } diff --git a/TelegramBotBase/Builder/BotBaseBuilder.cs b/TelegramBotBase/Builder/BotBaseBuilder.cs index 6ad24ee..216d09f 100644 --- a/TelegramBotBase/Builder/BotBaseBuilder.cs +++ b/TelegramBotBase/Builder/BotBaseBuilder.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Net.Http; -using System.Text; using Telegram.Bot; using Telegram.Bot.Types; using TelegramBotBase.Base; @@ -11,29 +10,27 @@ using TelegramBotBase.Factories; using TelegramBotBase.Form; using TelegramBotBase.Interfaces; using TelegramBotBase.Localizations; +using TelegramBotBase.MessageLoops; using TelegramBotBase.States; namespace TelegramBotBase.Builder { public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, IStartFormSelectionStage, IBuildingStage, INetworkingSelectionStage, IBotCommandsStage, ISessionSerializationStage, ILanguageSelectionStage { + private string _apiKey; - String _apiKey = null; + private IStartFormFactory _factory; - IStartFormFactory _factory = null; - - MessageClient _client = null; + private MessageClient _client; /// /// Contains different Botcommands for different areas. /// - Dictionary> _BotCommandScopes { get; set; } = new Dictionary>(); + private Dictionary> BotCommandScopes { get; set; } = new Dictionary>(); - //List _botcommands = new List(); + private IStateMachine _statemachine; - IStateMachine _statemachine = null; - - IMessageLoopFactory _messageloopfactory = null; + private IMessageLoopFactory _messageLoopFactory; private BotBaseBuilder() { @@ -49,15 +46,15 @@ namespace TelegramBotBase.Builder public IMessageLoopSelectionStage WithAPIKey(string apiKey) { - this._apiKey = apiKey; + _apiKey = apiKey; return this; } public IBuildingStage QuickStart(string apiKey, Type StartForm) { - this._apiKey = apiKey; - this._factory = new Factories.DefaultStartFormFactory(StartForm); + _apiKey = apiKey; + _factory = new DefaultStartFormFactory(StartForm); DefaultMessageLoop(); @@ -76,8 +73,8 @@ namespace TelegramBotBase.Builder public IBuildingStage QuickStart(string apiKey) where T : FormBase { - this._apiKey = apiKey; - this._factory = new Factories.DefaultStartFormFactory(typeof(T)); + _apiKey = apiKey; + _factory = new DefaultStartFormFactory(typeof(T)); DefaultMessageLoop(); @@ -94,8 +91,8 @@ namespace TelegramBotBase.Builder public IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory) { - this._apiKey = apiKey; - this._factory = StartFormFactory; + _apiKey = apiKey; + _factory = StartFormFactory; DefaultMessageLoop(); @@ -117,7 +114,7 @@ namespace TelegramBotBase.Builder public IStartFormSelectionStage DefaultMessageLoop() { - _messageloopfactory = new MessageLoops.FormBaseMessageLoop(); + _messageLoopFactory = new FormBaseMessageLoop(); return this; } @@ -125,7 +122,7 @@ namespace TelegramBotBase.Builder public IStartFormSelectionStage MinimalMessageLoop() { - _messageloopfactory = new MessageLoops.MinimalMessageLoop(); + _messageLoopFactory = new MinimalMessageLoop(); return this; } @@ -133,7 +130,7 @@ namespace TelegramBotBase.Builder public IStartFormSelectionStage CustomMessageLoop(IMessageLoopFactory messageLoopClass) { - _messageloopfactory = messageLoopClass; + _messageLoopFactory = messageLoopClass; return this; } @@ -141,7 +138,7 @@ namespace TelegramBotBase.Builder public IStartFormSelectionStage CustomMessageLoop() where T : class, new() { - _messageloopfactory = typeof(T).GetConstructor(new Type[] { })?.Invoke(new object[] { }) as IMessageLoopFactory; + _messageLoopFactory = typeof(T).GetConstructor(new Type[] { })?.Invoke(new object[] { }) as IMessageLoopFactory; return this; } @@ -153,33 +150,33 @@ namespace TelegramBotBase.Builder public INetworkingSelectionStage WithStartForm(Type startFormClass) { - this._factory = new Factories.DefaultStartFormFactory(startFormClass); + _factory = new DefaultStartFormFactory(startFormClass); return this; } public INetworkingSelectionStage WithStartForm() where T : FormBase, new() { - this._factory = new Factories.DefaultStartFormFactory(typeof(T)); + _factory = new DefaultStartFormFactory(typeof(T)); return this; } public INetworkingSelectionStage WithServiceProvider(Type startFormClass, IServiceProvider serviceProvider) { - this._factory = new ServiceProviderStartFormFactory(startFormClass, serviceProvider); + _factory = new ServiceProviderStartFormFactory(startFormClass, serviceProvider); return this; } public INetworkingSelectionStage WithServiceProvider(IServiceProvider serviceProvider) where T : FormBase { - this._factory = new ServiceProviderStartFormFactory(serviceProvider); + _factory = new ServiceProviderStartFormFactory(serviceProvider); return this; } public INetworkingSelectionStage WithStartFormFactory(IStartFormFactory factory) { - this._factory = factory; + _factory = factory; return this; } @@ -191,39 +188,64 @@ namespace TelegramBotBase.Builder public IBotCommandsStage WithProxy(string proxyAddress) { var url = new Uri(proxyAddress); - _client = new MessageClient(_apiKey, url); - _client.TelegramClient.Timeout = new TimeSpan(0, 1, 0); + _client = new MessageClient(_apiKey, url) + { + TelegramClient = + { + Timeout = new TimeSpan(0, 1, 0) + } + }; return this; } public IBotCommandsStage NoProxy() { - _client = new MessageClient(_apiKey); - _client.TelegramClient.Timeout = new TimeSpan(0, 1, 0); + _client = new MessageClient(_apiKey) + { + TelegramClient = + { + Timeout = new TimeSpan(0, 1, 0) + } + }; return this; } public IBotCommandsStage WithBotClient(TelegramBotClient tgclient) { - _client = new MessageClient(_apiKey, tgclient); - _client.TelegramClient.Timeout = new TimeSpan(0, 1, 0); + _client = new MessageClient(_apiKey, tgclient) + { + TelegramClient = + { + Timeout = new TimeSpan(0, 1, 0) + } + }; return this; } public IBotCommandsStage WithHostAndPort(string proxyHost, int proxyPort) { - _client = new MessageClient(_apiKey, proxyHost, proxyPort); - _client.TelegramClient.Timeout = new TimeSpan(0, 1, 0); + _client = new MessageClient(_apiKey, proxyHost, proxyPort) + { + TelegramClient = + { + Timeout = new TimeSpan(0, 1, 0) + } + }; return this; } public IBotCommandsStage WithHttpClient(HttpClient tgclient) { - _client = new MessageClient(_apiKey, tgclient); - _client.TelegramClient.Timeout = new TimeSpan(0, 1, 0); + _client = new MessageClient(_apiKey, tgclient) + { + TelegramClient = + { + Timeout = new TimeSpan(0, 1, 0) + } + }; return this; } @@ -240,7 +262,7 @@ namespace TelegramBotBase.Builder public ISessionSerializationStage OnlyStart() { - _BotCommandScopes.Start("Starts the bot"); + BotCommandScopes.Start("Starts the bot"); return this; @@ -248,15 +270,15 @@ namespace TelegramBotBase.Builder public ISessionSerializationStage DefaultCommands() { - _BotCommandScopes.Start("Starts the bot"); - _BotCommandScopes.Help("Should show you some help"); - _BotCommandScopes.Settings("Should show you some settings"); + BotCommandScopes.Start("Starts the bot"); + BotCommandScopes.Help("Should show you some help"); + BotCommandScopes.Settings("Should show you some settings"); return this; } public ISessionSerializationStage CustomCommands(Action>> action) { - action?.Invoke(_BotCommandScopes); + action?.Invoke(BotCommandScopes); return this; } @@ -272,26 +294,26 @@ namespace TelegramBotBase.Builder public ILanguageSelectionStage UseSerialization(IStateMachine machine) { - this._statemachine = machine; + _statemachine = machine; return this; } public ILanguageSelectionStage UseJSON(string path) { - this._statemachine = new JSONStateMachine(path); + _statemachine = new JsonStateMachine(path); return this; } public ILanguageSelectionStage UseSimpleJSON(string path) { - this._statemachine = new SimpleJSONStateMachine(path); + _statemachine = new SimpleJsonStateMachine(path); return this; } public ILanguageSelectionStage UseXML(string path) { - this._statemachine = new XMLStateMachine(path); + _statemachine = new XmlStateMachine(path); return this; } @@ -307,19 +329,19 @@ namespace TelegramBotBase.Builder public IBuildingStage UseEnglish() { - Localizations.Default.Language = new Localizations.English(); + Default.Language = new English(); return this; } public IBuildingStage UseGerman() { - Localizations.Default.Language = new Localizations.German(); + Default.Language = new German(); return this; } public IBuildingStage Custom(Localization language) { - Localizations.Default.Language = language; + Default.Language = language; return this; } @@ -328,20 +350,20 @@ namespace TelegramBotBase.Builder public BotBase Build() { - var bb = new BotBase(); - - bb.APIKey = _apiKey; - bb.StartFormFactory = _factory; - - bb.Client = _client; + var bb = new BotBase + { + ApiKey = _apiKey, + StartFormFactory = _factory, + Client = _client + }; bb.Sessions.Client = bb.Client; - bb.BotCommandScopes = _BotCommandScopes; + bb.BotCommandScopes = BotCommandScopes; bb.StateMachine = _statemachine; - bb.MessageLoopFactory = _messageloopfactory; + bb.MessageLoopFactory = _messageLoopFactory; bb.MessageLoopFactory.UnhandledCall += bb.MessageLoopFactory_UnhandledCall; diff --git a/TelegramBotBase/Builder/Interfaces/IAPIKeySelectionStage.cs b/TelegramBotBase/Builder/Interfaces/IAPIKeySelectionStage.cs index bd6f05e..44a1bb8 100644 --- a/TelegramBotBase/Builder/Interfaces/IAPIKeySelectionStage.cs +++ b/TelegramBotBase/Builder/Interfaces/IAPIKeySelectionStage.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using TelegramBotBase.Form; using TelegramBotBase.Interfaces; @@ -13,7 +11,7 @@ namespace TelegramBotBase.Builder.Interfaces /// /// /// - IMessageLoopSelectionStage WithAPIKey(String apiKey); + IMessageLoopSelectionStage WithAPIKey(string apiKey); /// @@ -23,7 +21,7 @@ namespace TelegramBotBase.Builder.Interfaces /// /// /// - IBuildingStage QuickStart(String apiKey, Type StartForm); + IBuildingStage QuickStart(string apiKey, Type StartForm); /// /// Quick and easy way to create a BotBase instance. @@ -31,7 +29,7 @@ namespace TelegramBotBase.Builder.Interfaces /// /// /// - IBuildingStage QuickStart(String apiKey) where T : FormBase; + IBuildingStage QuickStart(string apiKey) where T : FormBase; /// /// Quick and easy way to create a BotBase instance. @@ -40,6 +38,6 @@ namespace TelegramBotBase.Builder.Interfaces /// /// /// - IBuildingStage QuickStart(String apiKey, IStartFormFactory StartFormFactory); + IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory); } } diff --git a/TelegramBotBase/Builder/Interfaces/IBotCommandsStage.cs b/TelegramBotBase/Builder/Interfaces/IBotCommandsStage.cs index a275090..2b83453 100644 --- a/TelegramBotBase/Builder/Interfaces/IBotCommandsStage.cs +++ b/TelegramBotBase/Builder/Interfaces/IBotCommandsStage.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Text; using Telegram.Bot.Types; namespace TelegramBotBase.Builder.Interfaces diff --git a/TelegramBotBase/Builder/Interfaces/IBuildingStage.cs b/TelegramBotBase/Builder/Interfaces/IBuildingStage.cs index 8313b0b..d5b70df 100644 --- a/TelegramBotBase/Builder/Interfaces/IBuildingStage.cs +++ b/TelegramBotBase/Builder/Interfaces/IBuildingStage.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace TelegramBotBase.Builder.Interfaces +namespace TelegramBotBase.Builder.Interfaces { public interface IBuildingStage { diff --git a/TelegramBotBase/Builder/Interfaces/ILanguageSelectionStage.cs b/TelegramBotBase/Builder/Interfaces/ILanguageSelectionStage.cs index 2e5e01a..b7bbd28 100644 --- a/TelegramBotBase/Builder/Interfaces/ILanguageSelectionStage.cs +++ b/TelegramBotBase/Builder/Interfaces/ILanguageSelectionStage.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using TelegramBotBase.Localizations; +using TelegramBotBase.Localizations; namespace TelegramBotBase.Builder.Interfaces { diff --git a/TelegramBotBase/Builder/Interfaces/IMessageLoopSelectionStage.cs b/TelegramBotBase/Builder/Interfaces/IMessageLoopSelectionStage.cs index 429a81d..b9a8df0 100644 --- a/TelegramBotBase/Builder/Interfaces/IMessageLoopSelectionStage.cs +++ b/TelegramBotBase/Builder/Interfaces/IMessageLoopSelectionStage.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using TelegramBotBase.Form; -using TelegramBotBase.Interfaces; +using TelegramBotBase.Interfaces; namespace TelegramBotBase.Builder.Interfaces { diff --git a/TelegramBotBase/Builder/Interfaces/INetworkingSelectionStage.cs b/TelegramBotBase/Builder/Interfaces/INetworkingSelectionStage.cs index 4b5bcce..a7b0d8e 100644 --- a/TelegramBotBase/Builder/Interfaces/INetworkingSelectionStage.cs +++ b/TelegramBotBase/Builder/Interfaces/INetworkingSelectionStage.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Text; +using System.Net.Http; using Telegram.Bot; namespace TelegramBotBase.Builder.Interfaces @@ -14,7 +11,7 @@ namespace TelegramBotBase.Builder.Interfaces /// /// /// - IBotCommandsStage WithProxy(String proxyAddress); + IBotCommandsStage WithProxy(string proxyAddress); /// /// Do not choose a proxy as network configuration. @@ -37,7 +34,7 @@ namespace TelegramBotBase.Builder.Interfaces /// /// /// - IBotCommandsStage WithHostAndPort(String proxyHost, int Port); + IBotCommandsStage WithHostAndPort(string proxyHost, int Port); /// /// Uses a custom http client. diff --git a/TelegramBotBase/Builder/Interfaces/ISessionSerializationStage.cs b/TelegramBotBase/Builder/Interfaces/ISessionSerializationStage.cs index a729da2..9adc70f 100644 --- a/TelegramBotBase/Builder/Interfaces/ISessionSerializationStage.cs +++ b/TelegramBotBase/Builder/Interfaces/ISessionSerializationStage.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using TelegramBotBase.Interfaces; +using TelegramBotBase.Interfaces; namespace TelegramBotBase.Builder.Interfaces { @@ -27,7 +24,7 @@ namespace TelegramBotBase.Builder.Interfaces /// /// /// - ILanguageSelectionStage UseJSON(String path); + ILanguageSelectionStage UseJSON(string path); /// @@ -35,7 +32,7 @@ namespace TelegramBotBase.Builder.Interfaces /// /// /// - ILanguageSelectionStage UseSimpleJSON(String path); + ILanguageSelectionStage UseSimpleJSON(string path); /// @@ -43,7 +40,7 @@ namespace TelegramBotBase.Builder.Interfaces /// /// /// - ILanguageSelectionStage UseXML(String path); + ILanguageSelectionStage UseXML(string path); } } diff --git a/TelegramBotBase/Builder/Interfaces/IStartFormSelectionStage.cs b/TelegramBotBase/Builder/Interfaces/IStartFormSelectionStage.cs index 78692ea..52c1890 100644 --- a/TelegramBotBase/Builder/Interfaces/IStartFormSelectionStage.cs +++ b/TelegramBotBase/Builder/Interfaces/IStartFormSelectionStage.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using TelegramBotBase.Form; using TelegramBotBase.Interfaces; diff --git a/TelegramBotBase/Commands/Extensions.cs b/TelegramBotBase/Commands/Extensions.cs index 8237d4f..55721b8 100644 --- a/TelegramBotBase/Commands/Extensions.cs +++ b/TelegramBotBase/Commands/Extensions.cs @@ -1,8 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Data; +using System.Collections.Generic; using System.Linq; -using System.Text; using Telegram.Bot.Types; namespace TelegramBotBase.Commands @@ -15,7 +12,7 @@ namespace TelegramBotBase.Commands /// /// /// - public static void Add(this Dictionary> cmds, String command, String description, BotCommandScope scope = null) + public static void Add(this Dictionary> cmds, string command, string description, BotCommandScope scope = null) { if (scope == null) { @@ -26,11 +23,11 @@ namespace TelegramBotBase.Commands if (item.Value != null) { - item.Value.Add(new BotCommand() { Command = command, Description = description }); + item.Value.Add(new BotCommand { Command = command, Description = description }); } else { - cmds.Add(scope, new List { new BotCommand() { Command = command, Description = description } }); + cmds.Add(scope, new List { new BotCommand { Command = command, Description = description } }); } } @@ -64,33 +61,33 @@ namespace TelegramBotBase.Commands /// /// /// - public static void Start(this Dictionary> cmds, String description) => Add(cmds, "start", description, null); + public static void Start(this Dictionary> cmds, string description) => Add(cmds, "start", description); /// /// Adding the default /help command with a description. /// /// /// - public static void Help(this Dictionary> cmds, String description) => Add(cmds, "help", description, null); + public static void Help(this Dictionary> cmds, string description) => Add(cmds, "help", description); /// /// Adding the default /settings command with a description. /// /// /// - public static void Settings(this Dictionary> cmds, String description) => Add(cmds, "settings", description, null); + public static void Settings(this Dictionary> cmds, string description) => Add(cmds, "settings", description); /// /// Clears all default commands. /// /// - public static void ClearDefaultCommands(this Dictionary> cmds) => Clear(cmds, null); + public static void ClearDefaultCommands(this Dictionary> cmds) => Clear(cmds); /// /// Clears all commands of a specific device. /// /// - public static void ClearChatCommands(this Dictionary> cmds, long DeviceId) => Clear(cmds, new BotCommandScopeChat() { ChatId = DeviceId }); + public static void ClearChatCommands(this Dictionary> cmds, long deviceId) => Clear(cmds, new BotCommandScopeChat { ChatId = deviceId }); /// /// Adding a chat command with a description. @@ -98,7 +95,7 @@ namespace TelegramBotBase.Commands /// /// /// - public static void AddChatCommand(this Dictionary> cmds, long DeviceId, String command, String description) => Add(cmds, command, description, new BotCommandScopeChat() { ChatId = DeviceId }); + public static void AddChatCommand(this Dictionary> cmds, long deviceId, string command, string description) => Add(cmds, command, description, new BotCommandScopeChat { ChatId = deviceId }); /// /// Adding a group command with a description. @@ -106,7 +103,7 @@ namespace TelegramBotBase.Commands /// /// /// - public static void AddGroupCommand(this Dictionary> cmds, String command, String description) => Add(cmds, command, description, new BotCommandScopeAllGroupChats()); + public static void AddGroupCommand(this Dictionary> cmds, string command, string description) => Add(cmds, command, description, new BotCommandScopeAllGroupChats()); /// /// Clears all group commands. @@ -120,7 +117,7 @@ namespace TelegramBotBase.Commands /// /// /// - public static void AddGroupAdminCommand(this Dictionary> cmds, String command, String description) => Add(cmds, command, description, new BotCommandScopeAllChatAdministrators()); + public static void AddGroupAdminCommand(this Dictionary> cmds, string command, string description) => Add(cmds, command, description, new BotCommandScopeAllChatAdministrators()); /// /// Clears all group admin commands. @@ -134,7 +131,7 @@ namespace TelegramBotBase.Commands /// /// /// - public static void AddPrivateChatCommand(this Dictionary> cmds, String command, String description) => Add(cmds, command, description, new BotCommandScopeAllPrivateChats()); + public static void AddPrivateChatCommand(this Dictionary> cmds, string command, string description) => Add(cmds, command, description, new BotCommandScopeAllPrivateChats()); /// /// Clears all private commands. diff --git a/TelegramBotBase/Constants/Telegram.cs b/TelegramBotBase/Constants/Telegram.cs index d203123..a669022 100644 --- a/TelegramBotBase/Constants/Telegram.cs +++ b/TelegramBotBase/Constants/Telegram.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TelegramBotBase.Constants +namespace TelegramBotBase.Constants { public static class Telegram { diff --git a/TelegramBotBase/Controls/Hybrid/ButtonGrid.cs b/TelegramBotBase/Controls/Hybrid/ButtonGrid.cs index d62179f..f8662b2 100644 --- a/TelegramBotBase/Controls/Hybrid/ButtonGrid.cs +++ b/TelegramBotBase/Controls/Hybrid/ButtonGrid.cs @@ -1,50 +1,43 @@ using System; using System.Collections.Generic; using System.ComponentModel; -using System.Diagnostics.SymbolStore; using System.Linq; -using System.Text; using System.Threading.Tasks; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.ReplyMarkups; using TelegramBotBase.Args; using TelegramBotBase.Base; -using TelegramBotBase.Datasources; +using TelegramBotBase.DataSources; using TelegramBotBase.Enums; using TelegramBotBase.Exceptions; using TelegramBotBase.Form; +using TelegramBotBase.Localizations; using static TelegramBotBase.Base.Async; namespace TelegramBotBase.Controls.Hybrid { - public class ButtonGrid : Base.ControlBase + public class ButtonGrid : ControlBase { - public String Title { get; set; } = Localizations.Default.Language["ButtonGrid_Title"]; + public string Title { get; set; } = Default.Language["ButtonGrid_Title"]; - public String ConfirmationText { get; set; } = ""; + public string ConfirmationText { get; set; } = ""; - private bool RenderNecessary = true; + private bool _renderNecessary = true; - private static readonly object __evButtonClicked = new object(); + private static readonly object EvButtonClicked = new object(); - private readonly EventHandlerList Events = new EventHandlerList(); + private readonly EventHandlerList _events = new EventHandlerList(); /// - /// + /// /// [Obsolete("This property is obsolete. Please use the DataSource property instead.")] public ButtonForm ButtonsForm { - get - { - return DataSource.ButtonForm; - } - set - { - DataSource = new ButtonFormDataSource(value); - } + get => DataSource.ButtonForm; + set => DataSource = new ButtonFormDataSource(value); } /// @@ -88,23 +81,23 @@ namespace TelegramBotBase.Controls.Hybrid /// public bool EnableSearch { get; set; } = false; - public String SearchQuery { get; set; } + public string SearchQuery { get; set; } - public eNavigationBarVisibility NavigationBarVisibility { get; set; } = eNavigationBarVisibility.always; + public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always; /// /// Index of the current page /// - public int CurrentPageIndex { get; set; } = 0; + public int CurrentPageIndex { get; set; } - public String PreviousPageLabel = Localizations.Default.Language["ButtonGrid_PreviousPage"]; + public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"]; - public String NextPageLabel = Localizations.Default.Language["ButtonGrid_NextPage"]; + public string NextPageLabel = Default.Language["ButtonGrid_NextPage"]; - public String NoItemsLabel = Localizations.Default.Language["ButtonGrid_NoItems"]; + public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"]; - public String SearchLabel = Localizations.Default.Language["ButtonGrid_SearchFeature"]; + public string SearchLabel = Default.Language["ButtonGrid_SearchFeature"]; /// /// Layout of the buttons which should be displayed always on top. @@ -119,89 +112,80 @@ namespace TelegramBotBase.Controls.Hybrid /// /// Defines which type of Button Keyboard should be rendered. /// - public eKeyboardType KeyboardType + public EKeyboardType KeyboardType { - get - { - return m_eKeyboardType; - } + get => _mEKeyboardType; set { - if (m_eKeyboardType != value) + if (_mEKeyboardType != value) { - this.RenderNecessary = true; + _renderNecessary = true; Cleanup().Wait(); - m_eKeyboardType = value; + _mEKeyboardType = value; } } } - private eKeyboardType m_eKeyboardType = eKeyboardType.ReplyKeyboard; + private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard; public ButtonGrid() { - this.DataSource = new ButtonFormDataSource(); + DataSource = new ButtonFormDataSource(); } - public ButtonGrid(eKeyboardType type) : this() + public ButtonGrid(EKeyboardType type) : this() { - m_eKeyboardType = type; + _mEKeyboardType = type; } public ButtonGrid(ButtonForm form) { - this.DataSource = new ButtonFormDataSource(form); + DataSource = new ButtonFormDataSource(form); } public event AsyncEventHandler ButtonClicked { - add - { - this.Events.AddHandler(__evButtonClicked, value); - } - remove - { - this.Events.RemoveHandler(__evButtonClicked, value); - } + add => _events.AddHandler(EvButtonClicked, value); + remove => _events.RemoveHandler(EvButtonClicked, value); } public async Task OnButtonClicked(ButtonClickedEventArgs e) { - var handler = this.Events[__evButtonClicked]?.GetInvocationList().Cast>(); + var handler = _events[EvButtonClicked]?.GetInvocationList().Cast>(); if (handler == null) return; foreach (var h in handler) { - await Async.InvokeAllAsync(h, this, e); + await h.InvokeAllAsync(this, e); } } public override void Init() { - this.Device.MessageDeleted += Device_MessageDeleted; + Device.MessageDeleted += Device_MessageDeleted; } private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e) { - if (this.MessageId == null) + if (MessageId == null) return; - if (e.MessageId != this.MessageId) + if (e.MessageId != MessageId) return; - this.MessageId = null; + MessageId = null; } - public async override Task Load(MessageResult result) + public override async Task Load(MessageResult result) { - if (this.KeyboardType != eKeyboardType.ReplyKeyboard) + if (KeyboardType != EKeyboardType.ReplyKeyboard) return; if (!result.IsFirstHandler) @@ -212,7 +196,7 @@ namespace TelegramBotBase.Controls.Hybrid var matches = new List(); ButtonRow match = null; - int index = -1; + var index = -1; if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false) { @@ -244,7 +228,7 @@ namespace TelegramBotBase.Controls.Hybrid check: //Remove button click message - if (this.DeleteReplyMessage) + if (DeleteReplyMessage) await Device.DeleteMessage(result.MessageId); if (match != null) @@ -258,39 +242,39 @@ namespace TelegramBotBase.Controls.Hybrid if (result.MessageText == PreviousPageLabel) { - if (this.CurrentPageIndex > 0) - this.CurrentPageIndex--; + if (CurrentPageIndex > 0) + CurrentPageIndex--; - this.Updated(); + Updated(); } else if (result.MessageText == NextPageLabel) { - if (this.CurrentPageIndex < this.PageCount - 1) - this.CurrentPageIndex++; + if (CurrentPageIndex < PageCount - 1) + CurrentPageIndex++; - this.Updated(); + Updated(); } - else if (this.EnableSearch) + else if (EnableSearch) { if (result.MessageText.StartsWith("🔍")) { //Sent note about searching - if (this.SearchQuery == null) + if (SearchQuery == null) { - await this.Device.Send(this.SearchLabel); + await Device.Send(SearchLabel); } - this.SearchQuery = null; - this.Updated(); + SearchQuery = null; + Updated(); return; } - this.SearchQuery = result.MessageText; + SearchQuery = result.MessageText; - if (this.SearchQuery != null && this.SearchQuery != "") + if (SearchQuery != null && SearchQuery != "") { - this.CurrentPageIndex = 0; - this.Updated(); + CurrentPageIndex = 0; + Updated(); } } @@ -299,7 +283,7 @@ namespace TelegramBotBase.Controls.Hybrid } - public async override Task Action(MessageResult result, string value = null) + public override async Task Action(MessageResult result, string value = null) { if (result.Handled) return; @@ -308,13 +292,13 @@ namespace TelegramBotBase.Controls.Hybrid return; //Find clicked button depending on Text or Value (depending on markup type) - if (this.KeyboardType != eKeyboardType.InlineKeyBoard) + if (KeyboardType != EKeyboardType.InlineKeyBoard) return; - await result.ConfirmAction(this.ConfirmationText ?? ""); + await result.ConfirmAction(ConfirmationText ?? ""); ButtonRow match = null; - int index = -1; + var index = -1; if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) { @@ -358,18 +342,18 @@ namespace TelegramBotBase.Controls.Hybrid { case "$previous$": - if (this.CurrentPageIndex > 0) - this.CurrentPageIndex--; + if (CurrentPageIndex > 0) + CurrentPageIndex--; - this.Updated(); + Updated(); break; case "$next$": - if (this.CurrentPageIndex < this.PageCount - 1) - this.CurrentPageIndex++; + if (CurrentPageIndex < PageCount - 1) + CurrentPageIndex++; - this.Updated(); + Updated(); break; } @@ -381,49 +365,49 @@ namespace TelegramBotBase.Controls.Hybrid /// private void CheckGrid() { - switch (m_eKeyboardType) + switch (_mEKeyboardType) { - case eKeyboardType.InlineKeyBoard: + case EKeyboardType.InlineKeyBoard: - if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !this.EnablePaging) + if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging) { - throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; + throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; } if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols) { - throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; + throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; } break; - case eKeyboardType.ReplyKeyboard: + case EKeyboardType.ReplyKeyboard: - if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !this.EnablePaging) + if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging) { - throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows }; + throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows }; } if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols) { - throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols }; + throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols }; } break; } } - public async override Task Render(MessageResult result) + public override async Task Render(MessageResult result) { - if (!this.RenderNecessary) + if (!_renderNecessary) return; //Check for rows and column limits CheckGrid(); - this.RenderNecessary = false; + _renderNecessary = false; - ButtonForm form = this.DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (this.EnableSearch ? this.SearchQuery : null)); + var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (EnableSearch ? SearchQuery : null)); //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") @@ -435,42 +419,42 @@ namespace TelegramBotBase.Controls.Hybrid // form = form.Duplicate(); //} - if (this.EnablePaging) + if (EnablePaging) { IntegratePagingView(form); } - if (this.HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) + if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) { - form.InsertButtonRow(0, this.HeadLayoutButtonRow); + form.InsertButtonRow(0, HeadLayoutButtonRow); } - if (this.SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) + if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) { - if (this.IsNavigationBarVisible) + if (IsNavigationBarVisible) { - form.InsertButtonRow(2, this.SubHeadLayoutButtonRow); + form.InsertButtonRow(2, SubHeadLayoutButtonRow); } else { - form.InsertButtonRow(1, this.SubHeadLayoutButtonRow); + form.InsertButtonRow(1, SubHeadLayoutButtonRow); } } Message m = null; - switch (this.KeyboardType) + switch (KeyboardType) { //Reply Keyboard could only be updated with a new keyboard. - case eKeyboardType.ReplyKeyboard: + case EKeyboardType.ReplyKeyboard: if (form.Count == 0) { - if (this.MessageId != null) + if (MessageId != null) { - await this.Device.HideReplyKeyboard(); - this.MessageId = null; + await Device.HideReplyKeyboard(); + MessageId = null; } return; @@ -491,39 +475,39 @@ namespace TelegramBotBase.Controls.Hybrid var rkm = (ReplyKeyboardMarkup)form; - rkm.ResizeKeyboard = this.ResizeKeyboard; - rkm.OneTimeKeyboard = this.OneTimeKeyboard; - m = await this.Device.Send(this.Title, rkm, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false); + rkm.ResizeKeyboard = ResizeKeyboard; + rkm.OneTimeKeyboard = OneTimeKeyboard; + m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); //Prevent flicker of keyboard - if (this.DeletePreviousMessage && this.MessageId != null) - await this.Device.DeleteMessage(this.MessageId.Value); + if (DeletePreviousMessage && MessageId != null) + await Device.DeleteMessage(MessageId.Value); break; - case eKeyboardType.InlineKeyBoard: + case EKeyboardType.InlineKeyBoard: //Try to edit message if message id is available //When the returned message is null then the message has been already deleted, resend it - if (this.MessageId != null) + if (MessageId != null) { - m = await this.Device.Edit(this.MessageId.Value, this.Title, (InlineKeyboardMarkup)form); + m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form); if (m != null) { - this.MessageId = m.MessageId; + MessageId = m.MessageId; return; } } //When no message id is available or it has been deleted due the use of AutoCleanForm re-render automatically - m = await this.Device.Send(this.Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false); + m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); break; } if (m != null) { - this.MessageId = m.MessageId; + MessageId = m.MessageId; } @@ -531,23 +515,23 @@ namespace TelegramBotBase.Controls.Hybrid private void IntegratePagingView(ButtonForm dataForm) { - //No Items + //No Items if (dataForm.Rows == 0) { dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$")); } - if (this.IsNavigationBarVisible) + if (IsNavigationBarVisible) { //🔍 - ButtonRow row = new ButtonRow(); + var row = new ButtonRow(); row.Add(new ButtonBase(PreviousPageLabel, "$previous$")); - row.Add(new ButtonBase(String.Format(Localizations.Default.Language["ButtonGrid_CurrentPage"], this.CurrentPageIndex + 1, this.PageCount), "$site$")); + row.Add(new ButtonBase(string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), "$site$")); row.Add(new ButtonBase(NextPageLabel, "$next$")); - if (this.EnableSearch) + if (EnableSearch) { - row.Insert(2, new ButtonBase("🔍 " + (this.SearchQuery ?? ""), "$search$")); + row.Insert(2, new ButtonBase("🔍 " + (SearchQuery ?? ""), "$search$")); } dataForm.InsertButtonRow(0, row); @@ -560,12 +544,12 @@ namespace TelegramBotBase.Controls.Hybrid { get { - if (this.KeyboardType == eKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) + if (KeyboardType == EKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) { return true; } - if (this.KeyboardType == eKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows) + if (KeyboardType == EKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows) { return true; } @@ -578,7 +562,7 @@ namespace TelegramBotBase.Controls.Hybrid { get { - if (this.NavigationBarVisibility == eNavigationBarVisibility.always | (this.NavigationBarVisibility == eNavigationBarVisibility.auto && PagingNecessary)) + if (NavigationBarVisibility == ENavigationBarVisibility.always | (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary)) { return true; } @@ -594,30 +578,19 @@ namespace TelegramBotBase.Controls.Hybrid { get { - switch (this.KeyboardType) + return KeyboardType switch { - case eKeyboardType.InlineKeyBoard: - return Constants.Telegram.MaxInlineKeyBoardRows; - - case eKeyboardType.ReplyKeyboard: - return Constants.Telegram.MaxReplyKeyboardRows; - - default: - return 0; - } + EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows, + EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows, + _ => 0 + }; } } /// /// Returns the number of all rows (layout + navigation + content); /// - public int TotalRows - { - get - { - return this.LayoutRows + DataSource.RowCount; - } - } + public int TotalRows => LayoutRows + DataSource.RowCount; /// @@ -627,15 +600,15 @@ namespace TelegramBotBase.Controls.Hybrid { get { - int layoutRows = 0; + var layoutRows = 0; - if (this.NavigationBarVisibility == eNavigationBarVisibility.always | this.NavigationBarVisibility == eNavigationBarVisibility.auto) + if (NavigationBarVisibility == ENavigationBarVisibility.always | NavigationBarVisibility == ENavigationBarVisibility.auto) layoutRows += 2; - if (this.HeadLayoutButtonRow != null && this.HeadLayoutButtonRow.Count > 0) + if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) layoutRows++; - if (this.SubHeadLayoutButtonRow != null && this.SubHeadLayoutButtonRow.Count > 0) + if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) layoutRows++; return layoutRows; @@ -645,13 +618,7 @@ namespace TelegramBotBase.Controls.Hybrid /// /// Returns the number of item rows per page. /// - public int ItemRowsPerPage - { - get - { - return this.MaximumRow - this.LayoutRows; - } - } + public int ItemRowsPerPage => MaximumRow - LayoutRows; /// /// Return the number of pages. @@ -665,7 +632,7 @@ namespace TelegramBotBase.Controls.Hybrid //var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null); - var max = this.DataSource.CalculateMax(this.EnableSearch ? this.SearchQuery : null); + var max = DataSource.CalculateMax(EnableSearch ? SearchQuery : null); //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") //{ @@ -675,22 +642,24 @@ namespace TelegramBotBase.Controls.Hybrid if (max == 0) return 1; - return (int)Math.Ceiling((decimal)((decimal)max / (decimal)ItemRowsPerPage)); + return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage); } } - public override async Task Hidden(bool FormClose) + public override Task Hidden(bool formClose) { //Prepare for opening Modal, and comming back - if (!FormClose) + if (!formClose) { - this.Updated(); + Updated(); } else { //Remove event handler - this.Device.MessageDeleted -= Device_MessageDeleted; + Device.MessageDeleted -= Device_MessageDeleted; } + + return Task.CompletedTask; } /// @@ -698,31 +667,31 @@ namespace TelegramBotBase.Controls.Hybrid /// public void Updated() { - this.RenderNecessary = true; + _renderNecessary = true; } - public async override Task Cleanup() + public override async Task Cleanup() { - if (this.MessageId == null) + if (MessageId == null) return; - switch (this.KeyboardType) + switch (KeyboardType) { - case eKeyboardType.InlineKeyBoard: + case EKeyboardType.InlineKeyBoard: - await this.Device.DeleteMessage(this.MessageId.Value); + await Device.DeleteMessage(MessageId.Value); - this.MessageId = null; + MessageId = null; break; - case eKeyboardType.ReplyKeyboard: + case EKeyboardType.ReplyKeyboard: - if (this.HideKeyboardOnCleanup) + if (HideKeyboardOnCleanup) { - await this.Device.HideReplyKeyboard(); + await Device.HideReplyKeyboard(); } - this.MessageId = null; + MessageId = null; break; } diff --git a/TelegramBotBase/Controls/Hybrid/ButtonRow.cs b/TelegramBotBase/Controls/Hybrid/ButtonRow.cs index 2d0deab..c2ba68f 100644 --- a/TelegramBotBase/Controls/Hybrid/ButtonRow.cs +++ b/TelegramBotBase/Controls/Hybrid/ButtonRow.cs @@ -1,10 +1,7 @@ using System; -using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; -using System.Runtime.CompilerServices; -using System.Text; using TelegramBotBase.Form; namespace TelegramBotBase.Controls.Hybrid @@ -12,8 +9,7 @@ namespace TelegramBotBase.Controls.Hybrid [DebuggerDisplay("{Count} columns")] public class ButtonRow { - - List __buttons = new List(); + private List _buttons = new List(); public ButtonRow() { @@ -23,59 +19,47 @@ namespace TelegramBotBase.Controls.Hybrid public ButtonRow(params ButtonBase[] buttons) { - __buttons = buttons.ToList(); + _buttons = buttons.ToList(); } - public ButtonBase this[int index] - { - get - { - return __buttons[index]; - } - } + public ButtonBase this[int index] => _buttons[index]; - public int Count - { - get - { - return __buttons.Count; - } - } + public int Count => _buttons.Count; public void Add(ButtonBase button) { - __buttons.Add(button); + _buttons.Add(button); } public void AddRange(ButtonBase button) { - __buttons.Add(button); + _buttons.Add(button); } public void Insert(int index, ButtonBase button) { - __buttons.Insert(index, button); + _buttons.Insert(index, button); } public IEnumerator GetEnumerator() { - return __buttons.GetEnumerator(); + return _buttons.GetEnumerator(); } public ButtonBase[] ToArray() { - return __buttons.ToArray(); + return _buttons.ToArray(); } public List ToList() { - return __buttons.ToList(); + return _buttons.ToList(); } - public bool Matches(String text, bool useText = true) + public bool Matches(string text, bool useText = true) { - foreach (var b in __buttons) + foreach (var b in _buttons) { if (useText && b.Text.Trim().Equals(text, StringComparison.InvariantCultureIgnoreCase)) return true; @@ -92,9 +76,9 @@ namespace TelegramBotBase.Controls.Hybrid /// /// /// - public ButtonBase GetButtonMatch(String text, bool useText = true) + public ButtonBase GetButtonMatch(string text, bool useText = true) { - foreach (var b in __buttons) + foreach (var b in _buttons) { if (useText && b.Text.Trim().Equals(text, StringComparison.InvariantCultureIgnoreCase)) return b; @@ -106,7 +90,7 @@ namespace TelegramBotBase.Controls.Hybrid public static implicit operator ButtonRow(List list) { - return new ButtonRow() { __buttons = list }; + return new ButtonRow { _buttons = list }; } } } diff --git a/TelegramBotBase/Controls/Hybrid/CheckedButtonList.cs b/TelegramBotBase/Controls/Hybrid/CheckedButtonList.cs index 12026b2..5da90dc 100644 --- a/TelegramBotBase/Controls/Hybrid/CheckedButtonList.cs +++ b/TelegramBotBase/Controls/Hybrid/CheckedButtonList.cs @@ -1,49 +1,42 @@ using System; using System.Collections.Generic; using System.ComponentModel; -using System.Diagnostics.SymbolStore; using System.Linq; -using System.Text; using System.Threading.Tasks; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.ReplyMarkups; using TelegramBotBase.Args; using TelegramBotBase.Base; -using TelegramBotBase.Datasources; +using TelegramBotBase.DataSources; using TelegramBotBase.Enums; using TelegramBotBase.Exceptions; using TelegramBotBase.Form; +using TelegramBotBase.Localizations; using static TelegramBotBase.Base.Async; namespace TelegramBotBase.Controls.Hybrid { - public class CheckedButtonList : Base.ControlBase + public class CheckedButtonList : ControlBase { - public String Title { get; set; } = Localizations.Default.Language["ButtonGrid_Title"]; + public string Title { get; set; } = Default.Language["ButtonGrid_Title"]; - public String ConfirmationText { get; set; } = ""; + public string ConfirmationText { get; set; } = ""; - private bool RenderNecessary = true; + private bool _renderNecessary = true; - private static readonly object __evButtonClicked = new object(); + private static readonly object EvButtonClicked = new object(); - private static readonly object __evCheckedChanged = new object(); + private static readonly object EvCheckedChanged = new object(); - private readonly EventHandlerList Events = new EventHandlerList(); + private readonly EventHandlerList _events = new EventHandlerList(); [Obsolete("This property is obsolete. Please use the DataSource property instead.")] public ButtonForm ButtonsForm { - get - { - return DataSource.ButtonForm; - } - set - { - DataSource = new ButtonFormDataSource(value); - } + get => DataSource.ButtonForm; + set => DataSource = new ButtonFormDataSource(value); } /// @@ -51,7 +44,7 @@ namespace TelegramBotBase.Controls.Hybrid /// public ButtonFormDataSource DataSource { get; set; } - List CheckedRows { get; set; } = new List(); + private List CheckedRows { get; set; } = new List(); public int? MessageId { get; set; } @@ -91,25 +84,25 @@ namespace TelegramBotBase.Controls.Hybrid //public String SearchQuery { get; set; } - public eNavigationBarVisibility NavigationBarVisibility { get; set; } = eNavigationBarVisibility.always; + public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always; /// /// Index of the current page /// - public int CurrentPageIndex { get; set; } = 0; + public int CurrentPageIndex { get; set; } - public String PreviousPageLabel = Localizations.Default.Language["ButtonGrid_PreviousPage"]; + public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"]; - public String NextPageLabel = Localizations.Default.Language["ButtonGrid_NextPage"]; + public string NextPageLabel = Default.Language["ButtonGrid_NextPage"]; - public String NoItemsLabel = Localizations.Default.Language["ButtonGrid_NoItems"]; + public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"]; //public String SearchLabel = Localizations.Default.Language["ButtonGrid_SearchFeature"]; - public String CheckedIconLabel { get; set; } = "✅"; + public string CheckedIconLabel { get; set; } = "✅"; - public String UncheckedIconLabel { get; set; } = "◻️"; + public string UncheckedIconLabel { get; set; } = "◻️"; /// /// Layout of the buttons which should be displayed always on top. @@ -124,97 +117,82 @@ namespace TelegramBotBase.Controls.Hybrid /// /// Defines which type of Button Keyboard should be rendered. /// - public eKeyboardType KeyboardType + public EKeyboardType KeyboardType { - get - { - return m_eKeyboardType; - } + get => _mEKeyboardType; set { - if (m_eKeyboardType != value) + if (_mEKeyboardType != value) { - this.RenderNecessary = true; + _renderNecessary = true; Cleanup().Wait(); - m_eKeyboardType = value; + _mEKeyboardType = value; } } } - private eKeyboardType m_eKeyboardType = eKeyboardType.ReplyKeyboard; + private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard; public CheckedButtonList() { - this.DataSource = new ButtonFormDataSource(); + DataSource = new ButtonFormDataSource(); } - public CheckedButtonList(eKeyboardType type) : this() + public CheckedButtonList(EKeyboardType type) : this() { - m_eKeyboardType = type; + _mEKeyboardType = type; } public CheckedButtonList(ButtonForm form) { - this.DataSource = new ButtonFormDataSource(form); + DataSource = new ButtonFormDataSource(form); } public event AsyncEventHandler ButtonClicked { - add - { - this.Events.AddHandler(__evButtonClicked, value); - } - remove - { - this.Events.RemoveHandler(__evButtonClicked, value); - } + add => _events.AddHandler(EvButtonClicked, value); + remove => _events.RemoveHandler(EvButtonClicked, value); } public async Task OnButtonClicked(ButtonClickedEventArgs e) { - var handler = this.Events[__evButtonClicked]?.GetInvocationList().Cast>(); + var handler = _events[EvButtonClicked]?.GetInvocationList().Cast>(); if (handler == null) return; foreach (var h in handler) { - await Async.InvokeAllAsync(h, this, e); + await h.InvokeAllAsync(this, e); } } public event AsyncEventHandler CheckedChanged { - add - { - this.Events.AddHandler(__evCheckedChanged, value); - } - remove - { - this.Events.RemoveHandler(__evCheckedChanged, value); - } + add => _events.AddHandler(EvCheckedChanged, value); + remove => _events.RemoveHandler(EvCheckedChanged, value); } public async Task OnCheckedChanged(CheckedChangedEventArgs e) { - var handler = this.Events[__evCheckedChanged]?.GetInvocationList().Cast>(); + var handler = _events[EvCheckedChanged]?.GetInvocationList().Cast>(); if (handler == null) return; foreach (var h in handler) { - await Async.InvokeAllAsync(h, this, e); + await h.InvokeAllAsync(this, e); } } - public async override Task Load(MessageResult result) + public override async Task Load(MessageResult result) { - if (this.KeyboardType != eKeyboardType.ReplyKeyboard) + if (KeyboardType != EKeyboardType.ReplyKeyboard) return; if (!result.IsFirstHandler) @@ -225,7 +203,7 @@ namespace TelegramBotBase.Controls.Hybrid var matches = new List(); ButtonRow match = null; - int index = -1; + var index = -1; if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false) { @@ -260,36 +238,36 @@ namespace TelegramBotBase.Controls.Hybrid //Remove button click message - if (this.DeleteReplyMessage) + if (DeleteReplyMessage) await Device.DeleteMessage(result.MessageId); if (match == null) { if (result.MessageText == PreviousPageLabel) { - if (this.CurrentPageIndex > 0) - this.CurrentPageIndex--; + if (CurrentPageIndex > 0) + CurrentPageIndex--; - this.Updated(); + Updated(); } else if (result.MessageText == NextPageLabel) { - if (this.CurrentPageIndex < this.PageCount - 1) - this.CurrentPageIndex++; + if (CurrentPageIndex < PageCount - 1) + CurrentPageIndex++; - this.Updated(); + Updated(); } else if (result.MessageText.EndsWith(CheckedIconLabel)) { var s = result.MessageText.Split(' ', '.'); index = int.Parse(s[0]) - 1; - if (!this.CheckedRows.Contains(index)) + if (!CheckedRows.Contains(index)) return; - this.CheckedRows.Remove(index); + CheckedRows.Remove(index); - this.Updated(); + Updated(); await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, false)); @@ -299,13 +277,13 @@ namespace TelegramBotBase.Controls.Hybrid var s = result.MessageText.Split(' ', '.'); index = int.Parse(s[0]) - 1; - if (this.CheckedRows.Contains(index)) + if (CheckedRows.Contains(index)) return; - this.CheckedRows.Add(index); + CheckedRows.Add(index); - this.Updated(); + Updated(); await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, true)); @@ -355,7 +333,7 @@ namespace TelegramBotBase.Controls.Hybrid } - public async override Task Action(MessageResult result, string value = null) + public override async Task Action(MessageResult result, string value = null) { if (result.Handled) return; @@ -364,13 +342,13 @@ namespace TelegramBotBase.Controls.Hybrid return; //Find clicked button depending on Text or Value (depending on markup type) - if (this.KeyboardType != eKeyboardType.InlineKeyBoard) + if (KeyboardType != EKeyboardType.InlineKeyBoard) return; - await result.ConfirmAction(this.ConfirmationText ?? ""); + await result.ConfirmAction(ConfirmationText ?? ""); ButtonRow match = null; - int index = -1; + var index = -1; if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) { @@ -422,18 +400,18 @@ namespace TelegramBotBase.Controls.Hybrid { case "$previous$": - if (this.CurrentPageIndex > 0) - this.CurrentPageIndex--; + if (CurrentPageIndex > 0) + CurrentPageIndex--; - this.Updated(); + Updated(); break; case "$next$": - if (this.CurrentPageIndex < this.PageCount - 1) - this.CurrentPageIndex++; + if (CurrentPageIndex < PageCount - 1) + CurrentPageIndex++; - this.Updated(); + Updated(); break; @@ -448,11 +426,11 @@ namespace TelegramBotBase.Controls.Hybrid index = int.Parse(s[1]); - if (!this.CheckedRows.Contains(index)) + if (!CheckedRows.Contains(index)) { - this.CheckedRows.Add(index); + CheckedRows.Add(index); - this.Updated(); + Updated(); await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, true)); } @@ -463,11 +441,11 @@ namespace TelegramBotBase.Controls.Hybrid index = int.Parse(s[1]); - if (this.CheckedRows.Contains(index)) + if (CheckedRows.Contains(index)) { - this.CheckedRows.Remove(index); + CheckedRows.Remove(index); - this.Updated(); + Updated(); await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, false)); } @@ -487,51 +465,51 @@ namespace TelegramBotBase.Controls.Hybrid /// private void CheckGrid() { - switch (m_eKeyboardType) + switch (_mEKeyboardType) { - case eKeyboardType.InlineKeyBoard: + case EKeyboardType.InlineKeyBoard: - if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !this.EnablePaging) + if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging) { - throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; + throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; } if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols) { - throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; + throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; } break; - case eKeyboardType.ReplyKeyboard: + case EKeyboardType.ReplyKeyboard: - if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !this.EnablePaging) + if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging) { - throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows }; + throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows }; } if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols) { - throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols }; + throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols }; } break; } } - public async override Task Render(MessageResult result) + public override async Task Render(MessageResult result) { - if (!this.RenderNecessary) + if (!_renderNecessary) return; //Check for rows and column limits CheckGrid(); - this.RenderNecessary = false; + _renderNecessary = false; Message m = null; - ButtonForm form = this.DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, null); + var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage); //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") //{ @@ -542,7 +520,7 @@ namespace TelegramBotBase.Controls.Hybrid //form = form.Duplicate(); //} - if (this.EnablePaging) + if (EnablePaging) { IntegratePagingView(form); } @@ -551,34 +529,34 @@ namespace TelegramBotBase.Controls.Hybrid form = PrepareCheckableLayout(form); } - if (this.HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) + if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) { - form.InsertButtonRow(0, this.HeadLayoutButtonRow.ToArray()); + form.InsertButtonRow(0, HeadLayoutButtonRow.ToArray()); } - if (this.SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) + if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) { - if (this.IsNavigationBarVisible) + if (IsNavigationBarVisible) { - form.InsertButtonRow(2, this.SubHeadLayoutButtonRow.ToArray()); + form.InsertButtonRow(2, SubHeadLayoutButtonRow.ToArray()); } else { - form.InsertButtonRow(1, this.SubHeadLayoutButtonRow.ToArray()); + form.InsertButtonRow(1, SubHeadLayoutButtonRow.ToArray()); } } - switch (this.KeyboardType) + switch (KeyboardType) { //Reply Keyboard could only be updated with a new keyboard. - case eKeyboardType.ReplyKeyboard: + case EKeyboardType.ReplyKeyboard: if (form.Count == 0) { - if (this.MessageId != null) + if (MessageId != null) { - await this.Device.HideReplyKeyboard(); - this.MessageId = null; + await Device.HideReplyKeyboard(); + MessageId = null; } return; @@ -589,25 +567,25 @@ namespace TelegramBotBase.Controls.Hybrid var rkm = (ReplyKeyboardMarkup)form; - rkm.ResizeKeyboard = this.ResizeKeyboard; - rkm.OneTimeKeyboard = this.OneTimeKeyboard; - m = await this.Device.Send(this.Title, rkm, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false); + rkm.ResizeKeyboard = ResizeKeyboard; + rkm.OneTimeKeyboard = OneTimeKeyboard; + m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); //Prevent flicker of keyboard - if (this.DeletePreviousMessage && this.MessageId != null) - await this.Device.DeleteMessage(this.MessageId.Value); + if (DeletePreviousMessage && MessageId != null) + await Device.DeleteMessage(MessageId.Value); break; - case eKeyboardType.InlineKeyBoard: + case EKeyboardType.InlineKeyBoard: - if (this.MessageId != null) + if (MessageId != null) { - m = await this.Device.Edit(this.MessageId.Value, this.Title, (InlineKeyboardMarkup)form); + m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form); } else { - m = await this.Device.Send(this.Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false); + m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); } break; @@ -615,7 +593,7 @@ namespace TelegramBotBase.Controls.Hybrid if (m != null) { - this.MessageId = m.MessageId; + MessageId = m.MessageId; } @@ -623,23 +601,23 @@ namespace TelegramBotBase.Controls.Hybrid private void IntegratePagingView(ButtonForm dataForm) { - //No Items + //No Items if (dataForm.Rows == 0) { dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$")); } - ButtonForm bf = new ButtonForm(); + var bf = new ButtonForm(); bf = PrepareCheckableLayout(dataForm); - if (this.IsNavigationBarVisible) + if (IsNavigationBarVisible) { //🔍 - ButtonRow row = new ButtonRow(); + var row = new ButtonRow(); row.Add(new ButtonBase(PreviousPageLabel, "$previous$")); - row.Add(new ButtonBase(String.Format(Localizations.Default.Language["ButtonGrid_CurrentPage"], this.CurrentPageIndex + 1, this.PageCount), "$site$")); + row.Add(new ButtonBase(string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), "$site$")); row.Add(new ButtonBase(NextPageLabel, "$next$")); @@ -652,30 +630,30 @@ namespace TelegramBotBase.Controls.Hybrid private ButtonForm PrepareCheckableLayout(ButtonForm dataForm) { var bf = new ButtonForm(); - for (int i = 0; i < dataForm.Rows; i++) + for (var i = 0; i < dataForm.Rows; i++) { - int it = (this.CurrentPageIndex * (this.MaximumRow - LayoutRows)) + i; + var it = (CurrentPageIndex * (MaximumRow - LayoutRows)) + i; //if (it > dataForm.Rows - 1) // break; var r = dataForm[i]; - String s = CheckedRows.Contains(it) ? this.CheckedIconLabel : this.UncheckedIconLabel; + var s = CheckedRows.Contains(it) ? CheckedIconLabel : UncheckedIconLabel; //On reply keyboards we need a unique text. - if (this.KeyboardType == eKeyboardType.ReplyKeyboard) + if (KeyboardType == EKeyboardType.ReplyKeyboard) { s = $"{it + 1}. " + s; } if (CheckedRows.Contains(it)) { - r.Insert(0, new ButtonBase(s, "uncheck$" + it.ToString())); + r.Insert(0, new ButtonBase(s, "uncheck$" + it)); } else { - r.Insert(0, new ButtonBase(s, "check$" + it.ToString())); + r.Insert(0, new ButtonBase(s, "check$" + it)); } bf.AddButtonRow(r); @@ -688,12 +666,12 @@ namespace TelegramBotBase.Controls.Hybrid { get { - if (this.KeyboardType == eKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) + if (KeyboardType == EKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) { return true; } - if (this.KeyboardType == eKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows) + if (KeyboardType == EKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows) { return true; } @@ -706,7 +684,7 @@ namespace TelegramBotBase.Controls.Hybrid { get { - if (this.NavigationBarVisibility == eNavigationBarVisibility.always | (this.NavigationBarVisibility == eNavigationBarVisibility.auto && PagingNecessary)) + if (NavigationBarVisibility == ENavigationBarVisibility.always | (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary)) { return true; } @@ -722,30 +700,19 @@ namespace TelegramBotBase.Controls.Hybrid { get { - switch (this.KeyboardType) + return KeyboardType switch { - case eKeyboardType.InlineKeyBoard: - return Constants.Telegram.MaxInlineKeyBoardRows; - - case eKeyboardType.ReplyKeyboard: - return Constants.Telegram.MaxReplyKeyboardRows; - - default: - return 0; - } + EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows, + EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows, + _ => 0 + }; } } /// /// Returns the number of all rows (layout + navigation + content); /// - public int TotalRows - { - get - { - return this.LayoutRows + DataSource.RowCount; - } - } + public int TotalRows => LayoutRows + DataSource.RowCount; /// @@ -755,15 +722,15 @@ namespace TelegramBotBase.Controls.Hybrid { get { - int layoutRows = 0; + var layoutRows = 0; - if (this.NavigationBarVisibility == eNavigationBarVisibility.always | this.NavigationBarVisibility == eNavigationBarVisibility.auto) + if (NavigationBarVisibility == ENavigationBarVisibility.always | NavigationBarVisibility == ENavigationBarVisibility.auto) layoutRows += 2; - if (this.HeadLayoutButtonRow != null && this.HeadLayoutButtonRow.Count > 0) + if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) layoutRows++; - if (this.SubHeadLayoutButtonRow != null && this.SubHeadLayoutButtonRow.Count > 0) + if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) layoutRows++; return layoutRows; @@ -773,13 +740,7 @@ namespace TelegramBotBase.Controls.Hybrid /// /// Returns the number of item rows per page. /// - public int ItemRowsPerPage - { - get - { - return this.MaximumRow - this.LayoutRows; - } - } + public int ItemRowsPerPage => MaximumRow - LayoutRows; public int PageCount { @@ -790,7 +751,7 @@ namespace TelegramBotBase.Controls.Hybrid //var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null); - var max = this.DataSource.RowCount; + var max = DataSource.RowCount; //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") //{ @@ -800,28 +761,30 @@ namespace TelegramBotBase.Controls.Hybrid if (max == 0) return 1; - return (int)Math.Ceiling((decimal)((decimal)max / (decimal)ItemRowsPerPage)); + return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage); } } - public override async Task Hidden(bool FormClose) + public override Task Hidden(bool formClose) { //Prepare for opening Modal, and comming back - if (!FormClose) + if (!formClose) { - this.Updated(); + Updated(); } + + return Task.CompletedTask; } public List CheckedItems { get { - List lst = new List(); + var lst = new List(); foreach (var c in CheckedRows) { - lst.Add(this.ButtonsForm[c][0]); + lst.Add(ButtonsForm[c][0]); } return lst; @@ -834,31 +797,31 @@ namespace TelegramBotBase.Controls.Hybrid /// public void Updated() { - this.RenderNecessary = true; + _renderNecessary = true; } - public async override Task Cleanup() + public override async Task Cleanup() { - if (this.MessageId == null) + if (MessageId == null) return; - switch (this.KeyboardType) + switch (KeyboardType) { - case eKeyboardType.InlineKeyBoard: + case EKeyboardType.InlineKeyBoard: - await this.Device.DeleteMessage(this.MessageId.Value); + await Device.DeleteMessage(MessageId.Value); - this.MessageId = null; + MessageId = null; break; - case eKeyboardType.ReplyKeyboard: + case EKeyboardType.ReplyKeyboard: - if (this.HideKeyboardOnCleanup) + if (HideKeyboardOnCleanup) { - await this.Device.HideReplyKeyboard(); + await Device.HideReplyKeyboard(); } - this.MessageId = null; + MessageId = null; break; } diff --git a/TelegramBotBase/Controls/Hybrid/MultiView.cs b/TelegramBotBase/Controls/Hybrid/MultiView.cs index 83eb0e6..5008b73 100644 --- a/TelegramBotBase/Controls/Hybrid/MultiView.cs +++ b/TelegramBotBase/Controls/Hybrid/MultiView.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Text; +using System.Collections.Generic; using System.Threading.Tasks; using TelegramBotBase.Args; using TelegramBotBase.Base; @@ -13,33 +9,30 @@ namespace TelegramBotBase.Controls.Hybrid /// /// This Control is for having a basic form content switching control. /// - public abstract class MultiView : Base.ControlBase + public abstract class MultiView : ControlBase { /// /// Index of the current View. /// public int SelectedViewIndex { - get - { - return m_iSelectedViewIndex; - } + get => _mISelectedViewIndex; set { - m_iSelectedViewIndex = value; + _mISelectedViewIndex = value; //Already rendered? Re-Render - if (_Rendered) + if (_rendered) ForceRender().Wait(); } } - private int m_iSelectedViewIndex = 0; + private int _mISelectedViewIndex; /// /// Hold if the View has been rendered already. /// - private bool _Rendered = false; + private bool _rendered; private List Messages { get; set; } @@ -50,12 +43,13 @@ namespace TelegramBotBase.Controls.Hybrid } - private async Task Device_MessageSent(object sender, MessageSentEventArgs e) + private Task Device_MessageSent(object sender, MessageSentEventArgs e) { if (e.Origin == null || !e.Origin.IsSubclassOf(typeof(MultiView))) - return; + return Task.CompletedTask; - this.Messages.Add(e.MessageId); + Messages.Add(e.MessageId); + return Task.CompletedTask; } public override void Init() @@ -63,23 +57,24 @@ namespace TelegramBotBase.Controls.Hybrid Device.MessageSent += Device_MessageSent; } - public override async Task Load(MessageResult result) + public override Task Load(MessageResult result) { - _Rendered = false; + _rendered = false; + return Task.CompletedTask; } public override async Task Render(MessageResult result) { //When already rendered, skip rendering - if (_Rendered) + if (_rendered) return; await CleanUpView(); - await RenderView(new RenderViewEventArgs(this.SelectedViewIndex)); + await RenderView(new RenderViewEventArgs(SelectedViewIndex)); - _Rendered = true; + _rendered = true; } @@ -87,25 +82,24 @@ namespace TelegramBotBase.Controls.Hybrid /// Will get invoked on rendering the current controls view. /// /// - public virtual async Task RenderView(RenderViewEventArgs e) + public virtual Task RenderView(RenderViewEventArgs e) { - - + return Task.CompletedTask; } - async Task CleanUpView() + private async Task CleanUpView() { var tasks = new List(); - foreach (var msg in this.Messages) + foreach (var msg in Messages) { - tasks.Add(this.Device.DeleteMessage(msg)); + tasks.Add(Device.DeleteMessage(msg)); } await Task.WhenAll(tasks); - this.Messages.Clear(); + Messages.Clear(); } @@ -116,9 +110,9 @@ namespace TelegramBotBase.Controls.Hybrid { await CleanUpView(); - await RenderView(new RenderViewEventArgs(this.SelectedViewIndex)); + await RenderView(new RenderViewEventArgs(SelectedViewIndex)); - _Rendered = true; + _rendered = true; } public override async Task Cleanup() diff --git a/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs b/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs index cf0bc90..1270b8f 100644 --- a/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs +++ b/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs @@ -1,20 +1,18 @@ using System; using System.Collections.Generic; using System.ComponentModel; -using System.Diagnostics.SymbolStore; using System.Linq; -using System.Text; using System.Threading.Tasks; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; -using Telegram.Bot.Types.InlineQueryResults; using Telegram.Bot.Types.ReplyMarkups; using TelegramBotBase.Args; using TelegramBotBase.Base; -using TelegramBotBase.Datasources; +using TelegramBotBase.DataSources; using TelegramBotBase.Enums; using TelegramBotBase.Exceptions; using TelegramBotBase.Form; +using TelegramBotBase.Localizations; using static TelegramBotBase.Base.Async; namespace TelegramBotBase.Controls.Hybrid @@ -22,27 +20,21 @@ namespace TelegramBotBase.Controls.Hybrid public class TaggedButtonGrid : MultiView { - public String Title { get; set; } = Localizations.Default.Language["ButtonGrid_Title"]; + public string Title { get; set; } = Default.Language["ButtonGrid_Title"]; - public String ConfirmationText { get; set; } + public string ConfirmationText { get; set; } - private bool RenderNecessary = true; + private bool _renderNecessary = true; - private static readonly object __evButtonClicked = new object(); + private static readonly object EvButtonClicked = new object(); - private readonly EventHandlerList Events = new EventHandlerList(); + private readonly EventHandlerList _events = new EventHandlerList(); [Obsolete("This property is obsolete. Please use the DataSource property instead.")] public ButtonForm ButtonsForm { - get - { - return DataSource.ButtonForm; - } - set - { - DataSource = new ButtonFormDataSource(value); - } + get => DataSource.ButtonForm; + set => DataSource = new ButtonFormDataSource(value); } /// @@ -90,29 +82,29 @@ namespace TelegramBotBase.Controls.Hybrid /// public bool EnableSearch { get; set; } = false; - public String SearchQuery { get; set; } + public string SearchQuery { get; set; } - public eNavigationBarVisibility NavigationBarVisibility { get; set; } = eNavigationBarVisibility.always; + public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always; /// /// Index of the current page /// - public int CurrentPageIndex { get; set; } = 0; + public int CurrentPageIndex { get; set; } - public String PreviousPageLabel = Localizations.Default.Language["ButtonGrid_PreviousPage"]; + public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"]; - public String NextPageLabel = Localizations.Default.Language["ButtonGrid_NextPage"]; + public string NextPageLabel = Default.Language["ButtonGrid_NextPage"]; - public String NoItemsLabel = Localizations.Default.Language["ButtonGrid_NoItems"]; + public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"]; - public String SearchLabel = Localizations.Default.Language["ButtonGrid_SearchFeature"]; + public string SearchLabel = Default.Language["ButtonGrid_SearchFeature"]; - public String BackLabel = Localizations.Default.Language["ButtonGrid_Back"]; + public string BackLabel = Default.Language["ButtonGrid_Back"]; - public String CheckAllLabel = Localizations.Default.Language["ButtonGrid_CheckAll"]; + public string CheckAllLabel = Default.Language["ButtonGrid_CheckAll"]; - public String UncheckAllLabel = Localizations.Default.Language["ButtonGrid_UncheckAll"]; + public string UncheckAllLabel = Default.Language["ButtonGrid_UncheckAll"]; /// /// Layout of the buttons which should be displayed always on top. @@ -132,100 +124,91 @@ namespace TelegramBotBase.Controls.Hybrid /// /// List of Tags which will be allowed to filter by. /// - public List Tags { get; set; } + public List Tags { get; set; } /// /// List of Tags selected by the User. /// - public List SelectedTags { get; set; } + public List SelectedTags { get; set; } /// /// Defines which type of Button Keyboard should be rendered. /// - public eKeyboardType KeyboardType + public EKeyboardType KeyboardType { - get - { - return m_eKeyboardType; - } + get => _mEKeyboardType; set { - if (m_eKeyboardType != value) + if (_mEKeyboardType != value) { - this.RenderNecessary = true; + _renderNecessary = true; Cleanup().Wait(); - m_eKeyboardType = value; + _mEKeyboardType = value; } } } - private eKeyboardType m_eKeyboardType = eKeyboardType.ReplyKeyboard; + private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard; public TaggedButtonGrid() { - this.DataSource = new ButtonFormDataSource(); + DataSource = new ButtonFormDataSource(); - this.SelectedViewIndex = 0; + SelectedViewIndex = 0; } - public TaggedButtonGrid(eKeyboardType type) : this() + public TaggedButtonGrid(EKeyboardType type) : this() { - m_eKeyboardType = type; + _mEKeyboardType = type; } public TaggedButtonGrid(ButtonForm form) { - this.DataSource = new ButtonFormDataSource(form); + DataSource = new ButtonFormDataSource(form); } public event AsyncEventHandler ButtonClicked { - add - { - this.Events.AddHandler(__evButtonClicked, value); - } - remove - { - this.Events.RemoveHandler(__evButtonClicked, value); - } + add => _events.AddHandler(EvButtonClicked, value); + remove => _events.RemoveHandler(EvButtonClicked, value); } public async Task OnButtonClicked(ButtonClickedEventArgs e) { - var handler = this.Events[__evButtonClicked]?.GetInvocationList().Cast>(); + var handler = _events[EvButtonClicked]?.GetInvocationList().Cast>(); if (handler == null) return; foreach (var h in handler) { - await Async.InvokeAllAsync(h, this, e); + await h.InvokeAllAsync(this, e); } } public override void Init() { - this.Device.MessageDeleted += Device_MessageDeleted; + Device.MessageDeleted += Device_MessageDeleted; } private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e) { - if (this.MessageId == null) + if (MessageId == null) return; - if (e.MessageId != this.MessageId) + if (e.MessageId != MessageId) return; - this.MessageId = null; + MessageId = null; } - public async override Task Load(MessageResult result) + public override async Task Load(MessageResult result) { - if (this.KeyboardType != eKeyboardType.ReplyKeyboard) + if (KeyboardType != EKeyboardType.ReplyKeyboard) return; if (!result.IsFirstHandler) @@ -236,7 +219,7 @@ namespace TelegramBotBase.Controls.Hybrid var matches = new List(); ButtonRow match = null; - int index = -1; + var index = -1; if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false) { @@ -275,12 +258,12 @@ namespace TelegramBotBase.Controls.Hybrid - switch (this.SelectedViewIndex) + switch (SelectedViewIndex) { case 0: //Remove button click message - if (this.DeleteReplyMessage) + if (DeleteReplyMessage) await Device.DeleteMessage(result.MessageId); if (match != null) @@ -293,59 +276,57 @@ namespace TelegramBotBase.Controls.Hybrid if (result.MessageText == PreviousPageLabel) { - if (this.CurrentPageIndex > 0) - this.CurrentPageIndex--; + if (CurrentPageIndex > 0) + CurrentPageIndex--; - this.Updated(); + Updated(); result.Handled = true; } else if (result.MessageText == NextPageLabel) { - if (this.CurrentPageIndex < this.PageCount - 1) - this.CurrentPageIndex++; + if (CurrentPageIndex < PageCount - 1) + CurrentPageIndex++; - this.Updated(); + Updated(); result.Handled = true; } - else if (this.EnableSearch) + else if (EnableSearch) { if (result.MessageText.StartsWith("🔍")) { //Sent note about searching - if (this.SearchQuery == null) + if (SearchQuery == null) { - await this.Device.Send(this.SearchLabel); + await Device.Send(SearchLabel); } - this.SearchQuery = null; - this.Updated(); + SearchQuery = null; + Updated(); result.Handled = true; return; } - this.SearchQuery = result.MessageText; + SearchQuery = result.MessageText; - if (this.SearchQuery != null && this.SearchQuery != "") + if (SearchQuery != null && SearchQuery != "") { - this.CurrentPageIndex = 0; - this.Updated(); + CurrentPageIndex = 0; + Updated(); result.Handled = true; - return; } } - else if (this.Tags != null) + else if (Tags != null) { if (result.MessageText == "📁") { //Remove button click message - if (this.DeletePreviousMessage) + if (DeletePreviousMessage) await Device.DeleteMessage(result.MessageId); - this.SelectedViewIndex = 1; - this.Updated(); + SelectedViewIndex = 1; + Updated(); result.Handled = true; - return; } } @@ -353,23 +334,24 @@ namespace TelegramBotBase.Controls.Hybrid case 1: //Remove button click message - if (this.DeleteReplyMessage) + if (DeleteReplyMessage) await Device.DeleteMessage(result.MessageId); - if (result.MessageText == this.BackLabel) + if (result.MessageText == BackLabel) { - this.SelectedViewIndex = 0; - this.Updated(); + SelectedViewIndex = 0; + Updated(); result.Handled = true; return; } - else if (result.MessageText == this.CheckAllLabel) + + if (result.MessageText == CheckAllLabel) { - this.CheckAllTags(); + CheckAllTags(); } - else if (result.MessageText == this.UncheckAllLabel) + else if (result.MessageText == UncheckAllLabel) { - this.UncheckAllTags(); + UncheckAllTags(); } var i = result.MessageText.LastIndexOf(" "); @@ -378,16 +360,16 @@ namespace TelegramBotBase.Controls.Hybrid var t = result.MessageText.Substring(0, i); - if (this.SelectedTags.Contains(t)) + if (SelectedTags.Contains(t)) { - this.SelectedTags.Remove(t); + SelectedTags.Remove(t); } else { - this.SelectedTags.Add(t); + SelectedTags.Add(t); } - this.Updated(); + Updated(); result.Handled = true; @@ -399,7 +381,7 @@ namespace TelegramBotBase.Controls.Hybrid } - public async override Task Action(MessageResult result, string value = null) + public override async Task Action(MessageResult result, string value = null) { if (result.Handled) return; @@ -408,13 +390,13 @@ namespace TelegramBotBase.Controls.Hybrid return; //Find clicked button depending on Text or Value (depending on markup type) - if (this.KeyboardType != eKeyboardType.InlineKeyBoard) + if (KeyboardType != EKeyboardType.InlineKeyBoard) return; - await result.ConfirmAction(this.ConfirmationText ?? ""); + await result.ConfirmAction(ConfirmationText ?? ""); ButtonRow match = null; - int index = -1; + var index = -1; if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) { @@ -464,45 +446,45 @@ namespace TelegramBotBase.Controls.Hybrid { case "$previous$": - if (this.CurrentPageIndex > 0) - this.CurrentPageIndex--; + if (CurrentPageIndex > 0) + CurrentPageIndex--; - this.Updated(); + Updated(); break; case "$next$": - if (this.CurrentPageIndex < this.PageCount - 1) - this.CurrentPageIndex++; + if (CurrentPageIndex < PageCount - 1) + CurrentPageIndex++; - this.Updated(); + Updated(); break; case "$filter$": - this.SelectedViewIndex = 1; - this.Updated(); + SelectedViewIndex = 1; + Updated(); break; case "$back$": - this.SelectedViewIndex = 0; - this.Updated(); + SelectedViewIndex = 0; + Updated(); break; case "$checkall$": - this.CheckAllTags(); + CheckAllTags(); break; case "$uncheckall$": - this.UncheckAllTags(); + UncheckAllTags(); break; } @@ -514,49 +496,49 @@ namespace TelegramBotBase.Controls.Hybrid /// private void CheckGrid() { - switch (m_eKeyboardType) + switch (_mEKeyboardType) { - case eKeyboardType.InlineKeyBoard: + case EKeyboardType.InlineKeyBoard: - if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !this.EnablePaging) + if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging) { - throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; + throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; } if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols) { - throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; + throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; } break; - case eKeyboardType.ReplyKeyboard: + case EKeyboardType.ReplyKeyboard: - if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !this.EnablePaging) + if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging) { - throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows }; + throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows }; } if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols) { - throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols }; + throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols }; } break; } } - public async override Task Render(MessageResult result) + public override async Task Render(MessageResult result) { - if (!this.RenderNecessary) + if (!_renderNecessary) return; //Check for rows and column limits CheckGrid(); - this.RenderNecessary = false; + _renderNecessary = false; - switch (this.SelectedViewIndex) + switch (SelectedViewIndex) { case 0: @@ -586,7 +568,7 @@ namespace TelegramBotBase.Controls.Hybrid { Message m = null; - ButtonForm form = this.DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (this.EnableSearch ? this.SearchQuery : null)); + var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (EnableSearch ? SearchQuery : null)); //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") //{ @@ -597,111 +579,111 @@ namespace TelegramBotBase.Controls.Hybrid // form = form.Duplicate(); //} - if (this.Tags != null && this.SelectedTags != null) + if (Tags != null && SelectedTags != null) { - form = form.TagDuplicate(this.SelectedTags); + form = form.TagDuplicate(SelectedTags); } - if (this.EnablePaging) + if (EnablePaging) { IntegratePagingView(form); } - if (this.HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) + if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) { - form.InsertButtonRow(0, this.HeadLayoutButtonRow.ToArray()); + form.InsertButtonRow(0, HeadLayoutButtonRow.ToArray()); } - if (this.SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) + if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) { - if (this.IsNavigationBarVisible) + if (IsNavigationBarVisible) { - form.InsertButtonRow(2, this.SubHeadLayoutButtonRow.ToArray()); + form.InsertButtonRow(2, SubHeadLayoutButtonRow.ToArray()); } else { - form.InsertButtonRow(1, this.SubHeadLayoutButtonRow.ToArray()); + form.InsertButtonRow(1, SubHeadLayoutButtonRow.ToArray()); } } - switch (this.KeyboardType) + switch (KeyboardType) { //Reply Keyboard could only be updated with a new keyboard. - case eKeyboardType.ReplyKeyboard: + case EKeyboardType.ReplyKeyboard: if (form.Count == 0) { - if (this.MessageId != null) + if (MessageId != null) { - await this.Device.HideReplyKeyboard(); - this.MessageId = null; + await Device.HideReplyKeyboard(); + MessageId = null; } return; } var rkm = (ReplyKeyboardMarkup)form; - rkm.ResizeKeyboard = this.ResizeKeyboard; - rkm.OneTimeKeyboard = this.OneTimeKeyboard; - m = await this.Device.Send(this.Title, rkm, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false); + rkm.ResizeKeyboard = ResizeKeyboard; + rkm.OneTimeKeyboard = OneTimeKeyboard; + m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); //Prevent flicker of keyboard - if (this.DeletePreviousMessage && this.MessageId != null) - await this.Device.DeleteMessage(this.MessageId.Value); + if (DeletePreviousMessage && MessageId != null) + await Device.DeleteMessage(MessageId.Value); break; - case eKeyboardType.InlineKeyBoard: + case EKeyboardType.InlineKeyBoard: //Try to edit message if message id is available //When the returned message is null then the message has been already deleted, resend it - if (this.MessageId != null) + if (MessageId != null) { - m = await this.Device.Edit(this.MessageId.Value, this.Title, (InlineKeyboardMarkup)form); + m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form); if (m != null) { - this.MessageId = m.MessageId; + MessageId = m.MessageId; return; } } //When no message id is available or it has been deleted due the use of AutoCleanForm re-render automatically - m = await this.Device.Send(this.Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false); + m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); break; } if (m != null) { - this.MessageId = m.MessageId; + MessageId = m.MessageId; } } private void IntegratePagingView(ButtonForm dataForm) { - //No Items + //No Items if (dataForm.Rows == 0) { dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$")); } - if (this.IsNavigationBarVisible) + if (IsNavigationBarVisible) { //🔍 - ButtonRow row = new ButtonRow(); + var row = new ButtonRow(); row.Add(new ButtonBase(PreviousPageLabel, "$previous$")); - row.Add(new ButtonBase(String.Format(Localizations.Default.Language["ButtonGrid_CurrentPage"], this.CurrentPageIndex + 1, this.PageCount), "$site$")); + row.Add(new ButtonBase(string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), "$site$")); - if (this.Tags != null && this.Tags.Count > 0) + if (Tags != null && Tags.Count > 0) { row.Add(new ButtonBase("📁", "$filter$")); } row.Add(new ButtonBase(NextPageLabel, "$next$")); - if (this.EnableSearch) + if (EnableSearch) { - row.Insert(2, new ButtonBase("🔍 " + (this.SearchQuery ?? ""), "$search$")); + row.Insert(2, new ButtonBase("🔍 " + (SearchQuery ?? ""), "$search$")); } dataForm.InsertButtonRow(0, row); @@ -719,22 +701,22 @@ namespace TelegramBotBase.Controls.Hybrid private async Task RenderTagView() { Message m = null; - ButtonForm bf = new ButtonForm(); + var bf = new ButtonForm(); - bf.AddButtonRow(this.BackLabel, "$back$"); + bf.AddButtonRow(BackLabel, "$back$"); if (EnableCheckAllTools) { - this.TagsSubHeadLayoutButtonRow = new ButtonRow(new ButtonBase(CheckAllLabel, "$checkall$"), new ButtonBase(UncheckAllLabel, "$uncheckall$")); + TagsSubHeadLayoutButtonRow = new ButtonRow(new ButtonBase(CheckAllLabel, "$checkall$"), new ButtonBase(UncheckAllLabel, "$uncheckall$")); bf.AddButtonRow(TagsSubHeadLayoutButtonRow); } - foreach (var t in this.Tags) + foreach (var t in Tags) { - String s = t; + var s = t; - if (this.SelectedTags?.Contains(t) ?? false) + if (SelectedTags?.Contains(t) ?? false) { s += " ✅"; } @@ -743,17 +725,17 @@ namespace TelegramBotBase.Controls.Hybrid } - switch (this.KeyboardType) + switch (KeyboardType) { //Reply Keyboard could only be updated with a new keyboard. - case eKeyboardType.ReplyKeyboard: + case EKeyboardType.ReplyKeyboard: if (bf.Count == 0) { - if (this.MessageId != null) + if (MessageId != null) { - await this.Device.HideReplyKeyboard(); - this.MessageId = null; + await Device.HideReplyKeyboard(); + MessageId = null; } return; } @@ -763,25 +745,25 @@ namespace TelegramBotBase.Controls.Hybrid var rkm = (ReplyKeyboardMarkup)bf; - rkm.ResizeKeyboard = this.ResizeKeyboard; - rkm.OneTimeKeyboard = this.OneTimeKeyboard; - m = await this.Device.Send("Choose category", rkm, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false); + rkm.ResizeKeyboard = ResizeKeyboard; + rkm.OneTimeKeyboard = OneTimeKeyboard; + m = await Device.Send("Choose category", rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); //Prevent flicker of keyboard - if (this.DeletePreviousMessage && this.MessageId != null) - await this.Device.DeleteMessage(this.MessageId.Value); + if (DeletePreviousMessage && MessageId != null) + await Device.DeleteMessage(MessageId.Value); break; - case eKeyboardType.InlineKeyBoard: + case EKeyboardType.InlineKeyBoard: - if (this.MessageId != null) + if (MessageId != null) { - m = await this.Device.Edit(this.MessageId.Value, "Choose category", (InlineKeyboardMarkup)bf); + m = await Device.Edit(MessageId.Value, "Choose category", (InlineKeyboardMarkup)bf); } else { - m = await this.Device.Send("Choose category", (InlineKeyboardMarkup)bf, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false); + m = await Device.Send("Choose category", (InlineKeyboardMarkup)bf, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); } break; @@ -790,7 +772,7 @@ namespace TelegramBotBase.Controls.Hybrid if (m != null) - this.MessageId = m.MessageId; + MessageId = m.MessageId; } @@ -802,12 +784,12 @@ namespace TelegramBotBase.Controls.Hybrid { get { - if (this.KeyboardType == eKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) + if (KeyboardType == EKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) { return true; } - if (this.KeyboardType == eKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows) + if (KeyboardType == EKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows) { return true; } @@ -820,7 +802,7 @@ namespace TelegramBotBase.Controls.Hybrid { get { - if (this.NavigationBarVisibility == eNavigationBarVisibility.always | (this.NavigationBarVisibility == eNavigationBarVisibility.auto && PagingNecessary)) + if (NavigationBarVisibility == ENavigationBarVisibility.always | (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary)) { return true; } @@ -836,30 +818,19 @@ namespace TelegramBotBase.Controls.Hybrid { get { - switch (this.KeyboardType) + return KeyboardType switch { - case eKeyboardType.InlineKeyBoard: - return Constants.Telegram.MaxInlineKeyBoardRows; - - case eKeyboardType.ReplyKeyboard: - return Constants.Telegram.MaxReplyKeyboardRows; - - default: - return 0; - } + EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows, + EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows, + _ => 0 + }; } } /// /// Returns the number of all rows (layout + navigation + content); /// - public int TotalRows - { - get - { - return this.LayoutRows + DataSource.RowCount; - } - } + public int TotalRows => LayoutRows + DataSource.RowCount; /// @@ -869,18 +840,18 @@ namespace TelegramBotBase.Controls.Hybrid { get { - int layoutRows = 0; + var layoutRows = 0; - if (this.NavigationBarVisibility == eNavigationBarVisibility.always | this.NavigationBarVisibility == eNavigationBarVisibility.auto) + if (NavigationBarVisibility == ENavigationBarVisibility.always | NavigationBarVisibility == ENavigationBarVisibility.auto) layoutRows += 2; - if (this.HeadLayoutButtonRow != null && this.HeadLayoutButtonRow.Count > 0) + if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) layoutRows++; - if (this.SubHeadLayoutButtonRow != null && this.SubHeadLayoutButtonRow.Count > 0) + if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) layoutRows++; - if (EnableCheckAllTools && this.SelectedViewIndex == 1) + if (EnableCheckAllTools && SelectedViewIndex == 1) { layoutRows++; } @@ -892,13 +863,7 @@ namespace TelegramBotBase.Controls.Hybrid /// /// Returns the number of item rows per page. /// - public int ItemRowsPerPage - { - get - { - return this.MaximumRow - this.LayoutRows; - } - } + public int ItemRowsPerPage => MaximumRow - LayoutRows; public int PageCount { @@ -909,7 +874,7 @@ namespace TelegramBotBase.Controls.Hybrid //var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null); - var max = this.DataSource.CalculateMax(this.EnableSearch ? this.SearchQuery : null); + var max = DataSource.CalculateMax(EnableSearch ? SearchQuery : null); //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") //{ @@ -919,22 +884,24 @@ namespace TelegramBotBase.Controls.Hybrid if (max == 0) return 1; - return (int)Math.Ceiling((decimal)((decimal)max / (decimal)ItemRowsPerPage)); + return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage); } } - public override async Task Hidden(bool FormClose) + public override Task Hidden(bool formClose) { //Prepare for opening Modal, and comming back - if (!FormClose) + if (!formClose) { - this.Updated(); + Updated(); } else { //Remove event handler - this.Device.MessageDeleted -= Device_MessageDeleted; + Device.MessageDeleted -= Device_MessageDeleted; } + + return Task.CompletedTask; } /// @@ -942,31 +909,31 @@ namespace TelegramBotBase.Controls.Hybrid /// public void Updated() { - this.RenderNecessary = true; + _renderNecessary = true; } - public async override Task Cleanup() + public override async Task Cleanup() { - if (this.MessageId == null) + if (MessageId == null) return; - switch (this.KeyboardType) + switch (KeyboardType) { - case eKeyboardType.InlineKeyBoard: + case EKeyboardType.InlineKeyBoard: - await this.Device.DeleteMessage(this.MessageId.Value); + await Device.DeleteMessage(MessageId.Value); - this.MessageId = null; + MessageId = null; break; - case eKeyboardType.ReplyKeyboard: + case EKeyboardType.ReplyKeyboard: - if (this.HideKeyboardOnCleanup) + if (HideKeyboardOnCleanup) { - await this.Device.HideReplyKeyboard(); + await Device.HideReplyKeyboard(); } - this.MessageId = null; + MessageId = null; break; } @@ -979,11 +946,11 @@ namespace TelegramBotBase.Controls.Hybrid /// public void CheckAllTags() { - this.SelectedTags.Clear(); + SelectedTags.Clear(); - this.SelectedTags = this.Tags.Select(a => a).ToList(); + SelectedTags = Tags.Select(a => a).ToList(); - this.Updated(); + Updated(); } @@ -992,9 +959,9 @@ namespace TelegramBotBase.Controls.Hybrid /// public void UncheckAllTags() { - this.SelectedTags.Clear(); + SelectedTags.Clear(); - this.Updated(); + Updated(); } } diff --git a/TelegramBotBase/Controls/Inline/CalendarPicker.cs b/TelegramBotBase/Controls/Inline/CalendarPicker.cs index 0fc968d..ccdd1db 100644 --- a/TelegramBotBase/Controls/Inline/CalendarPicker.cs +++ b/TelegramBotBase/Controls/Inline/CalendarPicker.cs @@ -2,18 +2,17 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; -using System.Text; using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Enums; using TelegramBotBase.Form; -using TelegramBotBase.Tools; +using TelegramBotBase.Localizations; using static TelegramBotBase.Tools.Arrays; using static TelegramBotBase.Tools.Time; namespace TelegramBotBase.Controls.Inline { - public class CalendarPicker : Base.ControlBase + public class CalendarPicker : ControlBase { public DateTime SelectedDate { get; set; } @@ -27,31 +26,31 @@ namespace TelegramBotBase.Controls.Inline private int? MessageId { get; set; } - public String Title { get; set; } = Localizations.Default.Language["CalendarPicker_Title"]; + public string Title { get; set; } = Default.Language["CalendarPicker_Title"]; - public eMonthPickerMode PickerMode { get; set; } + public EMonthPickerMode PickerMode { get; set; } public bool EnableDayView { get; set; } = true; public bool EnableMonthView { get; set; } = true; public bool EnableYearView { get; set; } = true; - + public CalendarPicker(CultureInfo culture) { - this.SelectedDate = DateTime.Today; - this.VisibleMonth = DateTime.Today; - this.FirstDayOfWeek = DayOfWeek.Monday; - this.Culture = culture; - this.PickerMode = eMonthPickerMode.day; + SelectedDate = DateTime.Today; + VisibleMonth = DateTime.Today; + FirstDayOfWeek = DayOfWeek.Monday; + Culture = culture; + PickerMode = EMonthPickerMode.day; } - + public CalendarPicker() : this(new CultureInfo("en-en")) { } - public override async Task Action(MessageResult result, String value = null) + public override async Task Action(MessageResult result, string value = null) { await result.ConfirmAction(); @@ -59,99 +58,84 @@ namespace TelegramBotBase.Controls.Inline { case "$next$": - switch (this.PickerMode) + VisibleMonth = PickerMode switch { - case eMonthPickerMode.day: - this.VisibleMonth = this.VisibleMonth.AddMonths(1); - break; - - case eMonthPickerMode.month: - this.VisibleMonth = this.VisibleMonth.AddYears(1); - break; - - case eMonthPickerMode.year: - this.VisibleMonth = this.VisibleMonth.AddYears(10); - break; - } - + EMonthPickerMode.day => VisibleMonth.AddMonths(1), + EMonthPickerMode.month => VisibleMonth.AddYears(1), + EMonthPickerMode.year => VisibleMonth.AddYears(10), + _ => VisibleMonth + }; break; case "$prev$": - switch (this.PickerMode) + VisibleMonth = PickerMode switch { - case eMonthPickerMode.day: - this.VisibleMonth = this.VisibleMonth.AddMonths(-1); - break; - - case eMonthPickerMode.month: - this.VisibleMonth = this.VisibleMonth.AddYears(-1); - break; - - case eMonthPickerMode.year: - this.VisibleMonth = this.VisibleMonth.AddYears(-10); - break; - } + EMonthPickerMode.day => VisibleMonth.AddMonths(-1), + EMonthPickerMode.month => VisibleMonth.AddYears(-1), + EMonthPickerMode.year => VisibleMonth.AddYears(-10), + _ => VisibleMonth + }; break; case "$monthtitle$": - if (this.EnableMonthView) + if (EnableMonthView) { - this.PickerMode = eMonthPickerMode.month; + PickerMode = EMonthPickerMode.month; } break; case "$yeartitle$": - if (this.EnableYearView) + if (EnableYearView) { - this.PickerMode = eMonthPickerMode.year; + PickerMode = EMonthPickerMode.year; } break; case "$yearstitle$": - if (this.EnableMonthView) + if (EnableMonthView) { - this.PickerMode = eMonthPickerMode.month; + PickerMode = EMonthPickerMode.month; } - this.VisibleMonth = this.SelectedDate; + VisibleMonth = SelectedDate; break; default: - int day = 0; - if (result.RawData.StartsWith("d-") && TryParseDay(result.RawData.Split('-')[1], this.SelectedDate, out day)) + var day = 0; + if (result.RawData.StartsWith("d-") && TryParseDay(result.RawData.Split('-')[1], SelectedDate, out day)) { - this.SelectedDate = new DateTime(this.VisibleMonth.Year, this.VisibleMonth.Month, day); + SelectedDate = new DateTime(VisibleMonth.Year, VisibleMonth.Month, day); } - int month = 0; + var month = 0; if (result.RawData.StartsWith("m-") && TryParseMonth(result.RawData.Split('-')[1], out month)) { - this.SelectedDate = new DateTime(this.VisibleMonth.Year, month, 1); - this.VisibleMonth = this.SelectedDate; + SelectedDate = new DateTime(VisibleMonth.Year, month, 1); + VisibleMonth = SelectedDate; - if (this.EnableDayView) + if (EnableDayView) { - this.PickerMode = eMonthPickerMode.day; + PickerMode = EMonthPickerMode.day; } } - int year = 0; + var year = 0; if (result.RawData.StartsWith("y-") && TryParseYear(result.RawData.Split('-')[1], out year)) { - this.SelectedDate = new DateTime(year, SelectedDate.Month, SelectedDate.Day); - this.VisibleMonth = this.SelectedDate; + SelectedDate = new DateTime(year, SelectedDate.Month, SelectedDate.Day); + VisibleMonth = SelectedDate; - if (this.EnableMonthView) + if (EnableMonthView) { - this.PickerMode = eMonthPickerMode.month; + PickerMode = EMonthPickerMode.month; } } @@ -170,18 +154,18 @@ namespace TelegramBotBase.Controls.Inline - ButtonForm bf = new ButtonForm(); + var bf = new ButtonForm(); - switch (this.PickerMode) + switch (PickerMode) { - case eMonthPickerMode.day: + case EMonthPickerMode.day: - var month = this.VisibleMonth; + var month = VisibleMonth; - string[] dayNamesNormal = this.Culture.DateTimeFormat.ShortestDayNames; - string[] dayNamesShifted = Shift(dayNamesNormal, (int)this.FirstDayOfWeek); + var dayNamesNormal = Culture.DateTimeFormat.ShortestDayNames; + var dayNamesShifted = Shift(dayNamesNormal, (int)FirstDayOfWeek); - bf.AddButtonRow(new ButtonBase(Localizations.Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase(this.Culture.DateTimeFormat.MonthNames[month.Month - 1] + " " + month.Year.ToString(), "$monthtitle$"), new ButtonBase(Localizations.Default.Language["CalendarPicker_NextPage"], "$next$")); + bf.AddButtonRow(new ButtonBase(Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase(Culture.DateTimeFormat.MonthNames[month.Month - 1] + " " + month.Year, "$monthtitle$"), new ButtonBase(Default.Language["CalendarPicker_NextPage"], "$next$")); bf.AddButtonRow(dayNamesShifted.Select(a => new ButtonBase(a, a)).ToList()); @@ -192,20 +176,20 @@ namespace TelegramBotBase.Controls.Inline var lastDay = firstDay.LastDayOfMonth(); //Start of Week where first day of month is (left border) - var start = firstDay.StartOfWeek(this.FirstDayOfWeek); + var start = firstDay.StartOfWeek(FirstDayOfWeek); //End of week where last day of month is (right border) - var end = lastDay.EndOfWeek(this.FirstDayOfWeek); + var end = lastDay.EndOfWeek(FirstDayOfWeek); - for (int i = 0; i <= ((end - start).Days / 7); i++) + for (var i = 0; i <= ((end - start).Days / 7); i++) { var lst = new List(); - for (int id = 0; id < 7; id++) + for (var id = 0; id < 7; id++) { var d = start.AddDays((i * 7) + id); if (d < firstDay | d > lastDay) { - lst.Add(new ButtonBase("-", "m-" + d.Day.ToString())); + lst.Add(new ButtonBase("-", "m-" + d.Day)); continue; } @@ -216,35 +200,35 @@ namespace TelegramBotBase.Controls.Inline day = "(" + day + ")"; } - lst.Add(new ButtonBase((this.SelectedDate == d ? "[" + day + "]" : day), "d-" + d.Day.ToString())); + lst.Add(new ButtonBase((SelectedDate == d ? "[" + day + "]" : day), "d-" + d.Day)); } bf.AddButtonRow(lst); } break; - case eMonthPickerMode.month: + case EMonthPickerMode.month: - bf.AddButtonRow(new ButtonBase(Localizations.Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase(this.VisibleMonth.Year.ToString("0000"), "$yeartitle$"), new ButtonBase(Localizations.Default.Language["CalendarPicker_NextPage"], "$next$")); + bf.AddButtonRow(new ButtonBase(Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase(VisibleMonth.Year.ToString("0000"), "$yeartitle$"), new ButtonBase(Default.Language["CalendarPicker_NextPage"], "$next$")); - var months = this.Culture.DateTimeFormat.MonthNames; + var months = Culture.DateTimeFormat.MonthNames; - var buttons = months.Select((a, b) => new ButtonBase((b == this.SelectedDate.Month - 1 && this.SelectedDate.Year == this.VisibleMonth.Year ? "[ " + a + " ]" : a), "m-" + (b + 1).ToString())); + var buttons = months.Select((a, b) => new ButtonBase((b == SelectedDate.Month - 1 && SelectedDate.Year == VisibleMonth.Year ? "[ " + a + " ]" : a), "m-" + (b + 1))); - bf.AddSplitted(buttons, 2); + bf.AddSplitted(buttons); break; - case eMonthPickerMode.year: + case EMonthPickerMode.year: - bf.AddButtonRow(new ButtonBase(Localizations.Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase("Year", "$yearstitle$"), new ButtonBase(Localizations.Default.Language["CalendarPicker_NextPage"], "$next$")); + bf.AddButtonRow(new ButtonBase(Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase("Year", "$yearstitle$"), new ButtonBase(Default.Language["CalendarPicker_NextPage"], "$next$")); - var starti = Math.Floor(this.VisibleMonth.Year / 10f) * 10; + var starti = Math.Floor(VisibleMonth.Year / 10f) * 10; - for (int i = 0; i < 10; i++) + for (var i = 0; i < 10; i++) { var m = starti + (i * 2); - bf.AddButtonRow(new ButtonBase((this.SelectedDate.Year == m ? "[ " + m.ToString() + " ]" : m.ToString()), "y-" + m.ToString()), new ButtonBase((this.SelectedDate.Year == (m + 1) ? "[ " + (m + 1).ToString() + " ]" : (m + 1).ToString()), "y-" + (m + 1).ToString())); + bf.AddButtonRow(new ButtonBase((SelectedDate.Year == m ? "[ " + m + " ]" : m.ToString()), "y-" + m), new ButtonBase((SelectedDate.Year == (m + 1) ? "[ " + (m + 1) + " ]" : (m + 1).ToString()), "y-" + (m + 1))); } break; @@ -252,14 +236,14 @@ namespace TelegramBotBase.Controls.Inline } - if (this.MessageId != null) + if (MessageId != null) { - var m = await this.Device.Edit(this.MessageId.Value, this.Title, bf); + var m = await Device.Edit(MessageId.Value, Title, bf); } else { - var m = await this.Device.Send(this.Title, bf); - this.MessageId = m.MessageId; + var m = await Device.Send(Title, bf); + MessageId = m.MessageId; } } @@ -268,9 +252,9 @@ namespace TelegramBotBase.Controls.Inline public override async Task Cleanup() { - if (this.MessageId != null) + if (MessageId != null) { - await this.Device.DeleteMessage(this.MessageId.Value); + await Device.DeleteMessage(MessageId.Value); } } diff --git a/TelegramBotBase/Controls/Inline/MonthPicker.cs b/TelegramBotBase/Controls/Inline/MonthPicker.cs index 78c6fc2..a5032b1 100644 --- a/TelegramBotBase/Controls/Inline/MonthPicker.cs +++ b/TelegramBotBase/Controls/Inline/MonthPicker.cs @@ -1,12 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using TelegramBotBase.Base; -using TelegramBotBase.Enums; -using TelegramBotBase.Form; +using TelegramBotBase.Enums; namespace TelegramBotBase.Controls.Inline { @@ -17,8 +9,8 @@ namespace TelegramBotBase.Controls.Inline public MonthPicker() { - this.PickerMode = eMonthPickerMode.month; - this.EnableDayView = false; + PickerMode = EMonthPickerMode.month; + EnableDayView = false; } diff --git a/TelegramBotBase/Controls/Inline/MultiToggleButton.cs b/TelegramBotBase/Controls/Inline/MultiToggleButton.cs index 1828f2b..fa8f159 100644 --- a/TelegramBotBase/Controls/Inline/MultiToggleButton.cs +++ b/TelegramBotBase/Controls/Inline/MultiToggleButton.cs @@ -1,11 +1,10 @@ using System; using System.Collections.Generic; using System.ComponentModel; -using System.Linq; -using System.Text; using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; +using TelegramBotBase.Localizations; namespace TelegramBotBase.Controls.Inline { @@ -14,25 +13,25 @@ namespace TelegramBotBase.Controls.Inline /// /// This contains the selected icon. /// - public String SelectedIcon { get; set; } = Localizations.Default.Language["MultiToggleButton_SelectedIcon"]; + public string SelectedIcon { get; set; } = Default.Language["MultiToggleButton_SelectedIcon"]; /// /// This will appear on the ConfirmAction message (if not empty) /// - public String ChangedString { get; set; } = Localizations.Default.Language["MultiToggleButton_Changed"]; + public string ChangedString { get; set; } = Default.Language["MultiToggleButton_Changed"]; /// /// This holds the title of the control. /// - public String Title { get; set; } = Localizations.Default.Language["MultiToggleButton_Title"]; + public string Title { get; set; } = Default.Language["MultiToggleButton_Title"]; public int? MessageId { get; set; } - private bool RenderNecessary = true; + private bool _renderNecessary = true; - private static readonly object __evToggled = new object(); + private static readonly object EvToggled = new object(); - private readonly EventHandlerList Events = new EventHandlerList(); + private readonly EventHandlerList _events = new EventHandlerList(); /// /// This will hold all options available. @@ -52,27 +51,21 @@ namespace TelegramBotBase.Controls.Inline public event EventHandler Toggled { - add - { - this.Events.AddHandler(__evToggled, value); - } - remove - { - this.Events.RemoveHandler(__evToggled, value); - } + add => _events.AddHandler(EvToggled, value); + remove => _events.RemoveHandler(EvToggled, value); } public void OnToggled(EventArgs e) { - (this.Events[__evToggled] as EventHandler)?.Invoke(this, e); + (_events[EvToggled] as EventHandler)?.Invoke(this, e); } - public override async Task Action(MessageResult result, String value = null) + public override async Task Action(MessageResult result, string value = null) { if (result.Handled) return; - await result.ConfirmAction(this.ChangedString); + await result.ConfirmAction(ChangedString); switch (value ?? "unknown") { @@ -82,30 +75,30 @@ namespace TelegramBotBase.Controls.Inline if (s[0] == "check" && s.Length > 1) { - int index = 0; + var index = 0; if (!int.TryParse(s[1], out index)) { return; } - if(SelectedOption== null || SelectedOption != this.Options[index]) + if(SelectedOption== null || SelectedOption != Options[index]) { - this.SelectedOption = this.Options[index]; - OnToggled(new EventArgs()); + SelectedOption = Options[index]; + OnToggled(EventArgs.Empty); } - else if(this.AllowEmptySelection) + else if(AllowEmptySelection) { - this.SelectedOption = null; - OnToggled(new EventArgs()); + SelectedOption = null; + OnToggled(EventArgs.Empty); } - RenderNecessary = true; + _renderNecessary = true; return; } - RenderNecessary = false; + _renderNecessary = false; break; @@ -117,16 +110,16 @@ namespace TelegramBotBase.Controls.Inline public override async Task Render(MessageResult result) { - if (!RenderNecessary) + if (!_renderNecessary) return; var bf = new ButtonForm(this); var lst = new List(); - foreach (var o in this.Options) + foreach (var o in Options) { - var index = this.Options.IndexOf(o); - if (o == this.SelectedOption) + var index = Options.IndexOf(o); + if (o == SelectedOption) { lst.Add(new ButtonBase(SelectedIcon + " " + o.Text, "check$" + index)); continue; @@ -137,20 +130,20 @@ namespace TelegramBotBase.Controls.Inline bf.AddButtonRow(lst); - if (this.MessageId != null) + if (MessageId != null) { - var m = await this.Device.Edit(this.MessageId.Value, this.Title, bf); + var m = await Device.Edit(MessageId.Value, Title, bf); } else { - var m = await this.Device.Send(this.Title, bf, disableNotification: true); + var m = await Device.Send(Title, bf, disableNotification: true); if (m != null) { - this.MessageId = m.MessageId; + MessageId = m.MessageId; } } - this.RenderNecessary = false; + _renderNecessary = false; } diff --git a/TelegramBotBase/Controls/Inline/ProgressBar.cs b/TelegramBotBase/Controls/Inline/ProgressBar.cs index 14dd585..2dde19a 100644 --- a/TelegramBotBase/Controls/Inline/ProgressBar.cs +++ b/TelegramBotBase/Controls/Inline/ProgressBar.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading.Tasks; using TelegramBotBase.Base; @@ -10,9 +7,9 @@ namespace TelegramBotBase.Controls.Inline /// /// A simple control for show and managing progress. /// - public class ProgressBar : Base.ControlBase + public class ProgressBar : ControlBase { - public enum eProgressStyle + public enum EProgressStyle { standard = 0, squares = 1, @@ -22,104 +19,78 @@ namespace TelegramBotBase.Controls.Inline custom = 10 } - public eProgressStyle ProgressStyle + public EProgressStyle ProgressStyle { - get - { - return m_eStyle; - } + get => _mEStyle; set { - m_eStyle = value; + _mEStyle = value; LoadStyle(); } } - private eProgressStyle m_eStyle = eProgressStyle.standard; + private EProgressStyle _mEStyle = EProgressStyle.standard; public int Value { - get - { - return this.m_iValue; - } + get => _mIValue; set { - if (value > this.Max) + if (value > Max) { return; } - if (this.m_iValue != value) + if (_mIValue != value) { - this.RenderNecessary = true; + RenderNecessary = true; } - this.m_iValue = value; + _mIValue = value; } } - private int m_iValue = 0; + private int _mIValue; public int Max { - get - { - return this.m_iMax; - } + get => _mIMax; set { - if (this.m_iMax != value) + if (_mIMax != value) { - this.RenderNecessary = true; + RenderNecessary = true; } - this.m_iMax = value; + _mIMax = value; } } - private int m_iMax = 100; + private int _mIMax = 100; public int? MessageId { get; set; } - private bool RenderNecessary { get; set; } = false; + private bool RenderNecessary { get; set; } public int Steps { get { - switch (this.ProgressStyle) + return ProgressStyle switch { - case eProgressStyle.standard: - - return 1; - - case eProgressStyle.squares: - - return 10; - - case eProgressStyle.circles: - - return 10; - - case eProgressStyle.lines: - - return 5; - - case eProgressStyle.squaredLines: - - return 5; - - default: - - return 1; - } + EProgressStyle.standard => 1, + EProgressStyle.squares => 10, + EProgressStyle.circles => 10, + EProgressStyle.lines => 5, + EProgressStyle.squaredLines => 5, + _ => 1 + }; } } /// /// Filled block (reached percentage) /// - public String BlockChar + public string BlockChar { get; set; } @@ -127,7 +98,7 @@ namespace TelegramBotBase.Controls.Inline /// /// Unfilled block (not reached yet) /// - public String EmptyBlockChar + public string EmptyBlockChar { get; set; } @@ -135,7 +106,7 @@ namespace TelegramBotBase.Controls.Inline /// /// String at the beginning of the progress bar /// - public String StartChar + public string StartChar { get; set; } @@ -143,133 +114,133 @@ namespace TelegramBotBase.Controls.Inline /// /// String at the end of the progress bar /// - public String EndChar + public string EndChar { get; set; } public ProgressBar() { - this.ProgressStyle = eProgressStyle.standard; + ProgressStyle = EProgressStyle.standard; - this.Value = 0; - this.Max = 100; + Value = 0; + Max = 100; - this.RenderNecessary = true; + RenderNecessary = true; } - public ProgressBar(int Value, int Max, eProgressStyle Style) + public ProgressBar(int value, int max, EProgressStyle style) { - this.Value = Value; - this.Max = Max; - this.ProgressStyle = Style; + this.Value = value; + this.Max = max; + ProgressStyle = style; - this.RenderNecessary = true; + RenderNecessary = true; } public override async Task Cleanup() { - if (this.MessageId == null || this.MessageId == -1) + if (MessageId == null || MessageId == -1) return; - await this.Device.DeleteMessage(this.MessageId.Value); + await Device.DeleteMessage(MessageId.Value); } public void LoadStyle() { - this.StartChar = ""; - this.EndChar = ""; + StartChar = ""; + EndChar = ""; - switch (this.ProgressStyle) + switch (ProgressStyle) { - case eProgressStyle.circles: + case EProgressStyle.circles: - this.BlockChar = "⚫️ "; - this.EmptyBlockChar = "⚪️ "; + BlockChar = "⚫️ "; + EmptyBlockChar = "⚪️ "; break; - case eProgressStyle.squares: + case EProgressStyle.squares: - this.BlockChar = "⬛️ "; - this.EmptyBlockChar = "⬜️ "; + BlockChar = "⬛️ "; + EmptyBlockChar = "⬜️ "; break; - case eProgressStyle.lines: + case EProgressStyle.lines: - this.BlockChar = "█"; - this.EmptyBlockChar = "▁"; + BlockChar = "█"; + EmptyBlockChar = "▁"; break; - case eProgressStyle.squaredLines: + case EProgressStyle.squaredLines: - this.BlockChar = "▇"; - this.EmptyBlockChar = "—"; + BlockChar = "▇"; + EmptyBlockChar = "—"; - this.StartChar = "["; - this.EndChar = "]"; + StartChar = "["; + EndChar = "]"; break; - case eProgressStyle.standard: - case eProgressStyle.custom: + case EProgressStyle.standard: + case EProgressStyle.custom: - this.BlockChar = ""; - this.EmptyBlockChar = ""; + BlockChar = ""; + EmptyBlockChar = ""; break; } } - public async override Task Render(MessageResult result) + public override async Task Render(MessageResult result) { - if (!this.RenderNecessary) + if (!RenderNecessary) { return; } - if (this.Device == null) + if (Device == null) { return; } - String message = ""; - int blocks = 0; - int maxBlocks = 0; + var message = ""; + var blocks = 0; + var maxBlocks = 0; - switch (this.ProgressStyle) + switch (ProgressStyle) { - case eProgressStyle.standard: + case EProgressStyle.standard: - message = this.Value.ToString("0") + "%"; + message = Value.ToString("0") + "%"; break; - case eProgressStyle.squares: - case eProgressStyle.circles: - case eProgressStyle.lines: - case eProgressStyle.squaredLines: - case eProgressStyle.custom: + case EProgressStyle.squares: + case EProgressStyle.circles: + case EProgressStyle.lines: + case EProgressStyle.squaredLines: + case EProgressStyle.custom: - blocks = (int)Math.Floor((decimal)this.Value / this.Steps); + blocks = (int)Math.Floor((decimal)Value / Steps); - maxBlocks = (this.Max / this.Steps); + maxBlocks = (Max / Steps); - message += this.StartChar; + message += StartChar; - for (int i = 0; i < blocks; i++) + for (var i = 0; i < blocks; i++) { - message += this.BlockChar; + message += BlockChar; } - for (int i = 0; i < (maxBlocks - blocks); i++) + for (var i = 0; i < (maxBlocks - blocks); i++) { - message += this.EmptyBlockChar; + message += EmptyBlockChar; } - message += this.EndChar; + message += EndChar; - message += " " + this.Value.ToString("0") + "%"; + message += " " + Value.ToString("0") + "%"; break; @@ -278,18 +249,18 @@ namespace TelegramBotBase.Controls.Inline return; } - if (this.MessageId == null) + if (MessageId == null) { - var m = await this.Device.Send(message); + var m = await Device.Send(message); - this.MessageId = m.MessageId; + MessageId = m.MessageId; } else { - await this.Device.Edit(this.MessageId.Value, message); + await Device.Edit(MessageId.Value, message); } - this.RenderNecessary = false; + RenderNecessary = false; } } diff --git a/TelegramBotBase/Controls/Inline/ToggleButton.cs b/TelegramBotBase/Controls/Inline/ToggleButton.cs index 5343f7b..8f27415 100644 --- a/TelegramBotBase/Controls/Inline/ToggleButton.cs +++ b/TelegramBotBase/Controls/Inline/ToggleButton.cs @@ -1,38 +1,36 @@ using System; -using System.Collections.Generic; using System.ComponentModel; -using System.Linq; -using System.Text; using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; +using TelegramBotBase.Localizations; namespace TelegramBotBase.Controls.Inline { public class ToggleButton : ControlBase { - public String UncheckedIcon { get; set; } = Localizations.Default.Language["ToggleButton_OffIcon"]; + public string UncheckedIcon { get; set; } = Default.Language["ToggleButton_OffIcon"]; - public String CheckedIcon { get; set; } = Localizations.Default.Language["ToggleButton_OnIcon"]; + public string CheckedIcon { get; set; } = Default.Language["ToggleButton_OnIcon"]; - public String CheckedString { get; set; } = Localizations.Default.Language["ToggleButton_On"]; + public string CheckedString { get; set; } = Default.Language["ToggleButton_On"]; - public String UncheckedString { get; set; } = Localizations.Default.Language["ToggleButton_Off"]; + public string UncheckedString { get; set; } = Default.Language["ToggleButton_Off"]; - public String ChangedString { get; set; } = Localizations.Default.Language["ToggleButton_Changed"]; + public string ChangedString { get; set; } = Default.Language["ToggleButton_Changed"]; - public String Title { get; set; } = Localizations.Default.Language["ToggleButton_Title"]; + public string Title { get; set; } = Default.Language["ToggleButton_Title"]; public int? MessageId { get; set; } public bool Checked { get; set; } - private bool RenderNecessary = true; + private bool _renderNecessary = true; - private static readonly object __evToggled = new object(); + private static readonly object EvToggled = new object(); - private readonly EventHandlerList Events = new EventHandlerList(); + private readonly EventHandlerList _events = new EventHandlerList(); public ToggleButton() @@ -41,68 +39,62 @@ namespace TelegramBotBase.Controls.Inline } - public ToggleButton(String CheckedString, String UncheckedString) + public ToggleButton(string checkedString, string uncheckedString) { - this.CheckedString = CheckedString; - this.UncheckedString = UncheckedString; + this.CheckedString = checkedString; + this.UncheckedString = uncheckedString; } public event EventHandler Toggled { - add - { - this.Events.AddHandler(__evToggled, value); - } - remove - { - this.Events.RemoveHandler(__evToggled, value); - } + add => _events.AddHandler(EvToggled, value); + remove => _events.RemoveHandler(EvToggled, value); } public void OnToggled(EventArgs e) { - (this.Events[__evToggled] as EventHandler)?.Invoke(this, e); + (_events[EvToggled] as EventHandler)?.Invoke(this, e); } - public override async Task Action(MessageResult result, String value = null) + public override async Task Action(MessageResult result, string value = null) { if (result.Handled) return; - await result.ConfirmAction(this.ChangedString); + await result.ConfirmAction(ChangedString); switch (value ?? "unknown") { case "on": - if (this.Checked) + if (Checked) return; - RenderNecessary = true; + _renderNecessary = true; - this.Checked = true; + Checked = true; - OnToggled(new EventArgs()); + OnToggled(EventArgs.Empty); break; case "off": - if (!this.Checked) + if (!Checked) return; - RenderNecessary = true; + _renderNecessary = true; - this.Checked = false; + Checked = false; - OnToggled(new EventArgs()); + OnToggled(EventArgs.Empty); break; default: - RenderNecessary = false; + _renderNecessary = false; break; @@ -114,31 +106,31 @@ namespace TelegramBotBase.Controls.Inline public override async Task Render(MessageResult result) { - if (!RenderNecessary) + if (!_renderNecessary) return; var bf = new ButtonForm(this); - ButtonBase bOn = new ButtonBase((this.Checked ? CheckedIcon : UncheckedIcon) + " " + CheckedString, "on"); + var bOn = new ButtonBase((Checked ? CheckedIcon : UncheckedIcon) + " " + CheckedString, "on"); - ButtonBase bOff = new ButtonBase((!this.Checked ? CheckedIcon : UncheckedIcon) + " " + UncheckedString, "off"); + var bOff = new ButtonBase((!Checked ? CheckedIcon : UncheckedIcon) + " " + UncheckedString, "off"); bf.AddButtonRow(bOn, bOff); - if (this.MessageId != null) + if (MessageId != null) { - var m = await this.Device.Edit(this.MessageId.Value, this.Title, bf); + var m = await Device.Edit(MessageId.Value, Title, bf); } else { - var m = await this.Device.Send(this.Title, bf, disableNotification: true); + var m = await Device.Send(Title, bf, disableNotification: true); if (m != null) { - this.MessageId = m.MessageId; + MessageId = m.MessageId; } } - this.RenderNecessary = false; + _renderNecessary = false; } diff --git a/TelegramBotBase/Controls/Inline/TreeView.cs b/TelegramBotBase/Controls/Inline/TreeView.cs index 65c8f4f..e3b6612 100644 --- a/TelegramBotBase/Controls/Inline/TreeView.cs +++ b/TelegramBotBase/Controls/Inline/TreeView.cs @@ -1,10 +1,9 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; +using TelegramBotBase.Localizations; namespace TelegramBotBase.Controls.Inline { @@ -16,20 +15,20 @@ namespace TelegramBotBase.Controls.Inline public TreeViewNode VisibleNode { get; set; } - public String Title { get; set; } + public string Title { get; set; } private int? MessageId { get; set; } - public String MoveUpIcon { get; set; } = Localizations.Default.Language["TreeView_LevelUp"]; + public string MoveUpIcon { get; set; } = Default.Language["TreeView_LevelUp"]; public TreeView() { - this.Nodes = new List(); - this.Title = Localizations.Default.Language["TreeView_Title"]; + Nodes = new List(); + Title = Default.Language["TreeView_Title"]; } - public override async Task Action(MessageResult result, String value = null) + public override async Task Action(MessageResult result, string value = null) { await result.ConfirmAction(); @@ -43,14 +42,14 @@ namespace TelegramBotBase.Controls.Inline case "up": case "parent": - this.VisibleNode = (this.VisibleNode?.ParentNode); + VisibleNode = (VisibleNode?.ParentNode); result.Handled = true; break; default: - var n = (this.VisibleNode != null ? this.VisibleNode.FindNodeByValue(val) : this.Nodes.FirstOrDefault(a => a.Value == val)); + var n = (VisibleNode != null ? VisibleNode.FindNodeByValue(val) : Nodes.FirstOrDefault(a => a.Value == val)); if (n == null) return; @@ -58,11 +57,11 @@ namespace TelegramBotBase.Controls.Inline if (n.ChildNodes.Count > 0) { - this.VisibleNode = n; + VisibleNode = n; } else { - this.SelectedNode = (this.SelectedNode != n ? n : null); + SelectedNode = (SelectedNode != n ? n : null); } result.Handled = true; @@ -77,21 +76,21 @@ namespace TelegramBotBase.Controls.Inline public override async Task Render(MessageResult result) { - var startnode = this.VisibleNode; + var startnode = VisibleNode; - var nodes = (startnode?.ChildNodes ?? this.Nodes); + var nodes = (startnode?.ChildNodes ?? Nodes); - ButtonForm bf = new ButtonForm(); + var bf = new ButtonForm(); if (startnode != null) { - bf.AddButtonRow(new ButtonBase(this.MoveUpIcon, "up"), new ButtonBase(startnode.Text, "parent")); + bf.AddButtonRow(new ButtonBase(MoveUpIcon, "up"), new ButtonBase(startnode.Text, "parent")); } foreach (var n in nodes) { var s = n.Text; - if (this.SelectedNode == n) + if (SelectedNode == n) { s = "[ " + s + " ]"; } @@ -101,20 +100,20 @@ namespace TelegramBotBase.Controls.Inline - if (this.MessageId != null) + if (MessageId != null) { - var m = await this.Device.Edit(this.MessageId.Value, this.Title, bf); + var m = await Device.Edit(MessageId.Value, Title, bf); } else { - var m = await this.Device.Send(this.Title, bf); - this.MessageId = m.MessageId; + var m = await Device.Send(Title, bf); + MessageId = m.MessageId; } } - public String GetPath() + public string GetPath() { - return (this.VisibleNode?.GetPath() ?? "\\"); + return (VisibleNode?.GetPath() ?? "\\"); } diff --git a/TelegramBotBase/Controls/Inline/TreeViewNode.cs b/TelegramBotBase/Controls/Inline/TreeViewNode.cs index a871aae..4219f49 100644 --- a/TelegramBotBase/Controls/Inline/TreeViewNode.cs +++ b/TelegramBotBase/Controls/Inline/TreeViewNode.cs @@ -1,35 +1,32 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace TelegramBotBase.Controls.Inline { public class TreeViewNode { - public String Text { get; set; } + public string Text { get; set; } - public String Value { get; set; } + public string Value { get; set; } - public String Url { get; set; } + public string Url { get; set; } public List ChildNodes { get; set; } = new List(); public TreeViewNode ParentNode { get; set; } - public TreeViewNode(String Text, String Value) + public TreeViewNode(string text, string value) { - this.Text = Text; - this.Value = Value; + this.Text = text; + this.Value = value; } - public TreeViewNode(String Text, String Value, String Url) : this(Text, Value) + public TreeViewNode(string text, string value, string url) : this(text, value) { - this.Url = Url; + this.Url = url; } - public TreeViewNode(String Text, String Value, params TreeViewNode[] childnodes) : this(Text, Value) + public TreeViewNode(string text, string value, params TreeViewNode[] childnodes) : this(text, value) { foreach(var c in childnodes) { @@ -44,14 +41,14 @@ namespace TelegramBotBase.Controls.Inline ChildNodes.Add(node); } - public TreeViewNode FindNodeByValue(String Value) + public TreeViewNode FindNodeByValue(string value) { - return this.ChildNodes.FirstOrDefault(a => a.Value == Value); + return ChildNodes.FirstOrDefault(a => a.Value == value); } - public String GetPath() + public string GetPath() { - String s = "\\" + this.Value; + var s = "\\" + Value; var p = this; while (p.ParentNode != null) { diff --git a/TelegramBotBase/Datasources/ButtonFormDataSource.cs b/TelegramBotBase/DataSources/ButtonFormDataSource.cs similarity index 78% rename from TelegramBotBase/Datasources/ButtonFormDataSource.cs rename to TelegramBotBase/DataSources/ButtonFormDataSource.cs index e8fbfd4..3b90ec8 100644 --- a/TelegramBotBase/Datasources/ButtonFormDataSource.cs +++ b/TelegramBotBase/DataSources/ButtonFormDataSource.cs @@ -1,36 +1,29 @@ using System; using System.Collections.Generic; -using System.Text; using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Form; using TelegramBotBase.Interfaces; -namespace TelegramBotBase.Datasources +namespace TelegramBotBase.DataSources { - public class ButtonFormDataSource : Interfaces.IDataSource + public class ButtonFormDataSource : IDataSource { public virtual ButtonForm ButtonForm { - get - { - return __buttonform; - } - set - { - __buttonform = value; - } + get => _buttonform; + set => _buttonform = value; } - private ButtonForm __buttonform = null; + private ButtonForm _buttonform; public ButtonFormDataSource() { - __buttonform = new ButtonForm(); + _buttonform = new ButtonForm(); } public ButtonFormDataSource(ButtonForm bf) { - __buttonform = bf; + _buttonform = bf; } @@ -71,9 +64,9 @@ namespace TelegramBotBase.Datasources return ButtonForm.ToArray(); } - public virtual ButtonForm PickItems(int start, int count, String filter = null) + public virtual ButtonForm PickItems(int start, int count, string filter = null) { - ButtonForm bf = new ButtonForm(); + var bf = new ButtonForm(); ButtonForm dataForm = null; if (filter == null) @@ -85,9 +78,9 @@ namespace TelegramBotBase.Datasources dataForm = ButtonForm.FilterDuplicate(filter, true); } - for (int i = 0; i < count; i++) + for (var i = 0; i < count; i++) { - int it = start + i; + var it = start + i; if (it > dataForm.Rows - 1) break; @@ -98,7 +91,7 @@ namespace TelegramBotBase.Datasources return bf; } - public virtual ButtonForm PickAllItems(String filter = null) + public virtual ButtonForm PickAllItems(string filter = null) { if (filter == null) return ButtonForm.Duplicate(); @@ -107,7 +100,7 @@ namespace TelegramBotBase.Datasources return ButtonForm.FilterDuplicate(filter, true); } - public virtual Tuple FindRow(String text, bool useText = true) + public virtual Tuple FindRow(string text, bool useText = true) { return ButtonForm.FindRow(text, useText); } @@ -117,7 +110,7 @@ namespace TelegramBotBase.Datasources /// /// /// - public virtual int CalculateMax(String filter = null) + public virtual int CalculateMax(string filter = null) { return PickAllItems(filter).Rows; } diff --git a/TelegramBotBase/Datasources/StaticDataSource.cs b/TelegramBotBase/DataSources/StaticDataSource.cs similarity index 56% rename from TelegramBotBase/Datasources/StaticDataSource.cs rename to TelegramBotBase/DataSources/StaticDataSource.cs index 19ff96c..59e400e 100644 --- a/TelegramBotBase/Datasources/StaticDataSource.cs +++ b/TelegramBotBase/DataSources/StaticDataSource.cs @@ -1,13 +1,12 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; -using System.Text; +using TelegramBotBase.Interfaces; -namespace TelegramBotBase.Datasources +namespace TelegramBotBase.DataSources { - public class StaticDataSource : Interfaces.IDataSource + public class StaticDataSource : IDataSource { - List Data { get; set; } + private List Data { get; set; } public StaticDataSource() { @@ -16,17 +15,11 @@ namespace TelegramBotBase.Datasources public StaticDataSource(List data) { - this.Data = data; + Data = data; } - public int Count - { - get - { - return Data.Count; - } - } + public int Count => Data.Count; public T ItemAt(int index) { diff --git a/TelegramBotBase/Enums/eDeleteMode.cs b/TelegramBotBase/Enums/eDeleteMode.cs index 1596678..b4d190a 100644 --- a/TelegramBotBase/Enums/eDeleteMode.cs +++ b/TelegramBotBase/Enums/eDeleteMode.cs @@ -1,12 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TelegramBotBase.Enums +namespace TelegramBotBase.Enums { - public enum eDeleteMode + public enum EDeleteMode { /// /// Don't delete any message. diff --git a/TelegramBotBase/Enums/eDeleteSide.cs b/TelegramBotBase/Enums/eDeleteSide.cs index 6803291..1b91ea1 100644 --- a/TelegramBotBase/Enums/eDeleteSide.cs +++ b/TelegramBotBase/Enums/eDeleteSide.cs @@ -1,12 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TelegramBotBase.Enums +namespace TelegramBotBase.Enums { - public enum eDeleteSide + public enum EDeleteSide { /// /// Delete only messages from this bot. diff --git a/TelegramBotBase/Enums/eKeyboardType.cs b/TelegramBotBase/Enums/eKeyboardType.cs index 3cd255e..ed808a0 100644 --- a/TelegramBotBase/Enums/eKeyboardType.cs +++ b/TelegramBotBase/Enums/eKeyboardType.cs @@ -1,12 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TelegramBotBase.Enums +namespace TelegramBotBase.Enums { - public enum eKeyboardType + public enum EKeyboardType { /// /// Uses a ReplyKeyboardMarkup diff --git a/TelegramBotBase/Enums/eMonthPickerMode.cs b/TelegramBotBase/Enums/eMonthPickerMode.cs index be2a1c3..b5f318f 100644 --- a/TelegramBotBase/Enums/eMonthPickerMode.cs +++ b/TelegramBotBase/Enums/eMonthPickerMode.cs @@ -1,12 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TelegramBotBase.Enums +namespace TelegramBotBase.Enums { - public enum eMonthPickerMode + public enum EMonthPickerMode { /// /// Shows the calendar with day picker mode diff --git a/TelegramBotBase/Enums/eNavigationBarVisibility.cs b/TelegramBotBase/Enums/eNavigationBarVisibility.cs index d10e027..00b4d57 100644 --- a/TelegramBotBase/Enums/eNavigationBarVisibility.cs +++ b/TelegramBotBase/Enums/eNavigationBarVisibility.cs @@ -1,10 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace TelegramBotBase.Enums +namespace TelegramBotBase.Enums { - public enum eNavigationBarVisibility + public enum ENavigationBarVisibility { /// /// Shows it depending on the amount of items. diff --git a/TelegramBotBase/Enums/eSettings.cs b/TelegramBotBase/Enums/eSettings.cs index 7e55710..da63d21 100644 --- a/TelegramBotBase/Enums/eSettings.cs +++ b/TelegramBotBase/Enums/eSettings.cs @@ -1,10 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace TelegramBotBase.Enums +namespace TelegramBotBase.Enums { - public enum eSettings + public enum ESettings { /// /// How often could a form navigate to another (within one user action/call/message) diff --git a/TelegramBotBase/Exceptions/MaxLengthException.cs b/TelegramBotBase/Exceptions/MaxLengthException.cs index 4263a65..86d811a 100644 --- a/TelegramBotBase/Exceptions/MaxLengthException.cs +++ b/TelegramBotBase/Exceptions/MaxLengthException.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace TelegramBotBase.Exceptions { diff --git a/TelegramBotBase/Exceptions/MaximumColsException.cs b/TelegramBotBase/Exceptions/MaximumColsException.cs index de7cffc..8ddf203 100644 --- a/TelegramBotBase/Exceptions/MaximumColsException.cs +++ b/TelegramBotBase/Exceptions/MaximumColsException.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; namespace TelegramBotBase.Exceptions { @@ -11,12 +9,6 @@ namespace TelegramBotBase.Exceptions public int Maximum { get; set; } - public override string Message - { - get - { - return $"You have exceeded the maximum of columns by {Value.ToString()} / {Maximum.ToString()}"; - } - } + public override string Message => $"You have exceeded the maximum of columns by {Value.ToString()} / {Maximum.ToString()}"; } } diff --git a/TelegramBotBase/Exceptions/MaximumRowsException.cs b/TelegramBotBase/Exceptions/MaximumRowsException.cs index 1d00f18..10f5140 100644 --- a/TelegramBotBase/Exceptions/MaximumRowsException.cs +++ b/TelegramBotBase/Exceptions/MaximumRowsException.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; namespace TelegramBotBase.Exceptions { @@ -11,12 +9,6 @@ namespace TelegramBotBase.Exceptions public int Maximum { get; set; } - public override string Message - { - get - { - return $"You have exceeded the maximum of rows by {Value.ToString()} / {Maximum.ToString()}"; - } - } + public override string Message => $"You have exceeded the maximum of rows by {Value.ToString()} / {Maximum.ToString()}"; } } diff --git a/TelegramBotBase/Factories/DefaultStartFormFactory.cs b/TelegramBotBase/Factories/DefaultStartFormFactory.cs index e3c7c20..969d446 100644 --- a/TelegramBotBase/Factories/DefaultStartFormFactory.cs +++ b/TelegramBotBase/Factories/DefaultStartFormFactory.cs @@ -1,11 +1,10 @@ using System; -using System.Collections.Generic; -using System.Text; using TelegramBotBase.Form; +using TelegramBotBase.Interfaces; namespace TelegramBotBase.Factories { - public class DefaultStartFormFactory : Interfaces.IStartFormFactory + public class DefaultStartFormFactory : IStartFormFactory { private readonly Type _startFormClass; diff --git a/TelegramBotBase/Factories/LambdaStartFormFactory.cs b/TelegramBotBase/Factories/LambdaStartFormFactory.cs index c748b20..563e03e 100644 --- a/TelegramBotBase/Factories/LambdaStartFormFactory.cs +++ b/TelegramBotBase/Factories/LambdaStartFormFactory.cs @@ -1,11 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Text; -using TelegramBotBase.Form; +using TelegramBotBase.Form; +using TelegramBotBase.Interfaces; namespace TelegramBotBase.Factories { - public class LambdaStartFormFactory : Interfaces.IStartFormFactory + public class LambdaStartFormFactory : IStartFormFactory { public delegate FormBase CreateFormDelegate(); diff --git a/TelegramBotBase/Form/AlertDialog.cs b/TelegramBotBase/Form/AlertDialog.cs index d0a9731..fe7f472 100644 --- a/TelegramBotBase/Form/AlertDialog.cs +++ b/TelegramBotBase/Form/AlertDialog.cs @@ -1,11 +1,4 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using TelegramBotBase.Attributes; -using TelegramBotBase.Base; +using TelegramBotBase.Attributes; namespace TelegramBotBase.Form { @@ -15,12 +8,12 @@ namespace TelegramBotBase.Form [IgnoreState] public class AlertDialog : ConfirmDialog { - public String ButtonText { get; set; } + public string ButtonText { get; set; } - public AlertDialog(String Message, String ButtonText) : base(Message) + public AlertDialog(string message, string buttonText) : base(message) { - this.Buttons.Add(new ButtonBase(ButtonText, "ok")); - this.ButtonText = ButtonText; + Buttons.Add(new ButtonBase(buttonText, "ok")); + this.ButtonText = buttonText; } diff --git a/TelegramBotBase/Form/ArrayPromptDialog.cs b/TelegramBotBase/Form/ArrayPromptDialog.cs index 42749fe..4ce663c 100644 --- a/TelegramBotBase/Form/ArrayPromptDialog.cs +++ b/TelegramBotBase/Form/ArrayPromptDialog.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.ComponentModel; using System.Linq; -using System.Text; using System.Threading.Tasks; using TelegramBotBase.Args; using TelegramBotBase.Attributes; @@ -19,7 +18,7 @@ namespace TelegramBotBase.Form /// /// The message the users sees. /// - public String Message { get; set; } + public string Message { get; set; } /// /// An additional optional value. @@ -29,26 +28,24 @@ namespace TelegramBotBase.Form public ButtonBase[][] Buttons { get; set; } [Obsolete] - public Dictionary ButtonForms { get; set; } = new Dictionary(); + public Dictionary ButtonForms { get; set; } = new Dictionary(); - private EventHandlerList __Events { get; set; } = new EventHandlerList(); - - private static object __evButtonClicked { get; } = new object(); + private static object EvButtonClicked { get; } = new object(); public ArrayPromptDialog() { } - public ArrayPromptDialog(String Message) + public ArrayPromptDialog(string message) { - this.Message = Message; + this.Message = message; } - public ArrayPromptDialog(String Message, params ButtonBase[][] Buttons) + public ArrayPromptDialog(string message, params ButtonBase[][] buttons) { - this.Message = Message; - this.Buttons = Buttons; + this.Message = message; + this.Buttons = buttons; } public override async Task Action(MessageResult message) @@ -64,59 +61,53 @@ namespace TelegramBotBase.Form await message.DeleteMessage(); - var buttons = this.Buttons.Aggregate((a, b) => a.Union(b).ToArray()).ToList(); + var buttons = Buttons.Aggregate((a, b) => a.Union(b).ToArray()).ToList(); if(call==null) { return; } - ButtonBase button = buttons.FirstOrDefault(a => a.Value == call.Value); + var button = buttons.FirstOrDefault(a => a.Value == call.Value); if (button == null) { return; } - OnButtonClicked(new ButtonClickedEventArgs(button) { Tag = this.Tag }); + OnButtonClicked(new ButtonClickedEventArgs(button) { Tag = Tag }); - FormBase fb = ButtonForms.ContainsKey(call.Value) ? ButtonForms[call.Value] : null; + var fb = ButtonForms.ContainsKey(call.Value) ? ButtonForms[call.Value] : null; if (fb != null) { - await this.NavigateTo(fb); + await NavigateTo(fb); } } public override async Task Render(MessageResult message) { - ButtonForm btn = new ButtonForm(); + var btn = new ButtonForm(); - foreach(var bl in this.Buttons) + foreach(var bl in Buttons) { btn.AddButtonRow(bl.Select(a => new ButtonBase(a.Text, CallbackData.Create("action", a.Value))).ToList()); } - await this.Device.Send(this.Message, btn); + await Device.Send(Message, btn); } public event EventHandler ButtonClicked { - add - { - this.__Events.AddHandler(__evButtonClicked, value); - } - remove - { - this.__Events.RemoveHandler(__evButtonClicked, value); - } + add => Events.AddHandler(EvButtonClicked, value); + remove => Events.RemoveHandler(EvButtonClicked, value); } public void OnButtonClicked(ButtonClickedEventArgs e) { - (this.__Events[__evButtonClicked] as EventHandler)?.Invoke(this, e); + (Events[EvButtonClicked] as EventHandler)?.Invoke(this, e); } } } diff --git a/TelegramBotBase/Form/AutoCleanForm.cs b/TelegramBotBase/Form/AutoCleanForm.cs index b05938e..be2ff1e 100644 --- a/TelegramBotBase/Form/AutoCleanForm.cs +++ b/TelegramBotBase/Form/AutoCleanForm.cs @@ -22,35 +22,36 @@ namespace TelegramBotBase.Form public List OldMessages { get; set; } [SaveState] - public eDeleteMode DeleteMode { get; set; } + public EDeleteMode DeleteMode { get; set; } [SaveState] - public eDeleteSide DeleteSide { get; set; } + public EDeleteSide DeleteSide { get; set; } public AutoCleanForm() { - this.OldMessages = new List(); - this.DeleteMode = eDeleteMode.OnEveryCall; - this.DeleteSide = eDeleteSide.BotOnly; + OldMessages = new List(); + DeleteMode = EDeleteMode.OnEveryCall; + DeleteSide = EDeleteSide.BotOnly; - this.Init += AutoCleanForm_Init; + Init += AutoCleanForm_Init; - this.Closed += AutoCleanForm_Closed; + Closed += AutoCleanForm_Closed; } - private async Task AutoCleanForm_Init(object sender, InitEventArgs e) + private Task AutoCleanForm_Init(object sender, InitEventArgs e) { - if (this.Device == null) - return; + if (Device == null) + return Task.CompletedTask; - this.Device.MessageSent += Device_MessageSent; + Device.MessageSent += Device_MessageSent; - this.Device.MessageReceived += Device_MessageReceived; + Device.MessageReceived += Device_MessageReceived; - this.Device.MessageDeleted += Device_MessageDeleted; + Device.MessageDeleted += Device_MessageDeleted; + return Task.CompletedTask; } private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e) @@ -61,23 +62,24 @@ namespace TelegramBotBase.Form private void Device_MessageReceived(object sender, MessageReceivedEventArgs e) { - if (this.DeleteSide == eDeleteSide.BotOnly) + if (DeleteSide == EDeleteSide.BotOnly) return; - this.OldMessages.Add(e.Message.MessageId); + OldMessages.Add(e.Message.MessageId); } - private async Task Device_MessageSent(object sender, MessageSentEventArgs e) + private Task Device_MessageSent(object sender, MessageSentEventArgs e) { - if (this.DeleteSide == eDeleteSide.UserOnly) - return; + if (DeleteSide == EDeleteSide.UserOnly) + return Task.CompletedTask; - this.OldMessages.Add(e.Message.MessageId); + OldMessages.Add(e.Message.MessageId); + return Task.CompletedTask; } public override async Task PreLoad(MessageResult message) { - if (this.DeleteMode != eDeleteMode.OnEveryCall) + if (DeleteMode != EDeleteMode.OnEveryCall) return; await MessageCleanup(); @@ -89,7 +91,7 @@ namespace TelegramBotBase.Form /// public void AddMessage(Message m) { - this.OldMessages.Add(m.MessageId); + OldMessages.Add(m.MessageId); } @@ -99,16 +101,16 @@ namespace TelegramBotBase.Form /// public void AddMessage(int messageId) { - this.OldMessages.Add(messageId); + OldMessages.Add(messageId); } /// /// Keeps the message by removing it from the list /// - /// - public void LeaveMessage(int Id) + /// + public void LeaveMessage(int id) { - this.OldMessages.Remove(Id); + OldMessages.Remove(id); } /// @@ -116,18 +118,19 @@ namespace TelegramBotBase.Form /// public void LeaveLastMessage() { - if (this.OldMessages.Count == 0) + if (OldMessages.Count == 0) return; - this.OldMessages.RemoveAt(this.OldMessages.Count - 1); + OldMessages.RemoveAt(OldMessages.Count - 1); } - private async Task AutoCleanForm_Closed(object sender, EventArgs e) + private Task AutoCleanForm_Closed(object sender, EventArgs e) { - if (this.DeleteMode != eDeleteMode.OnLeavingForm) - return; + if (DeleteMode != EDeleteMode.OnLeavingForm) + return Task.CompletedTask; MessageCleanup().Wait(); + return Task.CompletedTask; } /// @@ -167,7 +170,7 @@ namespace TelegramBotBase.Form var retryAfterSeconds = ex.InnerExceptions .Where(e => e is ApiRequestException apiEx && apiEx.ErrorCode == 429) - .Max(e => (int?)((ApiRequestException)e).Parameters.RetryAfter) ?? 0; + .Max(e => ((ApiRequestException)e).Parameters.RetryAfter) ?? 0; retryAfterTask = Task.Delay(retryAfterSeconds * 1000); } @@ -207,7 +210,7 @@ namespace TelegramBotBase.Form var retryAfterSeconds = ex.InnerExceptions .Where(e => e is ApiRequestException apiEx && apiEx.ErrorCode == 429) - .Max(e => (int?)((ApiRequestException)e).Parameters.RetryAfter) ?? 0; + .Max(e => ((ApiRequestException)e).Parameters.RetryAfter) ?? 0; retryAfterTask = Task.Delay(retryAfterSeconds * 1000); } diff --git a/TelegramBotBase/Form/ButtonBase.cs b/TelegramBotBase/Form/ButtonBase.cs index efb4466..a068774 100644 --- a/TelegramBotBase/Form/ButtonBase.cs +++ b/TelegramBotBase/Form/ButtonBase.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Diagnostics; using Telegram.Bot.Types.ReplyMarkups; namespace TelegramBotBase.Form @@ -14,22 +9,22 @@ namespace TelegramBotBase.Form /// public class ButtonBase { - public virtual String Text { get; set; } + public virtual string Text { get; set; } - public String Value { get; set; } + public string Value { get; set; } - public String Url { get; set; } + public string Url { get; set; } public ButtonBase() { } - public ButtonBase(String Text, String Value, String Url = null) + public ButtonBase(string text, string value, string url = null) { - this.Text = Text; - this.Value = Value; - this.Url = Url; + this.Text = text; + this.Value = value; + this.Url = url; } @@ -40,16 +35,17 @@ namespace TelegramBotBase.Form /// public virtual InlineKeyboardButton ToInlineButton(ButtonForm form) { - String id = (form.DependencyControl != null ? form.DependencyControl.ControlID + "_" : ""); - if (this.Url == null) + var id = (form.DependencyControl != null ? form.DependencyControl.ControlId + "_" : ""); + if (Url == null) { - return InlineKeyboardButton.WithCallbackData(this.Text, id + this.Value); + return InlineKeyboardButton.WithCallbackData(Text, id + Value); } - var ikb = new InlineKeyboardButton(this.Text); - - //ikb.Text = this.Text; - ikb.Url = this.Url; + var ikb = new InlineKeyboardButton(Text) + { + //ikb.Text = this.Text; + Url = Url + }; return ikb; @@ -63,7 +59,7 @@ namespace TelegramBotBase.Form /// public virtual KeyboardButton ToKeyboardButton(ButtonForm form) { - return new KeyboardButton(this.Text); + return new KeyboardButton(Text); } } diff --git a/TelegramBotBase/Form/ButtonForm.cs b/TelegramBotBase/Form/ButtonForm.cs index c477b37..fea7fb9 100644 --- a/TelegramBotBase/Form/ButtonForm.cs +++ b/TelegramBotBase/Form/ButtonForm.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; using Telegram.Bot.Types.ReplyMarkups; using TelegramBotBase.Base; using TelegramBotBase.Controls.Hybrid; @@ -14,7 +12,7 @@ namespace TelegramBotBase.Form /// public class ButtonForm { - List Buttons = new List(); + private List _buttons = new List(); public IReplyMarkup Markup { get; set; } @@ -24,13 +22,7 @@ namespace TelegramBotBase.Form /// /// Contains the number of rows. /// - public int Rows - { - get - { - return Buttons.Count; - } - } + public int Rows => _buttons.Count; /// /// Contains the highest number of columns in an row. @@ -39,18 +31,12 @@ namespace TelegramBotBase.Form { get { - return Buttons.Select(a => a.Count).OrderByDescending(a => a).FirstOrDefault(); + return _buttons.Select(a => a.Count).OrderByDescending(a => a).FirstOrDefault(); } } - public ButtonRow this[int row] - { - get - { - return Buttons[row]; - } - } + public ButtonRow this[int row] => _buttons[row]; public ButtonForm() { @@ -59,12 +45,12 @@ namespace TelegramBotBase.Form public ButtonForm(ControlBase control) { - this.DependencyControl = control; + DependencyControl = control; } - public void AddButtonRow(String Text, String Value, String Url = null) + public void AddButtonRow(string text, string value, string url = null) { - Buttons.Add(new List() { new ButtonBase(Text, Value, Url) }); + _buttons.Add(new List { new ButtonBase(text, value, url) }); } //public void AddButtonRow(ButtonRow row) @@ -74,7 +60,7 @@ namespace TelegramBotBase.Form public void AddButtonRow(ButtonRow row) { - Buttons.Add(row); + _buttons.Add(row); } public void AddButtonRow(params ButtonBase[] row) @@ -84,17 +70,17 @@ namespace TelegramBotBase.Form public void AddButtonRows(IEnumerable rows) { - Buttons.AddRange(rows); + _buttons.AddRange(rows); } public void InsertButtonRow(int index, IEnumerable row) { - Buttons.Insert(index, row.ToList()); + _buttons.Insert(index, row.ToList()); } public void InsertButtonRow(int index, ButtonRow row) { - Buttons.Insert(index, row); + _buttons.Insert(index, row); } //public void InsertButtonRow(int index, params ButtonBase[] row) @@ -104,7 +90,7 @@ namespace TelegramBotBase.Form public static T[][] SplitTo(IEnumerable items, int itemsPerRow = 2) { - T[][] splitted = default(T[][]); + var splitted = default(T[][]); try { @@ -126,10 +112,10 @@ namespace TelegramBotBase.Form { get { - if (this.Buttons.Count == 0) + if (_buttons.Count == 0) return 0; - return this.Buttons.Select(a => a.ToArray()).ToList().Aggregate((a, b) => a.Union(b).ToArray()).Length; + return _buttons.Select(a => a.ToArray()).ToList().Aggregate((a, b) => a.Union(b).ToArray()).Length; } } @@ -140,7 +126,7 @@ namespace TelegramBotBase.Form /// public void AddSplitted(IEnumerable buttons, int buttonsPerRow = 2) { - var sp = SplitTo(buttons, buttonsPerRow); + var sp = SplitTo(buttons, buttonsPerRow); foreach (var bl in sp) { @@ -156,50 +142,50 @@ namespace TelegramBotBase.Form /// public List GetRange(int start, int count) { - return Buttons.Skip(start).Take(count).ToList(); + return _buttons.Skip(start).Take(count).ToList(); } public List ToList() { - return this.Buttons.DefaultIfEmpty(new List()).Select(a => a.ToList()).Aggregate((a, b) => a.Union(b).ToList()); + return _buttons.DefaultIfEmpty(new List()).Select(a => a.ToList()).Aggregate((a, b) => a.Union(b).ToList()); } public InlineKeyboardButton[][] ToInlineButtonArray() { - var ikb = this.Buttons.Select(a => a.ToArray().Select(b => b.ToInlineButton(this)).ToArray()).ToArray(); + var ikb = _buttons.Select(a => a.ToArray().Select(b => b.ToInlineButton(this)).ToArray()).ToArray(); return ikb; } public KeyboardButton[][] ToReplyButtonArray() { - var ikb = this.Buttons.Select(a => a.ToArray().Select(b => b.ToKeyboardButton(this)).ToArray()).ToArray(); + var ikb = _buttons.Select(a => a.ToArray().Select(b => b.ToKeyboardButton(this)).ToArray()).ToArray(); return ikb; } public List ToArray() { - return Buttons; + return _buttons; } public int FindRowByButton(ButtonBase button) { - var row = this.Buttons.FirstOrDefault(a => a.ToArray().Count(b => b == button) > 0); + var row = _buttons.FirstOrDefault(a => a.ToArray().Count(b => b == button) > 0); if (row == null) return -1; - return this.Buttons.IndexOf(row); + return _buttons.IndexOf(row); } - public Tuple FindRow(String text, bool useText = true) + public Tuple FindRow(string text, bool useText = true) { - var r = this.Buttons.FirstOrDefault(a => a.Matches(text, useText)); + var r = _buttons.FirstOrDefault(a => a.Matches(text, useText)); if (r == null) return null; - var i = this.Buttons.IndexOf(r); + var i = _buttons.IndexOf(r); return new Tuple(r, i); } @@ -209,9 +195,9 @@ namespace TelegramBotBase.Form /// /// /// - public ButtonBase GetButtonByValue(String value) + public ButtonBase GetButtonByValue(string value) { - return this.ToList().Where(a => a.Value == value).FirstOrDefault(); + return ToList().Where(a => a.Value == value).FirstOrDefault(); } public static implicit operator InlineKeyboardMarkup(ButtonForm form) @@ -219,7 +205,7 @@ namespace TelegramBotBase.Form if (form == null) return null; - InlineKeyboardMarkup ikm = new InlineKeyboardMarkup(form.ToInlineButtonArray()); + var ikm = new InlineKeyboardMarkup(form.ToInlineButtonArray()); return ikm; } @@ -229,7 +215,7 @@ namespace TelegramBotBase.Form if (form == null) return null; - ReplyKeyboardMarkup ikm = new ReplyKeyboardMarkup(form.ToReplyButtonArray()); + var ikm = new ReplyKeyboardMarkup(form.ToReplyButtonArray()); return ikm; } @@ -240,20 +226,20 @@ namespace TelegramBotBase.Form /// public ButtonForm Duplicate() { - var bf = new ButtonForm() + var bf = new ButtonForm { - Markup = this.Markup, - DependencyControl = this.DependencyControl + Markup = Markup, + DependencyControl = DependencyControl }; - foreach (var b in Buttons) + foreach (var b in _buttons) { var lst = new ButtonRow(); foreach (var b2 in b) { lst.Add(b2); } - bf.Buttons.Add(lst); + bf._buttons.Add(lst); } return bf; @@ -263,15 +249,15 @@ namespace TelegramBotBase.Form /// Creates a copy of this form and filters by the parameter. /// /// - public ButtonForm FilterDuplicate(String filter, bool ByRow = false) + public ButtonForm FilterDuplicate(string filter, bool byRow = false) { - var bf = new ButtonForm() + var bf = new ButtonForm { - Markup = this.Markup, - DependencyControl = this.DependencyControl + Markup = Markup, + DependencyControl = DependencyControl }; - foreach (var b in Buttons) + foreach (var b in _buttons) { var lst = new ButtonRow(); foreach (var b2 in b) @@ -280,19 +266,17 @@ namespace TelegramBotBase.Form continue; //Copy full row, when at least one match has found. - if (ByRow) + if (byRow) { lst = b; break; } - else - { - lst.Add(b2); - } + + lst.Add(b2); } if (lst.Count > 0) - bf.Buttons.Add(lst); + bf._buttons.Add(lst); } return bf; @@ -302,15 +286,15 @@ namespace TelegramBotBase.Form /// Creates a copy of this form and filters by the parameter. /// /// - public ButtonForm TagDuplicate(List tags, bool ByRow = false) + public ButtonForm TagDuplicate(List tags, bool byRow = false) { - var bf = new ButtonForm() + var bf = new ButtonForm { - Markup = this.Markup, - DependencyControl = this.DependencyControl + Markup = Markup, + DependencyControl = DependencyControl }; - foreach (var b in Buttons) + foreach (var b in _buttons) { var lst = new ButtonRow(); foreach (var b2 in b) @@ -322,19 +306,17 @@ namespace TelegramBotBase.Form continue; //Copy full row, when at least one match has found. - if (ByRow) + if (byRow) { lst = b; break; } - else - { - lst.Add(b2); - } + + lst.Add(b2); } if (lst.Count > 0) - bf.Buttons.Add(lst); + bf._buttons.Add(lst); } return bf; diff --git a/TelegramBotBase/Form/CallbackData.cs b/TelegramBotBase/Form/CallbackData.cs index 3b50e31..9cca33d 100644 --- a/TelegramBotBase/Form/CallbackData.cs +++ b/TelegramBotBase/Form/CallbackData.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; +using Newtonsoft.Json; namespace TelegramBotBase.Form { @@ -14,10 +8,10 @@ namespace TelegramBotBase.Form public class CallbackData { [JsonProperty("m")] - public String Method { get; set; } + public string Method { get; set; } [JsonProperty("v")] - public String Value { get; set; } + public string Value { get; set; } public CallbackData() @@ -25,13 +19,13 @@ namespace TelegramBotBase.Form } - public CallbackData(String method, String value) + public CallbackData(string method, string value) { - this.Method = method; - this.Value = value; + Method = method; + Value = value; } - public static String Create(String method, String value) + public static string Create(string method, string value) { return new CallbackData(method, value).Serialize(); } @@ -40,13 +34,13 @@ namespace TelegramBotBase.Form /// Serializes data to json string /// /// - public String Serialize() + public string Serialize() { - String s = ""; + var s = ""; try { - s = Newtonsoft.Json.JsonConvert.SerializeObject(this); + s = JsonConvert.SerializeObject(this); } catch { @@ -61,12 +55,12 @@ namespace TelegramBotBase.Form /// /// /// - public static CallbackData Deserialize(String data) + public static CallbackData Deserialize(string data) { CallbackData cd = null; try { - cd = Newtonsoft.Json.JsonConvert.DeserializeObject(data); + cd = JsonConvert.DeserializeObject(data); return cd; } diff --git a/TelegramBotBase/Form/ConfirmDialog.cs b/TelegramBotBase/Form/ConfirmDialog.cs index dc791db..0621fcb 100644 --- a/TelegramBotBase/Form/ConfirmDialog.cs +++ b/TelegramBotBase/Form/ConfirmDialog.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.ComponentModel; using System.Linq; -using System.Text; using System.Threading.Tasks; using TelegramBotBase.Args; using TelegramBotBase.Attributes; @@ -16,7 +15,7 @@ namespace TelegramBotBase.Form /// /// The message the users sees. /// - public String Message { get; set; } + public string Message { get; set; } /// /// An additional optional value. @@ -30,25 +29,23 @@ namespace TelegramBotBase.Form public List Buttons { get; set; } - private EventHandlerList __Events { get; set; } = new EventHandlerList(); - - private static object __evButtonClicked { get; } = new object(); + private static object EvButtonClicked { get; } = new object(); public ConfirmDialog() { } - public ConfirmDialog(String Message) + public ConfirmDialog(string message) { - this.Message = Message; - this.Buttons = new List(); + this.Message = message; + Buttons = new List(); } - public ConfirmDialog(String Message, params ButtonBase[] Buttons) + public ConfirmDialog(string message, params ButtonBase[] buttons) { - this.Message = Message; - this.Buttons = Buttons.ToList(); + this.Message = message; + this.Buttons = buttons.ToList(); } /// @@ -57,7 +54,7 @@ namespace TelegramBotBase.Form /// public void AddButton(ButtonBase button) { - this.Buttons.Add(button); + Buttons.Add(button); } public override async Task Action(MessageResult message) @@ -78,14 +75,14 @@ namespace TelegramBotBase.Form await message.DeleteMessage(); - ButtonBase button = this.Buttons.FirstOrDefault(a => a.Value == call.Value); + var button = Buttons.FirstOrDefault(a => a.Value == call.Value); if (button == null) { return; } - OnButtonClicked(new ButtonClickedEventArgs(button) { Tag = this.Tag }); + OnButtonClicked(new ButtonClickedEventArgs(button) { Tag = Tag }); if (AutoCloseOnClick) await CloseForm(); @@ -94,30 +91,24 @@ namespace TelegramBotBase.Form public override async Task Render(MessageResult message) { - ButtonForm btn = new ButtonForm(); + var btn = new ButtonForm(); - var buttons = this.Buttons.Select(a => new ButtonBase(a.Text, CallbackData.Create("action", a.Value))).ToList(); + var buttons = Buttons.Select(a => new ButtonBase(a.Text, CallbackData.Create("action", a.Value))).ToList(); btn.AddButtonRow(buttons); - await this.Device.Send(this.Message, btn); + await Device.Send(Message, btn); } public event EventHandler ButtonClicked { - add - { - this.__Events.AddHandler(__evButtonClicked, value); - } - remove - { - this.__Events.RemoveHandler(__evButtonClicked, value); - } + add => Events.AddHandler(EvButtonClicked, value); + remove => Events.RemoveHandler(EvButtonClicked, value); } public void OnButtonClicked(ButtonClickedEventArgs e) { - (this.__Events[__evButtonClicked] as EventHandler)?.Invoke(this, e); + (Events[EvButtonClicked] as EventHandler)?.Invoke(this, e); } } diff --git a/TelegramBotBase/Form/DynamicButton.cs b/TelegramBotBase/Form/DynamicButton.cs index 4935514..9dcc89b 100644 --- a/TelegramBotBase/Form/DynamicButton.cs +++ b/TelegramBotBase/Form/DynamicButton.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; namespace TelegramBotBase.Form { @@ -8,32 +6,26 @@ namespace TelegramBotBase.Form { public override string Text { - get - { - return GetText?.Invoke() ?? m_text; - } - set - { - m_text = value; - } + get => _getText?.Invoke() ?? _mText; + set => _mText = value; } - private String m_text = ""; + private string _mText = ""; - private Func GetText; + private Func _getText; - public DynamicButton(String Text, String Value, String Url = null) + public DynamicButton(string text, string value, string url = null) { - this.Text = Text; - this.Value = Value; - this.Url = Url; + this.Text = text; + this.Value = value; + this.Url = url; } - public DynamicButton(Func GetText, String Value, String Url = null) + public DynamicButton(Func getText, string value, string url = null) { - this.GetText = GetText; - this.Value = Value; - this.Url = Url; + this._getText = getText; + this.Value = value; + this.Url = url; } diff --git a/TelegramBotBase/Form/GroupForm.cs b/TelegramBotBase/Form/GroupForm.cs index ecdc01f..6134a43 100644 --- a/TelegramBotBase/Form/GroupForm.cs +++ b/TelegramBotBase/Form/GroupForm.cs @@ -1,8 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; +using Telegram.Bot.Types.Enums; using TelegramBotBase.Args; using TelegramBotBase.Base; @@ -10,38 +7,30 @@ namespace TelegramBotBase.Form { public class GroupForm : FormBase { - - - public GroupForm() - { - - - } - public override async Task Load(MessageResult message) { switch (message.MessageType) { - case Telegram.Bot.Types.Enums.MessageType.ChatMembersAdded: + case MessageType.ChatMembersAdded: - await OnMemberChanges(new MemberChangeEventArgs(Telegram.Bot.Types.Enums.MessageType.ChatMembersAdded, message, message.Message.NewChatMembers)); + await OnMemberChanges(new MemberChangeEventArgs(MessageType.ChatMembersAdded, message, message.Message.NewChatMembers)); break; - case Telegram.Bot.Types.Enums.MessageType.ChatMemberLeft: + case MessageType.ChatMemberLeft: - await OnMemberChanges(new MemberChangeEventArgs(Telegram.Bot.Types.Enums.MessageType.ChatMemberLeft, message, message.Message.LeftChatMember)); + await OnMemberChanges(new MemberChangeEventArgs(MessageType.ChatMemberLeft, message, message.Message.LeftChatMember)); break; - case Telegram.Bot.Types.Enums.MessageType.ChatPhotoChanged: - case Telegram.Bot.Types.Enums.MessageType.ChatPhotoDeleted: - case Telegram.Bot.Types.Enums.MessageType.ChatTitleChanged: - case Telegram.Bot.Types.Enums.MessageType.MigratedFromGroup: - case Telegram.Bot.Types.Enums.MessageType.MigratedToSupergroup: - case Telegram.Bot.Types.Enums.MessageType.MessagePinned: - case Telegram.Bot.Types.Enums.MessageType.GroupCreated: - case Telegram.Bot.Types.Enums.MessageType.SupergroupCreated: - case Telegram.Bot.Types.Enums.MessageType.ChannelCreated: + case MessageType.ChatPhotoChanged: + case MessageType.ChatPhotoDeleted: + case MessageType.ChatTitleChanged: + case MessageType.MigratedFromGroup: + case MessageType.MigratedToSupergroup: + case MessageType.MessagePinned: + case MessageType.GroupCreated: + case MessageType.SupergroupCreated: + case MessageType.ChannelCreated: await OnGroupChanged(new GroupChangedEventArgs(message.MessageType, message)); @@ -61,26 +50,26 @@ namespace TelegramBotBase.Form await OnMessageEdit(message); } - public virtual async Task OnMemberChanges(MemberChangeEventArgs e) + public virtual Task OnMemberChanges(MemberChangeEventArgs e) { - + return Task.CompletedTask; } - public virtual async Task OnGroupChanged(GroupChangedEventArgs e) + public virtual Task OnGroupChanged(GroupChangedEventArgs e) { - + return Task.CompletedTask; } - public virtual async Task OnMessage(MessageResult e) + public virtual Task OnMessage(MessageResult e) { - + return Task.CompletedTask; } - public virtual async Task OnMessageEdit(MessageResult e) + public virtual Task OnMessageEdit(MessageResult e) { - + return Task.CompletedTask; } } } diff --git a/TelegramBotBase/Form/ModalDialog.cs b/TelegramBotBase/Form/ModalDialog.cs index a3c8faa..06d7b7b 100644 --- a/TelegramBotBase/Form/ModalDialog.cs +++ b/TelegramBotBase/Form/ModalDialog.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Threading.Tasks; namespace TelegramBotBase.Form @@ -17,12 +15,12 @@ namespace TelegramBotBase.Form /// public async Task CloseForm() { - await this.CloseControls(); + await CloseControls(); - await this.OnClosed(new EventArgs()); + await OnClosed(EventArgs.Empty); - await this.ParentForm?.ReturnFromModal(this); + await ParentForm?.ReturnFromModal(this); } } } diff --git a/TelegramBotBase/Form/Navigation/NavigationController.cs b/TelegramBotBase/Form/Navigation/NavigationController.cs index d1858b9..94461ab 100644 --- a/TelegramBotBase/Form/Navigation/NavigationController.cs +++ b/TelegramBotBase/Form/Navigation/NavigationController.cs @@ -2,12 +2,13 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; -using System.Text; +using System.Reflection; using System.Threading.Tasks; using TelegramBotBase.Args; using TelegramBotBase.Attributes; using TelegramBotBase.Base; using TelegramBotBase.Interfaces; +using TelegramBotBase.Tools; namespace TelegramBotBase.Form.Navigation { @@ -33,15 +34,15 @@ namespace TelegramBotBase.Form.Navigation Index = -1; ForceCleanupOnLastPop = true; - this.Init += NavigationController_Init; - this.Opened += NavigationController_Opened; - this.Closed += NavigationController_Closed; + Init += NavigationController_Init; + Opened += NavigationController_Opened; + Closed += NavigationController_Closed; } public NavigationController(FormBase startForm, params FormBase[] forms) : this() { - this.Client = startForm.Client; - this.Device = startForm.Device; + Client = startForm.Client; + Device = startForm.Device; startForm.NavigationController = this; History.Add(startForm); @@ -54,7 +55,7 @@ namespace TelegramBotBase.Form.Navigation } } - private async Task NavigationController_Init(object sender, Args.InitEventArgs e) + private async Task NavigationController_Init(object sender, InitEventArgs e) { if (CurrentForm == null) return; @@ -97,21 +98,21 @@ namespace TelegramBotBase.Form.Navigation Device.FormSwitched = true; - await form.OnClosed(new EventArgs()); + await form.OnClosed(EventArgs.Empty); //Leave NavigationController and move to the last one if (ForceCleanupOnLastPop && History.Count == 1) { - var last_form = History[0]; - last_form.NavigationController = null; - await this.NavigateTo(last_form); + var lastForm = History[0]; + lastForm.NavigationController = null; + await NavigateTo(lastForm); return; } if (History.Count > 0) { form = History[Index]; - await form.OnOpened(new EventArgs()); + await form.OnOpened(EventArgs.Empty); } } @@ -134,11 +135,11 @@ namespace TelegramBotBase.Form.Navigation /// public virtual async Task PushAsync(FormBase form, params object[] args) { - form.Client = this.Client; - form.Device = this.Device; + form.Client = Client; + form.Device = Device; form.NavigationController = this; - this.History.Add(form); + History.Add(form); Index++; Device.FormSwitched = true; @@ -148,7 +149,7 @@ namespace TelegramBotBase.Form.Navigation await form.OnInit(new InitEventArgs(args)); - await form.OnOpened(new EventArgs()); + await form.OnOpened(EventArgs.Empty); } /// @@ -172,10 +173,10 @@ namespace TelegramBotBase.Form.Navigation { get { - if (this.History.Count == 0) + if (History.Count == 0) return null; - return this.History[Index]; + return History[Index]; } } @@ -191,12 +192,12 @@ namespace TelegramBotBase.Form.Navigation return; - int historyCount = e.GetInt("$controller.history.count"); + var historyCount = e.GetInt("$controller.history.count"); - for (int i = 0; i < historyCount; i++) + for (var i = 0; i < historyCount; i++) { - var c = e.GetObject($"$controller.history[{i}]") as Dictionary; + var c = e.GetObject($"$controller.history[{i}]") as Dictionary; @@ -205,23 +206,21 @@ namespace TelegramBotBase.Form.Navigation if (qname == null) continue; - Type t = Type.GetType(qname.ToString()); + var t = Type.GetType(qname); if (t == null || !t.IsSubclassOf(typeof(FormBase))) { continue; } - var form = t.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as FormBase; - //No default constructor, fallback - if (form == null) + if (t.GetConstructor(new Type[] { })?.Invoke(new object[] { }) is not FormBase form) { continue; } var properties = c.Where(a => a.Key.StartsWith("$")); - var fields = form.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); + var fields = form.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); foreach (var p in properties) { @@ -243,10 +242,10 @@ namespace TelegramBotBase.Form.Navigation f.SetValue(form, p.Value); } - catch (ArgumentException ex) + catch (ArgumentException) { - Tools.Conversion.CustomConversionChecks(form, p, f); + Conversion.CustomConversionChecks(form, p, f); } catch @@ -255,13 +254,13 @@ namespace TelegramBotBase.Form.Navigation } } - form.Device = this.Device; - form.Client = this.Client; + form.Device = Device; + form.Client = Client; form.NavigationController = this; form.OnInit(new InitEventArgs()); - this.History.Add(form); + History.Add(form); } } @@ -270,12 +269,12 @@ namespace TelegramBotBase.Form.Navigation { e.Set("$controller.history.count", History.Count.ToString()); - int i = 0; + var i = 0; foreach (var form in History) { - var fields = form.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); + var fields = form.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); - var dt = new Dictionary(); + var dt = new Dictionary(); foreach (var f in fields) { var val = f.GetValue(form); diff --git a/TelegramBotBase/Form/PromptDialog.cs b/TelegramBotBase/Form/PromptDialog.cs index ec9e61c..61a28bf 100644 --- a/TelegramBotBase/Form/PromptDialog.cs +++ b/TelegramBotBase/Form/PromptDialog.cs @@ -1,14 +1,12 @@ using System; -using System.Collections.Generic; using System.ComponentModel; -using System.Linq; -using System.Text; using System.Threading.Tasks; using Telegram.Bot.Types; using Telegram.Bot.Types.ReplyMarkups; using TelegramBotBase.Args; using TelegramBotBase.Attributes; using TelegramBotBase.Base; +using TelegramBotBase.Localizations; namespace TelegramBotBase.Form { @@ -18,25 +16,23 @@ namespace TelegramBotBase.Form /// /// The message the users sees. /// - public String Message { get; set; } + public string Message { get; set; } /// /// The returned text value by the user. /// - public String Value { get; set; } + public string Value { get; set; } /// /// An additional optional value. /// public object Tag { get; set; } - private EventHandlerList __Events { get; set; } = new EventHandlerList(); - - private static object __evCompleted { get; } = new object(); + private static object EvCompleted { get; } = new object(); public bool ShowBackButton { get; set; } = false; - public String BackLabel { get; set; } = Localizations.Default.Language["PromptDialog_Back"]; + public string BackLabel { get; set; } = Default.Language["PromptDialog_Back"]; /// /// Contains the RAW received message. @@ -48,12 +44,12 @@ namespace TelegramBotBase.Form } - public PromptDialog(String Message) + public PromptDialog(string message) { - this.Message = Message; + this.Message = message; } - public async override Task Load(MessageResult message) + public override async Task Load(MessageResult message) { if (message.Handled) return; @@ -61,16 +57,16 @@ namespace TelegramBotBase.Form if (!message.IsFirstHandler) return; - if (this.ShowBackButton && message.MessageText == BackLabel) + if (ShowBackButton && message.MessageText == BackLabel) { - await this.CloseForm(); + await CloseForm(); return; } - if (this.Value == null) + if (Value == null) { - this.Value = message.MessageText; + Value = message.MessageText; ReceivedMessage = message.Message; } @@ -81,44 +77,38 @@ namespace TelegramBotBase.Form public override async Task Render(MessageResult message) { - if (this.Value == null) + if (Value == null) { - if (this.ShowBackButton) + if (ShowBackButton) { - ButtonForm bf = new ButtonForm(); + var bf = new ButtonForm(); bf.AddButtonRow(new ButtonBase(BackLabel, "back")); - await this.Device.Send(this.Message, (ReplyMarkupBase)bf); + await Device.Send(Message, (ReplyMarkupBase)bf); return; } - await this.Device.Send(this.Message); + await Device.Send(Message); return; } message.Handled = true; - OnCompleted(new PromptDialogCompletedEventArgs() { Tag = this.Tag, Value = this.Value }); + OnCompleted(new PromptDialogCompletedEventArgs { Tag = Tag, Value = Value }); - await this.CloseForm(); + await CloseForm(); } public event EventHandler Completed { - add - { - this.__Events.AddHandler(__evCompleted, value); - } - remove - { - this.__Events.RemoveHandler(__evCompleted, value); - } + add => Events.AddHandler(EvCompleted, value); + remove => Events.RemoveHandler(EvCompleted, value); } public void OnCompleted(PromptDialogCompletedEventArgs e) { - (this.__Events[__evCompleted] as EventHandler)?.Invoke(this, e); + (Events[EvCompleted] as EventHandler)?.Invoke(this, e); } } diff --git a/TelegramBotBase/Form/SplitterForm.cs b/TelegramBotBase/Form/SplitterForm.cs index 89b3ce7..bfb9818 100644 --- a/TelegramBotBase/Form/SplitterForm.cs +++ b/TelegramBotBase/Form/SplitterForm.cs @@ -1,11 +1,7 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; +using Telegram.Bot.Types.Enums; using TelegramBotBase.Base; - namespace TelegramBotBase.Form { /// @@ -23,14 +19,14 @@ namespace TelegramBotBase.Form public override async Task Load(MessageResult message) { - if (message.Message.Chat.Type == Telegram.Bot.Types.Enums.ChatType.Channel) + if (message.Message.Chat.Type == ChatType.Channel) { if (await OpenChannel(message)) { return; } } - if (message.Message.Chat.Type == Telegram.Bot.Types.Enums.ChatType.Supergroup) + if (message.Message.Chat.Type == ChatType.Supergroup) { if (await OpenSupergroup(message)) { @@ -41,7 +37,7 @@ namespace TelegramBotBase.Form return; } } - if (message.Message.Chat.Type == Telegram.Bot.Types.Enums.ChatType.Group) + if (message.Message.Chat.Type == ChatType.Group) { if (await OpenGroup(message)) { @@ -53,24 +49,24 @@ namespace TelegramBotBase.Form } - public virtual async Task OpenSupergroup(MessageResult e) + public virtual Task OpenSupergroup(MessageResult e) { - return false; + return Task.FromResult(false); } - public virtual async Task OpenChannel(MessageResult e) + public virtual Task OpenChannel(MessageResult e) { - return false; + return Task.FromResult(false); } - public virtual async Task Open(MessageResult e) + public virtual Task Open(MessageResult e) { - return false; + return Task.FromResult(false); } - public virtual async Task OpenGroup(MessageResult e) + public virtual Task OpenGroup(MessageResult e) { - return false; + return Task.FromResult(false); } diff --git a/TelegramBotBase/Form/TagButtonBase.cs b/TelegramBotBase/Form/TagButtonBase.cs index add8b80..fd6f545 100644 --- a/TelegramBotBase/Form/TagButtonBase.cs +++ b/TelegramBotBase/Form/TagButtonBase.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Telegram.Bot.Types.ReplyMarkups; +using Telegram.Bot.Types.ReplyMarkups; namespace TelegramBotBase.Form { @@ -12,18 +7,18 @@ namespace TelegramBotBase.Form /// public class TagButtonBase : ButtonBase { - public String Tag { get; set; } + public string Tag { get; set; } public TagButtonBase() { } - public TagButtonBase(String Text, String Value, String Tag) + public TagButtonBase(string text, string value, string tag) { - this.Text = Text; - this.Value = Value; - this.Tag = Tag; + this.Text = text; + this.Value = value; + this.Tag = tag; } @@ -34,9 +29,9 @@ namespace TelegramBotBase.Form /// public override InlineKeyboardButton ToInlineButton(ButtonForm form) { - String id = (form.DependencyControl != null ? form.DependencyControl.ControlID + "_" : ""); + var id = (form.DependencyControl != null ? form.DependencyControl.ControlId + "_" : ""); - return InlineKeyboardButton.WithCallbackData(this.Text, id + this.Value); + return InlineKeyboardButton.WithCallbackData(Text, id + Value); } @@ -48,7 +43,7 @@ namespace TelegramBotBase.Form /// public override KeyboardButton ToKeyboardButton(ButtonForm form) { - return new KeyboardButton(this.Text); + return new KeyboardButton(Text); } } diff --git a/TelegramBotBase/Interfaces/IDataSource.cs b/TelegramBotBase/Interfaces/IDataSource.cs index d3662e5..7934972 100644 --- a/TelegramBotBase/Interfaces/IDataSource.cs +++ b/TelegramBotBase/Interfaces/IDataSource.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using TelegramBotBase.Controls.Hybrid; +using System.Collections.Generic; namespace TelegramBotBase.Interfaces { diff --git a/TelegramBotBase/Interfaces/IDeviceSession.cs b/TelegramBotBase/Interfaces/IDeviceSession.cs index de487b6..05ae969 100644 --- a/TelegramBotBase/Interfaces/IDeviceSession.cs +++ b/TelegramBotBase/Interfaces/IDeviceSession.cs @@ -1,11 +1,9 @@ using System; -using System.Collections.Generic; -using System.Text; using TelegramBotBase.Form; namespace TelegramBotBase.Interfaces { - interface IDeviceSession + internal interface IDeviceSession { /// /// Device or chat id @@ -15,7 +13,7 @@ namespace TelegramBotBase.Interfaces /// /// Username of user or group /// - String ChatTitle { get; set; } + string ChatTitle { get; set; } /// diff --git a/TelegramBotBase/Interfaces/IMessageLoopFactory.cs b/TelegramBotBase/Interfaces/IMessageLoopFactory.cs index fec857f..937e37a 100644 --- a/TelegramBotBase/Interfaces/IMessageLoopFactory.cs +++ b/TelegramBotBase/Interfaces/IMessageLoopFactory.cs @@ -1,8 +1,5 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Threading.Tasks; -using Telegram.Bot.Types; using TelegramBotBase.Args; using TelegramBotBase.Base; using TelegramBotBase.Sessions; @@ -12,7 +9,7 @@ namespace TelegramBotBase.Interfaces public interface IMessageLoopFactory { - Task MessageLoop(BotBase Bot, DeviceSession session, UpdateResult ur, MessageResult e); + Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult e); event EventHandler UnhandledCall; diff --git a/TelegramBotBase/Interfaces/IStartFormFactory.cs b/TelegramBotBase/Interfaces/IStartFormFactory.cs index 7c1c44d..e300928 100644 --- a/TelegramBotBase/Interfaces/IStartFormFactory.cs +++ b/TelegramBotBase/Interfaces/IStartFormFactory.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using TelegramBotBase.Form; +using TelegramBotBase.Form; namespace TelegramBotBase.Interfaces { diff --git a/TelegramBotBase/Interfaces/IStateForm.cs b/TelegramBotBase/Interfaces/IStateForm.cs index b7e3e69..f9346d7 100644 --- a/TelegramBotBase/Interfaces/IStateForm.cs +++ b/TelegramBotBase/Interfaces/IStateForm.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using TelegramBotBase.Args; -using TelegramBotBase.Base; +using TelegramBotBase.Args; namespace TelegramBotBase.Interfaces { diff --git a/TelegramBotBase/Interfaces/IStateMachine.cs b/TelegramBotBase/Interfaces/IStateMachine.cs index 7cd3e65..2c9c656 100644 --- a/TelegramBotBase/Interfaces/IStateMachine.cs +++ b/TelegramBotBase/Interfaces/IStateMachine.cs @@ -1,9 +1,6 @@ using System; -using System.Collections.Generic; -using System.Text; using TelegramBotBase.Args; using TelegramBotBase.Base; -using TelegramBotBase.Form; namespace TelegramBotBase.Interfaces { diff --git a/TelegramBotBase/Localizations/Default.cs b/TelegramBotBase/Localizations/Default.cs index 6b0a180..27fb412 100644 --- a/TelegramBotBase/Localizations/Default.cs +++ b/TelegramBotBase/Localizations/Default.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace TelegramBotBase.Localizations +namespace TelegramBotBase.Localizations { public static class Default { diff --git a/TelegramBotBase/Localizations/English.cs b/TelegramBotBase/Localizations/English.cs index d340291..2ba5fed 100644 --- a/TelegramBotBase/Localizations/English.cs +++ b/TelegramBotBase/Localizations/English.cs @@ -1,12 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace TelegramBotBase.Localizations +namespace TelegramBotBase.Localizations { public class English : Localization { - public English() : base() + public English() { Values["Language"] = "English"; Values["ButtonGrid_Title"] = "Menu"; diff --git a/TelegramBotBase/Localizations/German.cs b/TelegramBotBase/Localizations/German.cs index 5861e72..d34240a 100644 --- a/TelegramBotBase/Localizations/German.cs +++ b/TelegramBotBase/Localizations/German.cs @@ -1,12 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace TelegramBotBase.Localizations +namespace TelegramBotBase.Localizations { public class German : Localization { - public German() : base() + public German() { Values["Language"] = "Deutsch (German)"; Values["ButtonGrid_Title"] = "Menü"; diff --git a/TelegramBotBase/Localizations/Localization.cs b/TelegramBotBase/Localizations/Localization.cs index ed56cb0..b34fb88 100644 --- a/TelegramBotBase/Localizations/Localization.cs +++ b/TelegramBotBase/Localizations/Localization.cs @@ -1,27 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Text; +using System.Collections.Generic; namespace TelegramBotBase.Localizations { public abstract class Localization { - public Dictionary Values = new Dictionary(); - - public String this[String key] - { - get - { - return Values[key]; - } - } - - public Localization() - { - - - } + public Dictionary Values = new Dictionary(); + public string this[string key] => Values[key]; } } diff --git a/TelegramBotBase/Markdown/Generator.cs b/TelegramBotBase/Markdown/Generator.cs index 05dbfa7..748f62d 100644 --- a/TelegramBotBase/Markdown/Generator.cs +++ b/TelegramBotBase/Markdown/Generator.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading.Tasks; +using System.Linq; using Telegram.Bot.Types.Enums; namespace TelegramBotBase.Markdown @@ -22,16 +17,14 @@ namespace TelegramBotBase.Markdown /// /// /// - public static String Link(this String url, String title = null, String tooltip = null) + public static string Link(this string url, string title = null, string tooltip = null) { - switch (OutputMode) + return OutputMode switch { - case ParseMode.Markdown: - return "[" + (title ?? url) + "](" + url + " " + (tooltip ?? "") + ")"; - case ParseMode.Html: - return $"{title ?? ""}"; - } - return url; + ParseMode.Markdown => "[" + (title ?? url) + "](" + url + " " + (tooltip ?? "") + ")", + ParseMode.Html => $"{title ?? ""}", + _ => url + }; } /// @@ -40,9 +33,9 @@ namespace TelegramBotBase.Markdown /// /// /// - public static String MentionUser(this int userId, String title = null) + public static string MentionUser(this int userId, string title = null) { - return Link("tg://user?id=" + userId.ToString(), title); + return Link("tg://user?id=" + userId, title); } /// @@ -51,7 +44,7 @@ namespace TelegramBotBase.Markdown /// /// /// - public static String MentionUser(this String username, String title = null) + public static string MentionUser(this string username, string title = null) { return Link("tg://user?id=" + username, title); } @@ -61,16 +54,14 @@ namespace TelegramBotBase.Markdown /// /// /// - public static String Bold(this String text) + public static string Bold(this string text) { - switch (OutputMode) + return OutputMode switch { - case ParseMode.Markdown: - return "*" + text + "*"; - case ParseMode.Html: - return "" + text + ""; - } - return text; + ParseMode.Markdown => "*" + text + "*", + ParseMode.Html => "" + text + "", + _ => text + }; } /// @@ -78,16 +69,14 @@ namespace TelegramBotBase.Markdown /// /// /// - public static String Strikesthrough(this String text) + public static string Strikesthrough(this string text) { - switch (OutputMode) + return OutputMode switch { - case ParseMode.Markdown: - return "~" + text + "~"; - case ParseMode.Html: - return "" + text + ""; - } - return text; + ParseMode.Markdown => "~" + text + "~", + ParseMode.Html => "" + text + "", + _ => text + }; } /// @@ -95,16 +84,14 @@ namespace TelegramBotBase.Markdown /// /// /// - public static String Italic(this String text) + public static string Italic(this string text) { - switch (OutputMode) + return OutputMode switch { - case ParseMode.Markdown: - return "_" + text + "_"; - case ParseMode.Html: - return "" + text + ""; - } - return text; + ParseMode.Markdown => "_" + text + "_", + ParseMode.Html => "" + text + "", + _ => text + }; } /// @@ -112,16 +99,14 @@ namespace TelegramBotBase.Markdown /// /// /// - public static String Underline(this String text) + public static string Underline(this string text) { - switch (OutputMode) + return OutputMode switch { - case ParseMode.Markdown: - return "__" + text + "__"; - case ParseMode.Html: - return "" + text + ""; - } - return text; + ParseMode.Markdown => "__" + text + "__", + ParseMode.Html => "" + text + "", + _ => text + }; } /// @@ -129,16 +114,14 @@ namespace TelegramBotBase.Markdown /// /// /// - public static String Monospace(this String text) + public static string Monospace(this string text) { - switch (OutputMode) + return OutputMode switch { - case ParseMode.Markdown: - return "`" + text + "`"; - case ParseMode.Html: - return "" + text + ""; - } - return text; + ParseMode.Markdown => "`" + text + "`", + ParseMode.Html => "" + text + "", + _ => text + }; } /// @@ -146,16 +129,14 @@ namespace TelegramBotBase.Markdown /// /// /// - public static String MultiMonospace(this String text) + public static string MultiMonospace(this string text) { - switch (OutputMode) + return OutputMode switch { - case ParseMode.Markdown: - return "```" + text + "```"; - case ParseMode.Html: - return "
" + text + "
"; - } - return text; + ParseMode.Markdown => "```" + text + "```", + ParseMode.Html => "
" + text + "
", + _ => text + }; } /// @@ -163,14 +144,14 @@ namespace TelegramBotBase.Markdown /// /// /// - public static String MarkdownV2Escape(this String text, params char[] toKeep) + public static string MarkdownV2Escape(this string text, params char[] toKeep) { - char[] toEscape = new char[] { '_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!' }; + var toEscape = new[] { '_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!' }; return text.EscapeAll(toEscape.Where(a => !toKeep.Contains(a)).Select(a => a.ToString()).ToArray()); } - public static string EscapeAll(this string seed, String[] chars, char escapeCharacter = '\\') + public static string EscapeAll(this string seed, string[] chars, char escapeCharacter = '\\') { return chars.Aggregate(seed, (str, cItem) => str.Replace(cItem, escapeCharacter + cItem)); } diff --git a/TelegramBotBase/MessageLoops/FormBaseMessageLoop.cs b/TelegramBotBase/MessageLoops/FormBaseMessageLoop.cs index 3a6b00c..bfd6d81 100644 --- a/TelegramBotBase/MessageLoops/FormBaseMessageLoop.cs +++ b/TelegramBotBase/MessageLoops/FormBaseMessageLoop.cs @@ -1,13 +1,9 @@ using System; -using System.Collections.Generic; using System.ComponentModel; -using System.Linq; -using System.Text; using System.Threading.Tasks; -using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; using TelegramBotBase.Args; using TelegramBotBase.Base; -using TelegramBotBase.Enums; using TelegramBotBase.Interfaces; using TelegramBotBase.Sessions; @@ -18,32 +14,27 @@ namespace TelegramBotBase.MessageLoops ///
public class FormBaseMessageLoop : IMessageLoopFactory { - private static object __evUnhandledCall = new object(); + private static readonly object EvUnhandledCall = new object(); - private EventHandlerList __Events = new EventHandlerList(); + private readonly EventHandlerList _events = new EventHandlerList(); - public FormBaseMessageLoop() - { - - } - - public async Task MessageLoop(BotBase Bot, DeviceSession session, UpdateResult ur, MessageResult mr) + public async Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult mr) { var update = ur.RawData; - if (update.Type != Telegram.Bot.Types.Enums.UpdateType.Message - && update.Type != Telegram.Bot.Types.Enums.UpdateType.EditedMessage - && update.Type != Telegram.Bot.Types.Enums.UpdateType.CallbackQuery) + if (update.Type != UpdateType.Message + && update.Type != UpdateType.EditedMessage + && update.Type != UpdateType.CallbackQuery) { return; } //Is this a bot command ? - if (mr.IsFirstHandler && mr.IsBotCommand && Bot.IsKnownBotCommand(mr.BotCommand)) + if (mr.IsFirstHandler && mr.IsBotCommand && bot.IsKnownBotCommand(mr.BotCommand)) { var sce = new BotCommandEventArgs(mr.BotCommand, mr.BotCommandParameters, mr.Message, session.DeviceId, session); - await Bot.OnBotCommand(sce); + await bot.OnBotCommand(sce); if (sce.Handled) return; @@ -64,14 +55,14 @@ namespace TelegramBotBase.MessageLoops //Is Attachment ? (Photo, Audio, Video, Contact, Location, Document) (Ignore Callback Queries) - if (update.Type == Telegram.Bot.Types.Enums.UpdateType.Message) + if (update.Type == UpdateType.Message) { - if (mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Contact - | mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Document - | mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Location - | mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Photo - | mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Video - | mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Audio) + if (mr.MessageType == MessageType.Contact + | mr.MessageType == MessageType.Document + | mr.MessageType == MessageType.Location + | mr.MessageType == MessageType.Photo + | mr.MessageType == MessageType.Video + | mr.MessageType == MessageType.Audio) { await activeForm.SentData(new DataResult(ur)); } @@ -118,19 +109,13 @@ namespace TelegramBotBase.MessageLoops ///
public event EventHandler UnhandledCall { - add - { - this.__Events.AddHandler(__evUnhandledCall, value); - } - remove - { - this.__Events.RemoveHandler(__evUnhandledCall, value); - } + add => _events.AddHandler(EvUnhandledCall, value); + remove => _events.RemoveHandler(EvUnhandledCall, value); } public void OnUnhandledCall(UnhandledCallEventArgs e) { - (this.__Events[__evUnhandledCall] as EventHandler)?.Invoke(this, e); + (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); } } diff --git a/TelegramBotBase/MessageLoops/FullMessageLoop.cs b/TelegramBotBase/MessageLoops/FullMessageLoop.cs index 63e8160..1277094 100644 --- a/TelegramBotBase/MessageLoops/FullMessageLoop.cs +++ b/TelegramBotBase/MessageLoops/FullMessageLoop.cs @@ -1,13 +1,9 @@ using System; -using System.Collections.Generic; using System.ComponentModel; -using System.Linq; -using System.Text; using System.Threading.Tasks; -using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; using TelegramBotBase.Args; using TelegramBotBase.Base; -using TelegramBotBase.Enums; using TelegramBotBase.Interfaces; using TelegramBotBase.Sessions; @@ -18,25 +14,20 @@ namespace TelegramBotBase.MessageLoops ///
public class FullMessageLoop : IMessageLoopFactory { - private static object __evUnhandledCall = new object(); + private static readonly object EvUnhandledCall = new object(); - private EventHandlerList __Events = new EventHandlerList(); + private readonly EventHandlerList _events = new EventHandlerList(); - public FullMessageLoop() - { - - } - - public async Task MessageLoop(BotBase Bot, DeviceSession session, UpdateResult ur, MessageResult mr) + public async Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult mr) { var update = ur.RawData; //Is this a bot command ? - if (mr.IsFirstHandler && mr.IsBotCommand && Bot.IsKnownBotCommand(mr.BotCommand)) + if (mr.IsFirstHandler && mr.IsBotCommand && bot.IsKnownBotCommand(mr.BotCommand)) { var sce = new BotCommandEventArgs(mr.BotCommand, mr.BotCommandParameters, mr.Message, session.DeviceId, session); - await Bot.OnBotCommand(sce); + await bot.OnBotCommand(sce); if (sce.Handled) return; @@ -57,14 +48,14 @@ namespace TelegramBotBase.MessageLoops //Is Attachment ? (Photo, Audio, Video, Contact, Location, Document) (Ignore Callback Queries) - if (update.Type == Telegram.Bot.Types.Enums.UpdateType.Message) + if (update.Type == UpdateType.Message) { - if (mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Contact - | mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Document - | mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Location - | mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Photo - | mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Video - | mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Audio) + if (mr.MessageType == MessageType.Contact + | mr.MessageType == MessageType.Document + | mr.MessageType == MessageType.Location + | mr.MessageType == MessageType.Photo + | mr.MessageType == MessageType.Video + | mr.MessageType == MessageType.Audio) { await activeForm.SentData(new DataResult(ur)); } @@ -111,19 +102,13 @@ namespace TelegramBotBase.MessageLoops ///
public event EventHandler UnhandledCall { - add - { - this.__Events.AddHandler(__evUnhandledCall, value); - } - remove - { - this.__Events.RemoveHandler(__evUnhandledCall, value); - } + add => _events.AddHandler(EvUnhandledCall, value); + remove => _events.RemoveHandler(EvUnhandledCall, value); } public void OnUnhandledCall(UnhandledCallEventArgs e) { - (this.__Events[__evUnhandledCall] as EventHandler)?.Invoke(this, e); + (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); } } diff --git a/TelegramBotBase/MessageLoops/MinimalMessageLoop.cs b/TelegramBotBase/MessageLoops/MinimalMessageLoop.cs index 0be394b..2483668 100644 --- a/TelegramBotBase/MessageLoops/MinimalMessageLoop.cs +++ b/TelegramBotBase/MessageLoops/MinimalMessageLoop.cs @@ -1,13 +1,8 @@ using System; -using System.Collections.Generic; using System.ComponentModel; -using System.Linq; -using System.Text; using System.Threading.Tasks; -using Telegram.Bot.Types; using TelegramBotBase.Args; using TelegramBotBase.Base; -using TelegramBotBase.Enums; using TelegramBotBase.Interfaces; using TelegramBotBase.Sessions; @@ -18,16 +13,11 @@ namespace TelegramBotBase.MessageLoops ///
public class MinimalMessageLoop : IMessageLoopFactory { - private static object __evUnhandledCall = new object(); + private static readonly object EvUnhandledCall = new object(); - private EventHandlerList __Events = new EventHandlerList(); + private readonly EventHandlerList _events = new EventHandlerList(); - public MinimalMessageLoop() - { - - } - - public async Task MessageLoop(BotBase Bot, DeviceSession session, UpdateResult ur, MessageResult mr) + public async Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult mr) { var update = ur.RawData; @@ -46,19 +36,13 @@ namespace TelegramBotBase.MessageLoops ///
public event EventHandler UnhandledCall { - add - { - this.__Events.AddHandler(__evUnhandledCall, value); - } - remove - { - this.__Events.RemoveHandler(__evUnhandledCall, value); - } + add => _events.AddHandler(EvUnhandledCall, value); + remove => _events.RemoveHandler(EvUnhandledCall, value); } public void OnUnhandledCall(UnhandledCallEventArgs e) { - (this.__Events[__evUnhandledCall] as EventHandler)?.Invoke(this, e); + (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); } } diff --git a/TelegramBotBase/Properties/AssemblyInfo.cs b/TelegramBotBase/Properties/AssemblyInfo.cs index 23bb4de..14bc370 100644 --- a/TelegramBotBase/Properties/AssemblyInfo.cs +++ b/TelegramBotBase/Properties/AssemblyInfo.cs @@ -1,5 +1,4 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden diff --git a/TelegramBotBase/SessionBase.cs b/TelegramBotBase/SessionBase.cs index b94f59a..66ac76d 100644 --- a/TelegramBotBase/SessionBase.cs +++ b/TelegramBotBase/SessionBase.cs @@ -1,9 +1,7 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; -using System.Runtime.Serialization; -using System.Text; +using System.Reflection; using System.Threading.Tasks; using TelegramBotBase.Args; using TelegramBotBase.Attributes; @@ -11,6 +9,8 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; using TelegramBotBase.Interfaces; using TelegramBotBase.Sessions; +using TelegramBotBase.Tools; + namespace TelegramBotBase { /// @@ -37,7 +37,7 @@ namespace TelegramBotBase public SessionBase() { - this.SessionList = new Dictionary(); + SessionList = new Dictionary(); } /// @@ -47,14 +47,8 @@ namespace TelegramBotBase /// public DeviceSession this[long key] { - get - { - return this.SessionList[key]; - } - set - { - this.SessionList[key] = value; - } + get => SessionList[key]; + set => SessionList[key] = value; } /// @@ -64,7 +58,7 @@ namespace TelegramBotBase /// public DeviceSession GetSession(long deviceId) { - DeviceSession ds = this.SessionList.FirstOrDefault(a => a.Key == deviceId).Value ?? null; + var ds = SessionList.FirstOrDefault(a => a.Key == deviceId).Value ?? null; return ds; } @@ -77,16 +71,15 @@ namespace TelegramBotBase public async Task StartSession(long deviceId) { var start = BotBase.StartFormFactory.CreateForm(); - //T start = typeof(T).GetConstructor(new Type[] { }).Invoke(new object[] { }) as T; - start.Client = this.Client; + start.Client = Client; - DeviceSession ds = new Sessions.DeviceSession(deviceId, start); + var ds = new DeviceSession(deviceId, start); start.Device = ds; await start.OnInit(new InitEventArgs()); - await start.OnOpened(new EventArgs()); + await start.OnOpened(EventArgs.Empty); this[deviceId] = ds; return ds; @@ -101,7 +94,7 @@ namespace TelegramBotBase var d = this[deviceId]; if (d != null) { - this.SessionList.Remove(deviceId); + SessionList.Remove(deviceId); } } @@ -112,7 +105,7 @@ namespace TelegramBotBase /// public List GetUserSessions() { - return this.SessionList.Where(a => a.Key > 0).Select(a => a.Value).ToList(); + return SessionList.Where(a => a.Key > 0).Select(a => a.Value).ToList(); } /// @@ -121,7 +114,7 @@ namespace TelegramBotBase /// public List GetGroupSessions() { - return this.SessionList.Where(a => a.Key < 0).Select(a => a.Value).ToList(); + return SessionList.Where(a => a.Key < 0).Select(a => a.Value).ToList(); } /// @@ -152,20 +145,18 @@ namespace TelegramBotBase foreach (var s in container.States) { - Type t = Type.GetType(s.QualifiedName); + var t = Type.GetType(s.QualifiedName); if (t == null || !t.IsSubclassOf(typeof(FormBase))) { continue; } //Key already existing - if (this.SessionList.ContainsKey(s.DeviceId)) + if (SessionList.ContainsKey(s.DeviceId)) continue; - var form = t.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as FormBase; - //No default constructor, fallback - if (form == null) + if (!(t.GetConstructor(new Type[] { })?.Invoke(new object[] { }) is FormBase form)) { if (!statemachine.FallbackStateForm.IsSubclassOf(typeof(FormBase))) continue; @@ -182,7 +173,7 @@ namespace TelegramBotBase if (s.Values != null && s.Values.Count > 0) { var properties = s.Values.Where(a => a.Key.StartsWith("$")); - var fields = form.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); + var fields = form.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); foreach (var p in properties) { @@ -204,10 +195,10 @@ namespace TelegramBotBase f.SetValue(form, p.Value); } - catch (ArgumentException ex) + catch (ArgumentException) { - Tools.Conversion.CustomConversionChecks(form, p, f); + Conversion.CustomConversionChecks(form, p, f); } catch @@ -218,18 +209,20 @@ namespace TelegramBotBase } form.Client = Client; - var device = new DeviceSession(s.DeviceId, form); + var device = new DeviceSession(s.DeviceId, form) + { + ChatTitle = s.ChatTitle + }; - device.ChatTitle = s.ChatTitle; - - this.SessionList.Add(s.DeviceId, device); + SessionList.Add(s.DeviceId, device); //Is Subclass of IStateForm - var iform = form as IStateForm; - if (iform != null) + if (form is IStateForm iform) { - var ls = new LoadStateEventArgs(); - ls.Values = s.Values; + var ls = new LoadStateEventArgs + { + Values = s.Values + }; iform.LoadState(ls); } @@ -237,12 +230,12 @@ namespace TelegramBotBase { await form.OnInit(new InitEventArgs()); - await form.OnOpened(new EventArgs()); + await form.OnOpened(EventArgs.Empty); } catch { //Skip on exception - this.SessionList.Remove(s.DeviceId); + SessionList.Remove(s.DeviceId); } } @@ -263,7 +256,7 @@ namespace TelegramBotBase var states = new List(); - foreach (var s in this.SessionList) + foreach (var s in SessionList) { if (s.Value == null) { @@ -274,11 +267,13 @@ namespace TelegramBotBase try { - var se = new StateEntry(); - se.DeviceId = s.Key; - se.ChatTitle = s.Value.GetChatTitle(); - se.FormUri = form.GetType().FullName; - se.QualifiedName = form.GetType().AssemblyQualifiedName; + var se = new StateEntry + { + DeviceId = s.Key, + ChatTitle = s.Value.GetChatTitle(), + FormUri = form.GetType().FullName, + QualifiedName = form.GetType().AssemblyQualifiedName + }; //Skip classes where IgnoreState attribute is existing if (form.GetType().GetCustomAttributes(typeof(IgnoreState), true).Length != 0) @@ -295,18 +290,17 @@ namespace TelegramBotBase } //Is Subclass of IStateForm - var iform = form as IStateForm; - if (iform != null) + if (form is IStateForm iform) { //Loading Session states - SaveStateEventArgs ssea = new SaveStateEventArgs(); + var ssea = new SaveStateEventArgs(); iform.SaveState(ssea); se.Values = ssea.Values; } //Search for public properties with SaveState attribute - var fields = form.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); + var fields = form.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); foreach (var f in fields) { @@ -320,12 +314,13 @@ namespace TelegramBotBase catch { //Continue on error (skip this form) - continue; } } - var sc = new StateContainer(); - sc.States = states; + var sc = new StateContainer + { + States = states + }; statemachine.SaveFormStates(new SaveStatesEventArgs(sc)); } @@ -335,11 +330,11 @@ namespace TelegramBotBase /// public void SaveSessionStates() { - if (this.BotBase.StateMachine == null) + if (BotBase.StateMachine == null) return; - this.SaveSessionStates(this.BotBase.StateMachine); + SaveSessionStates(BotBase.StateMachine); } } } diff --git a/TelegramBotBase/Sessions/DeviceSession.cs b/TelegramBotBase/Sessions/DeviceSession.cs index 17d52e8..5c017c0 100644 --- a/TelegramBotBase/Sessions/DeviceSession.cs +++ b/TelegramBotBase/Sessions/DeviceSession.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; @@ -34,13 +33,13 @@ namespace TelegramBotBase.Sessions /// /// Username of user or group /// - public String ChatTitle { get; set; } + public string ChatTitle { get; set; } /// /// Returns the ChatTitle depending on groups/channels or users /// /// - public String GetChatTitle() + public string GetChatTitle() { return LastMessage?.Chat.Title ?? LastMessage?.Chat.Username @@ -71,70 +70,46 @@ namespace TelegramBotBase.Sessions /// /// Returns the ID of the last received message. /// - public int LastMessageId - { - get - { - return this.LastMessage?.MessageId ?? -1; - } - } + public int LastMessageId => LastMessage?.MessageId ?? -1; /// /// Returns the last received message. /// public Message LastMessage { get; set; } - public MessageClient Client - { - get - { - return this.ActiveForm.Client; - } - } + public MessageClient Client => ActiveForm.Client; /// /// Returns if the messages is posted within a group. /// - public bool IsGroup - { - get - { - return this.LastMessage != null && (this.LastMessage.Chat.Type == ChatType.Group | this.LastMessage.Chat.Type == ChatType.Supergroup); - } - } + public bool IsGroup => LastMessage != null && (LastMessage.Chat.Type == ChatType.Group | LastMessage.Chat.Type == ChatType.Supergroup); /// /// Returns if the messages is posted within a channel. /// - public bool IsChannel - { - get - { - return this.LastMessage != null && this.LastMessage.Chat.Type == ChatType.Channel; - } - } + public bool IsChannel => LastMessage != null && LastMessage.Chat.Type == ChatType.Channel; - private EventHandlerList __Events = new EventHandlerList(); + private readonly EventHandlerList _events = new EventHandlerList(); - private static object __evMessageSent = new object(); - private static object __evMessageReceived = new object(); - private static object __evMessageDeleted = new object(); + private static readonly object EvMessageSent = new object(); + private static readonly object EvMessageReceived = new object(); + private static readonly object EvMessageDeleted = new object(); public DeviceSession() { } - public DeviceSession(long DeviceId) + public DeviceSession(long deviceId) { - this.DeviceId = DeviceId; + this.DeviceId = deviceId; } - public DeviceSession(long DeviceId, FormBase StartForm) + public DeviceSession(long deviceId, FormBase startForm) { - this.DeviceId = DeviceId; - this.ActiveForm = StartForm; - this.ActiveForm.Device = this; + this.DeviceId = deviceId; + ActiveForm = startForm; + ActiveForm.Device = this; } @@ -143,11 +118,11 @@ namespace TelegramBotBase.Sessions /// /// /// - public async Task ConfirmAction(String CallbackQueryId, String message = "", bool showAlert = false, String urlToOpen = null) + public async Task ConfirmAction(string callbackQueryId, string message = "", bool showAlert = false, string urlToOpen = null) { try { - await this.Client.TelegramClient.AnswerCallbackQueryAsync(CallbackQueryId, message, showAlert, urlToOpen); + await Client.TelegramClient.AnswerCallbackQueryAsync(callbackQueryId, message, showAlert, urlToOpen); } catch { @@ -162,7 +137,7 @@ namespace TelegramBotBase.Sessions /// /// /// - public async Task Edit(int messageId, String text, ButtonForm buttons = null, ParseMode parseMode = ParseMode.Markdown) + public async Task Edit(int messageId, string text, ButtonForm buttons = null, ParseMode parseMode = ParseMode.Markdown) { InlineKeyboardMarkup markup = buttons; @@ -173,7 +148,7 @@ namespace TelegramBotBase.Sessions try { - return await API(a => a.EditMessageTextAsync(this.DeviceId, messageId, text, parseMode, replyMarkup: markup)); + return await Api(a => a.EditMessageTextAsync(DeviceId, messageId, text, parseMode, replyMarkup: markup)); } catch { @@ -191,7 +166,7 @@ namespace TelegramBotBase.Sessions /// /// /// - public async Task Edit(int messageId, String text, InlineKeyboardMarkup markup, ParseMode parseMode = ParseMode.Markdown) + public async Task Edit(int messageId, string text, InlineKeyboardMarkup markup, ParseMode parseMode = ParseMode.Markdown) { if (text.Length > Constants.Telegram.MaxMessageLength) { @@ -200,7 +175,7 @@ namespace TelegramBotBase.Sessions try { - return await API(a => a.EditMessageTextAsync(this.DeviceId, messageId, text, parseMode, replyMarkup: markup)); + return await Api(a => a.EditMessageTextAsync(DeviceId, messageId, text, parseMode, replyMarkup: markup)); } catch { @@ -229,7 +204,7 @@ namespace TelegramBotBase.Sessions try { - return await API(a => a.EditMessageTextAsync(this.DeviceId, message.MessageId, message.Text, parseMode, replyMarkup: markup)); + return await Api(a => a.EditMessageTextAsync(DeviceId, message.MessageId, message.Text, parseMode, replyMarkup: markup)); } catch { @@ -251,7 +226,7 @@ namespace TelegramBotBase.Sessions try { - return await API(a => a.EditMessageReplyMarkupAsync(this.DeviceId, messageId, bf)); + return await Api(a => a.EditMessageReplyMarkupAsync(DeviceId, messageId, bf)); } catch { @@ -269,9 +244,9 @@ namespace TelegramBotBase.Sessions /// /// /// - public async Task Send(long deviceId, String text, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool MarkdownV2AutoEscape = true) + public async Task Send(long deviceId, string text, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool markdownV2AutoEscape = true) { - if (this.ActiveForm == null) + if (ActiveForm == null) return null; InlineKeyboardMarkup markup = buttons; @@ -281,17 +256,17 @@ namespace TelegramBotBase.Sessions throw new MaxLengthException(text.Length); } - if (parseMode == ParseMode.MarkdownV2 && MarkdownV2AutoEscape) + if (parseMode == ParseMode.MarkdownV2 && markdownV2AutoEscape) { text = text.MarkdownV2Escape(); } try { - var t = API(a => a.SendTextMessageAsync(deviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); + var t = Api(a => a.SendTextMessageAsync(deviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); var o = GetOrigin(new StackTrace()); - + await OnMessageSent(new MessageSentEventArgs(await t, o)); return await t; @@ -310,9 +285,9 @@ namespace TelegramBotBase.Sessions /// /// /// - public async Task Send(String text, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool MarkdownV2AutoEscape = true) + public async Task Send(string text, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool markdownV2AutoEscape = true) { - return await Send(this.DeviceId, text, buttons, replyTo, disableNotification, parseMode, MarkdownV2AutoEscape); + return await Send(DeviceId, text, buttons, replyTo, disableNotification, parseMode, markdownV2AutoEscape); } /// @@ -323,9 +298,9 @@ namespace TelegramBotBase.Sessions /// /// /// - public async Task Send(String text, InlineKeyboardMarkup markup, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool MarkdownV2AutoEscape = true) + public async Task Send(string text, InlineKeyboardMarkup markup, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool markdownV2AutoEscape = true) { - if (this.ActiveForm == null) + if (ActiveForm == null) return null; if (text.Length > Constants.Telegram.MaxMessageLength) @@ -333,14 +308,14 @@ namespace TelegramBotBase.Sessions throw new MaxLengthException(text.Length); } - if (parseMode == ParseMode.MarkdownV2 && MarkdownV2AutoEscape) + if (parseMode == ParseMode.MarkdownV2 && markdownV2AutoEscape) { text = text.MarkdownV2Escape(); } try { - var t = API(a => a.SendTextMessageAsync(this.DeviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); + var t = Api(a => a.SendTextMessageAsync(DeviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); var o = GetOrigin(new StackTrace()); await OnMessageSent(new MessageSentEventArgs(await t, o)); @@ -361,9 +336,9 @@ namespace TelegramBotBase.Sessions /// /// /// - public async Task Send(String text, ReplyMarkupBase markup, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool MarkdownV2AutoEscape = true) + public async Task Send(string text, ReplyMarkupBase markup, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool markdownV2AutoEscape = true) { - if (this.ActiveForm == null) + if (ActiveForm == null) return null; if (text.Length > Constants.Telegram.MaxMessageLength) @@ -371,14 +346,14 @@ namespace TelegramBotBase.Sessions throw new MaxLengthException(text.Length); } - if (parseMode == ParseMode.MarkdownV2 && MarkdownV2AutoEscape) + if (parseMode == ParseMode.MarkdownV2 && markdownV2AutoEscape) { text = text.MarkdownV2Escape(); } try { - var t = API(a => a.SendTextMessageAsync(this.DeviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); + var t = Api(a => a.SendTextMessageAsync(DeviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); var o = GetOrigin(new StackTrace()); await OnMessageSent(new MessageSentEventArgs(await t, o)); @@ -399,16 +374,16 @@ namespace TelegramBotBase.Sessions /// /// /// - public async Task SendPhoto(InputOnlineFile file, String caption = null, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) + public async Task SendPhoto(InputOnlineFile file, string caption = null, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) { - if (this.ActiveForm == null) + if (ActiveForm == null) return null; InlineKeyboardMarkup markup = buttons; try { - var t = API(a => a.SendPhotoAsync(this.DeviceId, file, caption: caption, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); + var t = Api(a => a.SendPhotoAsync(DeviceId, file, caption: caption, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); var o = GetOrigin(new StackTrace()); await OnMessageSent(new MessageSentEventArgs(await t, o)); @@ -429,16 +404,16 @@ namespace TelegramBotBase.Sessions /// /// /// - public async Task SendVideo(InputOnlineFile file, String caption = null, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) + public async Task SendVideo(InputOnlineFile file, string caption = null, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) { - if (this.ActiveForm == null) + if (ActiveForm == null) return null; InlineKeyboardMarkup markup = buttons; try { - var t = API(a => a.SendVideoAsync(this.DeviceId, file, caption: caption, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); + var t = Api(a => a.SendVideoAsync(DeviceId, file, caption: caption, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); var o = GetOrigin(new StackTrace()); await OnMessageSent(new MessageSentEventArgs(await t, o)); @@ -459,16 +434,16 @@ namespace TelegramBotBase.Sessions /// /// /// - public async Task SendVideo(String url, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) + public async Task SendVideo(string url, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) { - if (this.ActiveForm == null) + if (ActiveForm == null) return null; InlineKeyboardMarkup markup = buttons; try { - var t = API(a => a.SendVideoAsync(this.DeviceId, new InputOnlineFile(url), parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); + var t = Api(a => a.SendVideoAsync(DeviceId, new InputOnlineFile(url), parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); var o = GetOrigin(new StackTrace()); await OnMessageSent(new MessageSentEventArgs(await t, o)); @@ -490,20 +465,20 @@ namespace TelegramBotBase.Sessions /// /// /// - public async Task SendVideo(String filename, byte[] video, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) + public async Task SendVideo(string filename, byte[] video, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) { - if (this.ActiveForm == null) + if (ActiveForm == null) return null; InlineKeyboardMarkup markup = buttons; try { - MemoryStream ms = new MemoryStream(video); + var ms = new MemoryStream(video); - InputOnlineFile fts = new InputOnlineFile(ms, filename); + var fts = new InputOnlineFile(ms, filename); - var t = API(a => a.SendVideoAsync(this.DeviceId, fts, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); + var t = Api(a => a.SendVideoAsync(DeviceId, fts, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); var o = GetOrigin(new StackTrace()); await OnMessageSent(new MessageSentEventArgs(await t, o)); @@ -525,22 +500,22 @@ namespace TelegramBotBase.Sessions /// /// /// - public async Task SendLocalVideo(String filepath, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) + public async Task SendLocalVideo(string filepath, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) { - if (this.ActiveForm == null) + if (ActiveForm == null) return null; InlineKeyboardMarkup markup = buttons; try { - FileStream fs = new FileStream(filepath, FileMode.Open); + var fs = new FileStream(filepath, FileMode.Open); var filename = Path.GetFileName(filepath); - InputOnlineFile fts = new InputOnlineFile(fs, filename); + var fts = new InputOnlineFile(fs, filename); - var t = API(a => a.SendVideoAsync(this.DeviceId, fts, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); + var t = Api(a => a.SendVideoAsync(DeviceId, fts, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); var o = GetOrigin(new StackTrace()); await OnMessageSent(new MessageSentEventArgs(await t, o)); @@ -563,11 +538,11 @@ namespace TelegramBotBase.Sessions /// /// /// - public async Task SendDocument(String filename, byte[] document, String caption = "", ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) + public async Task SendDocument(string filename, byte[] document, string caption = "", ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) { - MemoryStream ms = new MemoryStream(document); + var ms = new MemoryStream(document); - InputOnlineFile fts = new InputOnlineFile(ms, filename); + var fts = new InputOnlineFile(ms, filename); return await SendDocument(fts, caption, buttons, replyTo, disableNotification); } @@ -583,7 +558,7 @@ namespace TelegramBotBase.Sessions /// /// /// - public async Task SendTextFile(String filename, String textcontent, Encoding encoding = null, String caption = "", ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) + public async Task SendTextFile(string filename, string textcontent, Encoding encoding = null, string caption = "", ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) { encoding = encoding ?? Encoding.UTF8; @@ -607,7 +582,7 @@ namespace TelegramBotBase.Sessions /// /// /// - public async Task SendDocument(InputOnlineFile document, String caption = "", ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) + public async Task SendDocument(InputOnlineFile document, string caption = "", ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) { InlineKeyboardMarkup markup = null; if (buttons != null) @@ -617,7 +592,7 @@ namespace TelegramBotBase.Sessions try { - var t = API(a => a.SendDocumentAsync(this.DeviceId, document, caption, replyMarkup: markup, disableNotification: disableNotification, replyToMessageId: replyTo)); + var t = Api(a => a.SendDocumentAsync(DeviceId, document, caption, replyMarkup: markup, disableNotification: disableNotification, replyToMessageId: replyTo)); var o = GetOrigin(new StackTrace()); await OnMessageSent(new MessageSentEventArgs(await t, o)); @@ -637,7 +612,7 @@ namespace TelegramBotBase.Sessions /// public async Task SetAction(ChatAction action) { - await API(a => a.SendChatActionAsync(this.DeviceId, action)); + await Api(a => a.SendChatActionAsync(DeviceId, action)); } /// @@ -645,13 +620,15 @@ namespace TelegramBotBase.Sessions /// /// /// - /// + /// /// - public async Task RequestContact(String buttonText = "Send your contact", String requestMessage = "Give me your phone number!", bool OneTimeOnly = true) + public async Task RequestContact(string buttonText = "Send your contact", string requestMessage = "Give me your phone number!", bool oneTimeOnly = true) { - var rck = new ReplyKeyboardMarkup(KeyboardButton.WithRequestContact(buttonText)); - rck.OneTimeKeyboard = OneTimeOnly; - return await API(a => a.SendTextMessageAsync(this.DeviceId, requestMessage, replyMarkup: rck)); + var rck = new ReplyKeyboardMarkup(KeyboardButton.WithRequestContact(buttonText)) + { + OneTimeKeyboard = oneTimeOnly + }; + return await Api(a => a.SendTextMessageAsync(DeviceId, requestMessage, replyMarkup: rck)); } /// @@ -659,24 +636,26 @@ namespace TelegramBotBase.Sessions /// /// /// - /// + /// /// - public async Task RequestLocation(String buttonText = "Send your location", String requestMessage = "Give me your location!", bool OneTimeOnly = true) + public async Task RequestLocation(string buttonText = "Send your location", string requestMessage = "Give me your location!", bool oneTimeOnly = true) { - var rcl = new ReplyKeyboardMarkup(KeyboardButton.WithRequestLocation(buttonText)); - rcl.OneTimeKeyboard = OneTimeOnly; - return await API(a => a.SendTextMessageAsync(this.DeviceId, requestMessage, replyMarkup: rcl)); + var rcl = new ReplyKeyboardMarkup(KeyboardButton.WithRequestLocation(buttonText)) + { + OneTimeKeyboard = oneTimeOnly + }; + return await Api(a => a.SendTextMessageAsync(DeviceId, requestMessage, replyMarkup: rcl)); } - public async Task HideReplyKeyboard(String closedMsg = "Closed", bool autoDeleteResponse = true) + public async Task HideReplyKeyboard(string closedMsg = "Closed", bool autoDeleteResponse = true) { try { - var m = await this.Send(closedMsg, new ReplyKeyboardRemove()); + var m = await Send(closedMsg, new ReplyKeyboardRemove()); if (autoDeleteResponse && m != null) { - await this.DeleteMessage(m); + await DeleteMessage(m); } return m; @@ -696,7 +675,7 @@ namespace TelegramBotBase.Sessions public virtual async Task DeleteMessage(int messageId = -1) { - await RAW(a => a.DeleteMessageAsync(this.DeviceId, messageId)); + await Raw(a => a.DeleteMessageAsync(DeviceId, messageId)); OnMessageDeleted(new MessageDeletedEventArgs(messageId)); @@ -718,7 +697,7 @@ namespace TelegramBotBase.Sessions { try { - await API(a => a.SetChatPermissionsAsync(this.DeviceId, permissions)); + await Api(a => a.SetChatPermissionsAsync(DeviceId, permissions)); } catch { @@ -728,7 +707,7 @@ namespace TelegramBotBase.Sessions private Type GetOrigin(StackTrace stackTrace) { - for (int i = 0; i < stackTrace.FrameCount; i++) + for (var i = 0; i < stackTrace.FrameCount; i++) { var methodBase = stackTrace.GetFrame(i).GetMethod(); @@ -749,7 +728,7 @@ namespace TelegramBotBase.Sessions { try { - await API(a => a.RestrictChatMemberAsync(this.DeviceId, userId, permissions, until)); + await Api(a => a.RestrictChatMemberAsync(DeviceId, userId, permissions, until)); } catch { @@ -761,7 +740,7 @@ namespace TelegramBotBase.Sessions { try { - return await API(a => a.GetChatMemberAsync(this.DeviceId, userId)); + return await Api(a => a.GetChatMemberAsync(DeviceId, userId)); } catch { @@ -775,7 +754,7 @@ namespace TelegramBotBase.Sessions { try { - await API(a => a.BanChatMemberAsync(this.DeviceId, userId, until)); + await Api(a => a.BanChatMemberAsync(DeviceId, userId, until)); } catch { @@ -787,7 +766,7 @@ namespace TelegramBotBase.Sessions { try { - await API(a => a.BanChatMemberAsync(this.DeviceId, userId, until)); + await Api(a => a.BanChatMemberAsync(DeviceId, userId, until)); } catch { @@ -799,7 +778,7 @@ namespace TelegramBotBase.Sessions { try { - await API(a => a.UnbanChatMemberAsync(this.DeviceId, userId)); + await Api(a => a.UnbanChatMemberAsync(DeviceId, userId)); } catch { @@ -815,9 +794,9 @@ namespace TelegramBotBase.Sessions /// /// /// - public T RAW(Func call) + public T Raw(Func call) { - return call(this.Client.TelegramClient); + return call(Client.TelegramClient); } /// @@ -826,10 +805,10 @@ namespace TelegramBotBase.Sessions /// /// /// - public async Task API(Func> call) + public async Task Api(Func> call) { var numberOfTries = 0; - while (numberOfTries < DeviceSession.MaxNumberOfRetries) + while (numberOfTries < MaxNumberOfRetries) { try { @@ -854,10 +833,10 @@ namespace TelegramBotBase.Sessions /// /// /// - public async Task API(Func call) + public async Task Api(Func call) { var numberOfTries = 0; - while (numberOfTries < DeviceSession.MaxNumberOfRetries) + while (numberOfTries < MaxNumberOfRetries) { try { @@ -883,16 +862,10 @@ namespace TelegramBotBase.Sessions /// /// Eventhandler for sent messages /// - public event Base.Async.AsyncEventHandler MessageSent + public event Async.AsyncEventHandler MessageSent { - add - { - this.__Events.AddHandler(__evMessageSent, value); - } - remove - { - this.__Events.RemoveHandler(__evMessageSent, value); - } + add => _events.AddHandler(EvMessageSent, value); + remove => _events.RemoveHandler(EvMessageSent, value); } @@ -900,14 +873,14 @@ namespace TelegramBotBase.Sessions { if (e.Message == null) return; - - var handler = this.__Events[__evMessageSent]?.GetInvocationList().Cast>(); + + var handler = _events[EvMessageSent]?.GetInvocationList().Cast>(); if (handler == null) return; foreach (var h in handler) { - await Base.Async.InvokeAllAsync(h, this, e); + await h.InvokeAllAsync(this, e); } //(this.__Events[__evMessageSent] as EventHandler)?.Invoke(this, e); @@ -918,20 +891,14 @@ namespace TelegramBotBase.Sessions /// public event EventHandler MessageReceived { - add - { - this.__Events.AddHandler(__evMessageReceived, value); - } - remove - { - this.__Events.RemoveHandler(__evMessageReceived, value); - } + add => _events.AddHandler(EvMessageReceived, value); + remove => _events.RemoveHandler(EvMessageReceived, value); } public void OnMessageReceived(MessageReceivedEventArgs e) { - (this.__Events[__evMessageReceived] as EventHandler)?.Invoke(this, e); + (_events[EvMessageReceived] as EventHandler)?.Invoke(this, e); } /// @@ -939,20 +906,14 @@ namespace TelegramBotBase.Sessions /// public event EventHandler MessageDeleted { - add - { - this.__Events.AddHandler(__evMessageDeleted, value); - } - remove - { - this.__Events.RemoveHandler(__evMessageDeleted, value); - } + add => _events.AddHandler(EvMessageDeleted, value); + remove => _events.RemoveHandler(EvMessageDeleted, value); } public void OnMessageDeleted(MessageDeletedEventArgs e) { - (this.__Events[__evMessageDeleted] as EventHandler)?.Invoke(this, e); + (_events[EvMessageDeleted] as EventHandler)?.Invoke(this, e); } #endregion @@ -960,7 +921,7 @@ namespace TelegramBotBase.Sessions #region "Static" /// - /// Indicates the maximum number of times a request that received error + /// Indicates the maximum number of times a request that received error /// 429 will be sent again after a timeout until it receives code 200 or an error code not equal to 429. /// public static uint MaxNumberOfRetries { get; set; } diff --git a/TelegramBotBase/States/JSONStateMachine.cs b/TelegramBotBase/States/JSONStateMachine.cs index 7035692..944caf0 100644 --- a/TelegramBotBase/States/JSONStateMachine.cs +++ b/TelegramBotBase/States/JSONStateMachine.cs @@ -1,8 +1,6 @@ -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Runtime.Serialization.Formatters; -using System.Text; +using System; +using System.IO; +using Newtonsoft.Json; using TelegramBotBase.Args; using TelegramBotBase.Base; using TelegramBotBase.Form; @@ -13,9 +11,9 @@ namespace TelegramBotBase.States /// /// Is used for all complex data types. Use if other default machines are not working. /// - public class JSONStateMachine : IStateMachine + public class JsonStateMachine : IStateMachine { - public String FilePath { get; set; } + public string FilePath { get; set; } public bool Overwrite { get; set; } @@ -27,35 +25,30 @@ namespace TelegramBotBase.States /// Path of the file and name where to save the session details. /// Type of Form which will be saved instead of Form which has attribute declared. Needs to be subclass of . /// Declares of the file could be overwritten. - public JSONStateMachine(String file, Type fallbackStateForm = null, bool overwrite = true) + public JsonStateMachine(string file, Type fallbackStateForm = null, bool overwrite = true) { - if (file is null) - { - throw new ArgumentNullException(nameof(file)); - } + FallbackStateForm = fallbackStateForm; - this.FallbackStateForm = fallbackStateForm; - - if (this.FallbackStateForm != null && !this.FallbackStateForm.IsSubclassOf(typeof(FormBase))) + if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase))) { throw new ArgumentException("FallbackStateForm is not a subclass of FormBase"); } - this.FilePath = file; - this.Overwrite = overwrite; + FilePath = file ?? throw new ArgumentNullException(nameof(file)); + Overwrite = overwrite; } public StateContainer LoadFormStates() { try { - var content = System.IO.File.ReadAllText(FilePath); + var content = File.ReadAllText(FilePath); - var sc = Newtonsoft.Json.JsonConvert.DeserializeObject(content, new JsonSerializerSettings + var sc = JsonConvert.DeserializeObject(content, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All, TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple - }) as StateContainer; + }); return sc; } @@ -69,25 +62,25 @@ namespace TelegramBotBase.States public void SaveFormStates(SaveStatesEventArgs e) { - if (System.IO.File.Exists(FilePath)) + if (File.Exists(FilePath)) { - if (!this.Overwrite) + if (!Overwrite) { throw new Exception("File exists already."); } - System.IO.File.Delete(FilePath); + File.Delete(FilePath); } try { - var content = Newtonsoft.Json.JsonConvert.SerializeObject(e.States, Formatting.Indented, new JsonSerializerSettings + var content = JsonConvert.SerializeObject(e.States, Formatting.Indented, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All, TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple }); - System.IO.File.WriteAllText(FilePath, content); + File.WriteAllText(FilePath, content); } catch { diff --git a/TelegramBotBase/States/SimpleJSONStateMachine.cs b/TelegramBotBase/States/SimpleJSONStateMachine.cs index faba2af..5c84456 100644 --- a/TelegramBotBase/States/SimpleJSONStateMachine.cs +++ b/TelegramBotBase/States/SimpleJSONStateMachine.cs @@ -1,8 +1,6 @@ -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Runtime.Serialization.Formatters; -using System.Text; +using System; +using System.IO; +using Newtonsoft.Json; using TelegramBotBase.Args; using TelegramBotBase.Base; using TelegramBotBase.Form; @@ -13,9 +11,9 @@ namespace TelegramBotBase.States /// /// Is used for simple object structures like classes, lists or basic datatypes without generics and other compiler based data types. /// - public class SimpleJSONStateMachine : IStateMachine + public class SimpleJsonStateMachine : IStateMachine { - public String FilePath { get; set; } + public string FilePath { get; set; } public bool Overwrite { get; set; } @@ -27,31 +25,26 @@ namespace TelegramBotBase.States /// Path of the file and name where to save the session details. /// Type of Form which will be saved instead of Form which has attribute declared. Needs to be subclass of . /// Declares of the file could be overwritten. - public SimpleJSONStateMachine(String file, Type fallbackStateForm = null, bool overwrite = true) + public SimpleJsonStateMachine(string file, Type fallbackStateForm = null, bool overwrite = true) { - if (file is null) - { - throw new ArgumentNullException(nameof(file)); - } + FallbackStateForm = fallbackStateForm; - this.FallbackStateForm = fallbackStateForm; - - if (this.FallbackStateForm != null && !this.FallbackStateForm.IsSubclassOf(typeof(FormBase))) + if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase))) { throw new ArgumentException("FallbackStateForm is not a subclass of FormBase"); } - this.FilePath = file; - this.Overwrite = overwrite; + FilePath = file ?? throw new ArgumentNullException(nameof(file)); + Overwrite = overwrite; } public StateContainer LoadFormStates() { try { - var content = System.IO.File.ReadAllText(FilePath); + var content = File.ReadAllText(FilePath); - var sc = Newtonsoft.Json.JsonConvert.DeserializeObject(content) as StateContainer; + var sc = JsonConvert.DeserializeObject(content); return sc; } @@ -65,21 +58,21 @@ namespace TelegramBotBase.States public void SaveFormStates(SaveStatesEventArgs e) { - if (System.IO.File.Exists(FilePath)) + if (File.Exists(FilePath)) { - if (!this.Overwrite) + if (!Overwrite) { throw new Exception("File exists already."); } - System.IO.File.Delete(FilePath); + File.Delete(FilePath); } try { - var content = Newtonsoft.Json.JsonConvert.SerializeObject(e.States, Formatting.Indented); + var content = JsonConvert.SerializeObject(e.States, Formatting.Indented); - System.IO.File.WriteAllText(FilePath, content); + File.WriteAllText(FilePath, content); } catch { diff --git a/TelegramBotBase/States/XMLStateMachine.cs b/TelegramBotBase/States/XMLStateMachine.cs index 2542f6a..b472d27 100644 --- a/TelegramBotBase/States/XMLStateMachine.cs +++ b/TelegramBotBase/States/XMLStateMachine.cs @@ -1,10 +1,7 @@ using System; -using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; -using System.Text; using System.Xml; -using System.Xml.Serialization; using TelegramBotBase.Args; using TelegramBotBase.Base; using TelegramBotBase.Form; @@ -12,9 +9,9 @@ using TelegramBotBase.Interfaces; namespace TelegramBotBase.States { - public class XMLStateMachine : IStateMachine + public class XmlStateMachine : IStateMachine { - public String FilePath { get; set; } + public string FilePath { get; set; } public bool Overwrite { get; set; } @@ -26,35 +23,30 @@ namespace TelegramBotBase.States /// Path of the file and name where to save the session details. /// Type of Form which will be saved instead of Form which has attribute declared. Needs to be subclass of . /// Declares of the file could be overwritten. - public XMLStateMachine(String file, Type fallbackStateForm = null, bool overwrite = true) + public XmlStateMachine(string file, Type fallbackStateForm = null, bool overwrite = true) { - if (file is null) - { - throw new ArgumentNullException(nameof(file)); - } + FallbackStateForm = fallbackStateForm; - this.FallbackStateForm = fallbackStateForm; - - if (this.FallbackStateForm != null && !this.FallbackStateForm.IsSubclassOf(typeof(FormBase))) + if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase))) { throw new ArgumentException("FallbackStateForm is not a subclass of FormBase"); } - this.FilePath = file; - this.Overwrite = overwrite; + FilePath = file ?? throw new ArgumentNullException(nameof(file)); + Overwrite = overwrite; } public StateContainer LoadFormStates() { try { - DataContractSerializer serializer = new DataContractSerializer(typeof(StateContainer)); + var serializer = new DataContractSerializer(typeof(StateContainer)); using (var reader = new StreamReader(FilePath)) { using (var xml = new XmlTextReader(reader)) { - StateContainer sc = serializer.ReadObject(xml) as StateContainer; + var sc = serializer.ReadObject(xml) as StateContainer; return sc; } } @@ -69,21 +61,21 @@ namespace TelegramBotBase.States public void SaveFormStates(SaveStatesEventArgs e) { - if (System.IO.File.Exists(FilePath)) + if (File.Exists(FilePath)) { - if (!this.Overwrite) + if (!Overwrite) { throw new Exception("File exists already."); } - System.IO.File.Delete(FilePath); + File.Delete(FilePath); } try { - DataContractSerializer serializer = new DataContractSerializer(typeof(StateContainer)); + var serializer = new DataContractSerializer(typeof(StateContainer)); - using (var sw = new StreamWriter(this.FilePath)) + using (var sw = new StreamWriter(FilePath)) { using (var writer = new XmlTextWriter(sw)) { diff --git a/TelegramBotBase/TelegramBotBase.csproj b/TelegramBotBase/TelegramBotBase.csproj index a5b9666..4203025 100644 --- a/TelegramBotBase/TelegramBotBase.csproj +++ b/TelegramBotBase/TelegramBotBase.csproj @@ -2,6 +2,7 @@ netstandard2.0;net5;netcoreapp3.1;net6 + 9 false False true @@ -17,8 +18,6 @@ true snupkg $(VersionPrefix) - - portable @@ -62,8 +61,4 @@ - - - - diff --git a/TelegramBotBase/Tools/Arrays.cs b/TelegramBotBase/Tools/Arrays.cs index 01efa34..b3814b1 100644 --- a/TelegramBotBase/Tools/Arrays.cs +++ b/TelegramBotBase/Tools/Arrays.cs @@ -1,11 +1,4 @@ using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using TelegramBotBase.Base; -using TelegramBotBase.Form; namespace TelegramBotBase.Tools { @@ -13,7 +6,7 @@ namespace TelegramBotBase.Tools { public static T[] Shift(T[] array, int positions) { - T[] copy = new T[array.Length]; + var copy = new T[array.Length]; Array.Copy(array, 0, copy, array.Length - positions, positions); Array.Copy(array, positions, copy, 0, array.Length - positions); return copy; diff --git a/TelegramBotBase/Tools/Console.cs b/TelegramBotBase/Tools/Console.cs index a239df5..7baa187 100644 --- a/TelegramBotBase/Tools/Console.cs +++ b/TelegramBotBase/Tools/Console.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Runtime.InteropServices; -using System.Text; namespace TelegramBotBase.Tools { @@ -11,17 +10,18 @@ namespace TelegramBotBase.Tools private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add); private delegate bool EventHandler(CtrlType sig); - static EventHandler _handler; - static List Actions = new List(); + private static EventHandler __handler; - enum CtrlType + private static List __actions = new List(); + + private enum CtrlType { - CTRL_C_EVENT = 0, - CTRL_BREAK_EVENT = 1, - CTRL_CLOSE_EVENT = 2, - CTRL_LOGOFF_EVENT = 5, - CTRL_SHUTDOWN_EVENT = 6 + CtrlCEvent = 0, + CtrlBreakEvent = 1, + CtrlCloseEvent = 2, + CtrlLogoffEvent = 5, + CtrlShutdownEvent = 6 } static Console() @@ -31,25 +31,25 @@ namespace TelegramBotBase.Tools public static void SetHandler(Action action) { - Actions.Add(action); + __actions.Add(action); - if (_handler != null) + if (__handler != null) return; - _handler += new EventHandler(Handler); - SetConsoleCtrlHandler(_handler, true); + __handler += Handler; + SetConsoleCtrlHandler(__handler, true); } private static bool Handler(CtrlType sig) { switch (sig) { - case CtrlType.CTRL_C_EVENT: - case CtrlType.CTRL_LOGOFF_EVENT: - case CtrlType.CTRL_SHUTDOWN_EVENT: - case CtrlType.CTRL_CLOSE_EVENT: + case CtrlType.CtrlCEvent: + case CtrlType.CtrlLogoffEvent: + case CtrlType.CtrlShutdownEvent: + case CtrlType.CtrlCloseEvent: - foreach (var a in Actions) + foreach (var a in __actions) { a(); } diff --git a/TelegramBotBase/Tools/Conversion.cs b/TelegramBotBase/Tools/Conversion.cs index b9e40da..9993cd5 100644 --- a/TelegramBotBase/Tools/Conversion.cs +++ b/TelegramBotBase/Tools/Conversion.cs @@ -1,19 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Text; +using System.Collections.Generic; +using System.Reflection; using TelegramBotBase.Form; namespace TelegramBotBase.Tools { public static class Conversion { - public static void CustomConversionChecks(FormBase form, KeyValuePair p, System.Reflection.PropertyInfo f) + public static void CustomConversionChecks(FormBase form, KeyValuePair p, PropertyInfo f) { //Newtonsoft Int64/Int32 converter issue - if (f.PropertyType == typeof(Int32)) + if (f.PropertyType == typeof(int)) { - int i = 0; - if (int.TryParse(p.Value.ToString(), out i)) + if (int.TryParse(p.Value.ToString(), out var i)) { f.SetValue(form, i); } @@ -21,14 +19,13 @@ namespace TelegramBotBase.Tools } //Newtonsoft Double/Decimal converter issue - if (f.PropertyType == typeof(Decimal) | f.PropertyType == typeof(Nullable)) + if (f.PropertyType == typeof(decimal) | f.PropertyType == typeof(decimal?)) { decimal d = 0; if (decimal.TryParse(p.Value.ToString(), out d)) { f.SetValue(form, d); } - return; } diff --git a/TelegramBotBase/Tools/Time.cs b/TelegramBotBase/Tools/Time.cs index b0cd93f..f11733b 100644 --- a/TelegramBotBase/Tools/Time.cs +++ b/TelegramBotBase/Tools/Time.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace TelegramBotBase.Tools { @@ -25,7 +21,7 @@ namespace TelegramBotBase.Tools public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek) { - int diff = dt.DayOfWeek - startOfWeek; + var diff = dt.DayOfWeek - startOfWeek; if (diff < 0) { diff += 7; From 5ab15621a06e95a27e6945d4cfb49a01f662cf65 Mon Sep 17 00:00:00 2001 From: ZavaruKitsu Date: Sat, 8 Oct 2022 19:26:34 +0300 Subject: [PATCH 03/22] fix: reformat using C# rules --- Examples/AsyncFormUpdates/App.config | 794 ++++---- .../AsyncFormUpdates/AsyncFormUpdates.csproj | 144 +- Examples/AsyncFormUpdates/Program.cs | 16 +- .../Properties/AssemblyInfo.cs | 2 +- .../AsyncFormUpdates/forms/AsyncFormEdit.cs | 4 +- .../AsyncFormUpdates/forms/AsyncFormUpdate.cs | 4 +- Examples/AsyncFormUpdates/forms/Start.cs | 6 +- Examples/EFCoreBot/Database/BotDbContext.cs | 2 +- Examples/EFCoreBot/Database/User.cs | 2 +- Examples/EFCoreBot/EFCoreBot.csproj | 6 +- Examples/EFCoreBot/Program.cs | 19 +- Examples/EFCoreBot/StartForm.cs | 2 +- Examples/JoinHiderBot/JoinHiderBot.csproj | 14 +- Examples/JoinHiderBot/Program.cs | 24 +- .../JoinHiderBot/forms/GroupManageForm.cs | 23 +- Examples/JoinHiderBot/forms/Start.cs | 34 +- Examples/SystemCommandsBot/Program.cs | 54 +- .../SystemCommandsBot.csproj | 16 +- .../SystemCommandsBot/commands/Commando.cs | 28 +- Examples/SystemCommandsBot/config/Config.cs | 138 +- Examples/SystemCommandsBot/forms/CmdForm.cs | 306 ++- Examples/SystemCommandsBot/forms/StartForm.cs | 57 +- .../ImageExtensions.cs | 18 +- TelegramBotBase.Extensions.Images/README.md | 1 - .../TelegramBotBase.Extensions.Images.csproj | 36 +- .../BotBaseBuilderExtensions.cs | 29 +- .../MSSQLSerializer.cs | 38 +- .../README.md | 1 - ...xtensions.Serializer.Database.MSSQL.csproj | 48 +- .../create_tables.sql | 100 +- TelegramBotBase.Test/App.config | 18 +- TelegramBotBase.Test/Program.cs | 139 +- .../Properties/AssemblyInfo.cs | 2 +- .../TelegramBotBaseTest.csproj | 59 +- TelegramBotBase.Test/Tests/ButtonTestForm.cs | 125 +- .../Tests/Controls/ButtonGridForm.cs | 100 +- .../Tests/Controls/ButtonGridPagingForm.cs | 92 +- .../Tests/Controls/ButtonGridTagForm.cs | 121 +- .../Tests/Controls/CalendarPickerForm.cs | 128 +- .../Tests/Controls/CheckedButtonListForm.cs | 120 +- .../Tests/Controls/MonthPickerForm.cs | 124 +- .../Tests/Controls/MultiToggleButtons.cs | 86 +- .../Tests/Controls/MultiViewForm.cs | 84 +- .../Tests/Controls/Subclass/MultiViewTest.cs | 82 +- .../Tests/Controls/ToggleButtons.cs | 84 +- .../Tests/Controls/TreeViewForms.cs | 175 +- TelegramBotBase.Test/Tests/DataForm.cs | 146 +- .../Tests/DataSources/CustomDataSource.cs | 146 ++ .../Tests/DataSources/List.cs | 51 + .../Tests/Datasources/CustomDataSource.cs | 143 -- .../Tests/Datasources/List.cs | 55 - .../Tests/Groups/GroupChange.cs | 128 +- .../Tests/Groups/LinkReplaceTest.cs | 306 +-- .../Tests/Groups/WelcomeUser.cs | 151 +- TelegramBotBase.Test/Tests/Menu.cs | 449 ++--- .../Tests/Navigation/CustomController.cs | 65 +- .../Tests/Navigation/Form1.cs | 151 +- .../Tests/Navigation/Start.cs | 143 +- .../Tests/Notifications/Start.cs | 106 +- TelegramBotBase.Test/Tests/ProgressTest.cs | 216 +- .../Tests/Register/PerForm.cs | 162 +- .../Tests/Register/PerStep.cs | 51 +- TelegramBotBase.Test/Tests/Register/Start.cs | 86 +- .../Tests/Register/Steps/Data.cs | 16 +- .../Tests/Register/Steps/Step1.cs | 104 +- .../Tests/Register/Steps/Step2.cs | 70 +- .../Tests/Register/Steps/Step3.cs | 104 +- TelegramBotBase.Test/Tests/SimpleForm.cs | 108 +- TelegramBotBase.Test/Tests/Start.cs | 56 +- TelegramBotBase.Test/Tests/TestForm.cs | 123 +- TelegramBotBase.Test/Tests/TestForm2.cs | 209 +- TelegramBotBase.Test/packages.config | 8 +- TelegramBotBase/Args/BotCommandEventArgs.cs | 64 +- .../Args/ButtonClickedEventArgs.cs | 73 +- .../Args/CheckedChangedEventArgs.cs | 65 +- TelegramBotBase/Args/GroupChangedEventArgs.cs | 26 +- TelegramBotBase/Args/InitEventArgs.cs | 19 +- TelegramBotBase/Args/LoadStateEventArgs.cs | 102 +- TelegramBotBase/Args/MemberChangeEventArgs.cs | 45 +- .../Args/MessageDeletedEventArgs.cs | 21 +- .../Args/MessageIncomeEventArgs.cs | 34 +- .../Args/MessageReceivedEventArgs.cs | 22 +- TelegramBotBase/Args/MessageSentEventArgs.cs | 36 +- .../Args/PromptDialogCompletedEventArgs.cs | 14 +- TelegramBotBase/Args/RenderViewEventArgs.cs | 21 +- TelegramBotBase/Args/SaveStateEventArgs.cs | 67 +- TelegramBotBase/Args/SaveStatesEventArgs.cs | 18 +- TelegramBotBase/Args/SessionBeginEventArgs.cs | 23 +- .../Args/SystemExceptionEventArgs.cs | 45 +- .../Args/UnhandledCallEventArgs.cs | 65 +- TelegramBotBase/Attributes/IgnoreState.cs | 20 +- TelegramBotBase/Attributes/SaveState.cs | 18 +- TelegramBotBase/Base/Async.cs | 33 +- TelegramBotBase/Base/ControlBase.cs | 106 +- TelegramBotBase/Base/DataResult.cs | 318 ++- TelegramBotBase/Base/FormBase.cs | 827 ++++---- TelegramBotBase/Base/MessageClient.cs | 365 ++-- TelegramBotBase/Base/MessageResult.cs | 202 +- TelegramBotBase/Base/ResultBase.cs | 78 +- TelegramBotBase/Base/StateContainer.cs | 44 +- TelegramBotBase/Base/StateEntry.cs | 67 +- TelegramBotBase/Base/UpdateResult.cs | 52 +- TelegramBotBase/BotBase.cs | 784 ++++---- TelegramBotBase/Builder/BotBaseBuilder.cs | 710 ++++--- .../Interfaces/IAPIKeySelectionStage.cs | 67 +- .../Builder/Interfaces/IBotCommandsStage.cs | 54 +- .../Builder/Interfaces/IBuildingStage.cs | 11 +- .../Interfaces/ILanguageSelectionStage.cs | 51 +- .../Interfaces/IMessageLoopSelectionStage.cs | 58 +- .../Interfaces/INetworkingSelectionStage.cs | 72 +- .../Interfaces/ISessionSerializationStage.cs | 68 +- .../Interfaces/IStartFormSelectionStage.cs | 75 +- TelegramBotBase/Commands/Extensions.cs | 300 +-- TelegramBotBase/Constants/Telegram.cs | 28 +- TelegramBotBase/Controls/Hybrid/ButtonGrid.cs | 1204 +++++------ TelegramBotBase/Controls/Hybrid/ButtonRow.cs | 182 +- .../Controls/Hybrid/CheckedButtonList.cs | 1453 +++++++------- TelegramBotBase/Controls/Hybrid/MultiView.cs | 231 +-- .../Controls/Hybrid/TaggedButtonGrid.cs | 1760 +++++++++-------- .../Controls/Inline/CalendarPicker.cs | 423 ++-- .../Controls/Inline/MonthPicker.cs | 20 +- .../Controls/Inline/MultiToggleButton.cs | 231 ++- .../Controls/Inline/ProgressBar.cs | 509 +++-- .../Controls/Inline/ToggleButton.cs | 256 ++- TelegramBotBase/Controls/Inline/TreeView.cs | 178 +- .../Controls/Inline/TreeViewNode.cs | 111 +- .../DataSources/ButtonFormDataSource.cs | 254 +-- .../DataSources/StaticDataSource.cs | 62 +- TelegramBotBase/Enums/eDeleteMode.cs | 35 +- TelegramBotBase/Enums/eDeleteSide.cs | 35 +- TelegramBotBase/Enums/eKeyboardType.cs | 26 +- TelegramBotBase/Enums/eMonthPickerMode.cs | 35 +- .../Enums/eNavigationBarVisibility.cs | 34 +- TelegramBotBase/Enums/eSettings.cs | 52 +- .../Exceptions/MaxLengthException.cs | 16 +- .../Exceptions/MaximumColsException.cs | 16 +- .../Exceptions/MaximumRowsException.cs | 16 +- .../Factories/DefaultStartFormFactory.cs | 31 +- .../Factories/LambdaStartFormFactory.cs | 31 +- .../ServiceProviderStartFormFactory.cs | 41 +- TelegramBotBase/Form/AlertDialog.cs | 29 +- TelegramBotBase/Form/ArrayPromptDialog.cs | 169 +- TelegramBotBase/Form/AutoCleanForm.cs | 278 +-- TelegramBotBase/Form/ButtonBase.cs | 116 +- TelegramBotBase/Form/ButtonForm.cs | 626 +++--- TelegramBotBase/Form/CallbackData.cs | 133 +- TelegramBotBase/Form/ConfirmDialog.cs | 212 +- TelegramBotBase/Form/DynamicButton.cs | 53 +- TelegramBotBase/Form/GroupForm.cs | 110 +- TelegramBotBase/Form/ModalDialog.cs | 33 +- .../Form/Navigation/NavigationController.cs | 624 +++--- TelegramBotBase/Form/PromptDialog.cs | 203 +- TelegramBotBase/Form/SplitterForm.cs | 155 +- TelegramBotBase/Form/TagButtonBase.cs | 86 +- TelegramBotBase/Interfaces/IDataSource.cs | 58 +- TelegramBotBase/Interfaces/IDeviceSession.cs | 58 +- .../Interfaces/IMessageLoopFactory.cs | 16 +- .../Interfaces/IStartFormFactory.cs | 11 +- TelegramBotBase/Interfaces/IStateForm.cs | 21 +- TelegramBotBase/Interfaces/IStateMachine.cs | 15 +- TelegramBotBase/Localizations/Default.cs | 14 +- TelegramBotBase/Localizations/English.cs | 66 +- TelegramBotBase/Localizations/German.cs | 66 +- TelegramBotBase/Localizations/Localization.cs | 14 +- TelegramBotBase/Markdown/Generator.cs | 300 +-- .../MessageLoops/FormBaseMessageLoop.cs | 170 +- .../MessageLoops/FullMessageLoop.cs | 150 +- .../MessageLoops/MinimalMessageLoop.cs | 65 +- TelegramBotBase/Properties/AssemblyInfo.cs | 2 +- TelegramBotBase/SessionBase.cs | 542 ++--- TelegramBotBase/Sessions/DeviceSession.cs | 1746 ++++++++-------- TelegramBotBase/States/JSONStateMachine.cs | 126 +- .../States/SimpleJSONStateMachine.cs | 111 +- TelegramBotBase/States/XMLStateMachine.cs | 157 +- TelegramBotBase/TelegramBotBase.csproj | 102 +- TelegramBotBase/TelegramBotBase.nuspec | 52 +- TelegramBotBase/Tools/Arrays.cs | 19 +- TelegramBotBase/Tools/Console.cs | 115 +- TelegramBotBase/Tools/Conversion.cs | 41 +- TelegramBotBase/Tools/Time.cs | 85 +- 180 files changed, 13136 insertions(+), 13081 deletions(-) create mode 100644 TelegramBotBase.Test/Tests/DataSources/CustomDataSource.cs create mode 100644 TelegramBotBase.Test/Tests/DataSources/List.cs delete mode 100644 TelegramBotBase.Test/Tests/Datasources/CustomDataSource.cs delete mode 100644 TelegramBotBase.Test/Tests/Datasources/List.cs diff --git a/Examples/AsyncFormUpdates/App.config b/Examples/AsyncFormUpdates/App.config index 8ffc026..e784e10 100644 --- a/Examples/AsyncFormUpdates/App.config +++ b/Examples/AsyncFormUpdates/App.config @@ -1,378 +1,426 @@ - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj b/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj index 579f062..6c2fe0b 100644 --- a/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj +++ b/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj @@ -1,74 +1,74 @@  - - - Debug - AnyCPU - {673A56F5-6110-4AED-A68D-562FD6ED3EA6} - Exe - AsyncFormUpdates - AsyncFormUpdates - v4.8 - 512 - true - true - - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - - - - - - - - - ..\..\packages\Telegram.Bot.17.0.0\lib\netstandard2.0\Telegram.Bot.dll - - - - - - - - - - - - - - - {0bd16fb9-7ed4-4ccb-83eb-5cee538e1b6c} - TelegramBotBase - - - - - - - - - - - \ No newline at end of file + + + Debug + AnyCPU + {673A56F5-6110-4AED-A68D-562FD6ED3EA6} + Exe + AsyncFormUpdates + AsyncFormUpdates + v4.8 + 512 + true + true + + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + ..\..\packages\Telegram.Bot.17.0.0\lib\netstandard2.0\Telegram.Bot.dll + + + + + + + + + + + + + + + {0bd16fb9-7ed4-4ccb-83eb-5cee538e1b6c} + TelegramBotBase + + + + + + + + + + + diff --git a/Examples/AsyncFormUpdates/Program.cs b/Examples/AsyncFormUpdates/Program.cs index 27283f7..facc257 100644 --- a/Examples/AsyncFormUpdates/Program.cs +++ b/Examples/AsyncFormUpdates/Program.cs @@ -15,8 +15,8 @@ namespace AsyncFormUpdates var apiKey = "APIKey"; __bot = BotBaseBuilder.Create() - .QuickStart(apiKey) - .Build(); + .QuickStart(apiKey) + .Build(); __bot.Start(); @@ -33,17 +33,17 @@ namespace AsyncFormUpdates private static async void Timer_Elapsed(object sender, ElapsedEventArgs e) { - - foreach(var s in __bot.Sessions.SessionList) + foreach (var s in __bot.Sessions.SessionList) { //Only for AsyncUpdateForm - if (s.Value.ActiveForm.GetType() != typeof(AsyncFormUpdate) && s.Value.ActiveForm.GetType() != typeof(AsyncFormEdit)) + if (s.Value.ActiveForm.GetType() != typeof(AsyncFormUpdate) && + s.Value.ActiveForm.GetType() != typeof(AsyncFormEdit)) + { continue; + } await __bot.InvokeMessageLoop(s.Key); } - - } } -} +} \ No newline at end of file diff --git a/Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs b/Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs index 7703157..f89e22b 100644 --- a/Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs +++ b/Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs @@ -32,4 +32,4 @@ using System.Runtime.InteropServices; // indem Sie "*" wie unten gezeigt eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs b/Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs index c24b8c2..2ad3694 100644 --- a/Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs +++ b/Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs @@ -46,8 +46,6 @@ namespace AsyncFormUpdates.forms var m = await Device.Send($"Your current count is at: {_counter}", bf, disableNotification: true); _messageId = m.MessageId; } - } - } -} +} \ No newline at end of file diff --git a/Examples/AsyncFormUpdates/forms/AsyncFormUpdate.cs b/Examples/AsyncFormUpdates/forms/AsyncFormUpdate.cs index 9e888a5..8a3b0b1 100644 --- a/Examples/AsyncFormUpdates/forms/AsyncFormUpdate.cs +++ b/Examples/AsyncFormUpdates/forms/AsyncFormUpdate.cs @@ -38,7 +38,5 @@ namespace AsyncFormUpdates.forms await Device.Send($"Your current count is at: {_counter}", bf, disableNotification: true); } - - } -} +} \ No newline at end of file diff --git a/Examples/AsyncFormUpdates/forms/Start.cs b/Examples/AsyncFormUpdates/forms/Start.cs index a8a726d..8713a04 100644 --- a/Examples/AsyncFormUpdates/forms/Start.cs +++ b/Examples/AsyncFormUpdates/forms/Start.cs @@ -6,8 +6,6 @@ namespace AsyncFormUpdates.forms { public class Start : AutoCleanForm { - - public override async Task Action(MessageResult message) { await message.ConfirmAction(); @@ -30,7 +28,6 @@ namespace AsyncFormUpdates.forms break; } - } public override async Task Render(MessageResult message) @@ -43,6 +40,5 @@ namespace AsyncFormUpdates.forms await Device.Send("Choose your option", bf); } - } -} +} \ No newline at end of file diff --git a/Examples/EFCoreBot/Database/BotDbContext.cs b/Examples/EFCoreBot/Database/BotDbContext.cs index 18a3c4a..da7e42d 100644 --- a/Examples/EFCoreBot/Database/BotDbContext.cs +++ b/Examples/EFCoreBot/Database/BotDbContext.cs @@ -9,4 +9,4 @@ public class BotDbContext : DbContext } public DbSet Users { get; set; } -} +} \ No newline at end of file diff --git a/Examples/EFCoreBot/Database/User.cs b/Examples/EFCoreBot/Database/User.cs index e106815..fbe1662 100644 --- a/Examples/EFCoreBot/Database/User.cs +++ b/Examples/EFCoreBot/Database/User.cs @@ -4,4 +4,4 @@ public class User { public long Id { get; set; } public string LastMessage { get; set; } -} +} \ No newline at end of file diff --git a/Examples/EFCoreBot/EFCoreBot.csproj b/Examples/EFCoreBot/EFCoreBot.csproj index 7421594..885fc87 100644 --- a/Examples/EFCoreBot/EFCoreBot.csproj +++ b/Examples/EFCoreBot/EFCoreBot.csproj @@ -8,12 +8,12 @@ - - + + - + diff --git a/Examples/EFCoreBot/Program.cs b/Examples/EFCoreBot/Program.cs index fa427ee..3d983e1 100644 --- a/Examples/EFCoreBot/Program.cs +++ b/Examples/EFCoreBot/Program.cs @@ -10,14 +10,15 @@ var serviceCollection = new ServiceCollection() var serviceProvider = serviceCollection.BuildServiceProvider(); var bot = BotBaseBuilder.Create() - .WithAPIKey(Environment.GetEnvironmentVariable("API_KEY") ?? throw new Exception("API_KEY is not set")) - .DefaultMessageLoop() - .WithServiceProvider(serviceProvider) - .NoProxy() - .NoCommands() - .NoSerialization() - .DefaultLanguage() - .Build(); + .WithAPIKey(Environment.GetEnvironmentVariable("API_KEY") ?? + throw new Exception("API_KEY is not set")) + .DefaultMessageLoop() + .WithServiceProvider(serviceProvider) + .NoProxy() + .NoCommands() + .NoSerialization() + .DefaultLanguage() + .Build(); bot.Start(); -await Task.Delay(-1); +await Task.Delay(-1); \ No newline at end of file diff --git a/Examples/EFCoreBot/StartForm.cs b/Examples/EFCoreBot/StartForm.cs index 1bfee77..7081c1a 100644 --- a/Examples/EFCoreBot/StartForm.cs +++ b/Examples/EFCoreBot/StartForm.cs @@ -33,4 +33,4 @@ public class StartForm : FormBase user.LastMessage = string.IsNullOrWhiteSpace(message.MessageText) ? "" : message.MessageText; await _dbContext.SaveChangesAsync(); } -} +} \ No newline at end of file diff --git a/Examples/JoinHiderBot/JoinHiderBot.csproj b/Examples/JoinHiderBot/JoinHiderBot.csproj index aa8f8d7..76dddc9 100644 --- a/Examples/JoinHiderBot/JoinHiderBot.csproj +++ b/Examples/JoinHiderBot/JoinHiderBot.csproj @@ -1,12 +1,12 @@  - - Exe - net6.0 - + + Exe + net6.0 + - - - + + + diff --git a/Examples/JoinHiderBot/Program.cs b/Examples/JoinHiderBot/Program.cs index 369b758..9c0bfff 100644 --- a/Examples/JoinHiderBot/Program.cs +++ b/Examples/JoinHiderBot/Program.cs @@ -2,22 +2,20 @@ using JoinHiderBot.forms; using TelegramBotBase.Builder; -namespace JoinHiderBot +namespace JoinHiderBot; + +internal class Program { - internal class Program + private static void Main(string[] args) { - private static void Main(string[] args) - { + var apiKey = ""; - var apiKey = ""; + var bot = BotBaseBuilder.Create() + .QuickStart(apiKey) + .Build(); - var bot = BotBaseBuilder.Create() - .QuickStart(apiKey) - .Build(); + bot.Start(); - bot.Start(); - - Console.ReadLine(); - } + Console.ReadLine(); } -} +} \ No newline at end of file diff --git a/Examples/JoinHiderBot/forms/GroupManageForm.cs b/Examples/JoinHiderBot/forms/GroupManageForm.cs index 61fdadc..6ccf246 100644 --- a/Examples/JoinHiderBot/forms/GroupManageForm.cs +++ b/Examples/JoinHiderBot/forms/GroupManageForm.cs @@ -3,21 +3,20 @@ using Telegram.Bot.Types.Enums; using TelegramBotBase.Args; using TelegramBotBase.Form; -namespace JoinHiderBot.forms +namespace JoinHiderBot.forms; + +public class GroupManageForm : GroupForm { - public class GroupManageForm : GroupForm + public override async Task OnMemberChanges(MemberChangeEventArgs e) { - - public override async Task OnMemberChanges(MemberChangeEventArgs e) + if (e.Type != MessageType.ChatMembersAdded && e.Type != MessageType.ChatMemberLeft) { - if (e.Type != MessageType.ChatMembersAdded && e.Type != MessageType.ChatMemberLeft) - return; - - - var m = e.Result.Message; - - await Device.DeleteMessage(m); + return; } + + var m = e.Result.Message; + + await Device.DeleteMessage(m); } -} +} \ No newline at end of file diff --git a/Examples/JoinHiderBot/forms/Start.cs b/Examples/JoinHiderBot/forms/Start.cs index f506451..0b868b6 100644 --- a/Examples/JoinHiderBot/forms/Start.cs +++ b/Examples/JoinHiderBot/forms/Start.cs @@ -2,25 +2,23 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace JoinHiderBot.forms +namespace JoinHiderBot.forms; + +public class Start : SplitterForm { - public class Start : SplitterForm + public override async Task Open(MessageResult e) { - public override async Task Open(MessageResult e) - { - await Device.Send("This bot works only in groups."); - - return true; - } - - public override async Task OpenGroup(MessageResult e) - { - var gmf = new GroupManageForm(); - - await NavigateTo(gmf); - - return true; - } + await Device.Send("This bot works only in groups."); + return true; } -} + + public override async Task OpenGroup(MessageResult e) + { + var gmf = new GroupManageForm(); + + await NavigateTo(gmf); + + return true; + } +} \ No newline at end of file diff --git a/Examples/SystemCommandsBot/Program.cs b/Examples/SystemCommandsBot/Program.cs index d0131f9..b5330ac 100644 --- a/Examples/SystemCommandsBot/Program.cs +++ b/Examples/SystemCommandsBot/Program.cs @@ -3,39 +3,35 @@ using SystemCommandsBot.config; using SystemCommandsBot.forms; using TelegramBotBase.Builder; -namespace SystemCommandsBot +namespace SystemCommandsBot; + +internal class Program { - internal class Program + public static Config BotConfig { get; set; } + + + private static void Main(string[] args) { - public static Config BotConfig { get; set; } + BotConfig = Config.Load(); - - private static void Main(string[] args) + if (BotConfig.ApiKey == null || BotConfig.ApiKey.Trim() == "") { - - BotConfig = Config.Load(); - - if (BotConfig.ApiKey == null || BotConfig.ApiKey.Trim() == "") - { - Console.WriteLine("Config created..."); - Console.ReadLine(); - return; - } - - var bot = BotBaseBuilder.Create() - .QuickStart(BotConfig.ApiKey) - .Build(); - - bot.Start(); - - Console.WriteLine("Bot started"); - + Console.WriteLine("Config created..."); Console.ReadLine(); - - - bot.Stop(); - - + return; } + + var bot = BotBaseBuilder.Create() + .QuickStart(BotConfig.ApiKey) + .Build(); + + bot.Start(); + + Console.WriteLine("Bot started"); + + Console.ReadLine(); + + + bot.Stop(); } -} +} \ No newline at end of file diff --git a/Examples/SystemCommandsBot/SystemCommandsBot.csproj b/Examples/SystemCommandsBot/SystemCommandsBot.csproj index 4e20f6a..95990e5 100644 --- a/Examples/SystemCommandsBot/SystemCommandsBot.csproj +++ b/Examples/SystemCommandsBot/SystemCommandsBot.csproj @@ -1,13 +1,13 @@ - - Exe - net6.0 - + + Exe + net6.0 + - - - - + + + + diff --git a/Examples/SystemCommandsBot/commands/Commando.cs b/Examples/SystemCommandsBot/commands/Commando.cs index d93eb81..8eb56d1 100644 --- a/Examples/SystemCommandsBot/commands/Commando.cs +++ b/Examples/SystemCommandsBot/commands/Commando.cs @@ -1,25 +1,21 @@ -namespace SystemCommandsBot.commands +namespace SystemCommandsBot.commands; + +public class Commando { - public class Commando - { - public int Id { get; set; } + public int Id { get; set; } - public string Title { get; set; } + public string Title { get; set; } - public string ShellCmd { get; set; } + public string ShellCmd { get; set; } - public bool Enabled { get; set; } = true; + public bool Enabled { get; set; } = true; - public string Action { get; set; } + public string Action { get; set; } - public bool UseShell { get; set; } = true; + public bool UseShell { get; set; } = true; - public int? MaxInstances { get; set; } + public int? MaxInstances { get; set; } - public string ProcName - { - get;set; - } - } -} + public string ProcName { get; set; } +} \ No newline at end of file diff --git a/Examples/SystemCommandsBot/config/Config.cs b/Examples/SystemCommandsBot/config/Config.cs index f63b8fc..3125790 100644 --- a/Examples/SystemCommandsBot/config/Config.cs +++ b/Examples/SystemCommandsBot/config/Config.cs @@ -4,90 +4,90 @@ using System.IO; using Newtonsoft.Json; using SystemCommandsBot.commands; -namespace SystemCommandsBot.config +namespace SystemCommandsBot.config; + +public class Config { - public class Config + public Config() { - public string Password { get; set; } + Commandos = new List(); + } - public string ApiKey { get; set; } + public string Password { get; set; } - public List Commandos { get; set; } + public string ApiKey { get; set; } + public List Commandos { get; set; } - public Config() + public void LoadDefaultValues() + { + ApiKey = ""; + Commandos.Add(new Commando { - Commandos = new List(); + Id = 0, Enabled = true, Title = "Test Befehl", ShellCmd = "explorer.exe", Action = "start", MaxInstances = 2 + }); + } + + + public static Config Load() + { + try + { + return Load(AppContext.BaseDirectory + "config\\default.cfg"); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); } - public void LoadDefaultValues() + return null; + } + + + public static Config Load(string path) + { + try { - ApiKey = ""; - Commandos.Add(new Commando { Id = 0, Enabled = true, Title = "Test Befehl", ShellCmd = "explorer.exe", Action = "start", MaxInstances = 2 }); + var cfg = JsonConvert.DeserializeObject(File.ReadAllText(path)); + return cfg; + } + catch (DirectoryNotFoundException) + { + var di = new DirectoryInfo(path); + + if (!Directory.Exists(di.Parent.FullName)) + { + Directory.CreateDirectory(di.Parent.FullName); + } + + var cfg = new Config(); + cfg.LoadDefaultValues(); + cfg.Save(path); + return cfg; + } + catch (FileNotFoundException) + { + var cfg = new Config(); + cfg.LoadDefaultValues(); + cfg.Save(path); + return cfg; + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); } + return null; + } - public static Config Load() + public void Save(string path) + { + try { - try - { - return Load(AppContext.BaseDirectory + "config\\default.cfg"); - - - } - catch(Exception ex) - { - Console.WriteLine(ex.Message); - } - return null; + File.WriteAllText(path, JsonConvert.SerializeObject(this)); } - - - public static Config Load(string path) + catch { - try - { - var cfg = JsonConvert.DeserializeObject(File.ReadAllText(path)); - return cfg; - } - catch (DirectoryNotFoundException) - { - var di = new DirectoryInfo(path); - - if (!Directory.Exists(di.Parent.FullName)) - { - Directory.CreateDirectory(di.Parent.FullName); - } - - var cfg = new Config(); - cfg.LoadDefaultValues(); - cfg.Save(path); - return cfg; - } - catch (FileNotFoundException) - { - var cfg = new Config(); - cfg.LoadDefaultValues(); - cfg.Save(path); - return cfg; - } - catch(Exception ex) - { - Console.WriteLine(ex.Message); - } - return null; - } - - public void Save(string path) - { - try - { - File.WriteAllText(path, JsonConvert.SerializeObject(this)); - } - catch - { - - } } } -} +} \ No newline at end of file diff --git a/Examples/SystemCommandsBot/forms/CmdForm.cs b/Examples/SystemCommandsBot/forms/CmdForm.cs index d42e713..a5660fe 100644 --- a/Examples/SystemCommandsBot/forms/CmdForm.cs +++ b/Examples/SystemCommandsBot/forms/CmdForm.cs @@ -6,167 +6,151 @@ using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace SystemCommandsBot.forms +namespace SystemCommandsBot.forms; + +public class CmdForm : AutoCleanForm { - public class CmdForm : AutoCleanForm + public DateTime ExpiresAt { get; set; } + + public int? MessageId { get; set; } + + public override Task Load(MessageResult message) { - public DateTime ExpiresAt { get; set; } - - public int? MessageId { get; set; } - - public override Task Load(MessageResult message) - { - return Task.CompletedTask; - } - - public override async Task Action(MessageResult message) - { - var btn = message.RawData; - - var id = -1; - - if (!int.TryParse(btn, out id)) - { - - return; - } - - var cmd = Program.BotConfig.Commandos.Where(a => a.Enabled && a.Id == id).FirstOrDefault(); - if (cmd == null) - { - await Device.Send("Cmd nicht verfügbar."); - return; - } - - message.Handled = true; - - switch (cmd.Action) - { - case "start": - - var fi = new FileInfo(cmd.ShellCmd); - - if (cmd.MaxInstances != null && cmd.MaxInstances >= 0) - { - - if (Process.GetProcessesByName(cmd.ProcName).Count() >= cmd.MaxInstances) - { - await Device.Send("Anwendung läuft bereits."); - await message.ConfirmAction("Anwendung läuft bereits."); - - return; - } - - } - - var psi = new ProcessStartInfo - { - FileName = cmd.ShellCmd, - WorkingDirectory = fi.DirectoryName, - UseShellExecute = cmd.UseShell - }; - - Process.Start(psi); - - await Device.Send(fi.Name + " wurde gestarted."); - - await message.ConfirmAction(fi.Name + " wurde gestarted."); - - break; - - case "kill": - - var fi2 = new FileInfo(cmd.ShellCmd); - - var pros = fi2.Name.Replace(fi2.Extension, ""); - - var proc = Process.GetProcessesByName(pros).ToList(); - - foreach (var p in proc) - { - try - { - p.Kill(); - } - catch - { - - } - } - - await Device.Send(fi2.Name + " wurde beendet."); - - await message.ConfirmAction(fi2.Name + " wurde beendet."); - - break; - - case "restart": - - var fi3 = new FileInfo(cmd.ShellCmd); - - var pros2 = fi3.Name.Replace(fi3.Extension, ""); - - var proc2 = Process.GetProcessesByName(pros2).ToList(); - - foreach (var p in proc2) - { - try - { - p.Kill(); - } - catch - { - - } - } - - var fi4 = new FileInfo(cmd.ShellCmd); - - var psi2 = new ProcessStartInfo - { - FileName = cmd.ShellCmd, - WorkingDirectory = fi4.DirectoryName - }; - psi2.FileName = cmd.ShellCmd; - psi2.UseShellExecute = cmd.UseShell; - - Process.Start(psi2); - - await Device.Send(fi3.Name + " wurde neugestarted."); - await message.ConfirmAction(fi3.Name + " wurde neugestarted."); - - - break; - - default: - - await message.ConfirmAction(); - - break; - - } - - - - - } - - public override async Task Render(MessageResult message) - { - if (MessageId == null) - { - var buttons = Program.BotConfig.Commandos.Where(a => a.Enabled).Select(a => new ButtonBase(a.Title, a.Id.ToString())); - - var bf = new ButtonForm(); - bf.AddSplitted(buttons, 1); - await Device.Send("Deine Optionen", bf); - } - - - } - - - - + return Task.CompletedTask; } -} + + public override async Task Action(MessageResult message) + { + var btn = message.RawData; + + var id = -1; + + if (!int.TryParse(btn, out id)) + { + return; + } + + var cmd = Program.BotConfig.Commandos.Where(a => a.Enabled && a.Id == id).FirstOrDefault(); + if (cmd == null) + { + await Device.Send("Cmd nicht verfügbar."); + return; + } + + message.Handled = true; + + switch (cmd.Action) + { + case "start": + + var fi = new FileInfo(cmd.ShellCmd); + + if (cmd.MaxInstances != null && cmd.MaxInstances >= 0) + { + if (Process.GetProcessesByName(cmd.ProcName).Count() >= cmd.MaxInstances) + { + await Device.Send("Anwendung läuft bereits."); + await message.ConfirmAction("Anwendung läuft bereits."); + + return; + } + } + + var psi = new ProcessStartInfo + { + FileName = cmd.ShellCmd, + WorkingDirectory = fi.DirectoryName, + UseShellExecute = cmd.UseShell + }; + + Process.Start(psi); + + await Device.Send(fi.Name + " wurde gestarted."); + + await message.ConfirmAction(fi.Name + " wurde gestarted."); + + break; + + case "kill": + + var fi2 = new FileInfo(cmd.ShellCmd); + + var pros = fi2.Name.Replace(fi2.Extension, ""); + + var proc = Process.GetProcessesByName(pros).ToList(); + + foreach (var p in proc) + { + try + { + p.Kill(); + } + catch + { + } + } + + await Device.Send(fi2.Name + " wurde beendet."); + + await message.ConfirmAction(fi2.Name + " wurde beendet."); + + break; + + case "restart": + + var fi3 = new FileInfo(cmd.ShellCmd); + + var pros2 = fi3.Name.Replace(fi3.Extension, ""); + + var proc2 = Process.GetProcessesByName(pros2).ToList(); + + foreach (var p in proc2) + { + try + { + p.Kill(); + } + catch + { + } + } + + var fi4 = new FileInfo(cmd.ShellCmd); + + var psi2 = new ProcessStartInfo + { + FileName = cmd.ShellCmd, + WorkingDirectory = fi4.DirectoryName + }; + psi2.FileName = cmd.ShellCmd; + psi2.UseShellExecute = cmd.UseShell; + + Process.Start(psi2); + + await Device.Send(fi3.Name + " wurde neugestarted."); + await message.ConfirmAction(fi3.Name + " wurde neugestarted."); + + + break; + + default: + + await message.ConfirmAction(); + + break; + } + } + + public override async Task Render(MessageResult message) + { + if (MessageId == null) + { + var buttons = Program.BotConfig.Commandos.Where(a => a.Enabled) + .Select(a => new ButtonBase(a.Title, a.Id.ToString())); + + var bf = new ButtonForm(); + bf.AddSplitted(buttons, 1); + await Device.Send("Deine Optionen", bf); + } + } +} \ No newline at end of file diff --git a/Examples/SystemCommandsBot/forms/StartForm.cs b/Examples/SystemCommandsBot/forms/StartForm.cs index ede4203..7b34f4d 100644 --- a/Examples/SystemCommandsBot/forms/StartForm.cs +++ b/Examples/SystemCommandsBot/forms/StartForm.cs @@ -3,39 +3,36 @@ using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace SystemCommandsBot.forms +namespace SystemCommandsBot.forms; + +public class StartForm : FormBase { - public class StartForm : FormBase + public string Password { get; set; } + + public override Task Load(MessageResult message) { - public string Password { get; set; } - - public override Task Load(MessageResult message) + var inp = message.MessageText; + if (Program.BotConfig.Password == inp) { - var inp = message.MessageText; - if (Program.BotConfig.Password == inp) - { - Password = inp; - } - - return Task.CompletedTask; - } - - - public override async Task Render(MessageResult message) - { - if (Password == null || Password.Trim() == "") - { - await Device.Send("Bitte gib dein Passwort an."); - return; - } - - - var cmd = new CmdForm(); - cmd.ExpiresAt = DateTime.Now.AddDays(14); - - await NavigateTo(cmd); - + Password = inp; } + return Task.CompletedTask; } -} + + + public override async Task Render(MessageResult message) + { + if (Password == null || Password.Trim() == "") + { + await Device.Send("Bitte gib dein Passwort an."); + return; + } + + + var cmd = new CmdForm(); + cmd.ExpiresAt = DateTime.Now.AddDays(14); + + await NavigateTo(cmd); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Extensions.Images/ImageExtensions.cs b/TelegramBotBase.Extensions.Images/ImageExtensions.cs index 314679c..7ed5dc0 100644 --- a/TelegramBotBase.Extensions.Images/ImageExtensions.cs +++ b/TelegramBotBase.Extensions.Images/ImageExtensions.cs @@ -20,7 +20,7 @@ namespace TelegramBotBase.Extensions.Images } /// - /// Sends an image + /// Sends an image /// /// /// @@ -28,18 +28,20 @@ namespace TelegramBotBase.Extensions.Images /// /// /// - public static async Task SendPhoto(this DeviceSession session, Image image, string name, string caption, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) + public static async Task SendPhoto(this DeviceSession session, Image image, string name, + string caption, ButtonForm buttons = null, int replyTo = 0, + bool disableNotification = false) { using (var fileStream = ToStream(image, ImageFormat.Png)) { var fts = new InputOnlineFile(fileStream, name); - return await session.SendPhoto(fts, caption: caption, buttons, replyTo, disableNotification); + return await session.SendPhoto(fts, caption, buttons, replyTo, disableNotification); } } /// - /// Sends an image + /// Sends an image /// /// /// @@ -47,14 +49,16 @@ namespace TelegramBotBase.Extensions.Images /// /// /// - public static async Task SendPhoto(this DeviceSession session, Bitmap image, string name, string caption, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) + public static async Task SendPhoto(this DeviceSession session, Bitmap image, string name, + string caption, ButtonForm buttons = null, int replyTo = 0, + bool disableNotification = false) { using (var fileStream = ToStream(image, ImageFormat.Png)) { var fts = new InputOnlineFile(fileStream, name); - return await session.SendPhoto(fts, caption: caption, buttons, replyTo, disableNotification); + return await session.SendPhoto(fts, caption, buttons, replyTo, disableNotification); } } } -} +} \ No newline at end of file diff --git a/TelegramBotBase.Extensions.Images/README.md b/TelegramBotBase.Extensions.Images/README.md index 2611a85..072c797 100644 --- a/TelegramBotBase.Extensions.Images/README.md +++ b/TelegramBotBase.Extensions.Images/README.md @@ -3,6 +3,5 @@ [![NuGet version (TelegramBotBase)](https://img.shields.io/nuget/v/TelegramBotBase.Extensions.Images.svg?style=flat-square)](https://www.nuget.org/packages/TelegramBotBase.Extensions.Images/) [![Telegram chat](https://img.shields.io/badge/Support_Chat-Telegram-blue.svg?style=flat-square)](https://www.t.me/tgbotbase) - [![License](https://img.shields.io/github/license/MajMcCloud/telegrambotframework.svg?style=flat-square&maxAge=2592000&label=License)](https://raw.githubusercontent.com/MajMcCloud/TelegramBotFramework/master/LICENCE.md) [![Package Downloads](https://img.shields.io/nuget/dt/TelegramBotBase.Extensions.Images.svg?style=flat-square&label=Package%20Downloads)](https://www.nuget.org/packages/TelegramBotBase.Extensions.Images) diff --git a/TelegramBotBase.Extensions.Images/TelegramBotBase.Extensions.Images.csproj b/TelegramBotBase.Extensions.Images/TelegramBotBase.Extensions.Images.csproj index 0b84053..942981b 100644 --- a/TelegramBotBase.Extensions.Images/TelegramBotBase.Extensions.Images.csproj +++ b/TelegramBotBase.Extensions.Images/TelegramBotBase.Extensions.Images.csproj @@ -1,24 +1,24 @@  - - netstandard2.0;net5;netcoreapp3.1;net6 - https://github.com/MajMcCloud/TelegramBotFramework - https://github.com/MajMcCloud/TelegramBotFramework - MIT - true - snupkg - + + netstandard2.0;net5;netcoreapp3.1;net6 + https://github.com/MajMcCloud/TelegramBotFramework + https://github.com/MajMcCloud/TelegramBotFramework + MIT + true + snupkg + - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + - - - + + + diff --git a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/BotBaseBuilderExtensions.cs b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/BotBaseBuilderExtensions.cs index 06e1611..028cc02 100644 --- a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/BotBaseBuilderExtensions.cs +++ b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/BotBaseBuilderExtensions.cs @@ -6,16 +6,17 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL { public static class BotBaseBuilderExtensions { - /// - /// Uses an Microsoft SQL Server Database to save and restore sessions. + /// Uses an Microsoft SQL Server Database to save and restore sessions. /// /// /// /// /// /// - public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string connectionString, Type fallbackForm = null, string tablePrefix = "tgb_") + public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, + string connectionString, Type fallbackForm = null, + string tablePrefix = "tgb_") { var serializer = new MssqlSerializer(connectionString, tablePrefix, fallbackForm); @@ -26,7 +27,7 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL /// - /// Uses an Microsoft SQL Server Database to save and restore sessions. + /// Uses an Microsoft SQL Server Database to save and restore sessions. /// /// /// @@ -36,9 +37,12 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL /// /// /// - public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string hostOrIP, string databaseName, string userId, string password, Type fallbackForm = null, string tablePrefix = "tgb_") + public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string hostOrIP, + string databaseName, string userId, string password, + Type fallbackForm = null, string tablePrefix = "tgb_") { - var connectionString = $"Server={hostOrIP}; Database={databaseName}; User Id={userId}; Password={password}; TrustServerCertificate=true;"; + var connectionString = + $"Server={hostOrIP}; Database={databaseName}; User Id={userId}; Password={password}; TrustServerCertificate=true;"; var serializer = new MssqlSerializer(connectionString, tablePrefix, fallbackForm); @@ -48,7 +52,7 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL } /// - /// Uses an Microsoft SQL Server Database with Windows Authentication to save and restore sessions. + /// Uses an Microsoft SQL Server Database with Windows Authentication to save and restore sessions. /// /// /// @@ -56,12 +60,17 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL /// /// /// - public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string hostOrIP, string databaseName, bool integratedSecurity = true, Type fallbackForm = null, string tablePrefix = "tgb_") + public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string hostOrIP, + string databaseName, bool integratedSecurity = true, + Type fallbackForm = null, string tablePrefix = "tgb_") { if (!integratedSecurity) + { throw new ArgumentOutOfRangeException(); + } - var connectionString = $"Server={hostOrIP}; Database={databaseName}; Integrated Security=true; TrustServerCertificate=true;"; + var connectionString = + $"Server={hostOrIP}; Database={databaseName}; Integrated Security=true; TrustServerCertificate=true;"; var serializer = new MssqlSerializer(connectionString, tablePrefix, fallbackForm); @@ -70,4 +79,4 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL return builder as BotBaseBuilder; } } -} +} \ No newline at end of file diff --git a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/MSSQLSerializer.cs b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/MSSQLSerializer.cs index fe271e0..ed08d95 100644 --- a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/MSSQLSerializer.cs +++ b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/MSSQLSerializer.cs @@ -11,19 +11,19 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL { public class MssqlSerializer : IStateMachine { - public Type FallbackStateForm { get; set; } - public string ConnectionString { get; } - public string TablePrefix { get; set; } - /// - /// Will initialize the state machine. + /// Will initialize the state machine. /// /// Path of the file and name where to save the session details. - /// Type of Form which will be saved instead of Form which has attribute declared. Needs to be subclass of . + /// + /// Type of Form which will be saved instead of Form which has + /// attribute declared. Needs to be subclass of + /// . + /// /// Declares of the file could be overwritten. public MssqlSerializer(string connectionString, string tablePrefix = "tgb_", Type fallbackStateForm = null) { - this.ConnectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString)); + ConnectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString)); TablePrefix = tablePrefix; @@ -35,6 +35,10 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL } } + public string ConnectionString { get; } + public string TablePrefix { get; set; } + public Type FallbackStateForm { get; set; } + public StateContainer LoadFormStates() { var sc = new StateContainer(); @@ -44,7 +48,8 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL connection.Open(); var command = connection.CreateCommand(); - command.CommandText = "SELECT deviceId, deviceTitle, FormUri, QualifiedName FROM " + TablePrefix + "devices_sessions"; + command.CommandText = "SELECT deviceId, deviceTitle, FormUri, QualifiedName FROM " + TablePrefix + + "devices_sessions"; var dataTable = new DataTable(); using (var dataAdapter = new SqlDataAdapter(command)) @@ -73,7 +78,8 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL } var command2 = connection.CreateCommand(); - command2.CommandText = "SELECT [key], value, type FROM " + TablePrefix + "devices_sessions_data WHERE deviceId = @deviceId"; + command2.CommandText = "SELECT [key], value, type FROM " + TablePrefix + + "devices_sessions_data WHERE deviceId = @deviceId"; command2.Parameters.Add(new SqlParameter("@deviceId", r["deviceId"])); var dataTable2 = new DataTable(); @@ -91,13 +97,10 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL se.Values.Add(key, value); } } - } - } - connection.Close(); } @@ -127,13 +130,15 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL var sessionCommand = connection.CreateCommand(); var dataCommand = connection.CreateCommand(); - sessionCommand.CommandText = "INSERT INTO " + TablePrefix + "devices_sessions (deviceId, deviceTitle, FormUri, QualifiedName) VALUES (@deviceId, @deviceTitle, @FormUri, @QualifiedName)"; + sessionCommand.CommandText = "INSERT INTO " + TablePrefix + + "devices_sessions (deviceId, deviceTitle, FormUri, QualifiedName) VALUES (@deviceId, @deviceTitle, @FormUri, @QualifiedName)"; sessionCommand.Parameters.Add(new SqlParameter("@deviceId", "")); sessionCommand.Parameters.Add(new SqlParameter("@deviceTitle", "")); sessionCommand.Parameters.Add(new SqlParameter("@FormUri", "")); sessionCommand.Parameters.Add(new SqlParameter("@QualifiedName", "")); - dataCommand.CommandText = "INSERT INTO " + TablePrefix + "devices_sessions_data (deviceId, [key], value, type) VALUES (@deviceId, @key, @value, @type)"; + dataCommand.CommandText = "INSERT INTO " + TablePrefix + + "devices_sessions_data (deviceId, [key], value, type) VALUES (@deviceId, @key, @value, @type)"; dataCommand.Parameters.Add(new SqlParameter("@deviceId", "")); dataCommand.Parameters.Add(new SqlParameter("@key", "")); dataCommand.Parameters.Add(new SqlParameter("@value", "")); @@ -169,13 +174,10 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL dataCommand.ExecuteNonQuery(); } - } connection.Close(); } - - } } -} +} \ No newline at end of file diff --git a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/README.md b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/README.md index 1a7f027..1255d6e 100644 --- a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/README.md +++ b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/README.md @@ -3,7 +3,6 @@ [![NuGet version (TelegramBotBase)](https://img.shields.io/nuget/v/TelegramBotBase.Extensions.Serializer.Database.MSSQL.svg?style=flat-square)](https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Database.MSSQL/) [![Telegram chat](https://img.shields.io/badge/Support_Chat-Telegram-blue.svg?style=flat-square)](https://www.t.me/tgbotbase) - [![License](https://img.shields.io/github/license/MajMcCloud/telegrambotframework.svg?style=flat-square&maxAge=2592000&label=License)](https://raw.githubusercontent.com/MajMcCloud/TelegramBotFramework/master/LICENCE.md) [![Package Downloads](https://img.shields.io/nuget/dt/TelegramBotBase.Extensions.Serializer.Database.MSSQL.svg?style=flat-square&label=Package%20Downloads)](https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Database.MSSQL) diff --git a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/TelegramBotBase.Extensions.Serializer.Database.MSSQL.csproj b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/TelegramBotBase.Extensions.Serializer.Database.MSSQL.csproj index a0d40f7..4782e67 100644 --- a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/TelegramBotBase.Extensions.Serializer.Database.MSSQL.csproj +++ b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/TelegramBotBase.Extensions.Serializer.Database.MSSQL.csproj @@ -1,30 +1,30 @@  - - netstandard2.0;net5;netcoreapp3.1;net6 - True - https://github.com/MajMcCloud/TelegramBotFramework - https://github.com/MajMcCloud/TelegramBotFramework - MIT - true - snupkg - 1.0.1 - 1.0.1 - 1.0.1 - A session serializer for Microsoft SQL Server. - - + + netstandard2.0;net5;netcoreapp3.1;net6 + True + https://github.com/MajMcCloud/TelegramBotFramework + https://github.com/MajMcCloud/TelegramBotFramework + MIT + true + snupkg + 1.0.1 + 1.0.1 + 1.0.1 + A session serializer for Microsoft SQL Server. + + - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + - - - + + + diff --git a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/create_tables.sql b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/create_tables.sql index 587eb4f..8d895f8 100644 --- a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/create_tables.sql +++ b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/create_tables.sql @@ -1,37 +1,81 @@ -USE [telegram_bot] +USE +[telegram_bot] GO /****** Object: Table [dbo].[tgb_devices_sessions] Script Date: 30.06.2022 16:22:09 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -CREATE TABLE [dbo].[tgb_devices_sessions]( - [deviceId] [bigint] NOT NULL, - [deviceTitle] [nvarchar](512) NOT NULL, - [FormUri] [nvarchar](512) NOT NULL, - [QualifiedName] [nvarchar](512) NOT NULL, - CONSTRAINT [PK_tgb_devices_sessions_1] PRIMARY KEY CLUSTERED +CREATE TABLE [dbo].[tgb_devices_sessions] ( - [deviceId] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY] -) ON [PRIMARY] -GO + [ + deviceId] [ + bigint] + NOT + NULL, [ + deviceTitle] [ + nvarchar] +( + 512 +) NOT NULL, + [FormUri] [nvarchar] +( + 512 +) NOT NULL, + [QualifiedName] [nvarchar] +( + 512 +) NOT NULL, + CONSTRAINT [PK_tgb_devices_sessions_1] PRIMARY KEY CLUSTERED +( +[ + deviceId] ASC +) + WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) + ON [PRIMARY] + ) + ON [PRIMARY] + GO /****** Object: Table [dbo].[tgb_devices_sessions_data] Script Date: 30.06.2022 16:22:09 ******/ -SET ANSI_NULLS ON -GO -SET QUOTED_IDENTIFIER ON -GO -CREATE TABLE [dbo].[tgb_devices_sessions_data]( - [Id] [uniqueidentifier] NOT NULL, - [deviceId] [bigint] NOT NULL, - [key] [nvarchar](512) NOT NULL, - [value] [nvarchar](max) NOT NULL, - [type] [nvarchar](512) NOT NULL, - CONSTRAINT [PK_tgb_devices_session_data] PRIMARY KEY CLUSTERED + SET ANSI_NULLS + ON + GO + SET QUOTED_IDENTIFIER + ON + GO +CREATE TABLE [dbo].[tgb_devices_sessions_data] ( - [Id] ASC -)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY] -) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] -GO -ALTER TABLE [dbo].[tgb_devices_sessions_data] ADD CONSTRAINT [DF_tgb_devices_session_data_Id] DEFAULT (newid()) FOR [Id] -GO + [ + Id] [ + uniqueidentifier] + NOT + NULL, [ + deviceId] [ + bigint] + NOT + NULL, [ + key] [ + nvarchar] +( + 512 +) NOT NULL, + [value] [nvarchar] +( + max +) NOT NULL, + [type] [nvarchar] +( + 512 +) NOT NULL, + CONSTRAINT [PK_tgb_devices_session_data] PRIMARY KEY CLUSTERED +( +[ + Id] ASC +) + WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) + ON [PRIMARY] + ) + ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] + GO +ALTER TABLE [dbo].[tgb_devices_sessions_data] ADD CONSTRAINT [DF_tgb_devices_session_data_Id] DEFAULT (newid()) FOR [Id] + GO diff --git a/TelegramBotBase.Test/App.config b/TelegramBotBase.Test/App.config index fa1ddef..94f3e49 100644 --- a/TelegramBotBase.Test/App.config +++ b/TelegramBotBase.Test/App.config @@ -1,14 +1,14 @@ - + - - - - - - - - + + + + + + + + diff --git a/TelegramBotBase.Test/Program.cs b/TelegramBotBase.Test/Program.cs index a1d4b31..044dba2 100644 --- a/TelegramBotBase.Test/Program.cs +++ b/TelegramBotBase.Test/Program.cs @@ -7,109 +7,106 @@ using TelegramBotBase.Commands; using TelegramBotBase.Enums; using TelegramBotBaseTest.Tests; -namespace TelegramBotBaseTest +namespace TelegramBotBaseTest; + +internal class Program { - internal class Program + private static void Main(string[] args) { - private static void Main(string[] args) + var apiKey = ""; + + var bb = BotBaseBuilder + .Create() + .WithAPIKey(apiKey) + .DefaultMessageLoop() + .WithStartForm() + .NoProxy() + .CustomCommands(a => + { + a.Start("Starts the bot"); + a.Add("myid", "Returns my Device ID"); + a.Help("Should show you some help"); + a.Settings("Should show you some settings"); + a.Add("form1", "Opens test form 1"); + a.Add("form2", "Opens test form 2"); + a.Add("params", "Returns all send parameters as a message."); + }) + .NoSerialization() + .UseEnglish() + .Build(); + + + bb.BotCommand += Bb_BotCommand; + + //Update Bot commands to botfather + bb.UploadBotCommands().Wait(); + + bb.SetSetting(ESettings.LogAllMessages, true); + + bb.Message += (s, en) => { + Console.WriteLine(en.DeviceId + " " + en.Message.MessageText + " " + (en.Message.RawData ?? "")); + }; - var apiKey = ""; + bb.Start(); - var bb = BotBaseBuilder - .Create() - .WithAPIKey(apiKey) - .DefaultMessageLoop() - .WithStartForm() - .NoProxy() - .CustomCommands(a => - { - a.Start("Starts the bot"); - a.Add("myid", "Returns my Device ID"); - a.Help("Should show you some help"); - a.Settings("Should show you some settings"); - a.Add("form1", "Opens test form 1"); - a.Add("form2", "Opens test form 2"); - a.Add("params", "Returns all send parameters as a message."); - }) - .NoSerialization() - .UseEnglish() - .Build(); + Console.WriteLine("Telegram Bot started..."); + + Console.WriteLine("Press q to quit application."); - bb.BotCommand += Bb_BotCommand; + Console.ReadLine(); - //Update Bot commands to botfather - bb.UploadBotCommands().Wait(); + bb.Stop(); + } - bb.SetSetting(ESettings.LogAllMessages, true); - - bb.Message += (s, en) => - { - Console.WriteLine(en.DeviceId + " " + en.Message.MessageText + " " + (en.Message.RawData ?? "")); - }; - - bb.Start(); - - Console.WriteLine("Telegram Bot started..."); - - Console.WriteLine("Press q to quit application."); - - - Console.ReadLine(); - - bb.Stop(); - - } - - private static async Task Bb_BotCommand(object sender, BotCommandEventArgs en) + private static async Task Bb_BotCommand(object sender, BotCommandEventArgs en) + { + switch (en.Command) { - switch (en.Command) - { - case "/start": + case "/start": - var start = new Menu(); + var start = new Menu(); - await en.Device.ActiveForm.NavigateTo(start); + await en.Device.ActiveForm.NavigateTo(start); - break; - case "/form1": + break; + case "/form1": - var form1 = new TestForm(); + var form1 = new TestForm(); - await en.Device.ActiveForm.NavigateTo(form1); + await en.Device.ActiveForm.NavigateTo(form1); - break; + break; - case "/form2": + case "/form2": - var form2 = new TestForm2(); + var form2 = new TestForm2(); - await en.Device.ActiveForm.NavigateTo(form2); + await en.Device.ActiveForm.NavigateTo(form2); - break; + break; - case "/myid": + case "/myid": - await en.Device.Send($"Your Device ID is: {en.DeviceId}"); + await en.Device.Send($"Your Device ID is: {en.DeviceId}"); - en.Handled = true; + en.Handled = true; - break; + break; - case "/params": + case "/params": - var m = en.Parameters.DefaultIfEmpty("").Aggregate((a, b) => a + " and " + b); + var m = en.Parameters.DefaultIfEmpty("").Aggregate((a, b) => a + " and " + b); - await en.Device.Send("Your parameters are: " + m, replyTo: en.Device.LastMessageId); + await en.Device.Send("Your parameters are: " + m, replyTo: en.Device.LastMessageId); - en.Handled = true; + en.Handled = true; - break; - } + break; } } } diff --git a/TelegramBotBase.Test/Properties/AssemblyInfo.cs b/TelegramBotBase.Test/Properties/AssemblyInfo.cs index 53a2683..af85f77 100644 --- a/TelegramBotBase.Test/Properties/AssemblyInfo.cs +++ b/TelegramBotBase.Test/Properties/AssemblyInfo.cs @@ -32,4 +32,4 @@ using System.Runtime.InteropServices; // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/TelegramBotBase.Test/TelegramBotBaseTest.csproj b/TelegramBotBase.Test/TelegramBotBaseTest.csproj index a1abbf6..c40ee57 100644 --- a/TelegramBotBase.Test/TelegramBotBaseTest.csproj +++ b/TelegramBotBase.Test/TelegramBotBaseTest.csproj @@ -1,34 +1,35 @@  - - Exe - netcoreapp3.1;net5;net6 - false - Debug;Release - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - + + Exe + netcoreapp3.1;net5;net6 + 10 + false + Debug;Release + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + - - - - + + + + diff --git a/TelegramBotBase.Test/Tests/ButtonTestForm.cs b/TelegramBotBase.Test/Tests/ButtonTestForm.cs index 8f89af6..f19b7d0 100644 --- a/TelegramBotBase.Test/Tests/ButtonTestForm.cs +++ b/TelegramBotBase.Test/Tests/ButtonTestForm.cs @@ -3,97 +3,92 @@ using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests +namespace TelegramBotBaseTest.Tests; + +public class ButtonTestForm : AutoCleanForm { - public class ButtonTestForm : AutoCleanForm + public ButtonTestForm() { + Opened += ButtonTestForm_Opened; + } - public ButtonTestForm() + private async Task ButtonTestForm_Opened(object sender, EventArgs e) + { + await Device.Send("Hello world! (Click 'back' to get back to Start)"); + } + + public override async Task Action(MessageResult message) + { + var call = message.GetData(); + + await message.ConfirmAction(); + + + if (call == null) { - Opened += ButtonTestForm_Opened; + return; } - private async Task ButtonTestForm_Opened(object sender, EventArgs e) + message.Handled = true; + + switch (call.Value) { - await Device.Send("Hello world! (Click 'back' to get back to Start)"); - } + case "button1": - public override async Task Action(MessageResult message) - { + await Device.Send("Button 1 pressed"); - var call = message.GetData(); + break; - await message.ConfirmAction(); + case "button2": + await Device.Send("Button 2 pressed"); - if (call == null) - return; + break; - message.Handled = true; + case "button3": - switch (call.Value) - { - case "button1": + await Device.Send("Button 3 pressed"); - await Device.Send("Button 1 pressed"); + break; - break; + case "button4": - case "button2": + await Device.Send("Button 4 pressed"); - await Device.Send("Button 2 pressed"); + break; - break; + case "back": - case "button3": + var st = new Menu(); - await Device.Send("Button 3 pressed"); + await NavigateTo(st); - break; + break; - case "button4": - - await Device.Send("Button 4 pressed"); - - break; - - case "back": - - var st = new Menu(); - - await NavigateTo(st); - - break; - - default: - - message.Handled = false; - - break; - } - - - } - - - public override async Task Render(MessageResult message) - { - - var btn = new ButtonForm(); - - btn.AddButtonRow(new ButtonBase("Button 1", new CallbackData("a", "button1").Serialize()), new ButtonBase("Button 2", new CallbackData("a", "button2").Serialize())); - - btn.AddButtonRow(new ButtonBase("Button 3", new CallbackData("a", "button3").Serialize()), new ButtonBase("Button 4", new CallbackData("a", "button4").Serialize())); - - btn.AddButtonRow(new ButtonBase("Google.com", "google", "https://www.google.com"), new ButtonBase("Telegram", "telegram", "https://telegram.org/")); - - btn.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "back").Serialize())); - - await Device.Send("Click a button", btn); + default: + message.Handled = false; + break; } } -} + public override async Task Render(MessageResult message) + { + var btn = new ButtonForm(); + + btn.AddButtonRow(new ButtonBase("Button 1", new CallbackData("a", "button1").Serialize()), + new ButtonBase("Button 2", new CallbackData("a", "button2").Serialize())); + + btn.AddButtonRow(new ButtonBase("Button 3", new CallbackData("a", "button3").Serialize()), + new ButtonBase("Button 4", new CallbackData("a", "button4").Serialize())); + + btn.AddButtonRow(new ButtonBase("Google.com", "google", "https://www.google.com"), + new ButtonBase("Telegram", "telegram", "https://telegram.org/")); + + btn.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "back").Serialize())); + + await Device.Send("Click a button", btn); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs b/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs index 3a7bdd9..0669d2e 100644 --- a/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs @@ -4,68 +4,66 @@ using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls +namespace TelegramBotBaseTest.Tests.Controls; + +public class ButtonGridForm : AutoCleanForm { - public class ButtonGridForm : AutoCleanForm + private ButtonGrid _mButtons; + + public ButtonGridForm() { - private ButtonGrid _mButtons; + DeleteMode = EDeleteMode.OnLeavingForm; - public ButtonGridForm() + Init += ButtonGridForm_Init; + } + + private Task ButtonGridForm_Init(object sender, InitEventArgs e) + { + _mButtons = new ButtonGrid { - DeleteMode = EDeleteMode.OnLeavingForm; + KeyboardType = EKeyboardType.InlineKeyBoard + }; - Init += ButtonGridForm_Init; + var bf = new ButtonForm(); + + bf.AddButtonRow(new ButtonBase("Back", "back"), new ButtonBase("Switch Keyboard", "switch")); + + bf.AddButtonRow(new ButtonBase("Button1", "b1"), new ButtonBase("Button2", "b2")); + + bf.AddButtonRow(new ButtonBase("Button3", "b3"), new ButtonBase("Button4", "b4")); + + _mButtons.ButtonsForm = bf; + + _mButtons.ButtonClicked += Bg_ButtonClicked; + + AddControl(_mButtons); + return Task.CompletedTask; + } + + private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) + { + if (e.Button == null) + { + return; } - private Task ButtonGridForm_Init(object sender, InitEventArgs e) + if (e.Button.Value == "back") { - _mButtons = new ButtonGrid + var start = new Menu(); + await NavigateTo(start); + } + else if (e.Button.Value == "switch") + { + _mButtons.KeyboardType = _mButtons.KeyboardType switch { - KeyboardType = EKeyboardType.InlineKeyBoard + EKeyboardType.ReplyKeyboard => EKeyboardType.InlineKeyBoard, + EKeyboardType.InlineKeyBoard => EKeyboardType.ReplyKeyboard, + _ => _mButtons.KeyboardType }; - - var bf = new ButtonForm(); - - bf.AddButtonRow(new ButtonBase("Back", "back"), new ButtonBase("Switch Keyboard", "switch")); - - bf.AddButtonRow(new ButtonBase("Button1", "b1"), new ButtonBase("Button2", "b2")); - - bf.AddButtonRow(new ButtonBase("Button3", "b3"), new ButtonBase("Button4", "b4")); - - _mButtons.ButtonsForm = bf; - - _mButtons.ButtonClicked += Bg_ButtonClicked; - - AddControl(_mButtons); - return Task.CompletedTask; } - - private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) + else { - if (e.Button == null) - return; - - if (e.Button.Value == "back") - { - var start = new Menu(); - await NavigateTo(start); - } - else if (e.Button.Value == "switch") - { - _mButtons.KeyboardType = _mButtons.KeyboardType switch - { - EKeyboardType.ReplyKeyboard => EKeyboardType.InlineKeyBoard, - EKeyboardType.InlineKeyBoard => EKeyboardType.ReplyKeyboard, - _ => _mButtons.KeyboardType - }; - } - else - { - - await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); - } - - + await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); } } -} +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs b/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs index cc62321..47d6205 100644 --- a/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs @@ -6,63 +6,61 @@ using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls +namespace TelegramBotBaseTest.Tests.Controls; + +public class ButtonGridPagingForm : AutoCleanForm { - public class ButtonGridPagingForm : AutoCleanForm + private ButtonGrid _mButtons; + + public ButtonGridPagingForm() { - private ButtonGrid _mButtons; + DeleteMode = EDeleteMode.OnLeavingForm; - public ButtonGridPagingForm() + Init += ButtonGridForm_Init; + } + + private Task ButtonGridForm_Init(object sender, InitEventArgs e) + { + _mButtons = new ButtonGrid { - DeleteMode = EDeleteMode.OnLeavingForm; + KeyboardType = EKeyboardType.ReplyKeyboard, + EnablePaging = true, + EnableSearch = true, + HeadLayoutButtonRow = new List { new("Back", "back") } + }; - Init += ButtonGridForm_Init; + var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures); + + var bf = new ButtonForm(); + + foreach (var c in countries) + { + bf.AddButtonRow(new ButtonBase(c.EnglishName, c.EnglishName)); } - private Task ButtonGridForm_Init(object sender, InitEventArgs e) + _mButtons.ButtonsForm = bf; + + _mButtons.ButtonClicked += Bg_ButtonClicked; + + AddControl(_mButtons); + return Task.CompletedTask; + } + + private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) + { + if (e.Button == null) { - _mButtons = new ButtonGrid - { - KeyboardType = EKeyboardType.ReplyKeyboard, - EnablePaging = true, - EnableSearch = true, - HeadLayoutButtonRow = new List { new ButtonBase("Back", "back") } - }; - - var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures); - - var bf = new ButtonForm(); - - foreach (var c in countries) - { - bf.AddButtonRow(new ButtonBase(c.EnglishName, c.EnglishName)); - } - - _mButtons.ButtonsForm = bf; - - _mButtons.ButtonClicked += Bg_ButtonClicked; - - AddControl(_mButtons); - return Task.CompletedTask; + return; } - private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) + if (e.Button.Value == "back") { - if (e.Button == null) - return; - - if (e.Button.Value == "back") - { - var start = new Menu(); - await NavigateTo(start); - } - else - { - - await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); - } - - + var start = new Menu(); + await NavigateTo(start); + } + else + { + await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); } } -} +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs b/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs index 510f208..23b4b1d 100644 --- a/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs @@ -8,68 +8,67 @@ using TelegramBotBase.DataSources; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls +namespace TelegramBotBaseTest.Tests.Controls; + +public class ButtonGridTagForm : AutoCleanForm { - public class ButtonGridTagForm : AutoCleanForm + private TaggedButtonGrid _mButtons; + + public ButtonGridTagForm() { - private TaggedButtonGrid _mButtons; + DeleteMode = EDeleteMode.OnLeavingForm; - public ButtonGridTagForm() - { - DeleteMode = EDeleteMode.OnLeavingForm; - - Init += ButtonGridTagForm_Init; - } - - private Task ButtonGridTagForm_Init(object sender, InitEventArgs e) - { - _mButtons = new TaggedButtonGrid - { - KeyboardType = EKeyboardType.ReplyKeyboard, - EnablePaging = true, - HeadLayoutButtonRow = new List { new ButtonBase("Back", "back") } - }; - - - var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures); - - var bf = new ButtonForm(); - - foreach (var c in countries) - { - bf.AddButtonRow(new TagButtonBase(c.EnglishName, c.EnglishName, c.Parent.EnglishName)); - } - - _mButtons.Tags = countries.Select(a => a.Parent.EnglishName).Distinct().OrderBy(a => a).ToList(); - _mButtons.SelectedTags = countries.Select(a => a.Parent.EnglishName).Distinct().OrderBy(a => a).ToList(); - - _mButtons.EnableCheckAllTools = true; - - _mButtons.DataSource = new ButtonFormDataSource(bf); - - _mButtons.ButtonClicked += Bg_ButtonClicked; - - AddControl(_mButtons); - return Task.CompletedTask; - } - - private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) - { - if (e.Button == null) - return; - - switch (e.Button.Value) - { - - case "back": - var start = new Menu(); - await NavigateTo(start); - return; - - } - - - await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); - } + Init += ButtonGridTagForm_Init; } -} + + private Task ButtonGridTagForm_Init(object sender, InitEventArgs e) + { + _mButtons = new TaggedButtonGrid + { + KeyboardType = EKeyboardType.ReplyKeyboard, + EnablePaging = true, + HeadLayoutButtonRow = new List { new("Back", "back") } + }; + + + var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures); + + var bf = new ButtonForm(); + + foreach (var c in countries) + { + bf.AddButtonRow(new TagButtonBase(c.EnglishName, c.EnglishName, c.Parent.EnglishName)); + } + + _mButtons.Tags = countries.Select(a => a.Parent.EnglishName).Distinct().OrderBy(a => a).ToList(); + _mButtons.SelectedTags = countries.Select(a => a.Parent.EnglishName).Distinct().OrderBy(a => a).ToList(); + + _mButtons.EnableCheckAllTools = true; + + _mButtons.DataSource = new ButtonFormDataSource(bf); + + _mButtons.ButtonClicked += Bg_ButtonClicked; + + AddControl(_mButtons); + return Task.CompletedTask; + } + + private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) + { + if (e.Button == null) + { + return; + } + + switch (e.Button.Value) + { + case "back": + var start = new Menu(); + await NavigateTo(start); + return; + } + + + await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Controls/CalendarPickerForm.cs b/TelegramBotBase.Test/Tests/Controls/CalendarPickerForm.cs index 4d1eaac..69de30f 100644 --- a/TelegramBotBase.Test/Tests/Controls/CalendarPickerForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/CalendarPickerForm.cs @@ -5,75 +5,65 @@ using TelegramBotBase.Controls.Inline; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls +namespace TelegramBotBaseTest.Tests.Controls; + +public class CalendarPickerForm : AutoCleanForm { - public class CalendarPickerForm : AutoCleanForm + public CalendarPickerForm() { - - public CalendarPicker Picker { get; set; } - - private int? SelectedDateMessage { get; set; } - - public CalendarPickerForm() - { - DeleteMode = EDeleteMode.OnLeavingForm; - Init += CalendarPickerForm_Init; - } - - private Task CalendarPickerForm_Init(object sender, InitEventArgs e) - { - Picker = new CalendarPicker - { - Title = "Datum auswählen / Pick date" - }; - - AddControl(Picker); - return Task.CompletedTask; - } - - - public override async Task Action(MessageResult message) - { - - switch(message.RawData) - { - case "back": - - var s = new Menu(); - - await NavigateTo(s); - - break; - } - - } - - public override async Task Render(MessageResult message) - { - var s = ""; - - s = "Selected date is " + Picker.SelectedDate.ToShortDateString() + "\r\n"; - s += "Selected month is " + Picker.Culture.DateTimeFormat.MonthNames[Picker.VisibleMonth.Month - 1] + "\r\n"; - s += "Selected year is " + Picker.VisibleMonth.Year; - - var bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase("Back","back")); - - if (SelectedDateMessage != null) - { - await Device.Edit(SelectedDateMessage.Value, s, bf); - } - else - { - var m = await Device.Send(s, bf); - SelectedDateMessage = m.MessageId; - } - - - - } - - - + DeleteMode = EDeleteMode.OnLeavingForm; + Init += CalendarPickerForm_Init; } -} + + public CalendarPicker Picker { get; set; } + + private int? SelectedDateMessage { get; set; } + + private Task CalendarPickerForm_Init(object sender, InitEventArgs e) + { + Picker = new CalendarPicker + { + Title = "Datum auswählen / Pick date" + }; + + AddControl(Picker); + return Task.CompletedTask; + } + + + public override async Task Action(MessageResult message) + { + switch (message.RawData) + { + case "back": + + var s = new Menu(); + + await NavigateTo(s); + + break; + } + } + + public override async Task Render(MessageResult message) + { + var s = ""; + + s = "Selected date is " + Picker.SelectedDate.ToShortDateString() + "\r\n"; + s += "Selected month is " + Picker.Culture.DateTimeFormat.MonthNames[Picker.VisibleMonth.Month - 1] + "\r\n"; + s += "Selected year is " + Picker.VisibleMonth.Year; + + var bf = new ButtonForm(); + bf.AddButtonRow(new ButtonBase("Back", "back")); + + if (SelectedDateMessage != null) + { + await Device.Edit(SelectedDateMessage.Value, s, bf); + } + else + { + var m = await Device.Send(s, bf); + SelectedDateMessage = m.MessageId; + } + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Controls/CheckedButtonListForm.cs b/TelegramBotBase.Test/Tests/Controls/CheckedButtonListForm.cs index 6906c4f..33849ae 100644 --- a/TelegramBotBase.Test/Tests/Controls/CheckedButtonListForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/CheckedButtonListForm.cs @@ -6,81 +6,81 @@ using TelegramBotBase.DataSources; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls +namespace TelegramBotBaseTest.Tests.Controls; + +public class CheckedButtonListForm : AutoCleanForm { - public class CheckedButtonListForm : AutoCleanForm + private CheckedButtonList _mButtons; + + public CheckedButtonListForm() { - private CheckedButtonList _mButtons; + DeleteMode = EDeleteMode.OnLeavingForm; - public CheckedButtonListForm() + Init += CheckedButtonListForm_Init; + } + + private Task CheckedButtonListForm_Init(object sender, InitEventArgs e) + { + _mButtons = new CheckedButtonList { - DeleteMode = EDeleteMode.OnLeavingForm; + KeyboardType = EKeyboardType.InlineKeyBoard, + EnablePaging = true, + HeadLayoutButtonRow = new List { new("Back", "back"), new("Switch Keyboard", "switch") }, + SubHeadLayoutButtonRow = new List { new("No checked items", "$") } + }; - Init += CheckedButtonListForm_Init; + var bf = new ButtonForm(); + + for (var i = 0; i < 30; i++) + { + bf.AddButtonRow($"{i + 1}. Item", i.ToString()); } - private Task CheckedButtonListForm_Init(object sender, InitEventArgs e) + _mButtons.DataSource = new ButtonFormDataSource(bf); + + _mButtons.ButtonClicked += Bg_ButtonClicked; + _mButtons.CheckedChanged += M_Buttons_CheckedChanged; + + AddControl(_mButtons); + return Task.CompletedTask; + } + + private Task M_Buttons_CheckedChanged(object sender, CheckedChangedEventArgs e) + { + _mButtons.SubHeadLayoutButtonRow = new List + { new($"{_mButtons.CheckedItems.Count} checked items", "$") }; + return Task.CompletedTask; + } + + private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) + { + if (e.Button == null) { - _mButtons = new CheckedButtonList - { - KeyboardType = EKeyboardType.InlineKeyBoard, - EnablePaging = true, - HeadLayoutButtonRow = new List { new ButtonBase("Back", "back"), new ButtonBase("Switch Keyboard", "switch") }, - SubHeadLayoutButtonRow = new List { new ButtonBase("No checked items", "$") } - }; - - var bf = new ButtonForm(); - - for (var i = 0; i < 30; i++) - { - bf.AddButtonRow($"{i + 1}. Item", i.ToString()); - } - - _mButtons.DataSource = new ButtonFormDataSource(bf); - - _mButtons.ButtonClicked += Bg_ButtonClicked; - _mButtons.CheckedChanged += M_Buttons_CheckedChanged; - - AddControl(_mButtons); - return Task.CompletedTask; + return; } - private Task M_Buttons_CheckedChanged(object sender, CheckedChangedEventArgs e) + switch (e.Button.Value) { - _mButtons.SubHeadLayoutButtonRow = new List { new ButtonBase($"{_mButtons.CheckedItems.Count} checked items", "$") }; - return Task.CompletedTask; - } + case "back": - private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) - { - if (e.Button == null) - return; - - switch (e.Button.Value) - { - case "back": - - var start = new Menu(); - await NavigateTo(start); - break; + var start = new Menu(); + await NavigateTo(start); + break; - case "switch": - _mButtons.KeyboardType = _mButtons.KeyboardType switch - { - EKeyboardType.ReplyKeyboard => EKeyboardType.InlineKeyBoard, - EKeyboardType.InlineKeyBoard => EKeyboardType.ReplyKeyboard, - _ => _mButtons.KeyboardType - }; - - break; - - default: - await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); - break; - } + case "switch": + _mButtons.KeyboardType = _mButtons.KeyboardType switch + { + EKeyboardType.ReplyKeyboard => EKeyboardType.InlineKeyBoard, + EKeyboardType.InlineKeyBoard => EKeyboardType.ReplyKeyboard, + _ => _mButtons.KeyboardType + }; + break; + default: + await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); + break; } } -} +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Controls/MonthPickerForm.cs b/TelegramBotBase.Test/Tests/Controls/MonthPickerForm.cs index 3774430..c44021f 100644 --- a/TelegramBotBase.Test/Tests/Controls/MonthPickerForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/MonthPickerForm.cs @@ -5,73 +5,63 @@ using TelegramBotBase.Controls.Inline; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls +namespace TelegramBotBaseTest.Tests.Controls; + +public class MonthPickerForm : AutoCleanForm { - public class MonthPickerForm : AutoCleanForm + public MonthPickerForm() { - - public MonthPicker Picker { get; set; } - - private int? SelectedDateMessage { get; set; } - - public MonthPickerForm() - { - DeleteMode = EDeleteMode.OnLeavingForm; - Init += MonthPickerForm_Init; - } - - private Task MonthPickerForm_Init(object sender, InitEventArgs e) - { - Picker = new MonthPicker - { - Title = "Monat auswählen / Pick month" - }; - AddControl(Picker); - return Task.CompletedTask; - } - - - public override async Task Action(MessageResult message) - { - - switch(message.RawData) - { - case "back": - - var s = new Menu(); - - await NavigateTo(s); - - break; - } - - } - - public override async Task Render(MessageResult message) - { - var s = ""; - - s += "Selected month is " + Picker.Culture.DateTimeFormat.MonthNames[Picker.SelectedDate.Month - 1] + "\r\n"; - s += "Selected year is " + Picker.VisibleMonth.Year; - - var bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase("Back","back")); - - if (SelectedDateMessage != null) - { - await Device.Edit(SelectedDateMessage.Value, s, bf); - } - else - { - var m = await Device.Send(s, bf); - SelectedDateMessage = m.MessageId; - } - - - - } - - - + DeleteMode = EDeleteMode.OnLeavingForm; + Init += MonthPickerForm_Init; } -} + + public MonthPicker Picker { get; set; } + + private int? SelectedDateMessage { get; set; } + + private Task MonthPickerForm_Init(object sender, InitEventArgs e) + { + Picker = new MonthPicker + { + Title = "Monat auswählen / Pick month" + }; + AddControl(Picker); + return Task.CompletedTask; + } + + + public override async Task Action(MessageResult message) + { + switch (message.RawData) + { + case "back": + + var s = new Menu(); + + await NavigateTo(s); + + break; + } + } + + public override async Task Render(MessageResult message) + { + var s = ""; + + s += "Selected month is " + Picker.Culture.DateTimeFormat.MonthNames[Picker.SelectedDate.Month - 1] + "\r\n"; + s += "Selected year is " + Picker.VisibleMonth.Year; + + var bf = new ButtonForm(); + bf.AddButtonRow(new ButtonBase("Back", "back")); + + if (SelectedDateMessage != null) + { + await Device.Edit(SelectedDateMessage.Value, s, bf); + } + else + { + var m = await Device.Send(s, bf); + SelectedDateMessage = m.MessageId; + } + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Controls/MultiToggleButtons.cs b/TelegramBotBase.Test/Tests/Controls/MultiToggleButtons.cs index dfa774f..c75c065 100644 --- a/TelegramBotBase.Test/Tests/Controls/MultiToggleButtons.cs +++ b/TelegramBotBase.Test/Tests/Controls/MultiToggleButtons.cs @@ -7,51 +7,49 @@ using TelegramBotBase.Controls.Inline; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls +namespace TelegramBotBaseTest.Tests.Controls; + +public class MultiToggleButtons : AutoCleanForm { - public class MultiToggleButtons : AutoCleanForm + public MultiToggleButtons() { - public MultiToggleButtons() - { - DeleteMode = EDeleteMode.OnLeavingForm; + DeleteMode = EDeleteMode.OnLeavingForm; - Init += ToggleButtons_Init; - } - - private Task ToggleButtons_Init(object sender, InitEventArgs e) - { - - var mtb = new MultiToggleButton - { - Options = new List { new ButtonBase("Option 1", "1"), new ButtonBase("Option 2", "2"), new ButtonBase("Option 3", "3") } - }; - - mtb.SelectedOption = mtb.Options.FirstOrDefault(); - mtb.Toggled += Tb_Toggled; - AddControl(mtb); - - mtb = new MultiToggleButton - { - Options = new List { new ButtonBase("Option 4", "4"), new ButtonBase("Option 5", "5"), new ButtonBase("Option 6", "6") } - }; - - mtb.SelectedOption = mtb.Options.FirstOrDefault(); - mtb.AllowEmptySelection = false; - mtb.Toggled += Tb_Toggled; - AddControl(mtb); - return Task.CompletedTask; - } - - private void Tb_Toggled(object sender, EventArgs e) - { - var tb = sender as MultiToggleButton; - if (tb.SelectedOption != null) - { - Console.WriteLine(tb.Id + " was pressed, and toggled to " + tb.SelectedOption.Value); - return; - } - - Console.WriteLine("Selection for " + tb.Id + " has been removed."); - } + Init += ToggleButtons_Init; } -} + + private Task ToggleButtons_Init(object sender, InitEventArgs e) + { + var mtb = new MultiToggleButton + { + Options = new List { new("Option 1", "1"), new("Option 2", "2"), new("Option 3", "3") } + }; + + mtb.SelectedOption = mtb.Options.FirstOrDefault(); + mtb.Toggled += Tb_Toggled; + AddControl(mtb); + + mtb = new MultiToggleButton + { + Options = new List { new("Option 4", "4"), new("Option 5", "5"), new("Option 6", "6") } + }; + + mtb.SelectedOption = mtb.Options.FirstOrDefault(); + mtb.AllowEmptySelection = false; + mtb.Toggled += Tb_Toggled; + AddControl(mtb); + return Task.CompletedTask; + } + + private void Tb_Toggled(object sender, EventArgs e) + { + var tb = sender as MultiToggleButton; + if (tb.SelectedOption != null) + { + Console.WriteLine(tb.Id + " was pressed, and toggled to " + tb.SelectedOption.Value); + return; + } + + Console.WriteLine("Selection for " + tb.Id + " has been removed."); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs b/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs index e5f6431..0511cb6 100644 --- a/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs @@ -5,50 +5,46 @@ using TelegramBotBase.Enums; using TelegramBotBase.Form; using TelegramBotBaseTest.Tests.Controls.Subclass; -namespace TelegramBotBaseTest.Tests.Controls +namespace TelegramBotBaseTest.Tests.Controls; + +public class MultiViewForm : AutoCleanForm { - public class MultiViewForm : AutoCleanForm + private ButtonGrid _bg; + private MultiViewTest _mvt; + + public MultiViewForm() { - private MultiViewTest _mvt; - - private ButtonGrid _bg; - - public MultiViewForm() - { - DeleteMode = EDeleteMode.OnLeavingForm; - Init += MultiViewForm_Init; - } - - private Task MultiViewForm_Init(object sender, InitEventArgs e) - { - _mvt = new MultiViewTest(); - - AddControl(_mvt); - - _bg = new ButtonGrid - { - ButtonsForm = new ButtonForm() - }; - _bg.ButtonsForm.AddButtonRow("Back", "$back$"); - _bg.ButtonClicked += Bg_ButtonClicked; - _bg.KeyboardType = EKeyboardType.ReplyKeyboard; - AddControl(_bg); - return Task.CompletedTask; - } - - private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) - { - switch(e.Button.Value) - { - case "$back$": - - var mn = new Menu(); - await NavigateTo(mn); - - break; - } - } - - + DeleteMode = EDeleteMode.OnLeavingForm; + Init += MultiViewForm_Init; } -} + + private Task MultiViewForm_Init(object sender, InitEventArgs e) + { + _mvt = new MultiViewTest(); + + AddControl(_mvt); + + _bg = new ButtonGrid + { + ButtonsForm = new ButtonForm() + }; + _bg.ButtonsForm.AddButtonRow("Back", "$back$"); + _bg.ButtonClicked += Bg_ButtonClicked; + _bg.KeyboardType = EKeyboardType.ReplyKeyboard; + AddControl(_bg); + return Task.CompletedTask; + } + + private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) + { + switch (e.Button.Value) + { + case "$back$": + + var mn = new Menu(); + await NavigateTo(mn); + + break; + } + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs b/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs index 79dfeab..08c7649 100644 --- a/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs +++ b/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs @@ -4,59 +4,49 @@ using TelegramBotBase.Base; using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls.Subclass +namespace TelegramBotBaseTest.Tests.Controls.Subclass; + +public class MultiViewTest : MultiView { - public class MultiViewTest : MultiView + public override Task Action(MessageResult result, string value = null) { - - - public override Task Action(MessageResult result, string value = null) + switch (result.RawData) { - switch (result.RawData) - { - case "back": + case "back": - SelectedViewIndex--; + SelectedViewIndex--; - break; - case "next": + break; + case "next": - SelectedViewIndex++; + SelectedViewIndex++; - break; - } - - return Task.CompletedTask; + break; } - public override async Task RenderView(RenderViewEventArgs e) - { - - var bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase("Back", "back"), new ButtonBase("Next", "next")); - - switch (e.CurrentView) - { - case 0: - case 1: - case 2: - - await Device.Send($"Page {e.CurrentView + 1}", bf); - - break; - - default: - - await Device.Send("Unknown Page", bf); - - break; - - - } - - } - - - + return Task.CompletedTask; } -} + + public override async Task RenderView(RenderViewEventArgs e) + { + var bf = new ButtonForm(); + bf.AddButtonRow(new ButtonBase("Back", "back"), new ButtonBase("Next", "next")); + + switch (e.CurrentView) + { + case 0: + case 1: + case 2: + + await Device.Send($"Page {e.CurrentView + 1}", bf); + + break; + + default: + + await Device.Send("Unknown Page", bf); + + break; + } + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Controls/ToggleButtons.cs b/TelegramBotBase.Test/Tests/Controls/ToggleButtons.cs index cb46305..67db7e7 100644 --- a/TelegramBotBase.Test/Tests/Controls/ToggleButtons.cs +++ b/TelegramBotBase.Test/Tests/Controls/ToggleButtons.cs @@ -5,50 +5,48 @@ using TelegramBotBase.Controls.Inline; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls +namespace TelegramBotBaseTest.Tests.Controls; + +public class ToggleButtons : AutoCleanForm { - public class ToggleButtons : AutoCleanForm + public ToggleButtons() { - public ToggleButtons() - { - DeleteMode = EDeleteMode.OnLeavingForm; + DeleteMode = EDeleteMode.OnLeavingForm; - Init += ToggleButtons_Init; - } - - private Task ToggleButtons_Init(object sender, InitEventArgs e) - { - - var tb = new ToggleButton - { - Checked = true - }; - tb.Toggled += Tb_Toggled; - - AddControl(tb); - - tb = new ToggleButton - { - Checked = false - }; - tb.Toggled += Tb_Toggled; - - AddControl(tb); - - tb = new ToggleButton - { - Checked = true - }; - tb.Toggled += Tb_Toggled; - - AddControl(tb); - return Task.CompletedTask; - } - - private void Tb_Toggled(object sender, EventArgs e) - { - var tb = sender as ToggleButton; - Console.WriteLine(tb.Id + " was pressed, and toggled to " + (tb.Checked ? "Checked" : "Unchecked")); - } + Init += ToggleButtons_Init; } -} + + private Task ToggleButtons_Init(object sender, InitEventArgs e) + { + var tb = new ToggleButton + { + Checked = true + }; + tb.Toggled += Tb_Toggled; + + AddControl(tb); + + tb = new ToggleButton + { + Checked = false + }; + tb.Toggled += Tb_Toggled; + + AddControl(tb); + + tb = new ToggleButton + { + Checked = true + }; + tb.Toggled += Tb_Toggled; + + AddControl(tb); + return Task.CompletedTask; + } + + private void Tb_Toggled(object sender, EventArgs e) + { + var tb = sender as ToggleButton; + Console.WriteLine(tb.Id + " was pressed, and toggled to " + (tb.Checked ? "Checked" : "Unchecked")); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Controls/TreeViewForms.cs b/TelegramBotBase.Test/Tests/Controls/TreeViewForms.cs index 4a41460..b5d7465 100644 --- a/TelegramBotBase.Test/Tests/Controls/TreeViewForms.cs +++ b/TelegramBotBase.Test/Tests/Controls/TreeViewForms.cs @@ -5,93 +5,94 @@ using TelegramBotBase.Controls.Inline; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls +namespace TelegramBotBaseTest.Tests.Controls; + +public class TreeViewForms : AutoCleanForm { - public class TreeViewForms : AutoCleanForm + public TreeViewForms() { - public TreeView View { get; set; } - - private int? MessageId { get; set; } - - public TreeViewForms() - { - DeleteMode = EDeleteMode.OnLeavingForm; - Init += TreeViewForms_Init; - } - - private Task TreeViewForms_Init(object sender, InitEventArgs e) - { - View = new TreeView(); - - var tvn = new TreeViewNode("Cars", "cars"); - - tvn.AddNode(new TreeViewNode("Porsche", "porsche", new TreeViewNode("Website", "web", "https://www.porsche.com/germany/"), new TreeViewNode("911", "911"), new TreeViewNode("918 Spyder", "918"))); - tvn.AddNode(new TreeViewNode("BMW", "bmw")); - tvn.AddNode(new TreeViewNode("Audi", "audi")); - tvn.AddNode(new TreeViewNode("VW", "vw")); - tvn.AddNode(new TreeViewNode("Lamborghini", "lamborghini")); - - View.Nodes.Add(tvn); - - tvn = new TreeViewNode("Fruits", "fruits"); - - tvn.AddNode(new TreeViewNode("Apple", "apple")); - tvn.AddNode(new TreeViewNode("Orange", "orange")); - tvn.AddNode(new TreeViewNode("Lemon", "lemon")); - - View.Nodes.Add(tvn); - - AddControl(View); - return Task.CompletedTask; - } - - public override async Task Action(MessageResult message) - { - await message.ConfirmAction(); - - if (message.Handled) - return; - - switch (message.RawData) - { - case "back": - - message.Handled = true; - - var start = new Menu(); - - await NavigateTo(start); - - break; - - } - - } - - public override async Task Render(MessageResult message) - { - var s = ""; - - s += "Selected Node: " + (View.SelectedNode?.Text ?? "(null)") + "\r\n"; - - s += "Visible Node: " + (View.VisibleNode?.Text ?? "(top)") + "\r\n"; - - s += "Visible Path: " + View.GetPath() + "\r\n"; - s += "Selected Path: " + (View.SelectedNode?.GetPath() ?? "(null)") + "\r\n"; - - var bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase("Back", "back")); - - if (MessageId != null) - { - await Device.Edit(MessageId.Value, s, bf); - } - else - { - var m = await Device.Send(s, bf); - MessageId = m.MessageId; - } - } - + DeleteMode = EDeleteMode.OnLeavingForm; + Init += TreeViewForms_Init; } -} + + public TreeView View { get; set; } + + private int? MessageId { get; set; } + + private Task TreeViewForms_Init(object sender, InitEventArgs e) + { + View = new TreeView(); + + var tvn = new TreeViewNode("Cars", "cars"); + + tvn.AddNode(new TreeViewNode("Porsche", "porsche", + new TreeViewNode("Website", "web", "https://www.porsche.com/germany/"), + new TreeViewNode("911", "911"), + new TreeViewNode("918 Spyder", "918"))); + tvn.AddNode(new TreeViewNode("BMW", "bmw")); + tvn.AddNode(new TreeViewNode("Audi", "audi")); + tvn.AddNode(new TreeViewNode("VW", "vw")); + tvn.AddNode(new TreeViewNode("Lamborghini", "lamborghini")); + + View.Nodes.Add(tvn); + + tvn = new TreeViewNode("Fruits", "fruits"); + + tvn.AddNode(new TreeViewNode("Apple", "apple")); + tvn.AddNode(new TreeViewNode("Orange", "orange")); + tvn.AddNode(new TreeViewNode("Lemon", "lemon")); + + View.Nodes.Add(tvn); + + AddControl(View); + return Task.CompletedTask; + } + + public override async Task Action(MessageResult message) + { + await message.ConfirmAction(); + + if (message.Handled) + { + return; + } + + switch (message.RawData) + { + case "back": + + message.Handled = true; + + var start = new Menu(); + + await NavigateTo(start); + + break; + } + } + + public override async Task Render(MessageResult message) + { + var s = ""; + + s += "Selected Node: " + (View.SelectedNode?.Text ?? "(null)") + "\r\n"; + + s += "Visible Node: " + (View.VisibleNode?.Text ?? "(top)") + "\r\n"; + + s += "Visible Path: " + View.GetPath() + "\r\n"; + s += "Selected Path: " + (View.SelectedNode?.GetPath() ?? "(null)") + "\r\n"; + + var bf = new ButtonForm(); + bf.AddButtonRow(new ButtonBase("Back", "back")); + + if (MessageId != null) + { + await Device.Edit(MessageId.Value, s, bf); + } + else + { + var m = await Device.Send(s, bf); + MessageId = m.MessageId; + } + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/DataForm.cs b/TelegramBotBase.Test/Tests/DataForm.cs index 509e58b..7811d33 100644 --- a/TelegramBotBase.Test/Tests/DataForm.cs +++ b/TelegramBotBase.Test/Tests/DataForm.cs @@ -7,134 +7,126 @@ using Telegram.Bot.Types.ReplyMarkups; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests +namespace TelegramBotBaseTest.Tests; + +public class DataForm : AutoCleanForm { - public class DataForm : AutoCleanForm + public override async Task SentData(DataResult data) { + var tmp = ""; + InputOnlineFile file; - - public override async Task SentData(DataResult data) + switch (data.Type) { - var tmp = ""; - InputOnlineFile file; + case MessageType.Contact: - switch (data.Type) - { - case MessageType.Contact: + tmp += "Firstname: " + data.Contact.FirstName + "\r\n"; + tmp += "Lastname: " + data.Contact.LastName + "\r\n"; + tmp += "Phonenumber: " + data.Contact.PhoneNumber + "\r\n"; + tmp += "UserId: " + data.Contact.UserId + "\r\n"; - tmp += "Firstname: " + data.Contact.FirstName + "\r\n"; - tmp += "Lastname: " + data.Contact.LastName + "\r\n"; - tmp += "Phonenumber: " + data.Contact.PhoneNumber + "\r\n"; - tmp += "UserId: " + data.Contact.UserId + "\r\n"; + await Device.Send("Your contact: \r\n" + tmp, replyTo: data.MessageId); - await Device.Send("Your contact: \r\n" + tmp, replyTo: data.MessageId); + break; - break; + case MessageType.Document: - case MessageType.Document: + file = new InputOnlineFile(data.Document.FileId); - file = new InputOnlineFile(data.Document.FileId); - - await Device.SendDocument(file, "Your uploaded document"); + await Device.SendDocument(file, "Your uploaded document"); - break; + break; - case MessageType.Video: + case MessageType.Video: - file = new InputOnlineFile(data.Document.FileId); + file = new InputOnlineFile(data.Document.FileId); - await Device.SendDocument(file, "Your uploaded video"); + await Device.SendDocument(file, "Your uploaded video"); - break; + break; - case MessageType.Audio: + case MessageType.Audio: - file = new InputOnlineFile(data.Document.FileId); + file = new InputOnlineFile(data.Document.FileId); - await Device.SendDocument(file, "Your uploaded audio"); + await Device.SendDocument(file, "Your uploaded audio"); - break; + break; - case MessageType.Location: + case MessageType.Location: - tmp += "Lat: " + data.Location.Latitude + "\r\n"; - tmp += "Lng: " + data.Location.Longitude + "\r\n"; + tmp += "Lat: " + data.Location.Latitude + "\r\n"; + tmp += "Lng: " + data.Location.Longitude + "\r\n"; - await Device.Send("Your location: \r\n" + tmp, replyTo: data.MessageId); + await Device.Send("Your location: \r\n" + tmp, replyTo: data.MessageId); - break; + break; - case MessageType.Photo: + case MessageType.Photo: - var photo = new InputOnlineFile(data.Photos.Last().FileId); + var photo = new InputOnlineFile(data.Photos.Last().FileId); - await Device.Send("Your image: ", replyTo: data.MessageId); - await Client.TelegramClient.SendPhotoAsync(Device.DeviceId, photo); + await Device.Send("Your image: ", replyTo: data.MessageId); + await Client.TelegramClient.SendPhotoAsync(Device.DeviceId, photo); - break; + break; - default: + default: - await Device.Send("Unknown response"); + await Device.Send("Unknown response"); - break; - } + break; + } + } + public override async Task Action(MessageResult message) + { + await message.ConfirmAction(); + + if (message.Handled) + { + return; } - public override async Task Action(MessageResult message) + switch (message.RawData) { - await message.ConfirmAction(); + case "contact": - if (message.Handled) - return; + await Device.RequestContact(); - switch (message.RawData) - { - case "contact": + break; - await Device.RequestContact(); + case "location": - break; + await Device.RequestLocation(); - case "location": + break; - await Device.RequestLocation(); + case "back": - break; + message.Handled = true; - case "back": - - message.Handled = true; - - var start = new Menu(); - - await NavigateTo(start); - - break; - } + var start = new Menu(); + await NavigateTo(start); + break; } + } - public override async Task Render(MessageResult message) - { - var bf = new ButtonForm(); + public override async Task Render(MessageResult message) + { + var bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase("Request User contact", "contact")); + bf.AddButtonRow(new ButtonBase("Request User contact", "contact")); - bf.AddButtonRow(new ButtonBase("Request User location", "location")); + bf.AddButtonRow(new ButtonBase("Request User location", "location")); - bf.AddButtonRow(new ButtonBase("Back", "back")); + bf.AddButtonRow(new ButtonBase("Back", "back")); - InlineKeyboardMarkup ikv = bf; - - await Device.Send("Please upload a contact, photo, video, audio, document or location.", bf); - - - - } + InlineKeyboardMarkup ikv = bf; + await Device.Send("Please upload a contact, photo, video, audio, document or location.", bf); } } diff --git a/TelegramBotBase.Test/Tests/DataSources/CustomDataSource.cs b/TelegramBotBase.Test/Tests/DataSources/CustomDataSource.cs new file mode 100644 index 0000000..0246920 --- /dev/null +++ b/TelegramBotBase.Test/Tests/DataSources/CustomDataSource.cs @@ -0,0 +1,146 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using Newtonsoft.Json; +using TelegramBotBase.Controls.Hybrid; +using TelegramBotBase.DataSources; +using TelegramBotBase.Form; + +namespace TelegramBotBaseTest.Tests.DataSources; + +public class CustomDataSource : ButtonFormDataSource +{ + public List Countries = new() { "Country 1", "Country 2", "Country 3" }; + + public CustomDataSource() + { + LoadData(); + } + + public override int Count => Countries.Count; + + public override int ColumnCount => 1; + + public override int RowCount => Count; + + /// + /// This method has the example purpose of creating and loading some example data. + /// When using a database you do not need this kind of method. + /// + private void LoadData() + { + //Exists data source? Read it + if (File.Exists(AppContext.BaseDirectory + "countries.json")) + { + try + { + var list = JsonConvert.DeserializeObject>(File.ReadAllText("countries.json")); + + + Countries = list; + } + catch + { + } + + + return; + } + + //If not, create it + try + { + var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Select(a => a.DisplayName).ToList(); + + Countries = countries; + + var tmp = JsonConvert.SerializeObject(countries); + + File.WriteAllText(AppContext.BaseDirectory + "countries.json", tmp); + } + catch + { + } + } + + public override ButtonRow ItemAt(int index) + { + var item = Countries.ElementAt(index); + if (item == null) + { + return new ButtonRow(); + } + + return Render(item); + } + + public override List ItemRange(int start, int count) + { + var items = Countries.Skip(start).Take(count); + + var lst = new List(); + foreach (var c in items) + { + lst.Add(Render(c)); + } + + return lst; + } + + public override List AllItems() + { + var lst = new List(); + foreach (var c in Countries) + { + lst.Add(Render(c)); + } + + return lst; + } + + public override ButtonForm PickItems(int start, int count, string filter = null) + { + var rows = ItemRange(start, count); + + var lst = new ButtonForm(); + foreach (var c in rows) + { + lst.AddButtonRow(c); + } + + return lst; + } + + public override ButtonForm PickAllItems(string filter = null) + { + var rows = AllItems(); + + var bf = new ButtonForm(); + + bf.AddButtonRows(rows); + + return bf; + } + + public override int CalculateMax(string filter = null) + { + if (filter == null) + { + return Countries.Count; + } + + return Countries.Where(a => a.IndexOf(filter, StringComparison.InvariantCultureIgnoreCase) != -1).Count(); + } + + public override ButtonRow Render(object data) + { + if (!(data is string s)) + { + return new ButtonRow(new ButtonBase("Empty", "zero")); + } + + return new ButtonRow(new ButtonBase(s, s)); + } +} diff --git a/TelegramBotBase.Test/Tests/DataSources/List.cs b/TelegramBotBase.Test/Tests/DataSources/List.cs new file mode 100644 index 0000000..35c55d7 --- /dev/null +++ b/TelegramBotBase.Test/Tests/DataSources/List.cs @@ -0,0 +1,51 @@ +using System.Threading.Tasks; +using TelegramBotBase.Args; +using TelegramBotBase.Controls.Hybrid; +using TelegramBotBase.Enums; +using TelegramBotBase.Form; + +namespace TelegramBotBaseTest.Tests.DataSources; + +public class List : FormBase +{ + private ButtonGrid _buttons; + + public List() + { + Init += List_Init; + } + + private Task List_Init(object sender, InitEventArgs e) + { + _buttons = new ButtonGrid + { + EnablePaging = true, + EnableSearch = false + }; + + _buttons.ButtonClicked += __buttons_ButtonClicked; + _buttons.KeyboardType = EKeyboardType.ReplyKeyboard; + _buttons.DeleteReplyMessage = true; + + _buttons.HeadLayoutButtonRow = new ButtonRow(new ButtonBase("Back", "back")); + + var cds = new CustomDataSource(); + _buttons.DataSource = cds; + + AddControl(_buttons); + return Task.CompletedTask; + } + + private async Task __buttons_ButtonClicked(object sender, ButtonClickedEventArgs e) + { + switch (e.Button.Value) + { + case "back": + + var mn = new Menu(); + await NavigateTo(mn); + + break; + } + } +} diff --git a/TelegramBotBase.Test/Tests/Datasources/CustomDataSource.cs b/TelegramBotBase.Test/Tests/Datasources/CustomDataSource.cs deleted file mode 100644 index 1e418e8..0000000 --- a/TelegramBotBase.Test/Tests/Datasources/CustomDataSource.cs +++ /dev/null @@ -1,143 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using Newtonsoft.Json; -using TelegramBotBase.Controls.Hybrid; -using TelegramBotBase.DataSources; -using TelegramBotBase.Form; - -namespace TelegramBotBaseTest.Tests.Datasources -{ - public class CustomDataSource : ButtonFormDataSource - { - - public List Countries = new List { "Country 1", "Country 2", "Country 3" }; - - public CustomDataSource() - { - LoadData(); - } - - /// - /// This method has the example purpose of creating and loading some example data. - /// When using a database you do not need this kind of method. - /// - private void LoadData() - { - //Exists data source? Read it - if (File.Exists(AppContext.BaseDirectory + "countries.json")) - { - try - { - var list = JsonConvert.DeserializeObject>(File.ReadAllText("countries.json")); - - - Countries = list; - } - catch - { - - } - - - return; - } - - //If not, create it - try - { - var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Select(a => a.DisplayName).ToList(); - - Countries = countries; - - var tmp = JsonConvert.SerializeObject(countries); - - File.WriteAllText( AppContext.BaseDirectory + "countries.json", tmp); - } - catch - { - - } - - } - - public override ButtonRow ItemAt(int index) - { - var item = Countries.ElementAt(index); - if (item == null) - return new ButtonRow(); - - return Render(item); - } - - public override List ItemRange(int start, int count) - { - var items = Countries.Skip(start).Take(count); - - var lst = new List(); - foreach (var c in items) - { - lst.Add(Render(c)); - } - - return lst; - } - - public override List AllItems() - { - var lst = new List(); - foreach (var c in Countries) - { - lst.Add(Render(c)); - } - return lst; - } - - public override ButtonForm PickItems(int start, int count, string filter = null) - { - var rows = ItemRange(start, count); - - var lst = new ButtonForm(); - foreach (var c in rows) - { - lst.AddButtonRow(c); - } - return lst; - } - - public override ButtonForm PickAllItems(string filter = null) - { - var rows = AllItems(); - - var bf = new ButtonForm(); - - bf.AddButtonRows(rows); - - return bf; - } - - public override int CalculateMax(string filter = null) - { - if (filter == null) - return Countries.Count; - - return Countries.Where(a => a.IndexOf(filter, StringComparison.InvariantCultureIgnoreCase) != -1).Count(); - } - - public override ButtonRow Render(object data) - { - if (!(data is string s)) - return new ButtonRow(new ButtonBase("Empty", "zero")); - - return new ButtonRow(new ButtonBase(s, s)); - } - - public override int Count => Countries.Count; - - public override int ColumnCount => 1; - - public override int RowCount => Count; - } -} diff --git a/TelegramBotBase.Test/Tests/Datasources/List.cs b/TelegramBotBase.Test/Tests/Datasources/List.cs deleted file mode 100644 index d73d92a..0000000 --- a/TelegramBotBase.Test/Tests/Datasources/List.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System.Threading.Tasks; -using TelegramBotBase.Args; -using TelegramBotBase.Controls.Hybrid; -using TelegramBotBase.Enums; -using TelegramBotBase.Form; - -namespace TelegramBotBaseTest.Tests.Datasources -{ - public class List : FormBase - { - private ButtonGrid _buttons; - - public List() - { - Init += List_Init; - } - - private Task List_Init(object sender, InitEventArgs e) - { - - _buttons = new ButtonGrid - { - EnablePaging = true, - EnableSearch = false - }; - - _buttons.ButtonClicked += __buttons_ButtonClicked; - _buttons.KeyboardType = EKeyboardType.ReplyKeyboard; - _buttons.DeleteReplyMessage = true; - - _buttons.HeadLayoutButtonRow = new ButtonRow(new ButtonBase("Back", "back")); - - var cds = new CustomDataSource(); - _buttons.DataSource = cds; - - AddControl(_buttons); - return Task.CompletedTask; - } - - private async Task __buttons_ButtonClicked(object sender, ButtonClickedEventArgs e) - { - switch(e.Button.Value) - { - case "back": - - var mn = new Menu(); - await NavigateTo(mn); - - break; - } - } - - - } -} diff --git a/TelegramBotBase.Test/Tests/Groups/GroupChange.cs b/TelegramBotBase.Test/Tests/Groups/GroupChange.cs index 1d75ccf..fd984b6 100644 --- a/TelegramBotBase.Test/Tests/Groups/GroupChange.cs +++ b/TelegramBotBase.Test/Tests/Groups/GroupChange.cs @@ -4,71 +4,69 @@ using TelegramBotBase.Args; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Groups +namespace TelegramBotBaseTest.Tests.Groups; + +public class GroupChange : GroupForm { - public class GroupChange : GroupForm + public GroupChange() { - public GroupChange() - { - Opened += GroupChange_Opened; - } - - - private async Task GroupChange_Opened(object sender, EventArgs e) - { - - var bf = new ButtonForm(); - - bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange")); - bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser")); - bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace")); - - await Device.Send("GroupChange started, click to switch", bf); - - } - - public override async Task Action(MessageResult message) - { - if (message.Handled) - return; - - - var bn = message.RawData; - - await message.ConfirmAction(); - message.Handled = true; - - switch (bn) - { - case "groupchange": - - var gc = new GroupChange(); - - await NavigateTo(gc); - - break; - case "welcomeuser": - - var wu = new WelcomeUser(); - - await NavigateTo(wu); - - break; - case "linkreplace": - - var lr = new LinkReplaceTest(); - - await NavigateTo(lr); - - break; - } - - } - - public override async Task OnGroupChanged(GroupChangedEventArgs e) - { - await Device.Send("Group has been changed by " + e.OriginalMessage.Message.From.FirstName + " " + e.OriginalMessage.Message.From.LastName); - } - + Opened += GroupChange_Opened; } -} + + + private async Task GroupChange_Opened(object sender, EventArgs e) + { + var bf = new ButtonForm(); + + bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange")); + bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser")); + bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace")); + + await Device.Send("GroupChange started, click to switch", bf); + } + + public override async Task Action(MessageResult message) + { + if (message.Handled) + { + return; + } + + + var bn = message.RawData; + + await message.ConfirmAction(); + message.Handled = true; + + switch (bn) + { + case "groupchange": + + var gc = new GroupChange(); + + await NavigateTo(gc); + + break; + case "welcomeuser": + + var wu = new WelcomeUser(); + + await NavigateTo(wu); + + break; + case "linkreplace": + + var lr = new LinkReplaceTest(); + + await NavigateTo(lr); + + break; + } + } + + public override async Task OnGroupChanged(GroupChangedEventArgs e) + { + await Device.Send("Group has been changed by " + e.OriginalMessage.Message.From.FirstName + " " + + e.OriginalMessage.Message.From.LastName); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Groups/LinkReplaceTest.cs b/TelegramBotBase.Test/Tests/Groups/LinkReplaceTest.cs index 243d7d4..dd36756 100644 --- a/TelegramBotBase.Test/Tests/Groups/LinkReplaceTest.cs +++ b/TelegramBotBase.Test/Tests/Groups/LinkReplaceTest.cs @@ -7,159 +7,159 @@ using Telegram.Bot.Types.Enums; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Groups +namespace TelegramBotBaseTest.Tests.Groups; + +public class LinkReplaceTest : GroupForm { - public class LinkReplaceTest : GroupForm + private const int Maximum = 3; + + + public LinkReplaceTest() { - private Dictionary Counter { get; set; } = new Dictionary(); - - private const int Maximum = 3; - - - public LinkReplaceTest() - { - Opened += LinkReplaceTest_Opened; - } - - private async Task LinkReplaceTest_Opened(object sender, EventArgs e) - { - - var bf = new ButtonForm(); - - bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange")); - bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser")); - bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace")); - - await Device.Send("LinkReplaceTest started, click to switch", bf); - - } - - public override async Task Action(MessageResult message) - { - if (message.Handled) - return; - - var bn = message.RawData; - - await message.ConfirmAction(); - message.Handled = true; - - switch (bn) - { - case "groupchange": - - var gc = new GroupChange(); - - await NavigateTo(gc); - - break; - case "welcomeuser": - - var wu = new WelcomeUser(); - - await NavigateTo(wu); - - break; - case "linkreplace": - - var lr = new LinkReplaceTest(); - - await NavigateTo(lr); - - break; - } - - } - - public override async Task OnMessage(MessageResult e) - { - var from = e.Message.From.Id; - - if (e.Message.From.IsBot) - return; - - //Are urls inside his message ? - if (!HasLinks(e.MessageText)) - return; - - var u = await Device.GetChatUser(from); - - //Don't kick Admins or Creators - if (u.Status == ChatMemberStatus.Administrator | u.Status == ChatMemberStatus.Creator) - { - await Device.Send("You won't get kicked,...not this time."); - return; - } - - await e.Device.DeleteMessage(e.MessageId); - - var cp = new ChatPermissions - { - CanAddWebPagePreviews = false, - CanChangeInfo = false, - CanInviteUsers = false, - CanPinMessages = false, - CanSendMediaMessages = false, - CanSendMessages = false, - CanSendOtherMessages = false, - CanSendPolls = false - }; - - //Collect user "mistakes" with sending url, after 3 he gets kicked out. - if (Counter.ContainsKey(from)) - { - Counter[from]++; - } - else - { - Counter[from] = 1; - } - - - if (Counter[from] >= 3) - { - await e.Device.KickUser(from); - - await e.Device.Send(e.Message.From.FirstName + " " + e.Message.From.LastName + " has been removed from the group"); - } - else - { - await e.Device.RestrictUser(from, cp, DateTime.UtcNow.AddSeconds(30)); - - await e.Device.Send(e.Message.From.FirstName + " " + e.Message.From.LastName + " has been blocked for 30 seconds"); - } - - - - } - - /// - /// Call onmessage also on edited message, if someone want to spoof a failed message and insert a link. - /// - /// - /// - public override async Task OnMessageEdit(MessageResult message) - { - await OnMessage(message); - } - - /// - /// https://stackoverflow.com/a/20651284 - /// - /// - /// - private bool HasLinks(string str) - { - var tmp = str; - - var pattern = @"^(http|https|ftp|)\://|[a-zA-Z0-9\-\.]+\.[a-zA-Z](:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*[^\.\,\)\(\s]$"; - var r = new Regex(pattern); - - var matches = r.Matches(tmp); - - return (matches.Count > 0); - } - - + Opened += LinkReplaceTest_Opened; } -} + + private Dictionary Counter { get; } = new(); + + private async Task LinkReplaceTest_Opened(object sender, EventArgs e) + { + var bf = new ButtonForm(); + + bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange")); + bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser")); + bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace")); + + await Device.Send("LinkReplaceTest started, click to switch", bf); + } + + public override async Task Action(MessageResult message) + { + if (message.Handled) + { + return; + } + + var bn = message.RawData; + + await message.ConfirmAction(); + message.Handled = true; + + switch (bn) + { + case "groupchange": + + var gc = new GroupChange(); + + await NavigateTo(gc); + + break; + case "welcomeuser": + + var wu = new WelcomeUser(); + + await NavigateTo(wu); + + break; + case "linkreplace": + + var lr = new LinkReplaceTest(); + + await NavigateTo(lr); + + break; + } + } + + public override async Task OnMessage(MessageResult e) + { + var from = e.Message.From.Id; + + if (e.Message.From.IsBot) + { + return; + } + + //Are urls inside his message ? + if (!HasLinks(e.MessageText)) + { + return; + } + + var u = await Device.GetChatUser(from); + + //Don't kick Admins or Creators + if ((u.Status == ChatMemberStatus.Administrator) | (u.Status == ChatMemberStatus.Creator)) + { + await Device.Send("You won't get kicked,...not this time."); + return; + } + + await e.Device.DeleteMessage(e.MessageId); + + var cp = new ChatPermissions + { + CanAddWebPagePreviews = false, + CanChangeInfo = false, + CanInviteUsers = false, + CanPinMessages = false, + CanSendMediaMessages = false, + CanSendMessages = false, + CanSendOtherMessages = false, + CanSendPolls = false + }; + + //Collect user "mistakes" with sending url, after 3 he gets kicked out. + if (Counter.ContainsKey(from)) + { + Counter[from]++; + } + else + { + Counter[from] = 1; + } + + + if (Counter[from] >= 3) + { + await e.Device.KickUser(from); + + await e.Device.Send(e.Message.From.FirstName + " " + e.Message.From.LastName + + " has been removed from the group"); + } + else + { + await e.Device.RestrictUser(from, cp, DateTime.UtcNow.AddSeconds(30)); + + await e.Device.Send(e.Message.From.FirstName + " " + e.Message.From.LastName + + " has been blocked for 30 seconds"); + } + } + + /// + /// Call onmessage also on edited message, if someone want to spoof a failed message and insert a link. + /// + /// + /// + public override async Task OnMessageEdit(MessageResult message) + { + await OnMessage(message); + } + + /// + /// https://stackoverflow.com/a/20651284 + /// + /// + /// + private bool HasLinks(string str) + { + var tmp = str; + + var pattern = + @"^(http|https|ftp|)\://|[a-zA-Z0-9\-\.]+\.[a-zA-Z](:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*[^\.\,\)\(\s]$"; + var r = new Regex(pattern); + + var matches = r.Matches(tmp); + + return matches.Count > 0; + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs b/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs index c700f85..3dc8048 100644 --- a/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs +++ b/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs @@ -6,86 +6,77 @@ using TelegramBotBase.Args; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Groups +namespace TelegramBotBaseTest.Tests.Groups; + +public class WelcomeUser : GroupForm { - public class WelcomeUser : GroupForm + public WelcomeUser() { - - public WelcomeUser() - { - Opened += WelcomeUser_Opened; - } - - - private async Task WelcomeUser_Opened(object sender, EventArgs e) - { - - var bf = new ButtonForm(); - - bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange")); - bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser")); - bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace")); - - await Device.Send("WelcomeUser started, click to switch", bf); - - } - - public override async Task Action(MessageResult message) - { - if (message.Handled) - return; - - var bn = message.RawData; - - await message.ConfirmAction(); - message.Handled = true; - - switch (bn) - { - case "groupchange": - - var gc = new GroupChange(); - - await NavigateTo(gc); - - break; - case "welcomeuser": - - var wu = new WelcomeUser(); - - await NavigateTo(wu); - - break; - case "linkreplace": - - var lr = new LinkReplaceTest(); - - await NavigateTo(lr); - - break; - } - - } - - public override async Task OnMemberChanges(MemberChangeEventArgs e) - { - - if (e.Type == MessageType.ChatMembersAdded) - { - - await Device.Send("Welcome you new members!\r\n\r\n" + e.Members.Select(a => a.FirstName + " " + a.LastName).Aggregate((a, b) => a + "\r\n" + b)); - - } - else if (e.Type == MessageType.ChatMemberLeft) - { - await Device.Send(e.Members.Select(a => a.FirstName + " " + a.LastName).Aggregate((a, b) => a + " and " + b) + " has left the group"); - - } - - } - - - - + Opened += WelcomeUser_Opened; } -} + + + private async Task WelcomeUser_Opened(object sender, EventArgs e) + { + var bf = new ButtonForm(); + + bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange")); + bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser")); + bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace")); + + await Device.Send("WelcomeUser started, click to switch", bf); + } + + public override async Task Action(MessageResult message) + { + if (message.Handled) + { + return; + } + + var bn = message.RawData; + + await message.ConfirmAction(); + message.Handled = true; + + switch (bn) + { + case "groupchange": + + var gc = new GroupChange(); + + await NavigateTo(gc); + + break; + case "welcomeuser": + + var wu = new WelcomeUser(); + + await NavigateTo(wu); + + break; + case "linkreplace": + + var lr = new LinkReplaceTest(); + + await NavigateTo(lr); + + break; + } + } + + public override async Task OnMemberChanges(MemberChangeEventArgs e) + { + if (e.Type == MessageType.ChatMembersAdded) + { + await Device.Send("Welcome you new members!\r\n\r\n" + e.Members.Select(a => a.FirstName + " " + a.LastName) + .Aggregate((a, b) => a + "\r\n" + b)); + } + else if (e.Type == MessageType.ChatMemberLeft) + { + await Device.Send( + e.Members.Select(a => a.FirstName + " " + a.LastName).Aggregate((a, b) => a + " and " + b) + + " has left the group"); + } + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Menu.cs b/TelegramBotBase.Test/Tests/Menu.cs index 3f9d04d..3b161db 100644 --- a/TelegramBotBase.Test/Tests/Menu.cs +++ b/TelegramBotBase.Test/Tests/Menu.cs @@ -4,261 +4,262 @@ using TelegramBotBase.Base; using TelegramBotBase.Enums; using TelegramBotBase.Form; using TelegramBotBaseTest.Tests.Controls; -using TelegramBotBaseTest.Tests.Datasources; +using TelegramBotBaseTest.Tests.DataSources; using TelegramBotBaseTest.Tests.Groups; -namespace TelegramBotBaseTest.Tests +namespace TelegramBotBaseTest.Tests; + +public class Menu : AutoCleanForm { - public class Menu : AutoCleanForm + public Menu() { - public Menu() + DeleteMode = EDeleteMode.OnLeavingForm; + } + + public override async Task Load(MessageResult message) + { + if ((message.Message.Chat.Type == ChatType.Group) | (message.Message.Chat.Type == ChatType.Supergroup)) { - DeleteMode = EDeleteMode.OnLeavingForm; + var sf = new WelcomeUser(); + + await NavigateTo(sf); } - public override async Task Load(MessageResult message) + + await Device.HideReplyKeyboard(); + } + + public override async Task Action(MessageResult message) + { + var call = message.GetData(); + + await message.ConfirmAction(); + + + if (call == null) { + return; + } + message.Handled = true; - if (message.Message.Chat.Type == ChatType.Group | message.Message.Chat.Type == ChatType.Supergroup) - { - var sf = new WelcomeUser(); + switch (call.Value) + { + case "text": + + var sf = new SimpleForm(); await NavigateTo(sf); - } + + break; + + case "buttons": + + var bf = new ButtonTestForm(); + + await NavigateTo(bf); + + break; + + case "progress": + + var pf = new ProgressTest(); + + await NavigateTo(pf); + + break; + + case "registration": + + var reg = new Register.Start(); + + await NavigateTo(reg); + + break; + + case "form1": + + var form1 = new TestForm(); + + await NavigateTo(form1); + + break; + + case "form2": + + var form2 = new TestForm2(); + + await NavigateTo(form2); + + break; + + case "data": + + var data = new DataForm(); + + await NavigateTo(data); + + break; + + case "calendar": + + var calendar = new CalendarPickerForm(); + + await NavigateTo(calendar); + + break; + + case "month": + + var month = new MonthPickerForm(); + + await NavigateTo(month); + + break; + + case "treeview": + + var tree = new TreeViewForms(); + + await NavigateTo(tree); + + break; + + case "togglebuttons": + + var tb = new ToggleButtons(); + + await NavigateTo(tb); + + break; + + case "multitogglebuttons": + + var mtb = new MultiToggleButtons(); + + await NavigateTo(mtb); + + break; + + case "buttongrid": + + var bg = new ButtonGridForm(); + + await NavigateTo(bg); + + break; + + case "buttongridfilter": + + var bg2 = new ButtonGridPagingForm(); + + await NavigateTo(bg2); + + break; + + case "buttongridtags": + + var bg3 = new ButtonGridTagForm(); + + await NavigateTo(bg3); + + break; + + case "multiview": + + var mvf = new MultiViewForm(); + + await NavigateTo(mvf); - await Device.HideReplyKeyboard(); + break; + + case "checkedbuttonlist": + + var cbl = new CheckedButtonListForm(); + + await NavigateTo(cbl); + + + break; + + case "navigationcontroller": + + var nc = new Navigation.Start(); + + await NavigateTo(nc); + + + break; + + case "dynamicbuttongrid": + + var dg = new List(); + + await NavigateTo(dg); + + break; + + case "notifications": + + var not = new Notifications.Start(); + await NavigateTo(not); + + break; + + default: + + message.Handled = false; + + break; } + } - public override async Task Action(MessageResult message) - { - var call = message.GetData(); + public override async Task Render(MessageResult message) + { + var btn = new ButtonForm(); - await message.ConfirmAction(); + btn.AddButtonRow(new ButtonBase("#1 Simple Text", new CallbackData("a", "text").Serialize()), + new ButtonBase("#2 Button Test", new CallbackData("a", "buttons").Serialize())); + btn.AddButtonRow(new ButtonBase("#3 Progress Bar", new CallbackData("a", "progress").Serialize())); + btn.AddButtonRow(new ButtonBase("#4 Registration Example", new CallbackData("a", "registration").Serialize())); + btn.AddButtonRow(new ButtonBase("#5 Form1 Command", new CallbackData("a", "form1").Serialize())); - if (call == null) - return; + btn.AddButtonRow(new ButtonBase("#6 Form2 Command", new CallbackData("a", "form2").Serialize())); - message.Handled = true; + btn.AddButtonRow(new ButtonBase("#7 Data Handling", new CallbackData("a", "data").Serialize())); + btn.AddButtonRow(new ButtonBase("#8 Calendar Picker", new CallbackData("a", "calendar").Serialize())); + btn.AddButtonRow(new ButtonBase("#9 Month Picker", new CallbackData("a", "month").Serialize())); - switch (call.Value) - { - case "text": + btn.AddButtonRow(new ButtonBase("#10 TreeView", new CallbackData("a", "treeview").Serialize())); - var sf = new SimpleForm(); + btn.AddButtonRow(new ButtonBase("#11 ToggleButtons", new CallbackData("a", "togglebuttons").Serialize())); - await NavigateTo(sf); + btn.AddButtonRow(new ButtonBase("#11.2 MultiToggleButtons", + new CallbackData("a", "multitogglebuttons").Serialize())); - break; + btn.AddButtonRow(new ButtonBase("#12 ButtonGrid", new CallbackData("a", "buttongrid").Serialize())); - case "buttons": + btn.AddButtonRow(new ButtonBase("#13 ButtonGrid Paging & Filter", + new CallbackData("a", "buttongridfilter").Serialize())); - var bf = new ButtonTestForm(); + btn.AddButtonRow(new ButtonBase("#14 ButtonGrid Tags (Filter)", + new CallbackData("a", "buttongridtags").Serialize())); - await NavigateTo(bf); + btn.AddButtonRow(new ButtonBase("#15 MultiView", new CallbackData("a", "multiview").Serialize())); - break; + btn.AddButtonRow( + new ButtonBase("#16 CheckedButtonList", new CallbackData("a", "checkedbuttonlist").Serialize())); - case "progress": + btn.AddButtonRow(new ButtonBase("#17 NavigationController (Push/Pop)", + new CallbackData("a", "navigationcontroller").Serialize())); - var pf = new ProgressTest(); - - await NavigateTo(pf); - - break; - - case "registration": - - var reg = new Register.Start(); - - await NavigateTo(reg); - - break; - - case "form1": - - var form1 = new TestForm(); - - await NavigateTo(form1); - - break; - - case "form2": - - var form2 = new TestForm2(); - - await NavigateTo(form2); - - break; - - case "data": - - var data = new DataForm(); - - await NavigateTo(data); - - break; - - case "calendar": - - var calendar = new CalendarPickerForm(); - - await NavigateTo(calendar); - - break; - - case "month": - - var month = new MonthPickerForm(); - - await NavigateTo(month); - - break; - - case "treeview": - - var tree = new TreeViewForms(); - - await NavigateTo(tree); - - break; - - case "togglebuttons": - - var tb = new ToggleButtons(); - - await NavigateTo(tb); - - break; - - case "multitogglebuttons": - - var mtb = new MultiToggleButtons(); - - await NavigateTo(mtb); - - break; - - case "buttongrid": - - var bg = new ButtonGridForm(); - - await NavigateTo(bg); - - break; - - case "buttongridfilter": - - var bg2 = new ButtonGridPagingForm(); - - await NavigateTo(bg2); - - break; - - case "buttongridtags": - - var bg3 = new ButtonGridTagForm(); - - await NavigateTo(bg3); - - break; - - case "multiview": - - var mvf = new MultiViewForm(); - - await NavigateTo(mvf); - - - break; - - case "checkedbuttonlist": - - var cbl = new CheckedButtonListForm(); - - await NavigateTo(cbl); - - - break; - - case "navigationcontroller": - - var nc = new Navigation.Start(); - - await NavigateTo(nc); - - - break; - - case "dynamicbuttongrid": - - var dg = new List(); - - await NavigateTo(dg); - - break; - - case "notifications": - - var not = new Notifications.Start(); - await NavigateTo(not); - - break; - - default: - - message.Handled = false; - - break; - } - - - } - - public override async Task Render(MessageResult message) - { - - var btn = new ButtonForm(); - - btn.AddButtonRow(new ButtonBase("#1 Simple Text", new CallbackData("a", "text").Serialize()), new ButtonBase("#2 Button Test", new CallbackData("a", "buttons").Serialize())); - btn.AddButtonRow(new ButtonBase("#3 Progress Bar", new CallbackData("a", "progress").Serialize())); - btn.AddButtonRow(new ButtonBase("#4 Registration Example", new CallbackData("a", "registration").Serialize())); - - btn.AddButtonRow(new ButtonBase("#5 Form1 Command", new CallbackData("a", "form1").Serialize())); - - btn.AddButtonRow(new ButtonBase("#6 Form2 Command", new CallbackData("a", "form2").Serialize())); - - btn.AddButtonRow(new ButtonBase("#7 Data Handling", new CallbackData("a", "data").Serialize())); - btn.AddButtonRow(new ButtonBase("#8 Calendar Picker", new CallbackData("a", "calendar").Serialize())); - btn.AddButtonRow(new ButtonBase("#9 Month Picker", new CallbackData("a", "month").Serialize())); - - btn.AddButtonRow(new ButtonBase("#10 TreeView", new CallbackData("a", "treeview").Serialize())); - - btn.AddButtonRow(new ButtonBase("#11 ToggleButtons", new CallbackData("a", "togglebuttons").Serialize())); - - btn.AddButtonRow(new ButtonBase("#11.2 MultiToggleButtons", new CallbackData("a", "multitogglebuttons").Serialize())); - - btn.AddButtonRow(new ButtonBase("#12 ButtonGrid", new CallbackData("a", "buttongrid").Serialize())); - - btn.AddButtonRow(new ButtonBase("#13 ButtonGrid Paging & Filter", new CallbackData("a", "buttongridfilter").Serialize())); - - btn.AddButtonRow(new ButtonBase("#14 ButtonGrid Tags (Filter)", new CallbackData("a", "buttongridtags").Serialize())); - - btn.AddButtonRow(new ButtonBase("#15 MultiView", new CallbackData("a", "multiview").Serialize())); - - btn.AddButtonRow(new ButtonBase("#16 CheckedButtonList", new CallbackData("a", "checkedbuttonlist").Serialize())); - - btn.AddButtonRow(new ButtonBase("#17 NavigationController (Push/Pop)", new CallbackData("a", "navigationcontroller").Serialize())); - - btn.AddButtonRow(new ButtonBase("#18 Dynamic ButtonGrid (DataSources)", new CallbackData("a", "dynamicbuttongrid").Serialize())); - - btn.AddButtonRow(new ButtonBase("#19 Notifications", new CallbackData("a", "notifications").Serialize())); - - await Device.Send("Choose your test:", btn); - } + btn.AddButtonRow(new ButtonBase("#18 Dynamic ButtonGrid (DataSources)", + new CallbackData("a", "dynamicbuttongrid").Serialize())); + btn.AddButtonRow(new ButtonBase("#19 Notifications", new CallbackData("a", "notifications").Serialize())); + await Device.Send("Choose your test:", btn); } } diff --git a/TelegramBotBase.Test/Tests/Navigation/CustomController.cs b/TelegramBotBase.Test/Tests/Navigation/CustomController.cs index 5dff6fd..28d7015 100644 --- a/TelegramBotBase.Test/Tests/Navigation/CustomController.cs +++ b/TelegramBotBase.Test/Tests/Navigation/CustomController.cs @@ -3,40 +3,37 @@ using System.Threading.Tasks; using TelegramBotBase.Form; using TelegramBotBase.Form.Navigation; -namespace TelegramBotBaseTest.Tests.Navigation +namespace TelegramBotBaseTest.Tests.Navigation; + +internal class CustomController : NavigationController { - internal class CustomController : NavigationController + public CustomController(FormBase form) : base(form) { - public CustomController(FormBase form) : base(form) - { - - } - - - public override Task PushAsync(FormBase form, params object[] args) - { - Console.WriteLine($"Pushes form (Count on stack {Index + 1})"); - //Device.Send($"Pushes form (Count on stack {this.Index + 1})"); - - return base.PushAsync(form, args); - } - - - public override Task PopAsync() - { - Console.WriteLine($"Pops one form (Count on stack {Index + 1})"); - //Device.Send($"Pops one form (Count on stack {this.Index + 1})"); - - return base.PopAsync(); - } - - public override Task PopToRootAsync() - { - Console.WriteLine($"Moved back to root (Count on stack {Index + 1})"); - //Device.Send($"Moved back to root (Count on stack {this.Index + 1})"); - - return base.PopToRootAsync(); - } - } -} + + + public override Task PushAsync(FormBase form, params object[] args) + { + Console.WriteLine($"Pushes form (Count on stack {Index + 1})"); + //Device.Send($"Pushes form (Count on stack {this.Index + 1})"); + + return base.PushAsync(form, args); + } + + + public override Task PopAsync() + { + Console.WriteLine($"Pops one form (Count on stack {Index + 1})"); + //Device.Send($"Pops one form (Count on stack {this.Index + 1})"); + + return base.PopAsync(); + } + + public override Task PopToRootAsync() + { + Console.WriteLine($"Moved back to root (Count on stack {Index + 1})"); + //Device.Send($"Moved back to root (Count on stack {this.Index + 1})"); + + return base.PopToRootAsync(); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Navigation/Form1.cs b/TelegramBotBase.Test/Tests/Navigation/Form1.cs index b7270a6..c000fe7 100644 --- a/TelegramBotBase.Test/Tests/Navigation/Form1.cs +++ b/TelegramBotBase.Test/Tests/Navigation/Form1.cs @@ -4,83 +4,80 @@ using Telegram.Bot.Types; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Navigation +namespace TelegramBotBaseTest.Tests.Navigation; + +public class Form1 : FormBase { - public class Form1 : FormBase + private Message _msg; + + public Form1() { - private Message _msg; - - public Form1() - { - Closed += Form1_Closed; - } - - private async Task Form1_Closed(object sender, EventArgs e) - { - if (_msg == null) - return; - - await Device.DeleteMessage(_msg); - } - - public override async Task Action(MessageResult message) - { - if (message.Handled) - return; - - await message.ConfirmAction(); - - switch (message.RawData) - { - case "next": - - message.Handled = true; - - var f1 = new Form1(); - - await NavigationController.PushAsync(f1); - - - break; - - case "previous": - - message.Handled = true; - - //Pop's the current form and move the previous one. The root form will be the Start class. - await NavigationController.PopAsync(); - - break; - - case "root": - - message.Handled = true; - - await NavigationController.PopToRootAsync(); - - break; - - - } - - - - } - - public override async Task Render(MessageResult message) - { - if (_msg != null) - return; - - var bf = new ButtonForm(); - bf.AddButtonRow("Next page", "next"); - bf.AddButtonRow("Previous page", "previous"); - bf.AddButtonRow("Back to root", "root"); - - _msg = await Device.Send($"Choose your options (Count on stack {NavigationController.Index + 1})", bf); - - } - - + Closed += Form1_Closed; } -} + + private async Task Form1_Closed(object sender, EventArgs e) + { + if (_msg == null) + { + return; + } + + await Device.DeleteMessage(_msg); + } + + public override async Task Action(MessageResult message) + { + if (message.Handled) + { + return; + } + + await message.ConfirmAction(); + + switch (message.RawData) + { + case "next": + + message.Handled = true; + + var f1 = new Form1(); + + await NavigationController.PushAsync(f1); + + + break; + + case "previous": + + message.Handled = true; + + //Pop's the current form and move the previous one. The root form will be the Start class. + await NavigationController.PopAsync(); + + break; + + case "root": + + message.Handled = true; + + await NavigationController.PopToRootAsync(); + + break; + } + } + + public override async Task Render(MessageResult message) + { + if (_msg != null) + { + return; + } + + var bf = new ButtonForm(); + bf.AddButtonRow("Next page", "next"); + bf.AddButtonRow("Previous page", "previous"); + bf.AddButtonRow("Back to root", "root"); + + _msg = await Device.Send($"Choose your options (Count on stack {NavigationController.Index + 1})", bf); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Navigation/Start.cs b/TelegramBotBase.Test/Tests/Navigation/Start.cs index 2599ff3..034a653 100644 --- a/TelegramBotBase.Test/Tests/Navigation/Start.cs +++ b/TelegramBotBase.Test/Tests/Navigation/Start.cs @@ -3,77 +3,78 @@ using Telegram.Bot.Types; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Navigation +namespace TelegramBotBaseTest.Tests.Navigation; + +public class Start : FormBase { - public class Start : FormBase + private Message _msg; + + + public override Task Load(MessageResult message) { - private Message _msg; - - - public override Task Load(MessageResult message) - { - return Task.CompletedTask; - } - - public override async Task Action(MessageResult message) - { - if (message.Handled) - return; - - await message.ConfirmAction(); - - switch (message.RawData) - { - case "yes": - - message.Handled = true; - - //Create navigation controller and navigate to it, keep the current form as root form so we can get back to here later - var nc = new CustomController(this); - nc.ForceCleanupOnLastPop = true; - - var f1 = new Form1(); - - await nc.PushAsync(f1); - - await NavigateTo(nc); - - if (_msg == null) - return; - - await Device.DeleteMessage(_msg); - - - break; - case "no": - - message.Handled = true; - - var mn = new Menu(); - - await NavigateTo(mn); - - if (_msg == null) - return; - - await Device.DeleteMessage(_msg); - - break; - } - - } - - public override async Task Render(MessageResult message) - { - var bf = new ButtonForm(); - - bf.AddButtonRow("Yes", "yes"); - bf.AddButtonRow("No", "no"); - - _msg = await Device.Send("Open controller?", bf); - - - } - + return Task.CompletedTask; } -} + + public override async Task Action(MessageResult message) + { + if (message.Handled) + { + return; + } + + await message.ConfirmAction(); + + switch (message.RawData) + { + case "yes": + + message.Handled = true; + + //Create navigation controller and navigate to it, keep the current form as root form so we can get back to here later + var nc = new CustomController(this); + nc.ForceCleanupOnLastPop = true; + + var f1 = new Form1(); + + await nc.PushAsync(f1); + + await NavigateTo(nc); + + if (_msg == null) + { + return; + } + + await Device.DeleteMessage(_msg); + + + break; + case "no": + + message.Handled = true; + + var mn = new Menu(); + + await NavigateTo(mn); + + if (_msg == null) + { + return; + } + + await Device.DeleteMessage(_msg); + + break; + } + } + + public override async Task Render(MessageResult message) + { + var bf = new ButtonForm(); + + bf.AddButtonRow("Yes", "yes"); + bf.AddButtonRow("No", "no"); + + _msg = await Device.Send("Open controller?", bf); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Notifications/Start.cs b/TelegramBotBase.Test/Tests/Notifications/Start.cs index 702a9e7..a04b770 100644 --- a/TelegramBotBase.Test/Tests/Notifications/Start.cs +++ b/TelegramBotBase.Test/Tests/Notifications/Start.cs @@ -3,59 +3,59 @@ using TelegramBotBase.Base; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Notifications +namespace TelegramBotBaseTest.Tests.Notifications; + +public class Start : AutoCleanForm { - public class Start : AutoCleanForm + private bool _sent; + + public Start() { - private bool _sent; - - public Start() - { - DeleteMode = EDeleteMode.OnLeavingForm; - } - - public override async Task Action(MessageResult message) - { - if (message.Handled) - return; - - switch (message.RawData) - { - case "alert": - - await message.ConfirmAction("This is an alert.", true); - - break; - case "back": - - var mn = new Menu(); - await NavigateTo(mn); - - break; - default: - - await message.ConfirmAction("This is feedback"); - - break; - - } - - } - - public override async Task Render(MessageResult message) - { - if (_sent) - return; - - var bf = new ButtonForm(); - bf.AddButtonRow("Normal feeback", "normal"); - bf.AddButtonRow("Alert Box", "alert"); - bf.AddButtonRow("Back", "back"); - - await Device.Send("Choose your test", bf); - - _sent = true; - } - + DeleteMode = EDeleteMode.OnLeavingForm; } -} + + public override async Task Action(MessageResult message) + { + if (message.Handled) + { + return; + } + + switch (message.RawData) + { + case "alert": + + await message.ConfirmAction("This is an alert.", true); + + break; + case "back": + + var mn = new Menu(); + await NavigateTo(mn); + + break; + default: + + await message.ConfirmAction("This is feedback"); + + break; + } + } + + public override async Task Render(MessageResult message) + { + if (_sent) + { + return; + } + + var bf = new ButtonForm(); + bf.AddButtonRow("Normal feeback", "normal"); + bf.AddButtonRow("Alert Box", "alert"); + bf.AddButtonRow("Back", "back"); + + await Device.Send("Choose your test", bf); + + _sent = true; + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/ProgressTest.cs b/TelegramBotBase.Test/Tests/ProgressTest.cs index 0657c82..a8dcf70 100644 --- a/TelegramBotBase.Test/Tests/ProgressTest.cs +++ b/TelegramBotBase.Test/Tests/ProgressTest.cs @@ -6,133 +6,131 @@ using TelegramBotBase.Controls.Inline; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests +namespace TelegramBotBaseTest.Tests; + +public class ProgressTest : AutoCleanForm { - public class ProgressTest : AutoCleanForm + public ProgressTest() { + DeleteMode = EDeleteMode.OnLeavingForm; + Opened += ProgressTest_Opened; + Closed += ProgressTest_Closed; + } - public ProgressTest() + + private async Task ProgressTest_Opened(object sender, EventArgs e) + { + await Device.Send("Welcome to ProgressTest"); + } + + public override async Task Action(MessageResult message) + { + var call = message.GetData(); + + await message.ConfirmAction(); + + + if (call == null) { - DeleteMode = EDeleteMode.OnLeavingForm; - Opened += ProgressTest_Opened; - Closed += ProgressTest_Closed; + return; } + ProgressBar bar = null; - private async Task ProgressTest_Opened(object sender, EventArgs e) + switch (call.Value) { - await Device.Send("Welcome to ProgressTest"); - } + case "standard": - public override async Task Action(MessageResult message) - { - var call = message.GetData(); + bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.standard) + { + Device = Device + }; - await message.ConfirmAction(); + break; + case "squares": + + bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.squares) + { + Device = Device + }; + + break; + + case "circles": + + bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.circles) + { + Device = Device + }; + + break; + + case "lines": + + bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.lines) + { + Device = Device + }; + + break; + + case "squaredlines": + + bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.squaredLines) + { + Device = Device + }; + + break; + + case "start": + + var sf = new Menu(); + + await NavigateTo(sf); - if (call == null) return; - ProgressBar bar = null; + default: - switch (call.Value) - { - case "standard": - - bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.standard) - { - Device = Device - }; - - break; - - case "squares": - - bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.squares) - { - Device = Device - }; - - break; - - case "circles": - - bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.circles) - { - Device = Device - }; - - break; - - case "lines": - - bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.lines) - { - Device = Device - }; - - break; - - case "squaredlines": - - bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.squaredLines) - { - Device = Device - }; - - break; - - case "start": - - var sf = new Menu(); - - await NavigateTo(sf); - - return; - - default: - - return; - - } + return; + } - //Render Progress bar and show some "example" progress + //Render Progress bar and show some "example" progress + await bar.Render(message); + + Controls.Add(bar); + + for (var i = 0; i <= 100; i++) + { + bar.Value++; await bar.Render(message); - Controls.Add(bar); - - for (var i = 0; i <= 100; i++) - { - bar.Value++; - await bar.Render(message); - - Thread.Sleep(250); - } - - + Thread.Sleep(250); } - - - public override async Task Render(MessageResult message) - { - var btn = new ButtonForm(); - btn.AddButtonRow(new ButtonBase("Standard", new CallbackData("a", "standard").Serialize()), new ButtonBase("Squares", new CallbackData("a", "squares").Serialize())); - - btn.AddButtonRow(new ButtonBase("Circles", new CallbackData("a", "circles").Serialize()), new ButtonBase("Lines", new CallbackData("a", "lines").Serialize())); - - btn.AddButtonRow(new ButtonBase("Squared Line", new CallbackData("a", "squaredlines").Serialize())); - - btn.AddButtonRow(new ButtonBase("Back to start", new CallbackData("a", "start").Serialize())); - - await Device.Send("Choose your progress bar:", btn); - } - - private async Task ProgressTest_Closed(object sender, EventArgs e) - { - await Device.Send("Ciao from ProgressTest"); - } - } -} + + + public override async Task Render(MessageResult message) + { + var btn = new ButtonForm(); + btn.AddButtonRow(new ButtonBase("Standard", new CallbackData("a", "standard").Serialize()), + new ButtonBase("Squares", new CallbackData("a", "squares").Serialize())); + + btn.AddButtonRow(new ButtonBase("Circles", new CallbackData("a", "circles").Serialize()), + new ButtonBase("Lines", new CallbackData("a", "lines").Serialize())); + + btn.AddButtonRow(new ButtonBase("Squared Line", new CallbackData("a", "squaredlines").Serialize())); + + btn.AddButtonRow(new ButtonBase("Back to start", new CallbackData("a", "start").Serialize())); + + await Device.Send("Choose your progress bar:", btn); + } + + private async Task ProgressTest_Closed(object sender, EventArgs e) + { + await Device.Send("Ciao from ProgressTest"); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Register/PerForm.cs b/TelegramBotBase.Test/Tests/Register/PerForm.cs index ab703f7..fde7e05 100644 --- a/TelegramBotBase.Test/Tests/Register/PerForm.cs +++ b/TelegramBotBase.Test/Tests/Register/PerForm.cs @@ -2,99 +2,97 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Register +namespace TelegramBotBaseTest.Tests.Register; + +public class PerForm : AutoCleanForm { - public class PerForm : AutoCleanForm + public string EMail { get; set; } + + public string Firstname { get; set; } + + public string Lastname { get; set; } + + public override Task Load(MessageResult message) { - public string EMail { get; set; } - - public string Firstname { get; set; } - - public string Lastname { get; set; } - - public override Task Load(MessageResult message) + if (message.MessageText.Trim() == "") { - if (message.MessageText.Trim() == "") - return Task.CompletedTask; - - if (Firstname == null) - { - Firstname = message.MessageText; - return Task.CompletedTask; - } - - if (Lastname == null) - { - Lastname = message.MessageText; - return Task.CompletedTask; - } - - if (EMail == null) - { - EMail = message.MessageText; - return Task.CompletedTask; - } - return Task.CompletedTask; } - public override async Task Action(MessageResult message) + if (Firstname == null) { - var call = message.GetData(); - - await message.ConfirmAction(); - - if (call == null) - return; - - switch (call.Value) - { - case "back": - - var start = new Start(); - - await NavigateTo(start); - - break; - - } - - + Firstname = message.MessageText; + return Task.CompletedTask; } - public override async Task Render(MessageResult message) + if (Lastname == null) { - if (Firstname == null) - { - await Device.Send("Please sent your firstname:"); - return; - } - - if (Lastname == null) - { - await Device.Send("Please sent your lastname:"); - return; - } - - if (EMail == null) - { - await Device.Send("Please sent your email address:"); - return; - } - - - var s = ""; - - s += "Firstname: " + Firstname + "\r\n"; - s += "Lastname: " + Lastname + "\r\n"; - s += "E-Mail: " + EMail + "\r\n"; - - var bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "back").Serialize())); - - await Device.Send("Your details:\r\n" + s, bf); + Lastname = message.MessageText; + return Task.CompletedTask; } + if (EMail == null) + { + EMail = message.MessageText; + return Task.CompletedTask; + } + return Task.CompletedTask; } -} + + public override async Task Action(MessageResult message) + { + var call = message.GetData(); + + await message.ConfirmAction(); + + if (call == null) + { + return; + } + + switch (call.Value) + { + case "back": + + var start = new Start(); + + await NavigateTo(start); + + break; + } + } + + public override async Task Render(MessageResult message) + { + if (Firstname == null) + { + await Device.Send("Please sent your firstname:"); + return; + } + + if (Lastname == null) + { + await Device.Send("Please sent your lastname:"); + return; + } + + if (EMail == null) + { + await Device.Send("Please sent your email address:"); + return; + } + + + var s = ""; + + s += "Firstname: " + Firstname + "\r\n"; + s += "Lastname: " + Lastname + "\r\n"; + s += "E-Mail: " + EMail + "\r\n"; + + var bf = new ButtonForm(); + bf.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "back").Serialize())); + + await Device.Send("Your details:\r\n" + s, bf); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Register/PerStep.cs b/TelegramBotBase.Test/Tests/Register/PerStep.cs index b31779a..437dbce 100644 --- a/TelegramBotBase.Test/Tests/Register/PerStep.cs +++ b/TelegramBotBase.Test/Tests/Register/PerStep.cs @@ -3,42 +3,39 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; using TelegramBotBaseTest.Tests.Register.Steps; -namespace TelegramBotBaseTest.Tests.Register +namespace TelegramBotBaseTest.Tests.Register; + +public class PerStep : AutoCleanForm { - public class PerStep: AutoCleanForm + public override async Task Action(MessageResult message) { + await message.ConfirmAction(); - public override async Task Action(MessageResult message) + switch (message.RawData) { - await message.ConfirmAction(); + case "start": - switch (message.RawData) - { - case "start": + var step1 = new Step1(); - var step1 = new Step1(); + await NavigateTo(step1); - await NavigateTo(step1); + break; + case "back": - break; - case "back": + var start = new Start(); - var start = new Start(); + await NavigateTo(start); - await NavigateTo(start); - - break; - - } - } - - public override async Task Render(MessageResult message) - { - var bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase("Goto Step 1", "start")); - bf.AddButtonRow(new ButtonBase("Back", "back")); - - await Device.Send("Register Steps", bf); + break; } } -} + + public override async Task Render(MessageResult message) + { + var bf = new ButtonForm(); + bf.AddButtonRow(new ButtonBase("Goto Step 1", "start")); + bf.AddButtonRow(new ButtonBase("Back", "back")); + + await Device.Send("Register Steps", bf); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Register/Start.cs b/TelegramBotBase.Test/Tests/Register/Start.cs index a37c5c7..09b3516 100644 --- a/TelegramBotBase.Test/Tests/Register/Start.cs +++ b/TelegramBotBase.Test/Tests/Register/Start.cs @@ -2,62 +2,56 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Register +namespace TelegramBotBaseTest.Tests.Register; + +public class Start : AutoCleanForm { - public class Start : AutoCleanForm + public override async Task Action(MessageResult message) { - public override async Task Action(MessageResult message) + var call = message.GetData(); + + await message.ConfirmAction(); + + + if (call == null) { - var call = message.GetData(); - - await message.ConfirmAction(); - - - if (call == null) - return; - - switch (call.Value) - { - case "form": - - var form = new PerForm(); - - await NavigateTo(form); - - break; - case "step": - - var step = new PerStep(); - - await NavigateTo(step); - - break; - case "backtodashboard": - - var start = new Menu(); - - await NavigateTo(start); - - break; - } - - + return; } - public override async Task Render(MessageResult message) + switch (call.Value) { + case "form": - var btn = new ButtonForm(); + var form = new PerForm(); - btn.AddButtonRow(new ButtonBase("#4.1 Per Form", new CallbackData("a", "form").Serialize())); - btn.AddButtonRow(new ButtonBase("#4.2 Per Step", new CallbackData("a", "step").Serialize())); - btn.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "backtodashboard").Serialize())); + await NavigateTo(form); - await Device.Send("Choose your test:", btn); + break; + case "step": + var step = new PerStep(); + await NavigateTo(step); + + break; + case "backtodashboard": + + var start = new Menu(); + + await NavigateTo(start); + + break; } - - } -} + + public override async Task Render(MessageResult message) + { + var btn = new ButtonForm(); + + btn.AddButtonRow(new ButtonBase("#4.1 Per Form", new CallbackData("a", "form").Serialize())); + btn.AddButtonRow(new ButtonBase("#4.2 Per Step", new CallbackData("a", "step").Serialize())); + btn.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "backtodashboard").Serialize())); + + await Device.Send("Choose your test:", btn); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Register/Steps/Data.cs b/TelegramBotBase.Test/Tests/Register/Steps/Data.cs index fab243b..63a56ff 100644 --- a/TelegramBotBase.Test/Tests/Register/Steps/Data.cs +++ b/TelegramBotBase.Test/Tests/Register/Steps/Data.cs @@ -1,12 +1,10 @@ -namespace TelegramBotBaseTest.Tests.Register.Steps +namespace TelegramBotBaseTest.Tests.Register.Steps; + +public class Data { - public class Data - { - public string EMail { get; set; } + public string EMail { get; set; } - public string Firstname { get; set; } + public string Firstname { get; set; } - public string Lastname { get; set; } - - } -} + public string Lastname { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Register/Steps/Step1.cs b/TelegramBotBase.Test/Tests/Register/Steps/Step1.cs index 0b0616d..3cf1570 100644 --- a/TelegramBotBase.Test/Tests/Register/Steps/Step1.cs +++ b/TelegramBotBase.Test/Tests/Register/Steps/Step1.cs @@ -3,57 +3,59 @@ using TelegramBotBase.Args; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Register.Steps +namespace TelegramBotBaseTest.Tests.Register.Steps; + +public class Step1 : AutoCleanForm { - public class Step1 : AutoCleanForm + public Step1() { - public Data UserData { get; set; } - - public Step1() - { - Init += Step1_Init; - } - - private Task Step1_Init(object sender, InitEventArgs e) - { - UserData = new Data(); - return Task.CompletedTask; - } - - - public override Task Load(MessageResult message) - { - if (message.Handled) - return Task.CompletedTask; - - if (message.MessageText.Trim() == "") - return Task.CompletedTask; - - if (UserData.Firstname == null) - { - UserData.Firstname = message.MessageText; - return Task.CompletedTask; - } - - return Task.CompletedTask; - } - - public override async Task Render(MessageResult message) - { - if (UserData.Firstname == null) - { - await Device.Send("Please sent your firstname:"); - return; - } - - message.Handled = true; - - var step2 = new Step2(); - - step2.UserData = UserData; - - await NavigateTo(step2); - } - + Init += Step1_Init; } -} + + public Data UserData { get; set; } + + private Task Step1_Init(object sender, InitEventArgs e) + { + UserData = new Data(); + return Task.CompletedTask; + } + + + public override Task Load(MessageResult message) + { + if (message.Handled) + { + return Task.CompletedTask; + } + + if (message.MessageText.Trim() == "") + { + return Task.CompletedTask; + } + + if (UserData.Firstname == null) + { + UserData.Firstname = message.MessageText; + return Task.CompletedTask; + } + + return Task.CompletedTask; + } + + public override async Task Render(MessageResult message) + { + if (UserData.Firstname == null) + { + await Device.Send("Please sent your firstname:"); + return; + } + + message.Handled = true; + + var step2 = new Step2(); + + step2.UserData = UserData; + + await NavigateTo(step2); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Register/Steps/Step2.cs b/TelegramBotBase.Test/Tests/Register/Steps/Step2.cs index 5a954f4..fffd190 100644 --- a/TelegramBotBase.Test/Tests/Register/Steps/Step2.cs +++ b/TelegramBotBase.Test/Tests/Register/Steps/Step2.cs @@ -2,47 +2,49 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Register.Steps +namespace TelegramBotBaseTest.Tests.Register.Steps; + +public class Step2 : AutoCleanForm { - public class Step2 : AutoCleanForm + public Data UserData { get; set; } + + + public override Task Load(MessageResult message) { - public Data UserData { get; set; } - - - public override Task Load(MessageResult message) + if (message.Handled) { - if (message.Handled) - return Task.CompletedTask; - - if (message.MessageText.Trim() == "") - return Task.CompletedTask; - - if (UserData.Lastname == null) - { - UserData.Lastname = message.MessageText; - return Task.CompletedTask; - } - return Task.CompletedTask; } - - public override async Task Render(MessageResult message) + if (message.MessageText.Trim() == "") { - if (UserData.Lastname == null) - { - await Device.Send("Please sent your lastname:"); - return; - } - - message.Handled = true; - - var step3 = new Step3(); - - step3.UserData = UserData; - - await NavigateTo(step3); + return Task.CompletedTask; } + if (UserData.Lastname == null) + { + UserData.Lastname = message.MessageText; + return Task.CompletedTask; + } + + return Task.CompletedTask; } -} + + + public override async Task Render(MessageResult message) + { + if (UserData.Lastname == null) + { + await Device.Send("Please sent your lastname:"); + return; + } + + message.Handled = true; + + var step3 = new Step3(); + + step3.UserData = UserData; + + await NavigateTo(step3); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Register/Steps/Step3.cs b/TelegramBotBase.Test/Tests/Register/Steps/Step3.cs index 1f22924..45eaea8 100644 --- a/TelegramBotBase.Test/Tests/Register/Steps/Step3.cs +++ b/TelegramBotBase.Test/Tests/Register/Steps/Step3.cs @@ -2,68 +2,68 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Register.Steps +namespace TelegramBotBaseTest.Tests.Register.Steps; + +public class Step3 : AutoCleanForm { - public class Step3 : AutoCleanForm + public Data UserData { get; set; } + + public override Task Load(MessageResult message) { - public Data UserData { get; set; } - - public override Task Load(MessageResult message) + if (message.Handled) { - if (message.Handled) - return Task.CompletedTask; - - if (message.MessageText.Trim() == "") - return Task.CompletedTask; - - if (UserData.EMail == null) - { - UserData.EMail = message.MessageText; - return Task.CompletedTask; - } - return Task.CompletedTask; } - public override async Task Action(MessageResult message) + if (message.MessageText.Trim() == "") { - await message.ConfirmAction(); - - switch (message.RawData) - { - case "back": - - var start = new Start(); - - await NavigateTo(start); - - break; - - } - + return Task.CompletedTask; } - public override async Task Render(MessageResult message) + if (UserData.EMail == null) { - if (UserData.EMail == null) - { - await Device.Send("Please sent your email:"); - return; - } - - message.Handled = true; - - var s = ""; - - s += "Firstname: " + UserData.Firstname + "\r\n"; - s += "Lastname: " + UserData.Lastname + "\r\n"; - s += "E-Mail: " + UserData.EMail + "\r\n"; - - var bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase("Back", "back")); - - await Device.Send("Your details:\r\n" + s, bf); + UserData.EMail = message.MessageText; + return Task.CompletedTask; } + return Task.CompletedTask; } -} + + public override async Task Action(MessageResult message) + { + await message.ConfirmAction(); + + switch (message.RawData) + { + case "back": + + var start = new Start(); + + await NavigateTo(start); + + break; + } + } + + public override async Task Render(MessageResult message) + { + if (UserData.EMail == null) + { + await Device.Send("Please sent your email:"); + return; + } + + message.Handled = true; + + var s = ""; + + s += "Firstname: " + UserData.Firstname + "\r\n"; + s += "Lastname: " + UserData.Lastname + "\r\n"; + s += "E-Mail: " + UserData.EMail + "\r\n"; + + var bf = new ButtonForm(); + bf.AddButtonRow(new ButtonBase("Back", "back")); + + await Device.Send("Your details:\r\n" + s, bf); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/SimpleForm.cs b/TelegramBotBase.Test/Tests/SimpleForm.cs index 4f5c5fa..d776936 100644 --- a/TelegramBotBase.Test/Tests/SimpleForm.cs +++ b/TelegramBotBase.Test/Tests/SimpleForm.cs @@ -4,63 +4,59 @@ using TelegramBotBase.Base; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests +namespace TelegramBotBaseTest.Tests; + +public class SimpleForm : AutoCleanForm { - public class SimpleForm : AutoCleanForm + public SimpleForm() { + DeleteSide = EDeleteSide.Both; + DeleteMode = EDeleteMode.OnLeavingForm; - public SimpleForm() - { - DeleteSide = EDeleteSide.Both; - DeleteMode = EDeleteMode.OnLeavingForm; - - Opened += SimpleForm_Opened; - } - - private async Task SimpleForm_Opened(object sender, EventArgs e) - { - await Device.Send("Hello world! (send 'back' to get back to Start)\r\nOr\r\nhi, hello, maybe, bye and ciao"); - } - - public override async Task Load(MessageResult message) - { - //message.MessageText will work also, cause it is a string you could manage a lot different scenerios here - - var messageId = message.MessageId; - - switch (message.Command) - { - case "hello": - case "hi": - - //Send him a simple message - await Device.Send("Hello you there !"); - break; - - case "maybe": - - //Send him a simple message and reply to the one of himself - await Device.Send("Maybe what?", replyTo: messageId); - - break; - - case "bye": - case "ciao": - - //Send him a simple message - await Device.Send("Ok, take care !"); - break; - - case "back": - - var st = new Menu(); - - await NavigateTo(st); - - break; - } - } - - + Opened += SimpleForm_Opened; } -} + + private async Task SimpleForm_Opened(object sender, EventArgs e) + { + await Device.Send("Hello world! (send 'back' to get back to Start)\r\nOr\r\nhi, hello, maybe, bye and ciao"); + } + + public override async Task Load(MessageResult message) + { + //message.MessageText will work also, cause it is a string you could manage a lot different scenerios here + + var messageId = message.MessageId; + + switch (message.Command) + { + case "hello": + case "hi": + + //Send him a simple message + await Device.Send("Hello you there !"); + break; + + case "maybe": + + //Send him a simple message and reply to the one of himself + await Device.Send("Maybe what?", replyTo: messageId); + + break; + + case "bye": + case "ciao": + + //Send him a simple message + await Device.Send("Ok, take care !"); + break; + + case "back": + + var st = new Menu(); + + await NavigateTo(st); + + break; + } + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/Start.cs b/TelegramBotBase.Test/Tests/Start.cs index 5933011..bbe1783 100644 --- a/TelegramBotBase.Test/Tests/Start.cs +++ b/TelegramBotBase.Test/Tests/Start.cs @@ -3,36 +3,34 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; using TelegramBotBaseTest.Tests.Groups; -namespace TelegramBotBaseTest.Tests +namespace TelegramBotBaseTest.Tests; + +public class Start : SplitterForm { - public class Start : SplitterForm + public override async Task Open(MessageResult e) { - public override async Task Open(MessageResult e) - { - var st = new Menu(); - await NavigateTo(st); - - return true; - } - - - public override async Task OpenGroup(MessageResult e) - { - var st = new LinkReplaceTest(); - await NavigateTo(st); - - return true; - } - - public override Task OpenChannel(MessageResult e) - { - return base.OpenChannel(e); - } - - public override Task OpenSupergroup(MessageResult e) - { - return base.OpenSupergroup(e); - } + var st = new Menu(); + await NavigateTo(st); + return true; } -} + + + public override async Task OpenGroup(MessageResult e) + { + var st = new LinkReplaceTest(); + await NavigateTo(st); + + return true; + } + + public override Task OpenChannel(MessageResult e) + { + return base.OpenChannel(e); + } + + public override Task OpenSupergroup(MessageResult e) + { + return base.OpenSupergroup(e); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/TestForm.cs b/TelegramBotBase.Test/Tests/TestForm.cs index e248414..30cb824 100644 --- a/TelegramBotBase.Test/Tests/TestForm.cs +++ b/TelegramBotBase.Test/Tests/TestForm.cs @@ -3,70 +3,65 @@ using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests +namespace TelegramBotBaseTest.Tests; + +public class TestForm : FormBase { - public class TestForm : FormBase + public TestForm() { - private string LastMessage { get; set; } - - public TestForm() - { - Opened += TestForm_Opened; - Closed += TestForm_Closed; - } - - private async Task TestForm_Opened(object sender, EventArgs e) - { - await Device.Send("Welcome to Form 1"); - } - - private async Task TestForm_Closed(object sender, EventArgs e) - { - await Device.Send("Ciao from Form 1"); - } - - - public override async Task Action(MessageResult message) - { - switch (message.Command) - { - case "reply": - - - break; - - case "navigate": - - var tf = new TestForm2(); - - await NavigateTo(tf); - - break; - - default: - - if (message.UpdateData == null) - return; - - LastMessage = message.Message.Text; - - break; - } - - - } - - - public override async Task Render(MessageResult message) - { - if (message.Command == "reply") - { - - await Device.Send("Last message: " + LastMessage); - - } - - } - + Opened += TestForm_Opened; + Closed += TestForm_Closed; } -} + + private string LastMessage { get; set; } + + private async Task TestForm_Opened(object sender, EventArgs e) + { + await Device.Send("Welcome to Form 1"); + } + + private async Task TestForm_Closed(object sender, EventArgs e) + { + await Device.Send("Ciao from Form 1"); + } + + + public override async Task Action(MessageResult message) + { + switch (message.Command) + { + case "reply": + + + break; + + case "navigate": + + var tf = new TestForm2(); + + await NavigateTo(tf); + + break; + + default: + + if (message.UpdateData == null) + { + return; + } + + LastMessage = message.Message.Text; + + break; + } + } + + + public override async Task Render(MessageResult message) + { + if (message.Command == "reply") + { + await Device.Send("Last message: " + LastMessage); + } + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/Tests/TestForm2.cs b/TelegramBotBase.Test/Tests/TestForm2.cs index 93cced0..2cff462 100644 --- a/TelegramBotBase.Test/Tests/TestForm2.cs +++ b/TelegramBotBase.Test/Tests/TestForm2.cs @@ -6,118 +6,103 @@ using TelegramBotBase.Base; using TelegramBotBase.Extensions.Images; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests +namespace TelegramBotBaseTest.Tests; + +public class TestForm2 : FormBase { - public class TestForm2 : FormBase + public TestForm2() { - - - public TestForm2() - { - Opened += TestForm2_Opened; - Closed += TestForm2_Closed; - } - - private async Task TestForm2_Opened(object sender, EventArgs e) - { - await Device.Send("Welcome to Form 2"); - } - - private async Task TestForm2_Closed(object sender, EventArgs e) - { - await Device.Send("Ciao from Form 2"); - } - - - - - public override async Task Action(MessageResult message) - { - var call = message.GetData(); - - await message.ConfirmAction(); - - await message.DeleteMessage(); - - message.Handled = true; - - if (call.Value == "testform1") - { - - var tf = new TestForm(); - - await NavigateTo(tf); - } - else if (call.Value == "alert") - { - var ad = new AlertDialog("This is a message", "Ok"); - - ad.ButtonClicked += async (s, en) => - { - var fto = new TestForm2(); - await NavigateTo(fto); - }; - - await NavigateTo(ad); - } - else if (call.Value == "confirm") - { - var pd = new ConfirmDialog("Please confirm", new ButtonBase("Ok", "ok"), new ButtonBase("Cancel", "cancel")); - - pd.ButtonClicked += async (s, en) => - { - var tf = new TestForm2(); - - await pd.NavigateTo(tf); - }; - - await NavigateTo(pd); - } - else if (call.Value == "prompt") - { - var pd = new PromptDialog("Please tell me your name ?"); - - pd.Completed += async (s, en) => - { - await Device.Send("Hello " + pd.Value); - }; - - await OpenModal(pd); - } - - - } - - public override async Task Render(MessageResult message) - { - - var bmp = new Bitmap(800, 600); - using (var g = Graphics.FromImage(bmp)) - { - - g.FillRectangle(Brushes.White, 0, 0, bmp.Width, bmp.Height); - - g.DrawString("Test Image", new Font("Arial", 24, FontStyle.Bold, GraphicsUnit.Pixel), Brushes.Black, new PointF(50, 50)); - - } - - await Device.SetAction(ChatAction.UploadPhoto); - - var btn = new ButtonForm(); - - //btn.AddButtonRow(new ButtonBase("Zum Testformular 1", CallbackData.Create("navigate", "testform1")), new ButtonBase("Zum Testformular 1", CallbackData.Create("navigate", "testform1"))); - - btn.AddButtonRow(new ButtonBase("Information Prompt", CallbackData.Create("navigate", "alert"))); - - btn.AddButtonRow(new ButtonBase("Confirmation Prompt with event", CallbackData.Create("navigate", "confirm"))); - - btn.AddButtonRow(new ButtonBase("Request Prompt", CallbackData.Create("navigate", "prompt"))); - - - await Device.SendPhoto(bmp, "Test", "", btn); - - } - - + Opened += TestForm2_Opened; + Closed += TestForm2_Closed; } -} + + private async Task TestForm2_Opened(object sender, EventArgs e) + { + await Device.Send("Welcome to Form 2"); + } + + private async Task TestForm2_Closed(object sender, EventArgs e) + { + await Device.Send("Ciao from Form 2"); + } + + + public override async Task Action(MessageResult message) + { + var call = message.GetData(); + + await message.ConfirmAction(); + + await message.DeleteMessage(); + + message.Handled = true; + + if (call.Value == "testform1") + { + var tf = new TestForm(); + + await NavigateTo(tf); + } + else if (call.Value == "alert") + { + var ad = new AlertDialog("This is a message", "Ok"); + + ad.ButtonClicked += async (s, en) => + { + var fto = new TestForm2(); + await NavigateTo(fto); + }; + + await NavigateTo(ad); + } + else if (call.Value == "confirm") + { + var pd = new ConfirmDialog("Please confirm", new ButtonBase("Ok", "ok"), + new ButtonBase("Cancel", "cancel")); + + pd.ButtonClicked += async (s, en) => + { + var tf = new TestForm2(); + + await pd.NavigateTo(tf); + }; + + await NavigateTo(pd); + } + else if (call.Value == "prompt") + { + var pd = new PromptDialog("Please tell me your name ?"); + + pd.Completed += async (s, en) => { await Device.Send("Hello " + pd.Value); }; + + await OpenModal(pd); + } + } + + public override async Task Render(MessageResult message) + { + var bmp = new Bitmap(800, 600); + using (var g = Graphics.FromImage(bmp)) + { + g.FillRectangle(Brushes.White, 0, 0, bmp.Width, bmp.Height); + + g.DrawString("Test Image", new Font("Arial", 24, FontStyle.Bold, GraphicsUnit.Pixel), Brushes.Black, + new PointF(50, 50)); + } + + await Device.SetAction(ChatAction.UploadPhoto); + + var btn = new ButtonForm(); + + //btn.AddButtonRow(new ButtonBase("Zum Testformular 1", CallbackData.Create("navigate", "testform1")), new ButtonBase("Zum Testformular 1", CallbackData.Create("navigate", "testform1"))); + + btn.AddButtonRow(new ButtonBase("Information Prompt", CallbackData.Create("navigate", "alert"))); + + btn.AddButtonRow(new ButtonBase("Confirmation Prompt with event", CallbackData.Create("navigate", "confirm"))); + + btn.AddButtonRow(new ButtonBase("Request Prompt", CallbackData.Create("navigate", "prompt"))); + + + await Device.SendPhoto(bmp, "Test", "", btn); + } +} \ No newline at end of file diff --git a/TelegramBotBase.Test/packages.config b/TelegramBotBase.Test/packages.config index d654912..f74d058 100644 --- a/TelegramBotBase.Test/packages.config +++ b/TelegramBotBase.Test/packages.config @@ -1,6 +1,6 @@  - - - - \ No newline at end of file + + + + diff --git a/TelegramBotBase/Args/BotCommandEventArgs.cs b/TelegramBotBase/Args/BotCommandEventArgs.cs index 3f3d545..02ec9d8 100644 --- a/TelegramBotBase/Args/BotCommandEventArgs.cs +++ b/TelegramBotBase/Args/BotCommandEventArgs.cs @@ -3,40 +3,36 @@ using System.Collections.Generic; using Telegram.Bot.Types; using TelegramBotBase.Sessions; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +/// +/// Base class for given bot command results +/// +public class BotCommandEventArgs : EventArgs { - /// - /// Base class for given bot command results - /// - public class BotCommandEventArgs : EventArgs + public BotCommandEventArgs() { - public string Command { get; set; } - - public List Parameters { get; set; } - - public long DeviceId { get; set; } - - public DeviceSession Device { get; set; } - - public bool Handled { get; set; } = false; - - public Message OriginalMessage { get; set; } - - - public BotCommandEventArgs() - { - - - } - - public BotCommandEventArgs(string command, List parameters, Message message, long deviceId, DeviceSession device) - { - this.Command = command; - this.Parameters = parameters; - OriginalMessage = message; - this.DeviceId = deviceId; - this.Device = device; - } - } -} + + public BotCommandEventArgs(string command, List parameters, Message message, long deviceId, + DeviceSession device) + { + Command = command; + Parameters = parameters; + OriginalMessage = message; + DeviceId = deviceId; + Device = device; + } + + public string Command { get; set; } + + public List Parameters { get; set; } + + public long DeviceId { get; set; } + + public DeviceSession Device { get; set; } + + public bool Handled { get; set; } = false; + + public Message OriginalMessage { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/ButtonClickedEventArgs.cs b/TelegramBotBase/Args/ButtonClickedEventArgs.cs index 2227abd..1bb69a4 100644 --- a/TelegramBotBase/Args/ButtonClickedEventArgs.cs +++ b/TelegramBotBase/Args/ButtonClickedEventArgs.cs @@ -2,44 +2,41 @@ using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Form; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +/// +/// Button get clicked event +/// +public class ButtonClickedEventArgs : EventArgs { - /// - /// Button get clicked event - /// - public class ButtonClickedEventArgs : EventArgs + public ButtonClickedEventArgs() { - public ButtonBase Button { get; set; } - - public int Index { get; set; } - - public object Tag { get; set; } - - public ButtonRow Row { get; set; } - - - public ButtonClickedEventArgs() - { - - } - - public ButtonClickedEventArgs(ButtonBase button) - { - Button = button; - Index = -1; - } - - public ButtonClickedEventArgs(ButtonBase button, int index) - { - Button = button; - this.Index = index; - } - - public ButtonClickedEventArgs(ButtonBase button, int index, ButtonRow row) - { - Button = button; - this.Index = index; - Row = row; - } } -} + + public ButtonClickedEventArgs(ButtonBase button) + { + Button = button; + Index = -1; + } + + public ButtonClickedEventArgs(ButtonBase button, int index) + { + Button = button; + Index = index; + } + + public ButtonClickedEventArgs(ButtonBase button, int index, ButtonRow row) + { + Button = button; + Index = index; + Row = row; + } + + public ButtonBase Button { get; set; } + + public int Index { get; set; } + + public object Tag { get; set; } + + public ButtonRow Row { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/CheckedChangedEventArgs.cs b/TelegramBotBase/Args/CheckedChangedEventArgs.cs index 5ec61d3..6e5288e 100644 --- a/TelegramBotBase/Args/CheckedChangedEventArgs.cs +++ b/TelegramBotBase/Args/CheckedChangedEventArgs.cs @@ -1,41 +1,36 @@ using System; using TelegramBotBase.Controls.Hybrid; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class CheckedChangedEventArgs : EventArgs { - public class CheckedChangedEventArgs : EventArgs + public CheckedChangedEventArgs() { - /// - /// Contains the index of the row where the button is inside. - /// Contains -1 when it is a layout button or not found. - /// - public int Index { get; set; } - - - /// - /// Contains all buttons within this row, excluding the checkbox. - /// - public ButtonRow Row { get; set; } - - - /// - /// Contains the new checked status of the row. - /// - public bool Checked { get; set; } - - - public CheckedChangedEventArgs() - { - - } - - public CheckedChangedEventArgs(ButtonRow row, int index, bool @checked) - { - Row = row; - this.Index = index; - this.Checked = @checked; - } - - } -} + + public CheckedChangedEventArgs(ButtonRow row, int index, bool @checked) + { + Row = row; + Index = index; + Checked = @checked; + } + + /// + /// Contains the index of the row where the button is inside. + /// Contains -1 when it is a layout button or not found. + /// + public int Index { get; set; } + + + /// + /// Contains all buttons within this row, excluding the checkbox. + /// + public ButtonRow Row { get; set; } + + + /// + /// Contains the new checked status of the row. + /// + public bool Checked { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/GroupChangedEventArgs.cs b/TelegramBotBase/Args/GroupChangedEventArgs.cs index 5493f9d..5d8b9ae 100644 --- a/TelegramBotBase/Args/GroupChangedEventArgs.cs +++ b/TelegramBotBase/Args/GroupChangedEventArgs.cs @@ -2,21 +2,17 @@ using Telegram.Bot.Types.Enums; using TelegramBotBase.Base; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class GroupChangedEventArgs : EventArgs { - public class GroupChangedEventArgs : EventArgs + public GroupChangedEventArgs(MessageType type, MessageResult message) { - public MessageType Type { get; set; } - - public MessageResult OriginalMessage { get; set; } - - public GroupChangedEventArgs(MessageType type, MessageResult message) - { - Type = type; - OriginalMessage = message; - } - - - + Type = type; + OriginalMessage = message; } -} + + public MessageType Type { get; set; } + + public MessageResult OriginalMessage { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/InitEventArgs.cs b/TelegramBotBase/Args/InitEventArgs.cs index 360aaa1..a0af03a 100644 --- a/TelegramBotBase/Args/InitEventArgs.cs +++ b/TelegramBotBase/Args/InitEventArgs.cs @@ -1,14 +1,13 @@ using System; -namespace TelegramBotBase.Args -{ - public class InitEventArgs : EventArgs - { - public object[] Args { get; set; } +namespace TelegramBotBase.Args; - public InitEventArgs(params object[] args) - { - Args = args; - } +public class InitEventArgs : EventArgs +{ + public InitEventArgs(params object[] args) + { + Args = args; } -} + + public object[] Args { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/LoadStateEventArgs.cs b/TelegramBotBase/Args/LoadStateEventArgs.cs index 06834c7..42fc51b 100644 --- a/TelegramBotBase/Args/LoadStateEventArgs.cs +++ b/TelegramBotBase/Args/LoadStateEventArgs.cs @@ -1,55 +1,59 @@ using System.Collections.Generic; using System.Linq; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class LoadStateEventArgs { - public class LoadStateEventArgs + public LoadStateEventArgs() { - public Dictionary Values { get; set; } - - public LoadStateEventArgs() - { - Values = new Dictionary(); - } - - public List Keys => Values.Keys.ToList(); - - public string Get(string key) - { - return Values[key].ToString(); - } - - public int GetInt(string key) - { - var i = 0; - if (int.TryParse(Values[key].ToString(), out i)) - return i; - - return 0; - } - - public double GetDouble(string key) - { - double d = 0; - if (double.TryParse(Values[key].ToString(), out d)) - return d; - - return 0; - } - - public bool GetBool(string key) - { - var b = false; - if (bool.TryParse(Values[key].ToString(), out b)) - return b; - - return false; - } - - public object GetObject(string key) - { - return Values[key]; - } - + Values = new Dictionary(); } -} + + public Dictionary Values { get; set; } + + public List Keys => Values.Keys.ToList(); + + public string Get(string key) + { + return Values[key].ToString(); + } + + public int GetInt(string key) + { + var i = 0; + if (int.TryParse(Values[key].ToString(), out i)) + { + return i; + } + + return 0; + } + + public double GetDouble(string key) + { + double d = 0; + if (double.TryParse(Values[key].ToString(), out d)) + { + return d; + } + + return 0; + } + + public bool GetBool(string key) + { + var b = false; + if (bool.TryParse(Values[key].ToString(), out b)) + { + return b; + } + + return false; + } + + public object GetObject(string key) + { + return Values[key]; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/MemberChangeEventArgs.cs b/TelegramBotBase/Args/MemberChangeEventArgs.cs index 34519a9..f59f8c0 100644 --- a/TelegramBotBase/Args/MemberChangeEventArgs.cs +++ b/TelegramBotBase/Args/MemberChangeEventArgs.cs @@ -5,32 +5,25 @@ using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using TelegramBotBase.Base; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class MemberChangeEventArgs : EventArgs { - public class MemberChangeEventArgs : EventArgs + public MemberChangeEventArgs() { - public List Members { get; set; } - - public MessageType Type { get; set; } - - public MessageResult Result { get; set; } - - public MemberChangeEventArgs() - { - Members = new List(); - - } - - public MemberChangeEventArgs(MessageType type, MessageResult result, params User[] members) - { - Type = type; - Result = result; - Members = members.ToList(); - } - - - - - + Members = new List(); } -} + + public MemberChangeEventArgs(MessageType type, MessageResult result, params User[] members) + { + Type = type; + Result = result; + Members = members.ToList(); + } + + public List Members { get; set; } + + public MessageType Type { get; set; } + + public MessageResult Result { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/MessageDeletedEventArgs.cs b/TelegramBotBase/Args/MessageDeletedEventArgs.cs index bab0af6..34f174b 100644 --- a/TelegramBotBase/Args/MessageDeletedEventArgs.cs +++ b/TelegramBotBase/Args/MessageDeletedEventArgs.cs @@ -1,16 +1,11 @@ -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class MessageDeletedEventArgs { - public class MessageDeletedEventArgs + public MessageDeletedEventArgs(int messageId) { - public int MessageId - { - get;set; - } - - public MessageDeletedEventArgs(int messageId) - { - MessageId = messageId; - } - + MessageId = messageId; } -} + + public int MessageId { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/MessageIncomeEventArgs.cs b/TelegramBotBase/Args/MessageIncomeEventArgs.cs index 5e6de76..ddc0ac8 100644 --- a/TelegramBotBase/Args/MessageIncomeEventArgs.cs +++ b/TelegramBotBase/Args/MessageIncomeEventArgs.cs @@ -1,26 +1,20 @@ using System; using TelegramBotBase.Sessions; -namespace TelegramBotBase.Base +namespace TelegramBotBase.Base; + +public class MessageIncomeEventArgs : EventArgs { - public class MessageIncomeEventArgs : EventArgs + public MessageIncomeEventArgs(long deviceId, DeviceSession device, MessageResult message) { - - public long DeviceId { get; set; } - - public DeviceSession Device { get; set; } - - public MessageResult Message { get; set; } - - public MessageIncomeEventArgs(long deviceId, DeviceSession device, MessageResult message) - { - this.DeviceId = deviceId; - this.Device = device; - Message = message; - } - - - - + DeviceId = deviceId; + Device = device; + Message = message; } -} + + public long DeviceId { get; set; } + + public DeviceSession Device { get; set; } + + public MessageResult Message { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/MessageReceivedEventArgs.cs b/TelegramBotBase/Args/MessageReceivedEventArgs.cs index 497782f..85fce86 100644 --- a/TelegramBotBase/Args/MessageReceivedEventArgs.cs +++ b/TelegramBotBase/Args/MessageReceivedEventArgs.cs @@ -1,17 +1,15 @@ using Telegram.Bot.Types; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class MessageReceivedEventArgs { - public class MessageReceivedEventArgs + public MessageReceivedEventArgs(Message m) { - public int MessageId => Message.MessageId; - - public Message Message { get; set; } - - public MessageReceivedEventArgs(Message m) - { - Message = m; - } - + Message = m; } -} + + public int MessageId => Message.MessageId; + + public Message Message { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/MessageSentEventArgs.cs b/TelegramBotBase/Args/MessageSentEventArgs.cs index a776207..3086908 100644 --- a/TelegramBotBase/Args/MessageSentEventArgs.cs +++ b/TelegramBotBase/Args/MessageSentEventArgs.cs @@ -1,26 +1,22 @@ using System; using Telegram.Bot.Types; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class MessageSentEventArgs : EventArgs { - public class MessageSentEventArgs : EventArgs + public MessageSentEventArgs(Message message, Type origin) { - public int MessageId => Message.MessageId; - - public Message Message { get; set; } - - /// - /// Contains the element, which has called the method. - /// - public Type Origin { get; set; } - - - public MessageSentEventArgs(Message message, Type origin) - { - Message = message; - this.Origin = origin; - } - - + Message = message; + Origin = origin; } -} + + public int MessageId => Message.MessageId; + + public Message Message { get; set; } + + /// + /// Contains the element, which has called the method. + /// + public Type Origin { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/PromptDialogCompletedEventArgs.cs b/TelegramBotBase/Args/PromptDialogCompletedEventArgs.cs index b0b7e04..9de7888 100644 --- a/TelegramBotBase/Args/PromptDialogCompletedEventArgs.cs +++ b/TelegramBotBase/Args/PromptDialogCompletedEventArgs.cs @@ -1,10 +1,8 @@ -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class PromptDialogCompletedEventArgs { - public class PromptDialogCompletedEventArgs - { - public object Tag { get; set; } + public object Tag { get; set; } - public string Value { get; set; } - - } -} + public string Value { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/RenderViewEventArgs.cs b/TelegramBotBase/Args/RenderViewEventArgs.cs index 82df8e5..cc736eb 100644 --- a/TelegramBotBase/Args/RenderViewEventArgs.cs +++ b/TelegramBotBase/Args/RenderViewEventArgs.cs @@ -1,18 +1,13 @@ using System; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class RenderViewEventArgs : EventArgs { - public class RenderViewEventArgs : EventArgs + public RenderViewEventArgs(int viewIndex) { - public int CurrentView { get; set; } - - - public RenderViewEventArgs(int viewIndex) - { - - CurrentView = viewIndex; - } - - + CurrentView = viewIndex; } -} + + public int CurrentView { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/SaveStateEventArgs.cs b/TelegramBotBase/Args/SaveStateEventArgs.cs index bfc3984..39d3e46 100644 --- a/TelegramBotBase/Args/SaveStateEventArgs.cs +++ b/TelegramBotBase/Args/SaveStateEventArgs.cs @@ -1,39 +1,38 @@ using System.Collections.Generic; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class SaveStateEventArgs { - public class SaveStateEventArgs + public SaveStateEventArgs() { - public Dictionary Values { get; set; } - - public SaveStateEventArgs() - { - Values = new Dictionary(); - } - - public void Set(string key, string value) - { - Values[key] = value; - } - - public void SetInt(string key, int value) - { - Values[key] = value; - } - - public void SetBool(string key, bool value) - { - Values[key] = value; - } - - public void SetDouble(string key, double value) - { - Values[key] = value; - } - public void SetObject(string key, object value) - { - Values[key] = value; - } - + Values = new Dictionary(); } -} + + public Dictionary Values { get; set; } + + public void Set(string key, string value) + { + Values[key] = value; + } + + public void SetInt(string key, int value) + { + Values[key] = value; + } + + public void SetBool(string key, bool value) + { + Values[key] = value; + } + + public void SetDouble(string key, double value) + { + Values[key] = value; + } + + public void SetObject(string key, object value) + { + Values[key] = value; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/SaveStatesEventArgs.cs b/TelegramBotBase/Args/SaveStatesEventArgs.cs index e2d44f6..b300d11 100644 --- a/TelegramBotBase/Args/SaveStatesEventArgs.cs +++ b/TelegramBotBase/Args/SaveStatesEventArgs.cs @@ -1,15 +1,13 @@ using TelegramBotBase.Base; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class SaveStatesEventArgs { - public class SaveStatesEventArgs + public SaveStatesEventArgs(StateContainer states) { - public StateContainer States { get; set; } - - - public SaveStatesEventArgs(StateContainer states) - { - States = states; - } + States = states; } -} + + public StateContainer States { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/SessionBeginEventArgs.cs b/TelegramBotBase/Args/SessionBeginEventArgs.cs index 9187f0b..53a54b9 100644 --- a/TelegramBotBase/Args/SessionBeginEventArgs.cs +++ b/TelegramBotBase/Args/SessionBeginEventArgs.cs @@ -1,18 +1,17 @@ using System; using TelegramBotBase.Sessions; -namespace TelegramBotBase.Base +namespace TelegramBotBase.Base; + +public class SessionBeginEventArgs : EventArgs { - public class SessionBeginEventArgs : EventArgs + public SessionBeginEventArgs(long deviceId, DeviceSession device) { - public long DeviceId { get; set; } - - public DeviceSession Device { get; set; } - - public SessionBeginEventArgs(long deviceId, DeviceSession device) - { - this.DeviceId = deviceId; - this.Device = device; - } + DeviceId = deviceId; + Device = device; } -} + + public long DeviceId { get; set; } + + public DeviceSession Device { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/SystemExceptionEventArgs.cs b/TelegramBotBase/Args/SystemExceptionEventArgs.cs index cc19a62..5fbaf69 100644 --- a/TelegramBotBase/Args/SystemExceptionEventArgs.cs +++ b/TelegramBotBase/Args/SystemExceptionEventArgs.cs @@ -1,32 +1,27 @@ using System; using TelegramBotBase.Sessions; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class SystemExceptionEventArgs : EventArgs { - public class SystemExceptionEventArgs : EventArgs + public SystemExceptionEventArgs() { - - public string Command { get; set; } - - public long DeviceId { get; set; } - - public DeviceSession Device { get; set; } - - public Exception Error { get; set; } - - public SystemExceptionEventArgs() - { - - - } - - public SystemExceptionEventArgs(string command, long deviceId, DeviceSession device, Exception error) - { - this.Command = command; - this.DeviceId = deviceId; - this.Device = device; - Error = error; - } } -} + public SystemExceptionEventArgs(string command, long deviceId, DeviceSession device, Exception error) + { + Command = command; + DeviceId = deviceId; + Device = device; + Error = error; + } + + public string Command { get; set; } + + public long DeviceId { get; set; } + + public DeviceSession Device { get; set; } + + public Exception Error { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Args/UnhandledCallEventArgs.cs b/TelegramBotBase/Args/UnhandledCallEventArgs.cs index 279170f..844bc43 100644 --- a/TelegramBotBase/Args/UnhandledCallEventArgs.cs +++ b/TelegramBotBase/Args/UnhandledCallEventArgs.cs @@ -2,40 +2,37 @@ using Telegram.Bot.Types; using TelegramBotBase.Sessions; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class UnhandledCallEventArgs : EventArgs { - public class UnhandledCallEventArgs : EventArgs + public UnhandledCallEventArgs() { - public string Command { get; set; } - - public long DeviceId { get; set; } - - public DeviceSession Device {get;set;} - - public string RawData { get; set; } - - public int MessageId { get; set; } - - public Message Message { get; set; } - - public bool Handled { get; set; } - - - public UnhandledCallEventArgs() - { - Handled = false; - - } - - public UnhandledCallEventArgs(string command,string rawData, long deviceId, int messageId, Message message, DeviceSession device) : this() - { - this.Command = command; - this.RawData = rawData; - this.DeviceId = deviceId; - this.MessageId = messageId; - Message = message; - this.Device = device; - } - + Handled = false; } -} + + public UnhandledCallEventArgs(string command, string rawData, long deviceId, int messageId, Message message, + DeviceSession device) : this() + { + Command = command; + RawData = rawData; + DeviceId = deviceId; + MessageId = messageId; + Message = message; + Device = device; + } + + public string Command { get; set; } + + public long DeviceId { get; set; } + + public DeviceSession Device { get; set; } + + public string RawData { get; set; } + + public int MessageId { get; set; } + + public Message Message { get; set; } + + public bool Handled { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Attributes/IgnoreState.cs b/TelegramBotBase/Attributes/IgnoreState.cs index 72c4381..3deb6f4 100644 --- a/TelegramBotBase/Attributes/IgnoreState.cs +++ b/TelegramBotBase/Attributes/IgnoreState.cs @@ -1,15 +1,11 @@ using System; -namespace TelegramBotBase.Attributes +namespace TelegramBotBase.Attributes; + +/// +/// Declares that this class should not be getting serialized +/// +[AttributeUsage(AttributeTargets.Class)] +public class IgnoreState : Attribute { - - /// - /// Declares that this class should not be getting serialized - /// - [AttributeUsage(AttributeTargets.Class)] - public class IgnoreState : Attribute - { - - - } -} +} \ No newline at end of file diff --git a/TelegramBotBase/Attributes/SaveState.cs b/TelegramBotBase/Attributes/SaveState.cs index 9b9190b..71f5edc 100644 --- a/TelegramBotBase/Attributes/SaveState.cs +++ b/TelegramBotBase/Attributes/SaveState.cs @@ -1,13 +1,11 @@ using System; -namespace TelegramBotBase.Attributes -{ - /// - /// Declares that the field or property should be save and recovered an restart. - /// - public class SaveState : Attribute - { - public string Key { get; set; } +namespace TelegramBotBase.Attributes; - } -} +/// +/// Declares that the field or property should be save and recovered an restart. +/// +public class SaveState : Attribute +{ + public string Key { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Base/Async.cs b/TelegramBotBase/Base/Async.cs index 9eff287..9efe5be 100644 --- a/TelegramBotBase/Base/Async.cs +++ b/TelegramBotBase/Base/Async.cs @@ -3,22 +3,25 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace TelegramBotBase.Base -{ - public static class Async - { - public delegate Task AsyncEventHandler(object sender, TEventArgs e) where TEventArgs : EventArgs; +namespace TelegramBotBase.Base; - public static IEnumerable> GetHandlers( +public static class Async +{ + public delegate Task AsyncEventHandler(object sender, TEventArgs e) where TEventArgs : EventArgs; + + public static IEnumerable> GetHandlers( this AsyncEventHandler handler) where TEventArgs : EventArgs - => handler.GetInvocationList().Cast>(); - - public static Task InvokeAllAsync(this AsyncEventHandler handler, object sender, TEventArgs e) - where TEventArgs : EventArgs - => Task.WhenAll( - handler.GetHandlers() - .Select(handleAsync => handleAsync(sender, e))); - + { + return handler.GetInvocationList().Cast>(); } -} + + public static Task InvokeAllAsync(this AsyncEventHandler handler, object sender, + TEventArgs e) + where TEventArgs : EventArgs + { + return Task.WhenAll( + handler.GetHandlers() + .Select(handleAsync => handleAsync(sender, e))); + } +} \ No newline at end of file diff --git a/TelegramBotBase/Base/ControlBase.cs b/TelegramBotBase/Base/ControlBase.cs index b06b2d3..4c25177 100644 --- a/TelegramBotBase/Base/ControlBase.cs +++ b/TelegramBotBase/Base/ControlBase.cs @@ -1,63 +1,59 @@ using System.Threading.Tasks; using TelegramBotBase.Sessions; -namespace TelegramBotBase.Base +namespace TelegramBotBase.Base; + +/// +/// Base class for controls +/// +public class ControlBase { + public DeviceSession Device { get; set; } + + public int Id { get; set; } + + public string ControlId => "#c" + Id; + /// - /// Base class for controls + /// Defines if the control should be rendered and invoked with actions /// - public class ControlBase + public bool Enabled { get; set; } = true; + + /// + /// Get invoked when control will be added to a form and invoked. + /// + /// + public virtual void Init() { - public DeviceSession Device { get; set; } - - public int Id { get; set; } - - public string ControlId => "#c" + Id; - - /// - /// Defines if the control should be rendered and invoked with actions - /// - public bool Enabled { get; set; } = true; - - /// - /// Get invoked when control will be added to a form and invoked. - /// - /// - public virtual void Init() - { - - } - - public virtual Task Load(MessageResult result) - { - return Task.CompletedTask; - } - - public virtual Task Action(MessageResult result, string value = null) - { - return Task.CompletedTask; - } - - - - public virtual Task Render(MessageResult result) - { - return Task.CompletedTask; - } - - public virtual Task Hidden(bool formClose) - { - return Task.CompletedTask; - } - - /// - /// Will be called on a cleanup. - /// - /// - public virtual Task Cleanup() - { - return Task.CompletedTask; - } - } -} + + public virtual Task Load(MessageResult result) + { + return Task.CompletedTask; + } + + public virtual Task Action(MessageResult result, string value = null) + { + return Task.CompletedTask; + } + + + public virtual Task Render(MessageResult result) + { + return Task.CompletedTask; + } + + public virtual Task Hidden(bool formClose) + { + return Task.CompletedTask; + } + + /// + /// Will be called on a cleanup. + /// + /// + public virtual Task Cleanup() + { + return Task.CompletedTask; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Base/DataResult.cs b/TelegramBotBase/Base/DataResult.cs index bebef80..14c7d9b 100644 --- a/TelegramBotBase/Base/DataResult.cs +++ b/TelegramBotBase/Base/DataResult.cs @@ -7,166 +7,164 @@ using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using Telegram.Bot.Types.InputFiles; -namespace TelegramBotBase.Base +namespace TelegramBotBase.Base; + +/// +/// Returns a class to manage attachments within messages. +/// +public class DataResult : ResultBase { - /// - /// Returns a class to manage attachments within messages. - /// - public class DataResult : ResultBase + public DataResult(UpdateResult update) { - - //public Telegram.Bot.Args.MessageEventArgs RawMessageData { get; set; } - - public UpdateResult UpdateData { get; set; } - - - public Contact Contact => Message.Contact; - - public Location Location => Message.Location; - - public Document Document => Message.Document; - - public Audio Audio => Message.Audio; - - public Video Video => Message.Video; - - public PhotoSize[] Photos => Message.Photo; - - - public MessageType Type => Message?.Type ?? MessageType.Unknown; - - public override Message Message => UpdateData?.Message; - - /// - /// Returns the FileId of the first reachable element. - /// - public string FileId => - (Document?.FileId ?? - Audio?.FileId ?? - Video?.FileId ?? - Photos.FirstOrDefault()?.FileId); - - public DataResult(UpdateResult update) - { - UpdateData = update; - } - - - public async Task DownloadDocument() - { - var encryptedContent = new MemoryStream(); - encryptedContent.SetLength(Document.FileSize.Value); - var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, encryptedContent); - - return new InputOnlineFile(encryptedContent, Document.FileName); - } - - - /// - /// Downloads a file and saves it to the given path. - /// - /// - /// - public async Task DownloadDocument(string path) - { - var file = await Device.Client.TelegramClient.GetFileAsync(Document.FileId); - var fs = new FileStream(path, FileMode.Create); - await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); - fs.Close(); - fs.Dispose(); - } - - /// - /// Downloads the document and returns an byte array. - /// - /// - public async Task DownloadRawDocument() - { - var ms = new MemoryStream(); - await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, ms); - return ms.ToArray(); - } - - /// - /// Downloads a document and returns it as string. (txt,csv,etc) Default encoding ist UTF8. - /// - /// - public async Task DownloadRawTextDocument() - { - return await DownloadRawTextDocument(Encoding.UTF8); - } - - /// - /// Downloads a document and returns it as string. (txt,csv,etc) - /// - /// - public async Task DownloadRawTextDocument(Encoding encoding) - { - var ms = new MemoryStream(); - await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, ms); - - ms.Position = 0; - - var sr = new StreamReader(ms, encoding); - - return sr.ReadToEnd(); - } - - public async Task DownloadVideo() - { - var encryptedContent = new MemoryStream(); - encryptedContent.SetLength(Video.FileSize.Value); - var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Video.FileId, encryptedContent); - - return new InputOnlineFile(encryptedContent, ""); - } - - public async Task DownloadVideo(string path) - { - var file = await Device.Client.TelegramClient.GetFileAsync(Video.FileId); - var fs = new FileStream(path, FileMode.Create); - await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); - fs.Close(); - fs.Dispose(); - } - - public async Task DownloadAudio() - { - var encryptedContent = new MemoryStream(); - encryptedContent.SetLength(Audio.FileSize.Value); - var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Audio.FileId, encryptedContent); - - return new InputOnlineFile(encryptedContent, ""); - } - - public async Task DownloadAudio(string path) - { - var file = await Device.Client.TelegramClient.GetFileAsync(Audio.FileId); - var fs = new FileStream(path, FileMode.Create); - await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); - fs.Close(); - fs.Dispose(); - } - - public async Task DownloadPhoto(int index) - { - var photo = Photos[index]; - var encryptedContent = new MemoryStream(); - encryptedContent.SetLength(photo.FileSize.Value); - var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(photo.FileId, encryptedContent); - - return new InputOnlineFile(encryptedContent, ""); - } - - public async Task DownloadPhoto(int index, string path) - { - var photo = Photos[index]; - var file = await Device.Client.TelegramClient.GetFileAsync(photo.FileId); - var fs = new FileStream(path, FileMode.Create); - await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); - fs.Close(); - fs.Dispose(); - } - + UpdateData = update; } -} + + //public Telegram.Bot.Args.MessageEventArgs RawMessageData { get; set; } + + public UpdateResult UpdateData { get; set; } + + + public Contact Contact => Message.Contact; + + public Location Location => Message.Location; + + public Document Document => Message.Document; + + public Audio Audio => Message.Audio; + + public Video Video => Message.Video; + + public PhotoSize[] Photos => Message.Photo; + + + public MessageType Type => Message?.Type ?? MessageType.Unknown; + + public override Message Message => UpdateData?.Message; + + /// + /// Returns the FileId of the first reachable element. + /// + public string FileId => + Document?.FileId ?? + Audio?.FileId ?? + Video?.FileId ?? + Photos.FirstOrDefault()?.FileId; + + + public async Task DownloadDocument() + { + var encryptedContent = new MemoryStream(); + encryptedContent.SetLength(Document.FileSize.Value); + var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, + encryptedContent); + + return new InputOnlineFile(encryptedContent, Document.FileName); + } + + + /// + /// Downloads a file and saves it to the given path. + /// + /// + /// + public async Task DownloadDocument(string path) + { + var file = await Device.Client.TelegramClient.GetFileAsync(Document.FileId); + var fs = new FileStream(path, FileMode.Create); + await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); + fs.Close(); + fs.Dispose(); + } + + /// + /// Downloads the document and returns an byte array. + /// + /// + public async Task DownloadRawDocument() + { + var ms = new MemoryStream(); + await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, ms); + return ms.ToArray(); + } + + /// + /// Downloads a document and returns it as string. (txt,csv,etc) Default encoding ist UTF8. + /// + /// + public async Task DownloadRawTextDocument() + { + return await DownloadRawTextDocument(Encoding.UTF8); + } + + /// + /// Downloads a document and returns it as string. (txt,csv,etc) + /// + /// + public async Task DownloadRawTextDocument(Encoding encoding) + { + var ms = new MemoryStream(); + await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, ms); + + ms.Position = 0; + + var sr = new StreamReader(ms, encoding); + + return sr.ReadToEnd(); + } + + public async Task DownloadVideo() + { + var encryptedContent = new MemoryStream(); + encryptedContent.SetLength(Video.FileSize.Value); + var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Video.FileId, encryptedContent); + + return new InputOnlineFile(encryptedContent, ""); + } + + public async Task DownloadVideo(string path) + { + var file = await Device.Client.TelegramClient.GetFileAsync(Video.FileId); + var fs = new FileStream(path, FileMode.Create); + await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); + fs.Close(); + fs.Dispose(); + } + + public async Task DownloadAudio() + { + var encryptedContent = new MemoryStream(); + encryptedContent.SetLength(Audio.FileSize.Value); + var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Audio.FileId, encryptedContent); + + return new InputOnlineFile(encryptedContent, ""); + } + + public async Task DownloadAudio(string path) + { + var file = await Device.Client.TelegramClient.GetFileAsync(Audio.FileId); + var fs = new FileStream(path, FileMode.Create); + await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); + fs.Close(); + fs.Dispose(); + } + + public async Task DownloadPhoto(int index) + { + var photo = Photos[index]; + var encryptedContent = new MemoryStream(); + encryptedContent.SetLength(photo.FileSize.Value); + var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(photo.FileId, encryptedContent); + + return new InputOnlineFile(encryptedContent, ""); + } + + public async Task DownloadPhoto(int index, string path) + { + var photo = Photos[index]; + var file = await Device.Client.TelegramClient.GetFileAsync(photo.FileId); + var fs = new FileStream(path, FileMode.Create); + await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs); + fs.Close(); + fs.Dispose(); + } +} \ No newline at end of file diff --git a/TelegramBotBase/Base/FormBase.cs b/TelegramBotBase/Base/FormBase.cs index 583eabe..7557348 100644 --- a/TelegramBotBase/Base/FormBase.cs +++ b/TelegramBotBase/Base/FormBase.cs @@ -9,421 +9,442 @@ using TelegramBotBase.Form.Navigation; using TelegramBotBase.Sessions; using static TelegramBotBase.Base.Async; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +/// +/// Base class for forms +/// +public class FormBase : IDisposable { - /// - /// Base class for forms - /// - public class FormBase : IDisposable + private static readonly object EvInit = new(); + + private static readonly object EvOpened = new(); + + private static readonly object EvClosed = new(); + + + public EventHandlerList Events = new(); + + + public FormBase() { + Controls = new List(); + } - public NavigationController NavigationController { get; set; } + public FormBase(MessageClient client) : this() + { + Client = client; + } - public DeviceSession Device { get; set; } + public NavigationController NavigationController { get; set; } - public MessageClient Client { get; set; } + public DeviceSession Device { get; set; } - /// - /// has this formular already been disposed ? - /// - public bool IsDisposed { get; set; } + public MessageClient Client { get; set; } - public List Controls { get; set; } + /// + /// has this formular already been disposed ? + /// + public bool IsDisposed { get; set; } + + public List Controls { get; set; } + + /// + /// Cleanup + /// + public void Dispose() + { + Client = null; + Device = null; + IsDisposed = true; + } - public EventHandlerList Events = new EventHandlerList(); - - - private static readonly object EvInit = new object(); - - private static readonly object EvOpened = new object(); - - private static readonly object EvClosed = new object(); - - - public FormBase() + public async Task OnInit(InitEventArgs e) + { + var handler = Events[EvInit]?.GetInvocationList().Cast>(); + if (handler == null) { - Controls = new List(); + return; } - public FormBase(MessageClient client) : this() + foreach (var h in handler) { - this.Client = client; - } - - - public async Task OnInit(InitEventArgs e) - { - var handler = Events[EvInit]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) - { - await h.InvokeAllAsync(this, e); - } - } - - ///// - ///// Will get called at the initialization (once per context) - ///// - public event AsyncEventHandler Init - { - add => Events.AddHandler(EvInit, value); - remove => Events.RemoveHandler(EvInit, value); - } - - - - public async Task OnOpened(EventArgs e) - { - var handler = Events[EvOpened]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) - { - await h.InvokeAllAsync(this, e); - } - } - - /// - /// Gets invoked if gets navigated to this form - /// - /// - public event AsyncEventHandler Opened - { - add => Events.AddHandler(EvOpened, value); - remove => Events.RemoveHandler(EvOpened, value); - } - - - - public async Task OnClosed(EventArgs e) - { - var handler = Events[EvClosed]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) - { - await h.InvokeAllAsync(this, e); - } - } - - - /// - /// Form has been closed (left) - /// - /// - public event AsyncEventHandler Closed - { - add => Events.AddHandler(EvClosed, value); - remove => Events.RemoveHandler(EvClosed, value); - } - - /// - /// Get invoked when a modal child from has been closed. - /// - /// - /// - public virtual Task ReturnFromModal(ModalDialog modal) - { - return Task.CompletedTask; - } - - - /// - /// Pre to form close, cleanup all controls - /// - /// - public Task CloseControls() - { - foreach (var b in Controls) - { - b.Cleanup().Wait(); - } - - return Task.CompletedTask; - } - - public virtual Task PreLoad(MessageResult message) - { - return Task.CompletedTask; - } - - /// - /// Gets invoked if a message was sent or an action triggered - /// - /// - /// - public virtual async Task LoadControls(MessageResult message) - { - //Looking for the control by id, if not listened, raise event for all - if (message.RawData?.StartsWith("#c") ?? false) - { - var c = Controls.FirstOrDefault(a => a.ControlId == message.RawData.Split('_')[0]); - if (c != null) - { - await c.Load(message); - return; - } - } - - foreach (var b in Controls) - { - if (!b.Enabled) - continue; - - await b.Load(message); - } - } - - /// - /// Gets invoked if the form gets loaded and on every message belongs to this context - /// - /// - /// - public virtual Task Load(MessageResult message) - { - return Task.CompletedTask; - } - - /// - /// Gets invoked, when a messages has been edited. - /// - /// - /// - public virtual Task Edited(MessageResult message) - { - return Task.CompletedTask; - } - - - /// - /// Gets invoked if the user clicked a button. - /// - /// - /// - public virtual async Task ActionControls(MessageResult message) - { - //Looking for the control by id, if not listened, raise event for all - if (message.RawData.StartsWith("#c")) - { - var c = Controls.FirstOrDefault(a => a.ControlId == message.RawData.Split('_')[0]); - if (c != null) - { - await c.Action(message, message.RawData.Split('_')[1]); - return; - } - } - - foreach (var b in Controls) - { - if (!b.Enabled) - continue; - - await b.Action(message); - - if (message.Handled) - return; - } - } - - /// - /// Gets invoked if the user has clicked a button. - /// - /// - /// - public virtual Task Action(MessageResult message) - { - return Task.CompletedTask; - } - - /// - /// Gets invoked if the user has sent some media (Photo, Audio, Video, Contact, Location, Document) - /// - /// - /// - public virtual Task SentData(DataResult message) - { - return Task.CompletedTask; - } - - /// - /// Gets invoked at the end of the cycle to "Render" text, images, buttons, etc... - /// - /// - /// - public virtual async Task RenderControls(MessageResult message) - { - foreach (var b in Controls) - { - if (!b.Enabled) - continue; - - await b.Render(message); - } - } - - /// - /// Gets invoked at the end of the cycle to "Render" text, images, buttons, etc... - /// - /// - /// - public virtual Task Render(MessageResult message) - { - return Task.CompletedTask; - } - - - - /// - /// Navigates to a new form - /// - /// - /// - public virtual async Task NavigateTo(FormBase newForm, params object[] args) - { - var ds = Device; - if (ds == null) - return; - - ds.FormSwitched = true; - - ds.PreviousForm = ds.ActiveForm; - - ds.ActiveForm = newForm; - newForm.Client = Client; - newForm.Device = ds; - - //Notify prior to close - foreach (var b in Controls) - { - if (!b.Enabled) - continue; - - await b.Hidden(true); - } - - CloseControls().Wait(); - - await OnClosed(EventArgs.Empty); - - await newForm.OnInit(new InitEventArgs(args)); - - await newForm.OnOpened(EventArgs.Empty); - } - - /// - /// Opens this form modal, but don't closes the original ones - /// - /// - /// - public virtual async Task OpenModal(ModalDialog newForm, params object[] args) - { - var ds = Device; - if (ds == null) - return; - - var parentForm = this; - - ds.FormSwitched = true; - - ds.PreviousForm = ds.ActiveForm; - - ds.ActiveForm = newForm; - newForm.Client = parentForm.Client; - newForm.Device = ds; - newForm.ParentForm = parentForm; - - newForm.Closed += async (s, en) => - { - await CloseModal(newForm, parentForm); - }; - - foreach (var b in Controls) - { - if (!b.Enabled) - continue; - - await b.Hidden(false); - } - - await newForm.OnInit(new InitEventArgs(args)); - - await newForm.OnOpened(EventArgs.Empty); - } - - public Task CloseModal(ModalDialog modalForm, FormBase oldForm) - { - var ds = Device; - if (ds == null) - return Task.CompletedTask; - - if (modalForm == null) - throw new Exception("No modal form"); - - ds.FormSwitched = true; - - ds.PreviousForm = ds.ActiveForm; - - ds.ActiveForm = oldForm; - return Task.CompletedTask; - } - - /// - /// Adds a control to the formular and sets its ID and Device. - /// - /// - public void AddControl(ControlBase control) - { - //Duplicate check - if (Controls.Contains(control)) - throw new ArgumentException("Control has been already added."); - - control.Id = Controls.Count + 1; - control.Device = Device; - Controls.Add(control); - - control.Init(); - } - - /// - /// Removes control from the formular and runs a cleanup on it. - /// - /// - public void RemoveControl(ControlBase control) - { - if (!Controls.Contains(control)) - return; - - control.Cleanup().Wait(); - - Controls.Remove(control); - } - - /// - /// Removes all controls. - /// - public void RemoveAllControls() - { - foreach(var c in Controls) - { - c.Cleanup().Wait(); - - Controls.Remove(c); - } - } - - /// - /// Cleanup - /// - public void Dispose() - { - Client = null; - Device = null; - IsDisposed = true; + await h.InvokeAllAsync(this, e); } } -} + + ///// + ///// Will get called at the initialization (once per context) + ///// + public event AsyncEventHandler Init + { + add => Events.AddHandler(EvInit, value); + remove => Events.RemoveHandler(EvInit, value); + } + + + public async Task OnOpened(EventArgs e) + { + var handler = Events[EvOpened]?.GetInvocationList().Cast>(); + if (handler == null) + { + return; + } + + foreach (var h in handler) + { + await h.InvokeAllAsync(this, e); + } + } + + /// + /// Gets invoked if gets navigated to this form + /// + /// + public event AsyncEventHandler Opened + { + add => Events.AddHandler(EvOpened, value); + remove => Events.RemoveHandler(EvOpened, value); + } + + + public async Task OnClosed(EventArgs e) + { + var handler = Events[EvClosed]?.GetInvocationList().Cast>(); + if (handler == null) + { + return; + } + + foreach (var h in handler) + { + await h.InvokeAllAsync(this, e); + } + } + + + /// + /// Form has been closed (left) + /// + /// + public event AsyncEventHandler Closed + { + add => Events.AddHandler(EvClosed, value); + remove => Events.RemoveHandler(EvClosed, value); + } + + /// + /// Get invoked when a modal child from has been closed. + /// + /// + /// + public virtual Task ReturnFromModal(ModalDialog modal) + { + return Task.CompletedTask; + } + + + /// + /// Pre to form close, cleanup all controls + /// + /// + public Task CloseControls() + { + foreach (var b in Controls) + { + b.Cleanup().Wait(); + } + + return Task.CompletedTask; + } + + public virtual Task PreLoad(MessageResult message) + { + return Task.CompletedTask; + } + + /// + /// Gets invoked if a message was sent or an action triggered + /// + /// + /// + public virtual async Task LoadControls(MessageResult message) + { + //Looking for the control by id, if not listened, raise event for all + if (message.RawData?.StartsWith("#c") ?? false) + { + var c = Controls.FirstOrDefault(a => a.ControlId == message.RawData.Split('_')[0]); + if (c != null) + { + await c.Load(message); + return; + } + } + + foreach (var b in Controls) + { + if (!b.Enabled) + { + continue; + } + + await b.Load(message); + } + } + + /// + /// Gets invoked if the form gets loaded and on every message belongs to this context + /// + /// + /// + public virtual Task Load(MessageResult message) + { + return Task.CompletedTask; + } + + /// + /// Gets invoked, when a messages has been edited. + /// + /// + /// + public virtual Task Edited(MessageResult message) + { + return Task.CompletedTask; + } + + + /// + /// Gets invoked if the user clicked a button. + /// + /// + /// + public virtual async Task ActionControls(MessageResult message) + { + //Looking for the control by id, if not listened, raise event for all + if (message.RawData.StartsWith("#c")) + { + var c = Controls.FirstOrDefault(a => a.ControlId == message.RawData.Split('_')[0]); + if (c != null) + { + await c.Action(message, message.RawData.Split('_')[1]); + return; + } + } + + foreach (var b in Controls) + { + if (!b.Enabled) + { + continue; + } + + await b.Action(message); + + if (message.Handled) + { + return; + } + } + } + + /// + /// Gets invoked if the user has clicked a button. + /// + /// + /// + public virtual Task Action(MessageResult message) + { + return Task.CompletedTask; + } + + /// + /// Gets invoked if the user has sent some media (Photo, Audio, Video, Contact, Location, Document) + /// + /// + /// + public virtual Task SentData(DataResult message) + { + return Task.CompletedTask; + } + + /// + /// Gets invoked at the end of the cycle to "Render" text, images, buttons, etc... + /// + /// + /// + public virtual async Task RenderControls(MessageResult message) + { + foreach (var b in Controls) + { + if (!b.Enabled) + { + continue; + } + + await b.Render(message); + } + } + + /// + /// Gets invoked at the end of the cycle to "Render" text, images, buttons, etc... + /// + /// + /// + public virtual Task Render(MessageResult message) + { + return Task.CompletedTask; + } + + + /// + /// Navigates to a new form + /// + /// + /// + public virtual async Task NavigateTo(FormBase newForm, params object[] args) + { + var ds = Device; + if (ds == null) + { + return; + } + + ds.FormSwitched = true; + + ds.PreviousForm = ds.ActiveForm; + + ds.ActiveForm = newForm; + newForm.Client = Client; + newForm.Device = ds; + + //Notify prior to close + foreach (var b in Controls) + { + if (!b.Enabled) + { + continue; + } + + await b.Hidden(true); + } + + CloseControls().Wait(); + + await OnClosed(EventArgs.Empty); + + await newForm.OnInit(new InitEventArgs(args)); + + await newForm.OnOpened(EventArgs.Empty); + } + + /// + /// Opens this form modal, but don't closes the original ones + /// + /// + /// + public virtual async Task OpenModal(ModalDialog newForm, params object[] args) + { + var ds = Device; + if (ds == null) + { + return; + } + + var parentForm = this; + + ds.FormSwitched = true; + + ds.PreviousForm = ds.ActiveForm; + + ds.ActiveForm = newForm; + newForm.Client = parentForm.Client; + newForm.Device = ds; + newForm.ParentForm = parentForm; + + newForm.Closed += async (s, en) => { await CloseModal(newForm, parentForm); }; + + foreach (var b in Controls) + { + if (!b.Enabled) + { + continue; + } + + await b.Hidden(false); + } + + await newForm.OnInit(new InitEventArgs(args)); + + await newForm.OnOpened(EventArgs.Empty); + } + + public Task CloseModal(ModalDialog modalForm, FormBase oldForm) + { + var ds = Device; + if (ds == null) + { + return Task.CompletedTask; + } + + if (modalForm == null) + { + throw new Exception("No modal form"); + } + + ds.FormSwitched = true; + + ds.PreviousForm = ds.ActiveForm; + + ds.ActiveForm = oldForm; + return Task.CompletedTask; + } + + /// + /// Adds a control to the formular and sets its ID and Device. + /// + /// + public void AddControl(ControlBase control) + { + //Duplicate check + if (Controls.Contains(control)) + { + throw new ArgumentException("Control has been already added."); + } + + control.Id = Controls.Count + 1; + control.Device = Device; + Controls.Add(control); + + control.Init(); + } + + /// + /// Removes control from the formular and runs a cleanup on it. + /// + /// + public void RemoveControl(ControlBase control) + { + if (!Controls.Contains(control)) + { + return; + } + + control.Cleanup().Wait(); + + Controls.Remove(control); + } + + /// + /// Removes all controls. + /// + public void RemoveAllControls() + { + foreach (var c in Controls) + { + c.Cleanup().Wait(); + + Controls.Remove(c); + } + } +} \ No newline at end of file diff --git a/TelegramBotBase/Base/MessageClient.cs b/TelegramBotBase/Base/MessageClient.cs index 4813d86..a47ea16 100644 --- a/TelegramBotBase/Base/MessageClient.cs +++ b/TelegramBotBase/Base/MessageClient.cs @@ -10,193 +10,186 @@ using Telegram.Bot.Exceptions; using Telegram.Bot.Extensions.Polling; using Telegram.Bot.Types; -namespace TelegramBotBase.Base +namespace TelegramBotBase.Base; + +/// +/// Base class for message handling +/// +public class MessageClient { - /// - /// Base class for message handling - /// - public class MessageClient + private static readonly object EvOnMessageLoop = new(); + + private static object __evOnMessage = new(); + + private static object __evOnMessageEdit = new(); + + private static object __evCallbackQuery = new(); + + private CancellationTokenSource _cancellationTokenSource; + + + public MessageClient(string apiKey) { + ApiKey = apiKey; + TelegramClient = new TelegramBotClient(apiKey); - - public string ApiKey { get; set; } - - public ITelegramBotClient TelegramClient { get; set; } - - private EventHandlerList Events { get; set; } = new EventHandlerList(); - - private static readonly object EvOnMessageLoop = new object(); - - private static object __evOnMessage = new object(); - - private static object __evOnMessageEdit = new object(); - - private static object __evCallbackQuery = new object(); - - private CancellationTokenSource _cancellationTokenSource; - - - public MessageClient(string apiKey) - { - this.ApiKey = apiKey; - TelegramClient = new TelegramBotClient(apiKey); - - Prepare(); - } - - public MessageClient(string apiKey, HttpClient proxy) - { - this.ApiKey = apiKey; - TelegramClient = new TelegramBotClient(apiKey, proxy); - - - Prepare(); - } - - - - public MessageClient(string apiKey, Uri proxyUrl, NetworkCredential credential = null) - { - this.ApiKey = apiKey; - - var proxy = new WebProxy(proxyUrl) - { - Credentials = credential - }; - - var httpClient = new HttpClient( - new HttpClientHandler { Proxy = proxy, UseProxy = true } - ); - - TelegramClient = new TelegramBotClient(apiKey, httpClient); - - Prepare(); - } - - /// - /// Initializes the client with a proxy - /// - /// - /// i.e. 127.0.0.1 - /// i.e. 10000 - public MessageClient(string apiKey, string proxyHost, int proxyPort) - { - this.ApiKey = apiKey; - - var proxy = new WebProxy(proxyHost, proxyPort); - - var httpClient = new HttpClient( - new HttpClientHandler { Proxy = proxy, UseProxy = true } - ); - - TelegramClient = new TelegramBotClient(apiKey, httpClient); - - Prepare(); - } - - - - public MessageClient(string apiKey, TelegramBotClient client) - { - this.ApiKey = apiKey; - TelegramClient = client; - - Prepare(); - } - - - public void Prepare() - { - TelegramClient.Timeout = new TimeSpan(0, 0, 30); - - } - - - - public void StartReceiving() - { - _cancellationTokenSource = new CancellationTokenSource(); - - var receiverOptions = new ReceiverOptions(); - - TelegramClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, receiverOptions, _cancellationTokenSource.Token); - } - - public void StopReceiving() - { - _cancellationTokenSource.Cancel(); - } - - - public Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) - { - OnMessageLoop(new UpdateResult(update, null)); - - return Task.CompletedTask; - } - - public Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken) - { - if (exception is ApiRequestException exApi) - { - Console.WriteLine($"Telegram API Error:\n[{exApi.ErrorCode}]\n{exApi.Message}"); - } - else - { - Console.WriteLine(exception.ToString()); - } - return Task.CompletedTask; - } - - - /// - /// This will return the current list of bot commands. - /// - /// - public async Task GetBotCommands(BotCommandScope scope = null, string languageCode = null) - { - return await TelegramClient.GetMyCommandsAsync(scope, languageCode); - } - - - /// - /// This will set your bot commands to the given list. - /// - /// - /// - public async Task SetBotCommands(List botcommands, BotCommandScope scope = null, string languageCode = null) - { - await TelegramClient.SetMyCommandsAsync(botcommands, scope, languageCode); - } - - /// - /// This will delete the current list of bot commands. - /// - /// - public async Task DeleteBotCommands(BotCommandScope scope = null, string languageCode = null) - { - await TelegramClient.DeleteMyCommandsAsync(scope, languageCode); - } - - - #region "Events" - - - - public event Async.AsyncEventHandler MessageLoop - { - add => Events.AddHandler(EvOnMessageLoop, value); - remove => Events.RemoveHandler(EvOnMessageLoop, value); - } - - public void OnMessageLoop(UpdateResult update) - { - (Events[EvOnMessageLoop] as Async.AsyncEventHandler)?.Invoke(this, update); - } - - - #endregion - - + Prepare(); } -} + + public MessageClient(string apiKey, HttpClient proxy) + { + ApiKey = apiKey; + TelegramClient = new TelegramBotClient(apiKey, proxy); + + + Prepare(); + } + + + public MessageClient(string apiKey, Uri proxyUrl, NetworkCredential credential = null) + { + ApiKey = apiKey; + + var proxy = new WebProxy(proxyUrl) + { + Credentials = credential + }; + + var httpClient = new HttpClient( + new HttpClientHandler { Proxy = proxy, UseProxy = true } + ); + + TelegramClient = new TelegramBotClient(apiKey, httpClient); + + Prepare(); + } + + /// + /// Initializes the client with a proxy + /// + /// + /// i.e. 127.0.0.1 + /// i.e. 10000 + public MessageClient(string apiKey, string proxyHost, int proxyPort) + { + ApiKey = apiKey; + + var proxy = new WebProxy(proxyHost, proxyPort); + + var httpClient = new HttpClient( + new HttpClientHandler { Proxy = proxy, UseProxy = true } + ); + + TelegramClient = new TelegramBotClient(apiKey, httpClient); + + Prepare(); + } + + + public MessageClient(string apiKey, TelegramBotClient client) + { + ApiKey = apiKey; + TelegramClient = client; + + Prepare(); + } + + + public string ApiKey { get; set; } + + public ITelegramBotClient TelegramClient { get; set; } + + private EventHandlerList Events { get; } = new(); + + + public void Prepare() + { + TelegramClient.Timeout = new TimeSpan(0, 0, 30); + } + + + public void StartReceiving() + { + _cancellationTokenSource = new CancellationTokenSource(); + + var receiverOptions = new ReceiverOptions(); + + TelegramClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, receiverOptions, + _cancellationTokenSource.Token); + } + + public void StopReceiving() + { + _cancellationTokenSource.Cancel(); + } + + + public Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) + { + OnMessageLoop(new UpdateResult(update, null)); + + return Task.CompletedTask; + } + + public Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, + CancellationToken cancellationToken) + { + if (exception is ApiRequestException exApi) + { + Console.WriteLine($"Telegram API Error:\n[{exApi.ErrorCode}]\n{exApi.Message}"); + } + else + { + Console.WriteLine(exception.ToString()); + } + + return Task.CompletedTask; + } + + + /// + /// This will return the current list of bot commands. + /// + /// + public async Task GetBotCommands(BotCommandScope scope = null, string languageCode = null) + { + return await TelegramClient.GetMyCommandsAsync(scope, languageCode); + } + + + /// + /// This will set your bot commands to the given list. + /// + /// + /// + public async Task SetBotCommands(List botcommands, BotCommandScope scope = null, + string languageCode = null) + { + await TelegramClient.SetMyCommandsAsync(botcommands, scope, languageCode); + } + + /// + /// This will delete the current list of bot commands. + /// + /// + public async Task DeleteBotCommands(BotCommandScope scope = null, string languageCode = null) + { + await TelegramClient.DeleteMyCommandsAsync(scope, languageCode); + } + + + #region "Events" + + public event Async.AsyncEventHandler MessageLoop + { + add => Events.AddHandler(EvOnMessageLoop, value); + remove => Events.RemoveHandler(EvOnMessageLoop, value); + } + + public void OnMessageLoop(UpdateResult update) + { + (Events[EvOnMessageLoop] as Async.AsyncEventHandler)?.Invoke(this, update); + } + + #endregion +} \ No newline at end of file diff --git a/TelegramBotBase/Base/MessageResult.cs b/TelegramBotBase/Base/MessageResult.cs index 7d39fe7..531edf4 100644 --- a/TelegramBotBase/Base/MessageResult.cs +++ b/TelegramBotBase/Base/MessageResult.cs @@ -5,136 +5,134 @@ using Newtonsoft.Json; using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; -namespace TelegramBotBase.Base +namespace TelegramBotBase.Base; + +public class MessageResult : ResultBase { - public class MessageResult : ResultBase + internal MessageResult() { + } - public Update UpdateData { get; set; } + public MessageResult(Update update) + { + UpdateData = update; + } - /// - /// Returns the Device/ChatId - /// - public override long DeviceId => - UpdateData?.Message?.Chat?.Id - ?? UpdateData?.EditedMessage?.Chat.Id - ?? UpdateData?.CallbackQuery.Message?.Chat.Id - ?? Device?.DeviceId - ?? 0; + public Update UpdateData { get; set; } - /// - /// The message id - /// - public new int MessageId => - UpdateData?.Message?.MessageId - ?? Message?.MessageId - ?? UpdateData?.CallbackQuery?.Message?.MessageId - ?? 0; + /// + /// Returns the Device/ChatId + /// + public override long DeviceId => + UpdateData?.Message?.Chat?.Id + ?? UpdateData?.EditedMessage?.Chat.Id + ?? UpdateData?.CallbackQuery.Message?.Chat.Id + ?? Device?.DeviceId + ?? 0; - public string Command => UpdateData?.Message?.Text ?? ""; + /// + /// The message id + /// + public new int MessageId => + UpdateData?.Message?.MessageId + ?? Message?.MessageId + ?? UpdateData?.CallbackQuery?.Message?.MessageId + ?? 0; - public string MessageText => UpdateData?.Message?.Text ?? ""; + public string Command => UpdateData?.Message?.Text ?? ""; - public MessageType MessageType => Message?.Type ?? MessageType.Unknown; + public string MessageText => UpdateData?.Message?.Text ?? ""; - /// - /// Is this an action ? (i.e. button click) - /// - public bool IsAction => (UpdateData.CallbackQuery != null); + public MessageType MessageType => Message?.Type ?? MessageType.Unknown; - /// - /// Is this a command ? Starts with a slash '/' and a command - /// - public bool IsBotCommand => (MessageText.StartsWith("/")); + /// + /// Is this an action ? (i.e. button click) + /// + public bool IsAction => UpdateData.CallbackQuery != null; - /// - /// Returns a List of all parameters which has been sent with the command itself (i.e. /start 123 456 789 => 123,456,789) - /// - public List BotCommandParameters + /// + /// Is this a command ? Starts with a slash '/' and a command + /// + public bool IsBotCommand => MessageText.StartsWith("/"); + + /// + /// Returns a List of all parameters which has been sent with the command itself (i.e. /start 123 456 789 => + /// 123,456,789) + /// + public List BotCommandParameters + { + get { - get + if (!IsBotCommand) { - if (!IsBotCommand) - return new List(); - - //Split by empty space and skip first entry (command itself), return as list - return MessageText.Split(' ').Skip(1).ToList(); - } - } - - /// - /// Returns just the command (i.e. /start 1 2 3 => /start) - /// - public string BotCommand - { - get - { - if (!IsBotCommand) - return null; - - return MessageText.Split(' ')[0]; - } - } - - /// - /// Returns if this message will be used on the first form or not. - /// - public bool IsFirstHandler { get; set; } = true; - - public bool Handled { get; set; } = false; - - public string RawData => UpdateData?.CallbackQuery?.Data; - - public T GetData() - where T : class - { - T cd = null; - try - { - cd = JsonConvert.DeserializeObject(RawData); - - return cd; - } - catch - { - + return new List(); } - return null; + //Split by empty space and skip first entry (command itself), return as list + return MessageText.Split(' ').Skip(1).ToList(); } + } - /// - /// Confirm incomming action (i.e. Button click) - /// - /// - /// - public async Task ConfirmAction(string message = "", bool showAlert = false, string urlToOpen = null) + /// + /// Returns just the command (i.e. /start 1 2 3 => /start) + /// + public string BotCommand + { + get { - await Device.ConfirmAction(UpdateData.CallbackQuery.Id, message, showAlert, urlToOpen); - } - - public override async Task DeleteMessage() - { - try + if (!IsBotCommand) { - await base.DeleteMessage(MessageId); + return null; } - catch - { - } + return MessageText.Split(' ')[0]; } + } - internal MessageResult() + /// + /// Returns if this message will be used on the first form or not. + /// + public bool IsFirstHandler { get; set; } = true; + + public bool Handled { get; set; } = false; + + public string RawData => UpdateData?.CallbackQuery?.Data; + + public T GetData() + where T : class + { + T cd = null; + try { + cd = JsonConvert.DeserializeObject(RawData); + return cd; } - - public MessageResult(Update update) + catch { - UpdateData = update; - } + return null; + } + + /// + /// Confirm incomming action (i.e. Button click) + /// + /// + /// + public async Task ConfirmAction(string message = "", bool showAlert = false, string urlToOpen = null) + { + await Device.ConfirmAction(UpdateData.CallbackQuery.Id, message, showAlert, urlToOpen); + } + + public override async Task DeleteMessage() + { + try + { + await base.DeleteMessage(MessageId); + } + catch + { + } } } diff --git a/TelegramBotBase/Base/ResultBase.cs b/TelegramBotBase/Base/ResultBase.cs index 59a130f..2845237 100644 --- a/TelegramBotBase/Base/ResultBase.cs +++ b/TelegramBotBase/Base/ResultBase.cs @@ -4,48 +4,42 @@ using Telegram.Bot; using Telegram.Bot.Types; using TelegramBotBase.Sessions; -namespace TelegramBotBase.Base +namespace TelegramBotBase.Base; + +public class ResultBase : EventArgs { - public class ResultBase : EventArgs + public DeviceSession Device { get; set; } + + public virtual long DeviceId { get; set; } + + public int MessageId => Message.MessageId; + + public virtual Message Message { get; set; } + + /// + /// Deletes the current message + /// + /// + /// + public virtual async Task DeleteMessage() { - public DeviceSession Device - { - get; - set; - } - - public virtual long DeviceId { get; set; } - - public int MessageId => Message.MessageId; - - public virtual Message Message { get; set; } - - /// - /// Deletes the current message - /// - /// - /// - public virtual async Task DeleteMessage() - { - await DeleteMessage(MessageId); - } - - /// - ///Deletes the current message or the given one. - /// - /// - /// - public virtual async Task DeleteMessage(int messageId = -1) - { - try - { - await Device.Client.TelegramClient.DeleteMessageAsync(DeviceId, (messageId == -1 ? MessageId : messageId)); - } - catch - { - - } - } - + await DeleteMessage(MessageId); } -} + + /// + /// Deletes the current message or the given one. + /// + /// + /// + public virtual async Task DeleteMessage(int messageId = -1) + { + try + { + await Device.Client.TelegramClient.DeleteMessageAsync(DeviceId, + messageId == -1 ? MessageId : messageId); + } + catch + { + } + } +} \ No newline at end of file diff --git a/TelegramBotBase/Base/StateContainer.cs b/TelegramBotBase/Base/StateContainer.cs index 7e74cc6..de6b766 100644 --- a/TelegramBotBase/Base/StateContainer.cs +++ b/TelegramBotBase/Base/StateContainer.cs @@ -1,32 +1,24 @@ using System.Collections.Generic; using System.Linq; -namespace TelegramBotBase.Base +namespace TelegramBotBase.Base; + +public class StateContainer { - public class StateContainer + public StateContainer() { - public List States { get; set; } - - public List ChatIds - { - get - { - return States.Where(a => a.DeviceId > 0).Select(a => a.DeviceId).ToList(); - } - } - - public List GroupIds - { - get - { - return States.Where(a => a.DeviceId < 0).Select(a => a.DeviceId).ToList(); - } - } - - public StateContainer() - { - States = new List(); - } - + States = new List(); } -} + + public List States { get; set; } + + public List ChatIds + { + get { return States.Where(a => a.DeviceId > 0).Select(a => a.DeviceId).ToList(); } + } + + public List GroupIds + { + get { return States.Where(a => a.DeviceId < 0).Select(a => a.DeviceId).ToList(); } + } +} \ No newline at end of file diff --git a/TelegramBotBase/Base/StateEntry.cs b/TelegramBotBase/Base/StateEntry.cs index 13e272f..8513804 100644 --- a/TelegramBotBase/Base/StateEntry.cs +++ b/TelegramBotBase/Base/StateEntry.cs @@ -1,41 +1,38 @@ using System.Collections.Generic; using System.Diagnostics; -namespace TelegramBotBase.Base +namespace TelegramBotBase.Base; + +[DebuggerDisplay("Device: {DeviceId}, {FormUri}")] +public class StateEntry { - - [DebuggerDisplay("Device: {DeviceId}, {FormUri}")] - public class StateEntry + public StateEntry() { - /// - /// Contains the DeviceId of the entry. - /// - public long DeviceId { get; set; } - - /// - /// Contains the Username (on privat chats) or Group title on groups/channels. - /// - public string ChatTitle { get; set; } - - /// - /// Contains additional values to save. - /// - public Dictionary Values { get; set; } - - /// - /// Contains the full qualified namespace of the form to used for reload it via reflection. - /// - public string FormUri {get;set;} - - /// - /// Contains the assembly, where to find that form. - /// - public string QualifiedName { get; set; } - - public StateEntry() - { - Values = new Dictionary(); - } - + Values = new Dictionary(); } -} + + /// + /// Contains the DeviceId of the entry. + /// + public long DeviceId { get; set; } + + /// + /// Contains the Username (on privat chats) or Group title on groups/channels. + /// + public string ChatTitle { get; set; } + + /// + /// Contains additional values to save. + /// + public Dictionary Values { get; set; } + + /// + /// Contains the full qualified namespace of the form to used for reload it via reflection. + /// + public string FormUri { get; set; } + + /// + /// Contains the assembly, where to find that form. + /// + public string QualifiedName { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Base/UpdateResult.cs b/TelegramBotBase/Base/UpdateResult.cs index 4d8e430..82d46b3 100644 --- a/TelegramBotBase/Base/UpdateResult.cs +++ b/TelegramBotBase/Base/UpdateResult.cs @@ -1,35 +1,31 @@ using Telegram.Bot.Types; using TelegramBotBase.Sessions; -namespace TelegramBotBase.Base +namespace TelegramBotBase.Base; + +public class UpdateResult : ResultBase { - public class UpdateResult : ResultBase + public UpdateResult(Update rawData, DeviceSession device) { - public UpdateResult(Update rawData, DeviceSession device) - { - RawData = rawData; - Device = device; - - - } - - /// - /// Returns the Device/ChatId - /// - public override long DeviceId => - RawData?.Message?.Chat?.Id - ?? RawData?.CallbackQuery?.Message?.Chat?.Id - ?? Device?.DeviceId - ?? 0; - - public Update RawData { get; set; } - - public override Message Message => - RawData?.Message - ?? RawData?.EditedMessage - ?? RawData?.ChannelPost - ?? RawData?.EditedChannelPost - ?? RawData?.CallbackQuery?.Message; + RawData = rawData; + Device = device; } -} + /// + /// Returns the Device/ChatId + /// + public override long DeviceId => + RawData?.Message?.Chat?.Id + ?? RawData?.CallbackQuery?.Message?.Chat?.Id + ?? Device?.DeviceId + ?? 0; + + public Update RawData { get; set; } + + public override Message Message => + RawData?.Message + ?? RawData?.EditedMessage + ?? RawData?.ChannelPost + ?? RawData?.EditedChannelPost + ?? RawData?.CallbackQuery?.Message; +} \ No newline at end of file diff --git a/TelegramBotBase/BotBase.cs b/TelegramBotBase/BotBase.cs index 45b8a92..bac92e3 100644 --- a/TelegramBotBase/BotBase.cs +++ b/TelegramBotBase/BotBase.cs @@ -2,413 +2,409 @@ using System.Collections.Generic; using System.ComponentModel; using System.Linq; -using System.Text; -using System.Threading; using System.Threading.Tasks; using Telegram.Bot; -using Telegram.Bot.Exceptions; using Telegram.Bot.Types; -using Telegram.Bot.Types.Enums; using TelegramBotBase.Args; -using TelegramBotBase.Attributes; using TelegramBotBase.Base; using TelegramBotBase.Enums; -using TelegramBotBase.MessageLoops; -using TelegramBotBase.Form; using TelegramBotBase.Interfaces; using TelegramBotBase.Sessions; +using Console = TelegramBotBase.Tools.Console; -namespace TelegramBotBase +namespace TelegramBotBase; + +/// +/// Bot base class for full Device/Context and Messagehandling +/// +/// +public class BotBase { - /// - /// Bot base class for full Device/Context and Messagehandling - /// - /// - public class BotBase + public BotBase() { - public MessageClient Client { get; set; } + SystemSettings = new Dictionary(); - /// - /// Your TelegramBot APIKey - /// - public string ApiKey { get; set; } = ""; + SetSetting(ESettings.MaxNumberOfRetries, 5); + SetSetting(ESettings.NavigationMaximum, 10); + SetSetting(ESettings.LogAllMessages, false); + SetSetting(ESettings.SkipAllMessages, false); + SetSetting(ESettings.SaveSessionsOnConsoleExit, false); - /// - /// List of all running/active sessions - /// - public SessionBase Sessions { get; set; } + BotCommandScopes = new Dictionary>(); - /// - /// Contains System commands which will be available at everytime and didnt get passed to forms, i.e. /start - /// - public Dictionary> BotCommandScopes { get; set; } = new Dictionary>(); - - - #region "Events" - - private readonly EventHandlerList _events = new EventHandlerList(); - - private static readonly object EvSessionBegins = new object(); - - private static readonly object EvMessage = new object(); - - private static object __evSystemCall = new object(); - - public delegate Task BotCommandEventHandler(object sender, BotCommandEventArgs e); - - private static readonly object EvException = new object(); - - private static readonly object EvUnhandledCall = new object(); - - #endregion - - - /// - /// Enable the SessionState (you need to implement on call forms the IStateForm interface) - /// - public IStateMachine StateMachine { get; set; } - - /// - /// Offers functionality to manage the creation process of the start form. - /// - public IStartFormFactory StartFormFactory { get; set; } - - /// - /// Contains the message loop factory, which cares about "message-management." - /// - public IMessageLoopFactory MessageLoopFactory { get; set; } - - /// - /// All internal used settings. - /// - public Dictionary SystemSettings { get; private set; } - - public BotBase() + Sessions = new SessionBase { - SystemSettings = new Dictionary(); - - SetSetting(ESettings.MaxNumberOfRetries, 5); - SetSetting(ESettings.NavigationMaximum, 10); - SetSetting(ESettings.LogAllMessages, false); - SetSetting(ESettings.SkipAllMessages, false); - SetSetting(ESettings.SaveSessionsOnConsoleExit, false); - - BotCommandScopes = new Dictionary>(); - - Sessions = new SessionBase - { - BotBase = this - }; - } - - - - /// - /// Start your Bot - /// - public void Start() - { - if (Client == null) - return; - - Client.MessageLoop += Client_MessageLoop; - - - if (StateMachine != null) - { - Sessions.LoadSessionStates(StateMachine); - } - - //Enable auto session saving - if (GetSetting(ESettings.SaveSessionsOnConsoleExit, false)) - { - Tools.Console.SetHandler(() => - { - Sessions.SaveSessionStates(); - }); - } - - DeviceSession.MaxNumberOfRetries = GetSetting(ESettings.MaxNumberOfRetries, 5); - - Client.StartReceiving(); - } - - - private async Task Client_MessageLoop(object sender, UpdateResult e) - { - var ds = Sessions.GetSession(e.DeviceId); - if (ds == null) - { - ds = Sessions.StartSession(e.DeviceId).GetAwaiter().GetResult(); - e.Device = ds; - ds.LastMessage = e.RawData.Message; - - OnSessionBegins(new SessionBeginEventArgs(e.DeviceId, ds)); - } - - var mr = new MessageResult(e.RawData); - - var i = 0; - - //Should formulars get navigated (allow maximum of 10, to dont get loops) - do - { - i++; - - //Reset navigation - ds.FormSwitched = false; - - await MessageLoopFactory.MessageLoop(this, ds, e, mr); - - mr.IsFirstHandler = false; - - } while (ds.FormSwitched && i < GetSetting(ESettings.NavigationMaximum, 10)); - } - - - /// - /// Stop your Bot - /// - public void Stop() - { - if (Client == null) - return; - - Client.MessageLoop -= Client_MessageLoop; - - - Client.StopReceiving(); - - Sessions.SaveSessionStates(); - } - - /// - /// Send a message to all active Sessions. - /// - /// - /// - public async Task SentToAll(string message) - { - if (Client == null) - return; - - foreach (var s in Sessions.SessionList) - { - await Client.TelegramClient.SendTextMessageAsync(s.Key, message); - } - } - - - - /// - /// This will invoke the full message loop for the device even when no "userevent" like message or action has been raised. - /// - /// Contains the device/chat id of the device to update. - public async Task InvokeMessageLoop(long deviceId) - { - var mr = new MessageResult - { - UpdateData = new Update() - { - Message = new Message() - } - }; - - await InvokeMessageLoop(deviceId, mr); - } - - /// - /// This will invoke the full message loop for the device even when no "userevent" like message or action has been raised. - /// - /// Contains the device/chat id of the device to update. - /// - public async Task InvokeMessageLoop(long deviceId, MessageResult e) - { - try - { - var ds = Sessions.GetSession(deviceId); - e.Device = ds; - - await MessageLoopFactory.MessageLoop(this, ds, new UpdateResult(e.UpdateData, ds), e); - //await Client_Loop(this, e); - } - catch (Exception ex) - { - var ds = Sessions.GetSession(deviceId); - OnException(new SystemExceptionEventArgs(e.Message.Text, deviceId, ds, ex)); - } - } - - - /// - /// Will get invoke on an unhandled call. - /// - /// - /// - public void MessageLoopFactory_UnhandledCall(object sender, UnhandledCallEventArgs e) - { - OnUnhandledCall(e); - } - - /// - /// This method will update all local created bot commands to the botfather. - /// - public async Task UploadBotCommands() - { - foreach (var bs in BotCommandScopes) - { - if(bs.Value !=null) - { - await Client.SetBotCommands(bs.Value, bs.Key); - } - else - { - await Client.DeleteBotCommands(bs.Key); - } - - } - } - - /// - /// Searching if parameter is a known command in all configured BotCommandScopes. - /// - /// - /// - public bool IsKnownBotCommand(string command) - { - foreach (var scope in BotCommandScopes) - { - if (scope.Value.Any(a => "/" + a.Command == command)) - return true; - } - - return false; - } - - /// - /// Could set a variety of settings to improve the bot handling. - /// - /// - /// - public void SetSetting(ESettings set, uint value) - { - SystemSettings[set] = value; - } - - /// - /// Could set a variety of settings to improve the bot handling. - /// - /// - /// - public void SetSetting(ESettings set, bool value) - { - SystemSettings[set] = (value ? 1u : 0u); - } - - /// - /// Could get the current value of a setting - /// - /// - /// - /// - public uint GetSetting(ESettings set, uint defaultValue) - { - if (!SystemSettings.ContainsKey(set)) - return defaultValue; - - return SystemSettings[set]; - } - - /// - /// Could get the current value of a setting - /// - /// - /// - /// - public bool GetSetting(ESettings set, bool defaultValue) - { - if (!SystemSettings.ContainsKey(set)) - return defaultValue; - - return SystemSettings[set] == 0u ? false : true; - } - - #region "Events" - - /// - /// Will be called if a session/context gets started - /// - - public event EventHandler SessionBegins - { - add => _events.AddHandler(EvSessionBegins, value); - remove => _events.RemoveHandler(EvSessionBegins, value); - } - - public void OnSessionBegins(SessionBeginEventArgs e) - { - (_events[EvSessionBegins] as EventHandler)?.Invoke(this, e); - - } - - /// - /// Will be called on incomming message - /// - public event EventHandler Message - { - add => _events.AddHandler(EvMessage, value); - remove => _events.RemoveHandler(EvMessage, value); - } - - public void OnMessage(MessageIncomeEventArgs e) - { - (_events[EvMessage] as EventHandler)?.Invoke(this, e); - - } - - /// - /// Will be called if a bot command gets raised - /// - public event BotCommandEventHandler BotCommand; - - - public async Task OnBotCommand(BotCommandEventArgs e) - { - if (BotCommand != null) - await BotCommand(this, e); - } - - /// - /// Will be called on an inner exception - /// - public event EventHandler Exception - { - add => _events.AddHandler(EvException, value); - remove => _events.RemoveHandler(EvException, value); - } - - public void OnException(SystemExceptionEventArgs e) - { - (_events[EvException] as EventHandler)?.Invoke(this, e); - - } - - /// - /// Will be called if no form handeled this call - /// - public event EventHandler UnhandledCall - { - add => _events.AddHandler(EvUnhandledCall, value); - remove => _events.RemoveHandler(EvUnhandledCall, value); - } - - public void OnUnhandledCall(UnhandledCallEventArgs e) - { - (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); - - } - - #endregion - + BotBase = this + }; } -} + + public MessageClient Client { get; set; } + + /// + /// Your TelegramBot APIKey + /// + public string ApiKey { get; set; } = ""; + + /// + /// List of all running/active sessions + /// + public SessionBase Sessions { get; set; } + + /// + /// Contains System commands which will be available at everytime and didnt get passed to forms, i.e. /start + /// + public Dictionary> BotCommandScopes { get; set; } = new(); + + + /// + /// Enable the SessionState (you need to implement on call forms the IStateForm interface) + /// + public IStateMachine StateMachine { get; set; } + + /// + /// Offers functionality to manage the creation process of the start form. + /// + public IStartFormFactory StartFormFactory { get; set; } + + /// + /// Contains the message loop factory, which cares about "message-management." + /// + public IMessageLoopFactory MessageLoopFactory { get; set; } + + /// + /// All internal used settings. + /// + public Dictionary SystemSettings { get; } + + + /// + /// Start your Bot + /// + public void Start() + { + if (Client == null) + { + return; + } + + Client.MessageLoop += Client_MessageLoop; + + + if (StateMachine != null) + { + Sessions.LoadSessionStates(StateMachine); + } + + //Enable auto session saving + if (GetSetting(ESettings.SaveSessionsOnConsoleExit, false)) + { + Console.SetHandler(() => { Sessions.SaveSessionStates(); }); + } + + DeviceSession.MaxNumberOfRetries = GetSetting(ESettings.MaxNumberOfRetries, 5); + + Client.StartReceiving(); + } + + + private async Task Client_MessageLoop(object sender, UpdateResult e) + { + var ds = Sessions.GetSession(e.DeviceId); + if (ds == null) + { + ds = Sessions.StartSession(e.DeviceId).GetAwaiter().GetResult(); + e.Device = ds; + ds.LastMessage = e.RawData.Message; + + OnSessionBegins(new SessionBeginEventArgs(e.DeviceId, ds)); + } + + var mr = new MessageResult(e.RawData); + + var i = 0; + + //Should formulars get navigated (allow maximum of 10, to dont get loops) + do + { + i++; + + //Reset navigation + ds.FormSwitched = false; + + await MessageLoopFactory.MessageLoop(this, ds, e, mr); + + mr.IsFirstHandler = false; + } while (ds.FormSwitched && i < GetSetting(ESettings.NavigationMaximum, 10)); + } + + + /// + /// Stop your Bot + /// + public void Stop() + { + if (Client == null) + { + return; + } + + Client.MessageLoop -= Client_MessageLoop; + + + Client.StopReceiving(); + + Sessions.SaveSessionStates(); + } + + /// + /// Send a message to all active Sessions. + /// + /// + /// + public async Task SentToAll(string message) + { + if (Client == null) + { + return; + } + + foreach (var s in Sessions.SessionList) + { + await Client.TelegramClient.SendTextMessageAsync(s.Key, message); + } + } + + + /// + /// This will invoke the full message loop for the device even when no "userevent" like message or action has been + /// raised. + /// + /// Contains the device/chat id of the device to update. + public async Task InvokeMessageLoop(long deviceId) + { + var mr = new MessageResult + { + UpdateData = new Update + { + Message = new Message() + } + }; + + await InvokeMessageLoop(deviceId, mr); + } + + /// + /// This will invoke the full message loop for the device even when no "userevent" like message or action has been + /// raised. + /// + /// Contains the device/chat id of the device to update. + /// + public async Task InvokeMessageLoop(long deviceId, MessageResult e) + { + try + { + var ds = Sessions.GetSession(deviceId); + e.Device = ds; + + await MessageLoopFactory.MessageLoop(this, ds, new UpdateResult(e.UpdateData, ds), e); + //await Client_Loop(this, e); + } + catch (Exception ex) + { + var ds = Sessions.GetSession(deviceId); + OnException(new SystemExceptionEventArgs(e.Message.Text, deviceId, ds, ex)); + } + } + + + /// + /// Will get invoke on an unhandled call. + /// + /// + /// + public void MessageLoopFactory_UnhandledCall(object sender, UnhandledCallEventArgs e) + { + OnUnhandledCall(e); + } + + /// + /// This method will update all local created bot commands to the botfather. + /// + public async Task UploadBotCommands() + { + foreach (var bs in BotCommandScopes) + { + if (bs.Value != null) + { + await Client.SetBotCommands(bs.Value, bs.Key); + } + else + { + await Client.DeleteBotCommands(bs.Key); + } + } + } + + /// + /// Searching if parameter is a known command in all configured BotCommandScopes. + /// + /// + /// + public bool IsKnownBotCommand(string command) + { + foreach (var scope in BotCommandScopes) + { + if (scope.Value.Any(a => "/" + a.Command == command)) + { + return true; + } + } + + return false; + } + + /// + /// Could set a variety of settings to improve the bot handling. + /// + /// + /// + public void SetSetting(ESettings set, uint value) + { + SystemSettings[set] = value; + } + + /// + /// Could set a variety of settings to improve the bot handling. + /// + /// + /// + public void SetSetting(ESettings set, bool value) + { + SystemSettings[set] = value ? 1u : 0u; + } + + /// + /// Could get the current value of a setting + /// + /// + /// + /// + public uint GetSetting(ESettings set, uint defaultValue) + { + if (!SystemSettings.ContainsKey(set)) + { + return defaultValue; + } + + return SystemSettings[set]; + } + + /// + /// Could get the current value of a setting + /// + /// + /// + /// + public bool GetSetting(ESettings set, bool defaultValue) + { + if (!SystemSettings.ContainsKey(set)) + { + return defaultValue; + } + + return SystemSettings[set] == 0u ? false : true; + } + + + #region "Events" + + private readonly EventHandlerList _events = new(); + + private static readonly object EvSessionBegins = new(); + + private static readonly object EvMessage = new(); + + private static object __evSystemCall = new(); + + public delegate Task BotCommandEventHandler(object sender, BotCommandEventArgs e); + + private static readonly object EvException = new(); + + private static readonly object EvUnhandledCall = new(); + + #endregion + + #region "Events" + + /// + /// Will be called if a session/context gets started + /// + public event EventHandler SessionBegins + { + add => _events.AddHandler(EvSessionBegins, value); + remove => _events.RemoveHandler(EvSessionBegins, value); + } + + public void OnSessionBegins(SessionBeginEventArgs e) + { + (_events[EvSessionBegins] as EventHandler)?.Invoke(this, e); + } + + /// + /// Will be called on incomming message + /// + public event EventHandler Message + { + add => _events.AddHandler(EvMessage, value); + remove => _events.RemoveHandler(EvMessage, value); + } + + public void OnMessage(MessageIncomeEventArgs e) + { + (_events[EvMessage] as EventHandler)?.Invoke(this, e); + } + + /// + /// Will be called if a bot command gets raised + /// + public event BotCommandEventHandler BotCommand; + + + public async Task OnBotCommand(BotCommandEventArgs e) + { + if (BotCommand != null) + { + await BotCommand(this, e); + } + } + + /// + /// Will be called on an inner exception + /// + public event EventHandler Exception + { + add => _events.AddHandler(EvException, value); + remove => _events.RemoveHandler(EvException, value); + } + + public void OnException(SystemExceptionEventArgs e) + { + (_events[EvException] as EventHandler)?.Invoke(this, e); + } + + /// + /// Will be called if no form handeled this call + /// + public event EventHandler UnhandledCall + { + add => _events.AddHandler(EvUnhandledCall, value); + remove => _events.RemoveHandler(EvUnhandledCall, value); + } + + public void OnUnhandledCall(UnhandledCallEventArgs e) + { + (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); + } + + #endregion +} \ No newline at end of file diff --git a/TelegramBotBase/Builder/BotBaseBuilder.cs b/TelegramBotBase/Builder/BotBaseBuilder.cs index 216d09f..ffd2d58 100644 --- a/TelegramBotBase/Builder/BotBaseBuilder.cs +++ b/TelegramBotBase/Builder/BotBaseBuilder.cs @@ -13,362 +13,360 @@ using TelegramBotBase.Localizations; using TelegramBotBase.MessageLoops; using TelegramBotBase.States; -namespace TelegramBotBase.Builder +namespace TelegramBotBase.Builder; + +public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, IStartFormSelectionStage, + IBuildingStage, INetworkingSelectionStage, IBotCommandsStage, ISessionSerializationStage, + ILanguageSelectionStage { - public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, IStartFormSelectionStage, IBuildingStage, INetworkingSelectionStage, IBotCommandsStage, ISessionSerializationStage, ILanguageSelectionStage + private string _apiKey; + + private MessageClient _client; + + private IStartFormFactory _factory; + + private IMessageLoopFactory _messageLoopFactory; + + private IStateMachine _statemachine; + + private BotBaseBuilder() { - private string _apiKey; - - private IStartFormFactory _factory; - - private MessageClient _client; - - /// - /// Contains different Botcommands for different areas. - /// - private Dictionary> BotCommandScopes { get; set; } = new Dictionary>(); - - private IStateMachine _statemachine; - - private IMessageLoopFactory _messageLoopFactory; - - private BotBaseBuilder() - { - - } - - public static IAPIKeySelectionStage Create() - { - return new BotBaseBuilder(); - } - - #region "Step 1 (Basic Stuff)" - - public IMessageLoopSelectionStage WithAPIKey(string apiKey) - { - _apiKey = apiKey; - return this; - } - - - public IBuildingStage QuickStart(string apiKey, Type StartForm) - { - _apiKey = apiKey; - _factory = new DefaultStartFormFactory(StartForm); - - DefaultMessageLoop(); - - NoProxy(); - - OnlyStart(); - - NoSerialization(); - - DefaultLanguage(); - - return this; - } - - - public IBuildingStage QuickStart(string apiKey) - where T : FormBase - { - _apiKey = apiKey; - _factory = new DefaultStartFormFactory(typeof(T)); - - DefaultMessageLoop(); - - NoProxy(); - - OnlyStart(); - - NoSerialization(); - - DefaultLanguage(); - - return this; - } - - public IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory) - { - _apiKey = apiKey; - _factory = StartFormFactory; - - DefaultMessageLoop(); - - NoProxy(); - - OnlyStart(); - - NoSerialization(); - - DefaultLanguage(); - - return this; - } - - #endregion - - - #region "Step 2 (Message Loop)" - - public IStartFormSelectionStage DefaultMessageLoop() - { - _messageLoopFactory = new FormBaseMessageLoop(); - - return this; - } - - - public IStartFormSelectionStage MinimalMessageLoop() - { - _messageLoopFactory = new MinimalMessageLoop(); - - return this; - } - - - public IStartFormSelectionStage CustomMessageLoop(IMessageLoopFactory messageLoopClass) - { - _messageLoopFactory = messageLoopClass; - - return this; - } - - public IStartFormSelectionStage CustomMessageLoop() - where T : class, new() - { - _messageLoopFactory = typeof(T).GetConstructor(new Type[] { })?.Invoke(new object[] { }) as IMessageLoopFactory; - - return this; - } - - #endregion - - - #region "Step 3 (Start Form/Factory)" - - public INetworkingSelectionStage WithStartForm(Type startFormClass) - { - _factory = new DefaultStartFormFactory(startFormClass); - return this; - } - - public INetworkingSelectionStage WithStartForm() - where T : FormBase, new() - { - _factory = new DefaultStartFormFactory(typeof(T)); - return this; - } - - public INetworkingSelectionStage WithServiceProvider(Type startFormClass, IServiceProvider serviceProvider) - { - _factory = new ServiceProviderStartFormFactory(startFormClass, serviceProvider); - return this; - } - - public INetworkingSelectionStage WithServiceProvider(IServiceProvider serviceProvider) - where T : FormBase - { - _factory = new ServiceProviderStartFormFactory(serviceProvider); - return this; - } - - public INetworkingSelectionStage WithStartFormFactory(IStartFormFactory factory) - { - _factory = factory; - return this; - } - - #endregion - - - #region "Step 4 (Network Settings)" - - public IBotCommandsStage WithProxy(string proxyAddress) - { - var url = new Uri(proxyAddress); - _client = new MessageClient(_apiKey, url) - { - TelegramClient = - { - Timeout = new TimeSpan(0, 1, 0) - } - }; - return this; - } - - - public IBotCommandsStage NoProxy() - { - _client = new MessageClient(_apiKey) - { - TelegramClient = - { - Timeout = new TimeSpan(0, 1, 0) - } - }; - return this; - } - - - public IBotCommandsStage WithBotClient(TelegramBotClient tgclient) - { - _client = new MessageClient(_apiKey, tgclient) - { - TelegramClient = - { - Timeout = new TimeSpan(0, 1, 0) - } - }; - return this; - } - - - public IBotCommandsStage WithHostAndPort(string proxyHost, int proxyPort) - { - _client = new MessageClient(_apiKey, proxyHost, proxyPort) - { - TelegramClient = - { - Timeout = new TimeSpan(0, 1, 0) - } - }; - return this; - } - - public IBotCommandsStage WithHttpClient(HttpClient tgclient) - { - _client = new MessageClient(_apiKey, tgclient) - { - TelegramClient = - { - Timeout = new TimeSpan(0, 1, 0) - } - }; - return this; - } - - - #endregion - - - #region "Step 5 (Bot Commands)" - - public ISessionSerializationStage NoCommands() - { - return this; - } - - public ISessionSerializationStage OnlyStart() - { - BotCommandScopes.Start("Starts the bot"); - - return this; - - } - - public ISessionSerializationStage DefaultCommands() - { - BotCommandScopes.Start("Starts the bot"); - BotCommandScopes.Help("Should show you some help"); - BotCommandScopes.Settings("Should show you some settings"); - return this; - } - - public ISessionSerializationStage CustomCommands(Action>> action) - { - action?.Invoke(BotCommandScopes); - return this; - } - - #endregion - - - #region "Step 6 (Serialization)" - - public ILanguageSelectionStage NoSerialization() - { - return this; - } - - public ILanguageSelectionStage UseSerialization(IStateMachine machine) - { - _statemachine = machine; - return this; - } - - - public ILanguageSelectionStage UseJSON(string path) - { - _statemachine = new JsonStateMachine(path); - return this; - } - - public ILanguageSelectionStage UseSimpleJSON(string path) - { - _statemachine = new SimpleJsonStateMachine(path); - return this; - } - - public ILanguageSelectionStage UseXML(string path) - { - _statemachine = new XmlStateMachine(path); - return this; - } - - #endregion - - - #region "Step 7 (Language)" - - public IBuildingStage DefaultLanguage() - { - return this; - } - - public IBuildingStage UseEnglish() - { - Default.Language = new English(); - return this; - } - - public IBuildingStage UseGerman() - { - Default.Language = new German(); - return this; - } - - public IBuildingStage Custom(Localization language) - { - Default.Language = language; - return this; - } - - #endregion - - - public BotBase Build() - { - var bb = new BotBase - { - ApiKey = _apiKey, - StartFormFactory = _factory, - Client = _client - }; - - bb.Sessions.Client = bb.Client; - - bb.BotCommandScopes = BotCommandScopes; - - bb.StateMachine = _statemachine; - - bb.MessageLoopFactory = _messageLoopFactory; - - bb.MessageLoopFactory.UnhandledCall += bb.MessageLoopFactory_UnhandledCall; - - return bb; - } - } -} + + /// + /// Contains different Botcommands for different areas. + /// + private Dictionary> BotCommandScopes { get; } = new(); + + + public BotBase Build() + { + var bb = new BotBase + { + ApiKey = _apiKey, + StartFormFactory = _factory, + Client = _client + }; + + bb.Sessions.Client = bb.Client; + + bb.BotCommandScopes = BotCommandScopes; + + bb.StateMachine = _statemachine; + + bb.MessageLoopFactory = _messageLoopFactory; + + bb.MessageLoopFactory.UnhandledCall += bb.MessageLoopFactory_UnhandledCall; + + return bb; + } + + public static IAPIKeySelectionStage Create() + { + return new BotBaseBuilder(); + } + + #region "Step 1 (Basic Stuff)" + + public IMessageLoopSelectionStage WithAPIKey(string apiKey) + { + _apiKey = apiKey; + return this; + } + + + public IBuildingStage QuickStart(string apiKey, Type StartForm) + { + _apiKey = apiKey; + _factory = new DefaultStartFormFactory(StartForm); + + DefaultMessageLoop(); + + NoProxy(); + + OnlyStart(); + + NoSerialization(); + + DefaultLanguage(); + + return this; + } + + + public IBuildingStage QuickStart(string apiKey) + where T : FormBase + { + _apiKey = apiKey; + _factory = new DefaultStartFormFactory(typeof(T)); + + DefaultMessageLoop(); + + NoProxy(); + + OnlyStart(); + + NoSerialization(); + + DefaultLanguage(); + + return this; + } + + public IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory) + { + _apiKey = apiKey; + _factory = StartFormFactory; + + DefaultMessageLoop(); + + NoProxy(); + + OnlyStart(); + + NoSerialization(); + + DefaultLanguage(); + + return this; + } + + #endregion + + + #region "Step 2 (Message Loop)" + + public IStartFormSelectionStage DefaultMessageLoop() + { + _messageLoopFactory = new FormBaseMessageLoop(); + + return this; + } + + + public IStartFormSelectionStage MinimalMessageLoop() + { + _messageLoopFactory = new MinimalMessageLoop(); + + return this; + } + + + public IStartFormSelectionStage CustomMessageLoop(IMessageLoopFactory messageLoopClass) + { + _messageLoopFactory = messageLoopClass; + + return this; + } + + public IStartFormSelectionStage CustomMessageLoop() + where T : class, new() + { + _messageLoopFactory = + typeof(T).GetConstructor(new Type[] { })?.Invoke(new object[] { }) as IMessageLoopFactory; + + return this; + } + + #endregion + + + #region "Step 3 (Start Form/Factory)" + + public INetworkingSelectionStage WithStartForm(Type startFormClass) + { + _factory = new DefaultStartFormFactory(startFormClass); + return this; + } + + public INetworkingSelectionStage WithStartForm() + where T : FormBase, new() + { + _factory = new DefaultStartFormFactory(typeof(T)); + return this; + } + + public INetworkingSelectionStage WithServiceProvider(Type startFormClass, IServiceProvider serviceProvider) + { + _factory = new ServiceProviderStartFormFactory(startFormClass, serviceProvider); + return this; + } + + public INetworkingSelectionStage WithServiceProvider(IServiceProvider serviceProvider) + where T : FormBase + { + _factory = new ServiceProviderStartFormFactory(serviceProvider); + return this; + } + + public INetworkingSelectionStage WithStartFormFactory(IStartFormFactory factory) + { + _factory = factory; + return this; + } + + #endregion + + + #region "Step 4 (Network Settings)" + + public IBotCommandsStage WithProxy(string proxyAddress) + { + var url = new Uri(proxyAddress); + _client = new MessageClient(_apiKey, url) + { + TelegramClient = + { + Timeout = new TimeSpan(0, 1, 0) + } + }; + return this; + } + + + public IBotCommandsStage NoProxy() + { + _client = new MessageClient(_apiKey) + { + TelegramClient = + { + Timeout = new TimeSpan(0, 1, 0) + } + }; + return this; + } + + + public IBotCommandsStage WithBotClient(TelegramBotClient tgclient) + { + _client = new MessageClient(_apiKey, tgclient) + { + TelegramClient = + { + Timeout = new TimeSpan(0, 1, 0) + } + }; + return this; + } + + + public IBotCommandsStage WithHostAndPort(string proxyHost, int proxyPort) + { + _client = new MessageClient(_apiKey, proxyHost, proxyPort) + { + TelegramClient = + { + Timeout = new TimeSpan(0, 1, 0) + } + }; + return this; + } + + public IBotCommandsStage WithHttpClient(HttpClient tgclient) + { + _client = new MessageClient(_apiKey, tgclient) + { + TelegramClient = + { + Timeout = new TimeSpan(0, 1, 0) + } + }; + return this; + } + + #endregion + + + #region "Step 5 (Bot Commands)" + + public ISessionSerializationStage NoCommands() + { + return this; + } + + public ISessionSerializationStage OnlyStart() + { + BotCommandScopes.Start("Starts the bot"); + + return this; + } + + public ISessionSerializationStage DefaultCommands() + { + BotCommandScopes.Start("Starts the bot"); + BotCommandScopes.Help("Should show you some help"); + BotCommandScopes.Settings("Should show you some settings"); + return this; + } + + public ISessionSerializationStage CustomCommands(Action>> action) + { + action?.Invoke(BotCommandScopes); + return this; + } + + #endregion + + + #region "Step 6 (Serialization)" + + public ILanguageSelectionStage NoSerialization() + { + return this; + } + + public ILanguageSelectionStage UseSerialization(IStateMachine machine) + { + _statemachine = machine; + return this; + } + + + public ILanguageSelectionStage UseJSON(string path) + { + _statemachine = new JsonStateMachine(path); + return this; + } + + public ILanguageSelectionStage UseSimpleJSON(string path) + { + _statemachine = new SimpleJsonStateMachine(path); + return this; + } + + public ILanguageSelectionStage UseXML(string path) + { + _statemachine = new XmlStateMachine(path); + return this; + } + + #endregion + + + #region "Step 7 (Language)" + + public IBuildingStage DefaultLanguage() + { + return this; + } + + public IBuildingStage UseEnglish() + { + Default.Language = new English(); + return this; + } + + public IBuildingStage UseGerman() + { + Default.Language = new German(); + return this; + } + + public IBuildingStage Custom(Localization language) + { + Default.Language = language; + return this; + } + + #endregion +} \ No newline at end of file diff --git a/TelegramBotBase/Builder/Interfaces/IAPIKeySelectionStage.cs b/TelegramBotBase/Builder/Interfaces/IAPIKeySelectionStage.cs index 44a1bb8..bcbe23b 100644 --- a/TelegramBotBase/Builder/Interfaces/IAPIKeySelectionStage.cs +++ b/TelegramBotBase/Builder/Interfaces/IAPIKeySelectionStage.cs @@ -2,42 +2,41 @@ using TelegramBotBase.Form; using TelegramBotBase.Interfaces; -namespace TelegramBotBase.Builder.Interfaces +namespace TelegramBotBase.Builder.Interfaces; + +public interface IAPIKeySelectionStage { - public interface IAPIKeySelectionStage - { - /// - /// Sets the API Key which will be used by the telegram bot client. - /// - /// - /// - IMessageLoopSelectionStage WithAPIKey(string apiKey); + /// + /// Sets the API Key which will be used by the telegram bot client. + /// + /// + /// + IMessageLoopSelectionStage WithAPIKey(string apiKey); - /// - /// Quick and easy way to create a BotBase instance. - /// Uses: DefaultMessageLoop, NoProxy, OnlyStart, NoSerialization, DefaultLanguage - /// - /// - /// - /// - IBuildingStage QuickStart(string apiKey, Type StartForm); + /// + /// Quick and easy way to create a BotBase instance. + /// Uses: DefaultMessageLoop, NoProxy, OnlyStart, NoSerialization, DefaultLanguage + /// + /// + /// + /// + IBuildingStage QuickStart(string apiKey, Type StartForm); - /// - /// Quick and easy way to create a BotBase instance. - /// Uses: DefaultMessageLoop, NoProxy, OnlyStart, NoSerialization, DefaultLanguage - /// - /// - /// - IBuildingStage QuickStart(string apiKey) where T : FormBase; + /// + /// Quick and easy way to create a BotBase instance. + /// Uses: DefaultMessageLoop, NoProxy, OnlyStart, NoSerialization, DefaultLanguage + /// + /// + /// + IBuildingStage QuickStart(string apiKey) where T : FormBase; - /// - /// Quick and easy way to create a BotBase instance. - /// Uses: DefaultMessageLoop, NoProxy, OnlyStart, NoSerialization, DefaultLanguage - /// - /// - /// - /// - IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory); - } -} + /// + /// Quick and easy way to create a BotBase instance. + /// Uses: DefaultMessageLoop, NoProxy, OnlyStart, NoSerialization, DefaultLanguage + /// + /// + /// + /// + IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory); +} \ No newline at end of file diff --git a/TelegramBotBase/Builder/Interfaces/IBotCommandsStage.cs b/TelegramBotBase/Builder/Interfaces/IBotCommandsStage.cs index 2b83453..510db3b 100644 --- a/TelegramBotBase/Builder/Interfaces/IBotCommandsStage.cs +++ b/TelegramBotBase/Builder/Interfaces/IBotCommandsStage.cs @@ -2,39 +2,35 @@ using System.Collections.Generic; using Telegram.Bot.Types; -namespace TelegramBotBase.Builder.Interfaces +namespace TelegramBotBase.Builder.Interfaces; + +public interface IBotCommandsStage { - public interface IBotCommandsStage - { - /// - /// Does not create any commands. - /// - /// - ISessionSerializationStage NoCommands(); + /// + /// Does not create any commands. + /// + /// + ISessionSerializationStage NoCommands(); - /// - /// Creates default commands for start, help and settings. - /// - /// - ISessionSerializationStage DefaultCommands(); + /// + /// Creates default commands for start, help and settings. + /// + /// + ISessionSerializationStage DefaultCommands(); - /// - /// Only adds the start command. - /// - /// - ISessionSerializationStage OnlyStart(); + /// + /// Only adds the start command. + /// + /// + ISessionSerializationStage OnlyStart(); - /// - /// Gives you the ability to add custom commands. - /// - /// - /// - - ISessionSerializationStage CustomCommands(Action>> action); - - - } -} + /// + /// Gives you the ability to add custom commands. + /// + /// + /// + ISessionSerializationStage CustomCommands(Action>> action); +} \ No newline at end of file diff --git a/TelegramBotBase/Builder/Interfaces/IBuildingStage.cs b/TelegramBotBase/Builder/Interfaces/IBuildingStage.cs index d5b70df..17e49cc 100644 --- a/TelegramBotBase/Builder/Interfaces/IBuildingStage.cs +++ b/TelegramBotBase/Builder/Interfaces/IBuildingStage.cs @@ -1,7 +1,6 @@ -namespace TelegramBotBase.Builder.Interfaces +namespace TelegramBotBase.Builder.Interfaces; + +public interface IBuildingStage { - public interface IBuildingStage - { - BotBase Build(); - } -} + BotBase Build(); +} \ No newline at end of file diff --git a/TelegramBotBase/Builder/Interfaces/ILanguageSelectionStage.cs b/TelegramBotBase/Builder/Interfaces/ILanguageSelectionStage.cs index b7bbd28..e32f710 100644 --- a/TelegramBotBase/Builder/Interfaces/ILanguageSelectionStage.cs +++ b/TelegramBotBase/Builder/Interfaces/ILanguageSelectionStage.cs @@ -1,33 +1,30 @@ using TelegramBotBase.Localizations; -namespace TelegramBotBase.Builder.Interfaces +namespace TelegramBotBase.Builder.Interfaces; + +public interface ILanguageSelectionStage { - public interface ILanguageSelectionStage - { + /// + /// Selects the default language for control usage. (English) + /// + /// + IBuildingStage DefaultLanguage(); - /// - /// Selects the default language for control usage. (English) - /// - /// - IBuildingStage DefaultLanguage(); + /// + /// Selects english as the default language for control labels. + /// + /// + IBuildingStage UseEnglish(); - /// - /// Selects english as the default language for control labels. - /// - /// - IBuildingStage UseEnglish(); + /// + /// Selects german as the default language for control labels. + /// + /// + IBuildingStage UseGerman(); - /// - /// Selects german as the default language for control labels. - /// - /// - IBuildingStage UseGerman(); - - /// - /// Selects a custom language as the default language for control labels. - /// - /// - IBuildingStage Custom(Localization language); - - } -} + /// + /// Selects a custom language as the default language for control labels. + /// + /// + IBuildingStage Custom(Localization language); +} \ No newline at end of file diff --git a/TelegramBotBase/Builder/Interfaces/IMessageLoopSelectionStage.cs b/TelegramBotBase/Builder/Interfaces/IMessageLoopSelectionStage.cs index b9a8df0..21223e7 100644 --- a/TelegramBotBase/Builder/Interfaces/IMessageLoopSelectionStage.cs +++ b/TelegramBotBase/Builder/Interfaces/IMessageLoopSelectionStage.cs @@ -1,40 +1,36 @@ using TelegramBotBase.Interfaces; -namespace TelegramBotBase.Builder.Interfaces +namespace TelegramBotBase.Builder.Interfaces; + +public interface IMessageLoopSelectionStage { - public interface IMessageLoopSelectionStage - { - - /// - /// Chooses a default message loop. - /// - /// - /// - IStartFormSelectionStage DefaultMessageLoop(); + /// + /// Chooses a default message loop. + /// + /// + /// + IStartFormSelectionStage DefaultMessageLoop(); - /// - /// Chooses a minimalistic message loop, which catches all update types and only calls the Load function. - /// - /// - IStartFormSelectionStage MinimalMessageLoop(); + /// + /// Chooses a minimalistic message loop, which catches all update types and only calls the Load function. + /// + /// + IStartFormSelectionStage MinimalMessageLoop(); - /// - /// Chooses a custom message loop. - /// - /// - /// - IStartFormSelectionStage CustomMessageLoop(IMessageLoopFactory startFormClass); + /// + /// Chooses a custom message loop. + /// + /// + /// + IStartFormSelectionStage CustomMessageLoop(IMessageLoopFactory startFormClass); - /// - /// Chooses a custom message loop. - /// - /// - /// - IStartFormSelectionStage CustomMessageLoop() where T : class, new(); - - - } -} + /// + /// Chooses a custom message loop. + /// + /// + /// + IStartFormSelectionStage CustomMessageLoop() where T : class, new(); +} \ No newline at end of file diff --git a/TelegramBotBase/Builder/Interfaces/INetworkingSelectionStage.cs b/TelegramBotBase/Builder/Interfaces/INetworkingSelectionStage.cs index a7b0d8e..3e48b21 100644 --- a/TelegramBotBase/Builder/Interfaces/INetworkingSelectionStage.cs +++ b/TelegramBotBase/Builder/Interfaces/INetworkingSelectionStage.cs @@ -1,48 +1,44 @@ using System.Net.Http; using Telegram.Bot; -namespace TelegramBotBase.Builder.Interfaces +namespace TelegramBotBase.Builder.Interfaces; + +public interface INetworkingSelectionStage { - public interface INetworkingSelectionStage - { + /// + /// Chooses a proxy as network configuration. + /// + /// + /// + IBotCommandsStage WithProxy(string proxyAddress); - /// - /// Chooses a proxy as network configuration. - /// - /// - /// - IBotCommandsStage WithProxy(string proxyAddress); - - /// - /// Do not choose a proxy as network configuration. - /// - /// - IBotCommandsStage NoProxy(); + /// + /// Do not choose a proxy as network configuration. + /// + /// + IBotCommandsStage NoProxy(); - /// - /// Chooses a custom instance of TelegramBotClient. - /// - /// - /// - IBotCommandsStage WithBotClient(TelegramBotClient client); + /// + /// Chooses a custom instance of TelegramBotClient. + /// + /// + /// + IBotCommandsStage WithBotClient(TelegramBotClient client); - /// - /// Sets the custom proxy host and port. - /// - /// - /// - /// - IBotCommandsStage WithHostAndPort(string proxyHost, int Port); + /// + /// Sets the custom proxy host and port. + /// + /// + /// + /// + IBotCommandsStage WithHostAndPort(string proxyHost, int Port); - /// - /// Uses a custom http client. - /// - /// - /// - IBotCommandsStage WithHttpClient(HttpClient client); - - - } -} + /// + /// Uses a custom http client. + /// + /// + /// + IBotCommandsStage WithHttpClient(HttpClient client); +} \ No newline at end of file diff --git a/TelegramBotBase/Builder/Interfaces/ISessionSerializationStage.cs b/TelegramBotBase/Builder/Interfaces/ISessionSerializationStage.cs index 9adc70f..5ed022b 100644 --- a/TelegramBotBase/Builder/Interfaces/ISessionSerializationStage.cs +++ b/TelegramBotBase/Builder/Interfaces/ISessionSerializationStage.cs @@ -1,46 +1,44 @@ using TelegramBotBase.Interfaces; -namespace TelegramBotBase.Builder.Interfaces +namespace TelegramBotBase.Builder.Interfaces; + +public interface ISessionSerializationStage { - public interface ISessionSerializationStage - { - /// - /// Do not uses serialization. - /// - /// - ILanguageSelectionStage NoSerialization(); + /// + /// Do not uses serialization. + /// + /// + ILanguageSelectionStage NoSerialization(); - /// - /// Sets the state machine for serialization. - /// - /// - /// - ILanguageSelectionStage UseSerialization(IStateMachine machine); + /// + /// Sets the state machine for serialization. + /// + /// + /// + ILanguageSelectionStage UseSerialization(IStateMachine machine); - /// - /// Using the complex version of .Net JSON, which can serialize all objects. - /// - /// - /// - ILanguageSelectionStage UseJSON(string path); + /// + /// Using the complex version of .Net JSON, which can serialize all objects. + /// + /// + /// + ILanguageSelectionStage UseJSON(string path); - /// - /// Use the easy version of .Net JSON, which can serialize basic types, but not generics and others. - /// - /// - /// - ILanguageSelectionStage UseSimpleJSON(string path); + /// + /// Use the easy version of .Net JSON, which can serialize basic types, but not generics and others. + /// + /// + /// + ILanguageSelectionStage UseSimpleJSON(string path); - /// - /// Uses the XML serializer for session serialization. - /// - /// - /// - ILanguageSelectionStage UseXML(string path); - - } -} + /// + /// Uses the XML serializer for session serialization. + /// + /// + /// + ILanguageSelectionStage UseXML(string path); +} \ No newline at end of file diff --git a/TelegramBotBase/Builder/Interfaces/IStartFormSelectionStage.cs b/TelegramBotBase/Builder/Interfaces/IStartFormSelectionStage.cs index 52c1890..1254693 100644 --- a/TelegramBotBase/Builder/Interfaces/IStartFormSelectionStage.cs +++ b/TelegramBotBase/Builder/Interfaces/IStartFormSelectionStage.cs @@ -2,47 +2,44 @@ using TelegramBotBase.Form; using TelegramBotBase.Interfaces; -namespace TelegramBotBase.Builder.Interfaces +namespace TelegramBotBase.Builder.Interfaces; + +public interface IStartFormSelectionStage { - public interface IStartFormSelectionStage - { + /// + /// Chooses a start form type which will be used for new sessions. + /// + /// + /// + INetworkingSelectionStage WithStartForm(Type startFormClass); - /// - /// Chooses a start form type which will be used for new sessions. - /// - /// - /// - INetworkingSelectionStage WithStartForm(Type startFormClass); + /// + /// Chooses a generic start form which will be used for new sessions. + /// + /// + /// + INetworkingSelectionStage WithStartForm() where T : FormBase, new(); - /// - /// Chooses a generic start form which will be used for new sessions. - /// - /// - /// - INetworkingSelectionStage WithStartForm() where T : FormBase, new(); + /// + /// Chooses a StartFormFactory which will be use for new sessions. + /// + /// + /// + /// + INetworkingSelectionStage WithServiceProvider(Type startFormClass, IServiceProvider serviceProvider); - /// - /// Chooses a StartFormFactory which will be use for new sessions. - /// - /// - /// - /// - INetworkingSelectionStage WithServiceProvider(Type startFormClass, IServiceProvider serviceProvider); + /// + /// Chooses a StartFormFactory which will be use for new sessions. + /// + /// + /// + /// + INetworkingSelectionStage WithServiceProvider(IServiceProvider serviceProvider) where T : FormBase; - /// - /// Chooses a StartFormFactory which will be use for new sessions. - /// - /// - /// - /// - INetworkingSelectionStage WithServiceProvider(IServiceProvider serviceProvider) where T : FormBase; - - /// - /// Chooses a StartFormFactory which will be use for new sessions. - /// - /// - /// - INetworkingSelectionStage WithStartFormFactory(IStartFormFactory factory); - - } -} + /// + /// Chooses a StartFormFactory which will be use for new sessions. + /// + /// + /// + INetworkingSelectionStage WithStartFormFactory(IStartFormFactory factory); +} \ No newline at end of file diff --git a/TelegramBotBase/Commands/Extensions.cs b/TelegramBotBase/Commands/Extensions.cs index 55721b8..6a19ce1 100644 --- a/TelegramBotBase/Commands/Extensions.cs +++ b/TelegramBotBase/Commands/Extensions.cs @@ -2,141 +2,181 @@ using System.Linq; using Telegram.Bot.Types; -namespace TelegramBotBase.Commands +namespace TelegramBotBase.Commands; + +public static class Extensions { - public static class Extensions + /// + /// Adding the command with a description. + /// + /// + /// + /// + public static void Add(this Dictionary> cmds, string command, + string description, BotCommandScope scope = null) { - /// - /// Adding the command with a description. - /// - /// - /// - /// - public static void Add(this Dictionary> cmds, string command, string description, BotCommandScope scope = null) + if (scope == null) { - if (scope == null) - { - scope = BotCommandScope.Default(); - } - - var item = cmds.FirstOrDefault(a => a.Key.Type == scope.Type); - - if (item.Value != null) - { - item.Value.Add(new BotCommand { Command = command, Description = description }); - } - else - { - cmds.Add(scope, new List { new BotCommand { Command = command, Description = description } }); - } + scope = BotCommandScope.Default(); } - /// - /// Adding the command with a description. - /// - /// - /// - /// - public static void Clear(this Dictionary> cmds, BotCommandScope scope = null) + var item = cmds.FirstOrDefault(a => a.Key.Type == scope.Type); + + if (item.Value != null) { - if (scope == null) - { - scope = BotCommandScope.Default(); - } - - var item = cmds.FirstOrDefault(a => a.Key.Type == scope.Type); - - if (item.Key != null) - { - cmds[item.Key] = null; - } - else - { - cmds[scope] = null; - } + item.Value.Add(new BotCommand { Command = command, Description = description }); + } + else + { + cmds.Add(scope, new List { new() { Command = command, Description = description } }); } - - /// - /// Adding the default /start command with a description. - /// - /// - /// - public static void Start(this Dictionary> cmds, string description) => Add(cmds, "start", description); - - /// - /// Adding the default /help command with a description. - /// - /// - /// - public static void Help(this Dictionary> cmds, string description) => Add(cmds, "help", description); - - /// - /// Adding the default /settings command with a description. - /// - /// - /// - public static void Settings(this Dictionary> cmds, string description) => Add(cmds, "settings", description); - - /// - /// Clears all default commands. - /// - /// - public static void ClearDefaultCommands(this Dictionary> cmds) => Clear(cmds); - - /// - /// Clears all commands of a specific device. - /// - /// - public static void ClearChatCommands(this Dictionary> cmds, long deviceId) => Clear(cmds, new BotCommandScopeChat { ChatId = deviceId }); - - /// - /// Adding a chat command with a description. - /// - /// - /// - /// - public static void AddChatCommand(this Dictionary> cmds, long deviceId, string command, string description) => Add(cmds, command, description, new BotCommandScopeChat { ChatId = deviceId }); - - /// - /// Adding a group command with a description. - /// - /// - /// - /// - public static void AddGroupCommand(this Dictionary> cmds, string command, string description) => Add(cmds, command, description, new BotCommandScopeAllGroupChats()); - - /// - /// Clears all group commands. - /// - /// - public static void ClearGroupCommands(this Dictionary> cmds) => Clear(cmds, new BotCommandScopeAllGroupChats()); - - /// - /// Adding group admin command with a description. - /// - /// - /// - /// - public static void AddGroupAdminCommand(this Dictionary> cmds, string command, string description) => Add(cmds, command, description, new BotCommandScopeAllChatAdministrators()); - - /// - /// Clears all group admin commands. - /// - /// - public static void ClearGroupAdminCommand(this Dictionary> cmds) => Clear(cmds, new BotCommandScopeAllChatAdministrators()); - - /// - /// Adding a privat command with a description. - /// - /// - /// - /// - public static void AddPrivateChatCommand(this Dictionary> cmds, string command, string description) => Add(cmds, command, description, new BotCommandScopeAllPrivateChats()); - - /// - /// Clears all private commands. - /// - /// - public static void ClearPrivateChatCommand(this Dictionary> cmds) => Clear(cmds, new BotCommandScopeAllPrivateChats()); } -} + + /// + /// Adding the command with a description. + /// + /// + /// + /// + public static void Clear(this Dictionary> cmds, BotCommandScope scope = null) + { + if (scope == null) + { + scope = BotCommandScope.Default(); + } + + var item = cmds.FirstOrDefault(a => a.Key.Type == scope.Type); + + if (item.Key != null) + { + cmds[item.Key] = null; + } + else + { + cmds[scope] = null; + } + } + + /// + /// Adding the default /start command with a description. + /// + /// + /// + public static void Start(this Dictionary> cmds, string description) + { + Add(cmds, "start", description); + } + + /// + /// Adding the default /help command with a description. + /// + /// + /// + public static void Help(this Dictionary> cmds, string description) + { + Add(cmds, "help", description); + } + + /// + /// Adding the default /settings command with a description. + /// + /// + /// + public static void Settings(this Dictionary> cmds, string description) + { + Add(cmds, "settings", description); + } + + /// + /// Clears all default commands. + /// + /// + public static void ClearDefaultCommands(this Dictionary> cmds) + { + Clear(cmds); + } + + /// + /// Clears all commands of a specific device. + /// + /// + public static void ClearChatCommands(this Dictionary> cmds, long deviceId) + { + Clear(cmds, new BotCommandScopeChat { ChatId = deviceId }); + } + + /// + /// Adding a chat command with a description. + /// + /// + /// + /// + public static void AddChatCommand(this Dictionary> cmds, long deviceId, + string command, string description) + { + Add(cmds, command, description, new BotCommandScopeChat { ChatId = deviceId }); + } + + /// + /// Adding a group command with a description. + /// + /// + /// + /// + public static void AddGroupCommand(this Dictionary> cmds, string command, + string description) + { + Add(cmds, command, description, new BotCommandScopeAllGroupChats()); + } + + /// + /// Clears all group commands. + /// + /// + public static void ClearGroupCommands(this Dictionary> cmds) + { + Clear(cmds, new BotCommandScopeAllGroupChats()); + } + + /// + /// Adding group admin command with a description. + /// + /// + /// + /// + public static void AddGroupAdminCommand(this Dictionary> cmds, string command, + string description) + { + Add(cmds, command, description, new BotCommandScopeAllChatAdministrators()); + } + + /// + /// Clears all group admin commands. + /// + /// + public static void ClearGroupAdminCommand(this Dictionary> cmds) + { + Clear(cmds, new BotCommandScopeAllChatAdministrators()); + } + + /// + /// Adding a privat command with a description. + /// + /// + /// + /// + public static void AddPrivateChatCommand(this Dictionary> cmds, + string command, string description) + { + Add(cmds, command, description, new BotCommandScopeAllPrivateChats()); + } + + /// + /// Clears all private commands. + /// + /// + public static void ClearPrivateChatCommand(this Dictionary> cmds) + { + Clear(cmds, new BotCommandScopeAllPrivateChats()); + } +} \ No newline at end of file diff --git a/TelegramBotBase/Constants/Telegram.cs b/TelegramBotBase/Constants/Telegram.cs index a669022..a2837d7 100644 --- a/TelegramBotBase/Constants/Telegram.cs +++ b/TelegramBotBase/Constants/Telegram.cs @@ -1,21 +1,19 @@ -namespace TelegramBotBase.Constants +namespace TelegramBotBase.Constants; + +public static class Telegram { - public static class Telegram - { - /// - /// The maximum length of message text before the API throws an exception. (We will catch it before) - /// - public const int MaxMessageLength = 4096; + /// + /// The maximum length of message text before the API throws an exception. (We will catch it before) + /// + public const int MaxMessageLength = 4096; - public const int MaxInlineKeyBoardRows = 13; + public const int MaxInlineKeyBoardRows = 13; - public const int MaxInlineKeyBoardCols = 8; + public const int MaxInlineKeyBoardCols = 8; - public const int MaxReplyKeyboardRows = 25; + public const int MaxReplyKeyboardRows = 25; - public const int MaxReplyKeyboardCols = 12; + public const int MaxReplyKeyboardCols = 12; - public const int MessageDeletionsPerSecond = 30; - - } -} + public const int MessageDeletionsPerSecond = 30; +} \ No newline at end of file diff --git a/TelegramBotBase/Controls/Hybrid/ButtonGrid.cs b/TelegramBotBase/Controls/Hybrid/ButtonGrid.cs index f8662b2..e2871d9 100644 --- a/TelegramBotBase/Controls/Hybrid/ButtonGrid.cs +++ b/TelegramBotBase/Controls/Hybrid/ButtonGrid.cs @@ -15,208 +15,339 @@ using TelegramBotBase.Form; using TelegramBotBase.Localizations; using static TelegramBotBase.Base.Async; -namespace TelegramBotBase.Controls.Hybrid +namespace TelegramBotBase.Controls.Hybrid; + +public class ButtonGrid : ControlBase { - public class ButtonGrid : ControlBase + private static readonly object EvButtonClicked = new(); + + private readonly EventHandlerList _events = new(); + + private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard; + + private bool _renderNecessary = true; + + public string NextPageLabel = Default.Language["ButtonGrid_NextPage"]; + + public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"]; + + public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"]; + + public string SearchLabel = Default.Language["ButtonGrid_SearchFeature"]; + + public ButtonGrid() { + DataSource = new ButtonFormDataSource(); + } - public string Title { get; set; } = Default.Language["ButtonGrid_Title"]; + public ButtonGrid(EKeyboardType type) : this() + { + _mEKeyboardType = type; + } - public string ConfirmationText { get; set; } = ""; - private bool _renderNecessary = true; + public ButtonGrid(ButtonForm form) + { + DataSource = new ButtonFormDataSource(form); + } - private static readonly object EvButtonClicked = new object(); + public string Title { get; set; } = Default.Language["ButtonGrid_Title"]; - private readonly EventHandlerList _events = new EventHandlerList(); + public string ConfirmationText { get; set; } = ""; - /// - /// - /// - [Obsolete("This property is obsolete. Please use the DataSource property instead.")] - public ButtonForm ButtonsForm + /// + /// + [Obsolete("This property is obsolete. Please use the DataSource property instead.")] + public ButtonForm ButtonsForm + { + get => DataSource.ButtonForm; + set => DataSource = new ButtonFormDataSource(value); + } + + /// + /// Data source of the items. + /// + public ButtonFormDataSource DataSource { get; set; } + + public int? MessageId { get; set; } + + + /// + /// Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if + /// there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same + /// height as the app's standard keyboard. + /// Source: https://core.telegram.org/bots/api#replykeyboardmarkup + /// + public bool ResizeKeyboard { get; set; } = false; + + public bool OneTimeKeyboard { get; set; } = false; + + public bool HideKeyboardOnCleanup { get; set; } = true; + + public bool DeletePreviousMessage { get; set; } = true; + + /// + /// Removes the reply message from a user. + /// + public bool DeleteReplyMessage { get; set; } = true; + + /// + /// Parsemode of the message. + /// + public ParseMode MessageParseMode { get; set; } = ParseMode.Markdown; + + /// + /// Enables automatic paging of buttons when the amount of rows is exceeding the limits. + /// + public bool EnablePaging { get; set; } = false; + + + /// + /// Enabled a search function. + /// + public bool EnableSearch { get; set; } = false; + + public string SearchQuery { get; set; } + + public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always; + + + /// + /// Index of the current page + /// + public int CurrentPageIndex { get; set; } + + /// + /// Layout of the buttons which should be displayed always on top. + /// + public ButtonRow HeadLayoutButtonRow { get; set; } + + /// + /// Layout of columns which should be displayed below the header + /// + public ButtonRow SubHeadLayoutButtonRow { get; set; } + + /// + /// Defines which type of Button Keyboard should be rendered. + /// + public EKeyboardType KeyboardType + { + get => _mEKeyboardType; + set { - get => DataSource.ButtonForm; - set => DataSource = new ButtonFormDataSource(value); - } - - /// - /// Data source of the items. - /// - public ButtonFormDataSource DataSource { get; set; } - - public int? MessageId { get; set; } - - - /// - /// Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard. - /// Source: https://core.telegram.org/bots/api#replykeyboardmarkup - /// - public bool ResizeKeyboard { get; set; } = false; - - public bool OneTimeKeyboard { get; set; } = false; - - public bool HideKeyboardOnCleanup { get; set; } = true; - - public bool DeletePreviousMessage { get; set; } = true; - - /// - /// Removes the reply message from a user. - /// - public bool DeleteReplyMessage { get; set; } = true; - - /// - /// Parsemode of the message. - /// - public ParseMode MessageParseMode { get; set; } = ParseMode.Markdown; - - /// - /// Enables automatic paging of buttons when the amount of rows is exceeding the limits. - /// - public bool EnablePaging { get; set; } = false; - - - /// - /// Enabled a search function. - /// - public bool EnableSearch { get; set; } = false; - - public string SearchQuery { get; set; } - - public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always; - - - /// - /// Index of the current page - /// - public int CurrentPageIndex { get; set; } - - public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"]; - - public string NextPageLabel = Default.Language["ButtonGrid_NextPage"]; - - public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"]; - - public string SearchLabel = Default.Language["ButtonGrid_SearchFeature"]; - - /// - /// Layout of the buttons which should be displayed always on top. - /// - public ButtonRow HeadLayoutButtonRow { get; set; } - - /// - /// Layout of columns which should be displayed below the header - /// - public ButtonRow SubHeadLayoutButtonRow { get; set; } - - /// - /// Defines which type of Button Keyboard should be rendered. - /// - public EKeyboardType KeyboardType - { - get => _mEKeyboardType; - set + if (_mEKeyboardType != value) { - if (_mEKeyboardType != value) - { - _renderNecessary = true; + _renderNecessary = true; - Cleanup().Wait(); - - _mEKeyboardType = value; - } + Cleanup().Wait(); + _mEKeyboardType = value; } } + } - private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard; - - public ButtonGrid() + public bool PagingNecessary + { + get { - DataSource = new ButtonFormDataSource(); - - } - - public ButtonGrid(EKeyboardType type) : this() - { - _mEKeyboardType = type; - } - - - public ButtonGrid(ButtonForm form) - { - DataSource = new ButtonFormDataSource(form); - } - - - public event AsyncEventHandler ButtonClicked - { - add => _events.AddHandler(EvButtonClicked, value); - remove => _events.RemoveHandler(EvButtonClicked, value); - } - - public async Task OnButtonClicked(ButtonClickedEventArgs e) - { - var handler = _events[EvButtonClicked]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) + if (KeyboardType == EKeyboardType.InlineKeyBoard && + TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) { - await h.InvokeAllAsync(this, e); - } - } - - public override void Init() - { - Device.MessageDeleted += Device_MessageDeleted; - } - - private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e) - { - if (MessageId == null) - return; - - if (e.MessageId != MessageId) - return; - - MessageId = null; - } - - public override async Task Load(MessageResult result) - { - if (KeyboardType != EKeyboardType.ReplyKeyboard) - return; - - if (!result.IsFirstHandler) - return; - - if (result.MessageText == null || result.MessageText == "") - return; - - var matches = new List(); - ButtonRow match = null; - var index = -1; - - if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false) - { - match = HeadLayoutButtonRow; - goto check; + return true; } - if (SubHeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + if (KeyboardType == EKeyboardType.ReplyKeyboard && + TotalRows > Constants.Telegram.MaxReplyKeyboardRows) { - match = SubHeadLayoutButtonRow; - goto check; + return true; } - var br = DataSource.FindRow(result.MessageText); - if (br != null) + return false; + } + } + + public bool IsNavigationBarVisible + { + get + { + if ((NavigationBarVisibility == ENavigationBarVisibility.always) | + (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary)) { - match = br.Item1; - index = br.Item2; + return true; } + return false; + } + } + + /// + /// Returns the maximum number of rows + /// + public int MaximumRow + { + get + { + return KeyboardType switch + { + EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows, + EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows, + _ => 0 + }; + } + } + + /// + /// Returns the number of all rows (layout + navigation + content); + /// + public int TotalRows => LayoutRows + DataSource.RowCount; + + + /// + /// Contains the Number of Rows which are used by the layout. + /// + private int LayoutRows + { + get + { + var layoutRows = 0; + + if ((NavigationBarVisibility == ENavigationBarVisibility.always) | + (NavigationBarVisibility == ENavigationBarVisibility.auto)) + { + layoutRows += 2; + } + + if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) + { + layoutRows++; + } + + if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) + { + layoutRows++; + } + + return layoutRows; + } + } + + /// + /// Returns the number of item rows per page. + /// + public int ItemRowsPerPage => MaximumRow - LayoutRows; + + /// + /// Return the number of pages. + /// + public int PageCount + { + get + { + if (DataSource.RowCount == 0) + { + return 1; + } + + //var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null); + + var max = DataSource.CalculateMax(EnableSearch ? SearchQuery : null); + + //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") + //{ + // bf = bf.FilterDuplicate(this.SearchQuery); + //} + + if (max == 0) + { + return 1; + } + + return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage); + } + } + + + public event AsyncEventHandler ButtonClicked + { + add => _events.AddHandler(EvButtonClicked, value); + remove => _events.RemoveHandler(EvButtonClicked, value); + } + + public async Task OnButtonClicked(ButtonClickedEventArgs e) + { + var handler = _events[EvButtonClicked]?.GetInvocationList() + .Cast>(); + if (handler == null) + { + return; + } + + foreach (var h in handler) + { + await h.InvokeAllAsync(this, e); + } + } + + public override void Init() + { + Device.MessageDeleted += Device_MessageDeleted; + } + + private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e) + { + if (MessageId == null) + { + return; + } + + if (e.MessageId != MessageId) + { + return; + } + + MessageId = null; + } + + public override async Task Load(MessageResult result) + { + if (KeyboardType != EKeyboardType.ReplyKeyboard) + { + return; + } + + if (!result.IsFirstHandler) + { + return; + } + + if (result.MessageText == null || result.MessageText == "") + { + return; + } + + var matches = new List(); + ButtonRow match = null; + var index = -1; + + if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + { + match = HeadLayoutButtonRow; + goto check; + } + + if (SubHeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + { + match = SubHeadLayoutButtonRow; + goto check; + } + + var br = DataSource.FindRow(result.MessageText); + if (br != null) + { + match = br.Item1; + index = br.Item2; + } + //var button = HeadLayoutButtonRow?. .FirstOrDefault(a => a.Text.Trim() == result.MessageText) // ?? SubHeadLayoutButtonRow?.FirstOrDefault(a => a.Text.Trim() == result.MessageText); @@ -227,98 +358,106 @@ namespace TelegramBotBase.Controls.Hybrid check: - //Remove button click message - if (DeleteReplyMessage) - await Device.DeleteMessage(result.MessageId); - - if (match != null) - { - await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.MessageText), index, match)); - - result.Handled = true; - return; - } - - - if (result.MessageText == PreviousPageLabel) - { - if (CurrentPageIndex > 0) - CurrentPageIndex--; - - Updated(); - } - else if (result.MessageText == NextPageLabel) - { - if (CurrentPageIndex < PageCount - 1) - CurrentPageIndex++; - - Updated(); - } - else if (EnableSearch) - { - if (result.MessageText.StartsWith("🔍")) - { - //Sent note about searching - if (SearchQuery == null) - { - await Device.Send(SearchLabel); - } - - SearchQuery = null; - Updated(); - return; - } - - SearchQuery = result.MessageText; - - if (SearchQuery != null && SearchQuery != "") - { - CurrentPageIndex = 0; - Updated(); - } - - } - - - + //Remove button click message + if (DeleteReplyMessage) + { + await Device.DeleteMessage(result.MessageId); } - public override async Task Action(MessageResult result, string value = null) + if (match != null) { - if (result.Handled) - return; + await OnButtonClicked( + new ButtonClickedEventArgs(match.GetButtonMatch(result.MessageText), index, match)); - if (!result.IsFirstHandler) - return; + result.Handled = true; + return; + } - //Find clicked button depending on Text or Value (depending on markup type) - if (KeyboardType != EKeyboardType.InlineKeyBoard) - return; - await result.ConfirmAction(ConfirmationText ?? ""); - - ButtonRow match = null; - var index = -1; - - if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) + if (result.MessageText == PreviousPageLabel) + { + if (CurrentPageIndex > 0) { - match = HeadLayoutButtonRow; - goto check; + CurrentPageIndex--; } - if (SubHeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) + Updated(); + } + else if (result.MessageText == NextPageLabel) + { + if (CurrentPageIndex < PageCount - 1) { - match = SubHeadLayoutButtonRow; - goto check; + CurrentPageIndex++; } - var br = DataSource.FindRow(result.RawData, false); - if (br != null) + Updated(); + } + else if (EnableSearch) + { + if (result.MessageText.StartsWith("🔍")) { - match = br.Item1; - index = br.Item2; + //Sent note about searching + if (SearchQuery == null) + { + await Device.Send(SearchLabel); + } + + SearchQuery = null; + Updated(); + return; } + SearchQuery = result.MessageText; + + if (SearchQuery != null && SearchQuery != "") + { + CurrentPageIndex = 0; + Updated(); + } + } + } + + public override async Task Action(MessageResult result, string value = null) + { + if (result.Handled) + { + return; + } + + if (!result.IsFirstHandler) + { + return; + } + + //Find clicked button depending on Text or Value (depending on markup type) + if (KeyboardType != EKeyboardType.InlineKeyBoard) + { + return; + } + + await result.ConfirmAction(ConfirmationText ?? ""); + + ButtonRow match = null; + var index = -1; + + if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) + { + match = HeadLayoutButtonRow; + goto check; + } + + if (SubHeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) + { + match = SubHeadLayoutButtonRow; + goto check; + } + + var br = DataSource.FindRow(result.RawData, false); + if (br != null) + { + match = br.Item1; + index = br.Item2; + } //var bf = DataSource.ButtonForm; @@ -330,378 +469,281 @@ namespace TelegramBotBase.Controls.Hybrid //var index = bf.FindRowByButton(button); check: - if (match != null) - { - await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.RawData, false), index, match)); - - result.Handled = true; - return; - } - - switch (result.RawData) - { - case "$previous$": - - if (CurrentPageIndex > 0) - CurrentPageIndex--; - - Updated(); - - break; - case "$next$": - - if (CurrentPageIndex < PageCount - 1) - CurrentPageIndex++; - - Updated(); - - break; - } + if (match != null) + { + await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.RawData, false), index, + match)); + result.Handled = true; + return; } - /// - /// This method checks of the amount of buttons - /// - private void CheckGrid() + switch (result.RawData) { - switch (_mEKeyboardType) - { - case EKeyboardType.InlineKeyBoard: + case "$previous$": - if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging) - { - throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; - } - - if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols) - { - throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; - } - - break; - - case EKeyboardType.ReplyKeyboard: - - if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging) - { - throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows }; - } - - if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols) - { - throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols }; - } - - break; - } - } - - public override async Task Render(MessageResult result) - { - if (!_renderNecessary) - return; - - //Check for rows and column limits - CheckGrid(); - - _renderNecessary = false; - - var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (EnableSearch ? SearchQuery : null)); - - - //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") - //{ - // form = form.FilterDuplicate(this.SearchQuery, true); - //} - //else - //{ - // form = form.Duplicate(); - //} - - if (EnablePaging) - { - IntegratePagingView(form); - } - - if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) - { - form.InsertButtonRow(0, HeadLayoutButtonRow); - } - - if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) - { - if (IsNavigationBarVisible) + if (CurrentPageIndex > 0) { - form.InsertButtonRow(2, SubHeadLayoutButtonRow); + CurrentPageIndex--; } - else + + Updated(); + + break; + case "$next$": + + if (CurrentPageIndex < PageCount - 1) { - form.InsertButtonRow(1, SubHeadLayoutButtonRow); + CurrentPageIndex++; } - } - Message m = null; + Updated(); - switch (KeyboardType) - { - //Reply Keyboard could only be updated with a new keyboard. - case EKeyboardType.ReplyKeyboard: + break; + } + } + /// + /// This method checks of the amount of buttons + /// + private void CheckGrid() + { + switch (_mEKeyboardType) + { + case EKeyboardType.InlineKeyBoard: - if (form.Count == 0) - { - if (MessageId != null) - { - await Device.HideReplyKeyboard(); - MessageId = null; - } + if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging) + { + throw new MaximumRowsReachedException + { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; + } - return; - } + if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols) + { + throw new MaximumColsException + { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; + } - //if (this.MessageId != null) - //{ - // if (form.Count == 0) - // { - // await this.Device.HideReplyKeyboard(); - // this.MessageId = null; - // return; - // } - //} + break; - //if (form.Count == 0) - // return; + case EKeyboardType.ReplyKeyboard: + if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging) + { + throw new MaximumRowsReachedException + { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows }; + } - var rkm = (ReplyKeyboardMarkup)form; - rkm.ResizeKeyboard = ResizeKeyboard; - rkm.OneTimeKeyboard = OneTimeKeyboard; - m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); - - //Prevent flicker of keyboard - if (DeletePreviousMessage && MessageId != null) - await Device.DeleteMessage(MessageId.Value); - - break; - - case EKeyboardType.InlineKeyBoard: - - //Try to edit message if message id is available - //When the returned message is null then the message has been already deleted, resend it - if (MessageId != null) - { - m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form); - if (m != null) - { - MessageId = m.MessageId; - return; - } - } - - //When no message id is available or it has been deleted due the use of AutoCleanForm re-render automatically - m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); - - break; - } - - if (m != null) - { - MessageId = m.MessageId; - } + if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols) + { + throw new MaximumColsException + { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols }; + } + break; + } + } + public override async Task Render(MessageResult result) + { + if (!_renderNecessary) + { + return; } - private void IntegratePagingView(ButtonForm dataForm) - { - //No Items - if (dataForm.Rows == 0) - { - dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$")); - } + //Check for rows and column limits + CheckGrid(); + _renderNecessary = false; + + var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, + EnableSearch ? SearchQuery : null); + + + //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") + //{ + // form = form.FilterDuplicate(this.SearchQuery, true); + //} + //else + //{ + // form = form.Duplicate(); + //} + + if (EnablePaging) + { + IntegratePagingView(form); + } + + if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) + { + form.InsertButtonRow(0, HeadLayoutButtonRow); + } + + if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) + { if (IsNavigationBarVisible) { - //🔍 - var row = new ButtonRow(); - row.Add(new ButtonBase(PreviousPageLabel, "$previous$")); - row.Add(new ButtonBase(string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), "$site$")); - row.Add(new ButtonBase(NextPageLabel, "$next$")); - - if (EnableSearch) - { - row.Insert(2, new ButtonBase("🔍 " + (SearchQuery ?? ""), "$search$")); - } - - dataForm.InsertButtonRow(0, row); - - dataForm.AddButtonRow(row); - } - } - - public bool PagingNecessary - { - get - { - if (KeyboardType == EKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) - { - return true; - } - - if (KeyboardType == EKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows) - { - return true; - } - - return false; - } - } - - public bool IsNavigationBarVisible - { - get - { - if (NavigationBarVisibility == ENavigationBarVisibility.always | (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary)) - { - return true; - } - - return false; - } - } - - /// - /// Returns the maximum number of rows - /// - public int MaximumRow - { - get - { - return KeyboardType switch - { - EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows, - EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows, - _ => 0 - }; - } - } - - /// - /// Returns the number of all rows (layout + navigation + content); - /// - public int TotalRows => LayoutRows + DataSource.RowCount; - - - /// - /// Contains the Number of Rows which are used by the layout. - /// - private int LayoutRows - { - get - { - var layoutRows = 0; - - if (NavigationBarVisibility == ENavigationBarVisibility.always | NavigationBarVisibility == ENavigationBarVisibility.auto) - layoutRows += 2; - - if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) - layoutRows++; - - if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) - layoutRows++; - - return layoutRows; - } - } - - /// - /// Returns the number of item rows per page. - /// - public int ItemRowsPerPage => MaximumRow - LayoutRows; - - /// - /// Return the number of pages. - /// - public int PageCount - { - get - { - if (DataSource.RowCount == 0) - return 1; - - //var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null); - - var max = DataSource.CalculateMax(EnableSearch ? SearchQuery : null); - - //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") - //{ - // bf = bf.FilterDuplicate(this.SearchQuery); - //} - - if (max == 0) - return 1; - - return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage); - } - } - - public override Task Hidden(bool formClose) - { - //Prepare for opening Modal, and comming back - if (!formClose) - { - Updated(); + form.InsertButtonRow(2, SubHeadLayoutButtonRow); } else { - //Remove event handler - Device.MessageDeleted -= Device_MessageDeleted; + form.InsertButtonRow(1, SubHeadLayoutButtonRow); } - - return Task.CompletedTask; } - /// - /// Tells the control that it has been updated. - /// - public void Updated() + Message m = null; + + switch (KeyboardType) { - _renderNecessary = true; - } + //Reply Keyboard could only be updated with a new keyboard. + case EKeyboardType.ReplyKeyboard: - public override async Task Cleanup() - { - if (MessageId == null) - return; - switch (KeyboardType) - { - case EKeyboardType.InlineKeyBoard: - - await Device.DeleteMessage(MessageId.Value); - - MessageId = null; - - break; - case EKeyboardType.ReplyKeyboard: - - if (HideKeyboardOnCleanup) + if (form.Count == 0) + { + if (MessageId != null) { await Device.HideReplyKeyboard(); + MessageId = null; } - MessageId = null; + return; + } - break; - } + //if (this.MessageId != null) + //{ + // if (form.Count == 0) + // { + // await this.Device.HideReplyKeyboard(); + // this.MessageId = null; + // return; + // } + //} + + //if (form.Count == 0) + // return; + var rkm = (ReplyKeyboardMarkup)form; + rkm.ResizeKeyboard = ResizeKeyboard; + rkm.OneTimeKeyboard = OneTimeKeyboard; + m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, + markdownV2AutoEscape: false); + //Prevent flicker of keyboard + if (DeletePreviousMessage && MessageId != null) + { + await Device.DeleteMessage(MessageId.Value); + } + break; + + case EKeyboardType.InlineKeyBoard: + + //Try to edit message if message id is available + //When the returned message is null then the message has been already deleted, resend it + if (MessageId != null) + { + m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form); + if (m != null) + { + MessageId = m.MessageId; + return; + } + } + + //When no message id is available or it has been deleted due the use of AutoCleanForm re-render automatically + m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, + parseMode: MessageParseMode, markdownV2AutoEscape: false); + + break; } + if (m != null) + { + MessageId = m.MessageId; + } } + private void IntegratePagingView(ButtonForm dataForm) + { + //No Items + if (dataForm.Rows == 0) + { + dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$")); + } -} + if (IsNavigationBarVisible) + { + //🔍 + var row = new ButtonRow(); + row.Add(new ButtonBase(PreviousPageLabel, "$previous$")); + row.Add(new ButtonBase( + string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), + "$site$")); + row.Add(new ButtonBase(NextPageLabel, "$next$")); + + if (EnableSearch) + { + row.Insert(2, new ButtonBase("🔍 " + (SearchQuery ?? ""), "$search$")); + } + + dataForm.InsertButtonRow(0, row); + + dataForm.AddButtonRow(row); + } + } + + public override Task Hidden(bool formClose) + { + //Prepare for opening Modal, and comming back + if (!formClose) + { + Updated(); + } + else + //Remove event handler + { + Device.MessageDeleted -= Device_MessageDeleted; + } + + return Task.CompletedTask; + } + + /// + /// Tells the control that it has been updated. + /// + public void Updated() + { + _renderNecessary = true; + } + + public override async Task Cleanup() + { + if (MessageId == null) + { + return; + } + + switch (KeyboardType) + { + case EKeyboardType.InlineKeyBoard: + + await Device.DeleteMessage(MessageId.Value); + + MessageId = null; + + break; + case EKeyboardType.ReplyKeyboard: + + if (HideKeyboardOnCleanup) + { + await Device.HideReplyKeyboard(); + } + + MessageId = null; + + break; + } + } +} \ No newline at end of file diff --git a/TelegramBotBase/Controls/Hybrid/ButtonRow.cs b/TelegramBotBase/Controls/Hybrid/ButtonRow.cs index c2ba68f..fbf6dee 100644 --- a/TelegramBotBase/Controls/Hybrid/ButtonRow.cs +++ b/TelegramBotBase/Controls/Hybrid/ButtonRow.cs @@ -4,93 +4,101 @@ using System.Diagnostics; using System.Linq; using TelegramBotBase.Form; -namespace TelegramBotBase.Controls.Hybrid +namespace TelegramBotBase.Controls.Hybrid; + +[DebuggerDisplay("{Count} columns")] +public class ButtonRow { - [DebuggerDisplay("{Count} columns")] - public class ButtonRow + private List _buttons = new(); + + public ButtonRow() { - private List _buttons = new List(); - - public ButtonRow() - { - - - } - - public ButtonRow(params ButtonBase[] buttons) - { - _buttons = buttons.ToList(); - } - - - public ButtonBase this[int index] => _buttons[index]; - - public int Count => _buttons.Count; - - public void Add(ButtonBase button) - { - _buttons.Add(button); - } - - public void AddRange(ButtonBase button) - { - _buttons.Add(button); - } - - public void Insert(int index, ButtonBase button) - { - _buttons.Insert(index, button); - } - - public IEnumerator GetEnumerator() - { - return _buttons.GetEnumerator(); - } - - public ButtonBase[] ToArray() - { - return _buttons.ToArray(); - } - - public List ToList() - { - return _buttons.ToList(); - } - - public bool Matches(string text, bool useText = true) - { - foreach (var b in _buttons) - { - if (useText && b.Text.Trim().Equals(text, StringComparison.InvariantCultureIgnoreCase)) - return true; - - if (!useText && b.Value.Equals(text, StringComparison.InvariantCultureIgnoreCase)) - return true; - } - return false; - } - - /// - /// Returns the button inside of the row which matches. - /// - /// - /// - /// - public ButtonBase GetButtonMatch(string text, bool useText = true) - { - foreach (var b in _buttons) - { - if (useText && b.Text.Trim().Equals(text, StringComparison.InvariantCultureIgnoreCase)) - return b; - if (!useText && b.Value.Equals(text, StringComparison.InvariantCultureIgnoreCase)) - return b; - } - return null; - } - - public static implicit operator ButtonRow(List list) - { - return new ButtonRow { _buttons = list }; - } } -} + + public ButtonRow(params ButtonBase[] buttons) + { + _buttons = buttons.ToList(); + } + + + public ButtonBase this[int index] => _buttons[index]; + + public int Count => _buttons.Count; + + public void Add(ButtonBase button) + { + _buttons.Add(button); + } + + public void AddRange(ButtonBase button) + { + _buttons.Add(button); + } + + public void Insert(int index, ButtonBase button) + { + _buttons.Insert(index, button); + } + + public IEnumerator GetEnumerator() + { + return _buttons.GetEnumerator(); + } + + public ButtonBase[] ToArray() + { + return _buttons.ToArray(); + } + + public List ToList() + { + return _buttons.ToList(); + } + + public bool Matches(string text, bool useText = true) + { + foreach (var b in _buttons) + { + if (useText && b.Text.Trim().Equals(text, StringComparison.InvariantCultureIgnoreCase)) + { + return true; + } + + if (!useText && b.Value.Equals(text, StringComparison.InvariantCultureIgnoreCase)) + { + return true; + } + } + + return false; + } + + /// + /// Returns the button inside of the row which matches. + /// + /// + /// + /// + public ButtonBase GetButtonMatch(string text, bool useText = true) + { + foreach (var b in _buttons) + { + if (useText && b.Text.Trim().Equals(text, StringComparison.InvariantCultureIgnoreCase)) + { + return b; + } + + if (!useText && b.Value.Equals(text, StringComparison.InvariantCultureIgnoreCase)) + { + return b; + } + } + + return null; + } + + public static implicit operator ButtonRow(List list) + { + return new ButtonRow { _buttons = list }; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Controls/Hybrid/CheckedButtonList.cs b/TelegramBotBase/Controls/Hybrid/CheckedButtonList.cs index 5da90dc..6e49ebe 100644 --- a/TelegramBotBase/Controls/Hybrid/CheckedButtonList.cs +++ b/TelegramBotBase/Controls/Hybrid/CheckedButtonList.cs @@ -15,215 +15,357 @@ using TelegramBotBase.Form; using TelegramBotBase.Localizations; using static TelegramBotBase.Base.Async; -namespace TelegramBotBase.Controls.Hybrid +namespace TelegramBotBase.Controls.Hybrid; + +public class CheckedButtonList : ControlBase { - public class CheckedButtonList : ControlBase + private static readonly object EvButtonClicked = new(); + + private static readonly object EvCheckedChanged = new(); + + private readonly EventHandlerList _events = new(); + + private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard; + + private bool _renderNecessary = true; + + public string NextPageLabel = Default.Language["ButtonGrid_NextPage"]; + + public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"]; + + public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"]; + + public CheckedButtonList() { + DataSource = new ButtonFormDataSource(); + } - public string Title { get; set; } = Default.Language["ButtonGrid_Title"]; + public CheckedButtonList(EKeyboardType type) : this() + { + _mEKeyboardType = type; + } - public string ConfirmationText { get; set; } = ""; - private bool _renderNecessary = true; + public CheckedButtonList(ButtonForm form) + { + DataSource = new ButtonFormDataSource(form); + } - private static readonly object EvButtonClicked = new object(); + public string Title { get; set; } = Default.Language["ButtonGrid_Title"]; - private static readonly object EvCheckedChanged = new object(); + public string ConfirmationText { get; set; } = ""; - private readonly EventHandlerList _events = new EventHandlerList(); + [Obsolete("This property is obsolete. Please use the DataSource property instead.")] + public ButtonForm ButtonsForm + { + get => DataSource.ButtonForm; + set => DataSource = new ButtonFormDataSource(value); + } - [Obsolete("This property is obsolete. Please use the DataSource property instead.")] - public ButtonForm ButtonsForm + /// + /// Data source of the items. + /// + public ButtonFormDataSource DataSource { get; set; } + + private List CheckedRows { get; } = new(); + + public int? MessageId { get; set; } + + + /// + /// Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if + /// there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same + /// height as the app's standard keyboard. + /// Source: https://core.telegram.org/bots/api#replykeyboardmarkup + /// + public bool ResizeKeyboard { get; set; } = false; + + public bool OneTimeKeyboard { get; set; } = false; + + public bool HideKeyboardOnCleanup { get; set; } = true; + + public bool DeletePreviousMessage { get; set; } = true; + + /// + /// Removes the reply message from a user. + /// + public bool DeleteReplyMessage { get; set; } = true; + + /// + /// Parsemode of the message. + /// + public ParseMode MessageParseMode { get; set; } = ParseMode.Markdown; + + /// + /// Enables automatic paging of buttons when the amount of rows is exceeding the limits. + /// + public bool EnablePaging { get; set; } = false; + + + ///// + ///// Enabled a search function. + ///// + //public bool EnableSearch { get; set; } = false; + + //public String SearchQuery { get; set; } + + public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always; + + + /// + /// Index of the current page + /// + public int CurrentPageIndex { get; set; } + + //public String SearchLabel = Localizations.Default.Language["ButtonGrid_SearchFeature"]; + + public string CheckedIconLabel { get; set; } = "✅"; + + public string UncheckedIconLabel { get; set; } = "◻️"; + + /// + /// Layout of the buttons which should be displayed always on top. + /// + public ButtonRow HeadLayoutButtonRow { get; set; } + + /// + /// Layout of columns which should be displayed below the header + /// + public ButtonRow SubHeadLayoutButtonRow { get; set; } + + /// + /// Defines which type of Button Keyboard should be rendered. + /// + public EKeyboardType KeyboardType + { + get => _mEKeyboardType; + set { - get => DataSource.ButtonForm; - set => DataSource = new ButtonFormDataSource(value); - } - - /// - /// Data source of the items. - /// - public ButtonFormDataSource DataSource { get; set; } - - private List CheckedRows { get; set; } = new List(); - - public int? MessageId { get; set; } - - - /// - /// Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard. - /// Source: https://core.telegram.org/bots/api#replykeyboardmarkup - /// - public bool ResizeKeyboard { get; set; } = false; - - public bool OneTimeKeyboard { get; set; } = false; - - public bool HideKeyboardOnCleanup { get; set; } = true; - - public bool DeletePreviousMessage { get; set; } = true; - - /// - /// Removes the reply message from a user. - /// - public bool DeleteReplyMessage { get; set; } = true; - - /// - /// Parsemode of the message. - /// - public ParseMode MessageParseMode { get; set; } = ParseMode.Markdown; - - /// - /// Enables automatic paging of buttons when the amount of rows is exceeding the limits. - /// - public bool EnablePaging { get; set; } = false; - - - ///// - ///// Enabled a search function. - ///// - //public bool EnableSearch { get; set; } = false; - - //public String SearchQuery { get; set; } - - public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always; - - - /// - /// Index of the current page - /// - public int CurrentPageIndex { get; set; } - - public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"]; - - public string NextPageLabel = Default.Language["ButtonGrid_NextPage"]; - - public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"]; - - //public String SearchLabel = Localizations.Default.Language["ButtonGrid_SearchFeature"]; - - public string CheckedIconLabel { get; set; } = "✅"; - - public string UncheckedIconLabel { get; set; } = "◻️"; - - /// - /// Layout of the buttons which should be displayed always on top. - /// - public ButtonRow HeadLayoutButtonRow { get; set; } - - /// - /// Layout of columns which should be displayed below the header - /// - public ButtonRow SubHeadLayoutButtonRow { get; set; } - - /// - /// Defines which type of Button Keyboard should be rendered. - /// - public EKeyboardType KeyboardType - { - get => _mEKeyboardType; - set + if (_mEKeyboardType != value) { - if (_mEKeyboardType != value) - { - _renderNecessary = true; + _renderNecessary = true; - Cleanup().Wait(); - - _mEKeyboardType = value; - } + Cleanup().Wait(); + _mEKeyboardType = value; } } + } - private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard; - - public CheckedButtonList() + public bool PagingNecessary + { + get { - DataSource = new ButtonFormDataSource(); - - - } - - public CheckedButtonList(EKeyboardType type) : this() - { - _mEKeyboardType = type; - } - - - public CheckedButtonList(ButtonForm form) - { - DataSource = new ButtonFormDataSource(form); - } - - public event AsyncEventHandler ButtonClicked - { - add => _events.AddHandler(EvButtonClicked, value); - remove => _events.RemoveHandler(EvButtonClicked, value); - } - - public async Task OnButtonClicked(ButtonClickedEventArgs e) - { - var handler = _events[EvButtonClicked]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) + if (KeyboardType == EKeyboardType.InlineKeyBoard && + TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) { - await h.InvokeAllAsync(this, e); - } - } - - public event AsyncEventHandler CheckedChanged - { - add => _events.AddHandler(EvCheckedChanged, value); - remove => _events.RemoveHandler(EvCheckedChanged, value); - } - - public async Task OnCheckedChanged(CheckedChangedEventArgs e) - { - var handler = _events[EvCheckedChanged]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) - { - await h.InvokeAllAsync(this, e); - } - } - - public override async Task Load(MessageResult result) - { - if (KeyboardType != EKeyboardType.ReplyKeyboard) - return; - - if (!result.IsFirstHandler) - return; - - if (result.MessageText == null || result.MessageText == "") - return; - - var matches = new List(); - ButtonRow match = null; - var index = -1; - - if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false) - { - match = HeadLayoutButtonRow; - goto check; + return true; } - if (SubHeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + if (KeyboardType == EKeyboardType.ReplyKeyboard && + TotalRows > Constants.Telegram.MaxReplyKeyboardRows) { - match = SubHeadLayoutButtonRow; - goto check; + return true; } - var br = DataSource.FindRow(result.MessageText); - if (br != null) + return false; + } + } + + public bool IsNavigationBarVisible + { + get + { + if ((NavigationBarVisibility == ENavigationBarVisibility.always) | + (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary)) { - match = br.Item1; - index = br.Item2; + return true; } + return false; + } + } + + /// + /// Returns the maximum number of rows + /// + public int MaximumRow + { + get + { + return KeyboardType switch + { + EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows, + EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows, + _ => 0 + }; + } + } + + /// + /// Returns the number of all rows (layout + navigation + content); + /// + public int TotalRows => LayoutRows + DataSource.RowCount; + + + /// + /// Contains the Number of Rows which are used by the layout. + /// + private int LayoutRows + { + get + { + var layoutRows = 0; + + if ((NavigationBarVisibility == ENavigationBarVisibility.always) | + (NavigationBarVisibility == ENavigationBarVisibility.auto)) + { + layoutRows += 2; + } + + if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) + { + layoutRows++; + } + + if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) + { + layoutRows++; + } + + return layoutRows; + } + } + + /// + /// Returns the number of item rows per page. + /// + public int ItemRowsPerPage => MaximumRow - LayoutRows; + + public int PageCount + { + get + { + if (DataSource.RowCount == 0) + { + return 1; + } + + //var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null); + + var max = DataSource.RowCount; + + //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") + //{ + // bf = bf.FilterDuplicate(this.SearchQuery); + //} + + if (max == 0) + { + return 1; + } + + return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage); + } + } + + public List CheckedItems + { + get + { + var lst = new List(); + + foreach (var c in CheckedRows) + { + lst.Add(ButtonsForm[c][0]); + } + + return lst; + } + } + + public event AsyncEventHandler ButtonClicked + { + add => _events.AddHandler(EvButtonClicked, value); + remove => _events.RemoveHandler(EvButtonClicked, value); + } + + public async Task OnButtonClicked(ButtonClickedEventArgs e) + { + var handler = _events[EvButtonClicked]?.GetInvocationList() + .Cast>(); + if (handler == null) + { + return; + } + + foreach (var h in handler) + { + await h.InvokeAllAsync(this, e); + } + } + + public event AsyncEventHandler CheckedChanged + { + add => _events.AddHandler(EvCheckedChanged, value); + remove => _events.RemoveHandler(EvCheckedChanged, value); + } + + public async Task OnCheckedChanged(CheckedChangedEventArgs e) + { + var handler = _events[EvCheckedChanged]?.GetInvocationList() + .Cast>(); + if (handler == null) + { + return; + } + + foreach (var h in handler) + { + await h.InvokeAllAsync(this, e); + } + } + + public override async Task Load(MessageResult result) + { + if (KeyboardType != EKeyboardType.ReplyKeyboard) + { + return; + } + + if (!result.IsFirstHandler) + { + return; + } + + if (result.MessageText == null || result.MessageText == "") + { + return; + } + + var matches = new List(); + ButtonRow match = null; + var index = -1; + + if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + { + match = HeadLayoutButtonRow; + goto check; + } + + if (SubHeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + { + match = SubHeadLayoutButtonRow; + goto check; + } + + var br = DataSource.FindRow(result.MessageText); + if (br != null) + { + match = br.Item1; + index = br.Item2; + } + //var button = HeadLayoutButtonRow?. .FirstOrDefault(a => a.Text.Trim() == result.MessageText) // ?? SubHeadLayoutButtonRow?.FirstOrDefault(a => a.Text.Trim() == result.MessageText); @@ -233,142 +375,152 @@ namespace TelegramBotBase.Controls.Hybrid //var index = bf.FindRowByButton(button); - check: - //Remove button click message - if (DeleteReplyMessage) - await Device.DeleteMessage(result.MessageId); - - if (match == null) - { - if (result.MessageText == PreviousPageLabel) - { - if (CurrentPageIndex > 0) - CurrentPageIndex--; - - Updated(); - } - else if (result.MessageText == NextPageLabel) - { - if (CurrentPageIndex < PageCount - 1) - CurrentPageIndex++; - - Updated(); - } - else if (result.MessageText.EndsWith(CheckedIconLabel)) - { - var s = result.MessageText.Split(' ', '.'); - index = int.Parse(s[0]) - 1; - - if (!CheckedRows.Contains(index)) - return; - - CheckedRows.Remove(index); - - Updated(); - - await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, false)); - - } - else if (result.MessageText.EndsWith(UncheckedIconLabel)) - { - var s = result.MessageText.Split(' ', '.'); - index = int.Parse(s[0]) - 1; - - if (CheckedRows.Contains(index)) - return; - - - CheckedRows.Add(index); - - Updated(); - - await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, true)); - - } - //else if (this.EnableSearch) - //{ - // if (result.MessageText.StartsWith("🔍")) - // { - // //Sent note about searching - // if (this.SearchQuery == null) - // { - // await this.Device.Send(this.SearchLabel); - // } - - // this.SearchQuery = null; - // this.Updated(); - // return; - // } - - // this.SearchQuery = result.MessageText; - - // if (this.SearchQuery != null && this.SearchQuery != "") - // { - // this.CurrentPageIndex = 0; - // this.Updated(); - // } - - //} - - - - return; - } - - - await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.MessageText), index, match)); - - result.Handled = true; - - //await OnButtonClicked(new ButtonClickedEventArgs(button, index)); - - ////Remove button click message - //if (this.DeletePreviousMessage) - // await Device.DeleteMessage(result.MessageId); - - //result.Handled = true; - + //Remove button click message + if (DeleteReplyMessage) + { + await Device.DeleteMessage(result.MessageId); } - public override async Task Action(MessageResult result, string value = null) + if (match == null) { - if (result.Handled) - return; - - if (!result.IsFirstHandler) - return; - - //Find clicked button depending on Text or Value (depending on markup type) - if (KeyboardType != EKeyboardType.InlineKeyBoard) - return; - - await result.ConfirmAction(ConfirmationText ?? ""); - - ButtonRow match = null; - var index = -1; - - if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) + if (result.MessageText == PreviousPageLabel) { - match = HeadLayoutButtonRow; - goto check; - } + if (CurrentPageIndex > 0) + { + CurrentPageIndex--; + } - if (SubHeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) + Updated(); + } + else if (result.MessageText == NextPageLabel) { - match = SubHeadLayoutButtonRow; - goto check; - } + if (CurrentPageIndex < PageCount - 1) + { + CurrentPageIndex++; + } - var br = DataSource.FindRow(result.RawData, false); - if (br != null) + Updated(); + } + else if (result.MessageText.EndsWith(CheckedIconLabel)) { - match = br.Item1; - index = br.Item2; - } + var s = result.MessageText.Split(' ', '.'); + index = int.Parse(s[0]) - 1; + if (!CheckedRows.Contains(index)) + { + return; + } + + CheckedRows.Remove(index); + + Updated(); + + await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, false)); + } + else if (result.MessageText.EndsWith(UncheckedIconLabel)) + { + var s = result.MessageText.Split(' ', '.'); + index = int.Parse(s[0]) - 1; + + if (CheckedRows.Contains(index)) + { + return; + } + + + CheckedRows.Add(index); + + Updated(); + + await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, true)); + } + //else if (this.EnableSearch) + //{ + // if (result.MessageText.StartsWith("🔍")) + // { + // //Sent note about searching + // if (this.SearchQuery == null) + // { + // await this.Device.Send(this.SearchLabel); + // } + + // this.SearchQuery = null; + // this.Updated(); + // return; + // } + + // this.SearchQuery = result.MessageText; + + // if (this.SearchQuery != null && this.SearchQuery != "") + // { + // this.CurrentPageIndex = 0; + // this.Updated(); + // } + + //} + + + return; + } + + + await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.MessageText), index, match)); + + result.Handled = true; + + //await OnButtonClicked(new ButtonClickedEventArgs(button, index)); + + ////Remove button click message + //if (this.DeletePreviousMessage) + // await Device.DeleteMessage(result.MessageId); + + //result.Handled = true; + } + + public override async Task Action(MessageResult result, string value = null) + { + if (result.Handled) + { + return; + } + + if (!result.IsFirstHandler) + { + return; + } + + //Find clicked button depending on Text or Value (depending on markup type) + if (KeyboardType != EKeyboardType.InlineKeyBoard) + { + return; + } + + await result.ConfirmAction(ConfirmationText ?? ""); + + ButtonRow match = null; + var index = -1; + + if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) + { + match = HeadLayoutButtonRow; + goto check; + } + + if (SubHeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) + { + match = SubHeadLayoutButtonRow; + goto check; + } + + var br = DataSource.FindRow(result.RawData, false); + if (br != null) + { + match = br.Item1; + index = br.Item2; + } //var bf = DataSource.ButtonForm; @@ -380,458 +532,347 @@ namespace TelegramBotBase.Controls.Hybrid //var index = bf.FindRowByButton(button); check: - if (match != null) - { - await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.RawData, false), index, match)); - - result.Handled = true; - return; - } - - //if (button != null) - //{ - // await OnButtonClicked(new ButtonClickedEventArgs(button, index)); - - // result.Handled = true; - // return; - //} - - switch (result.RawData) - { - case "$previous$": - - if (CurrentPageIndex > 0) - CurrentPageIndex--; - - Updated(); - - break; - case "$next$": - - if (CurrentPageIndex < PageCount - 1) - CurrentPageIndex++; - - Updated(); - - break; - - default: - - var s = result.RawData.Split('$'); - - - switch (s[0]) - { - case "check": - - index = int.Parse(s[1]); - - if (!CheckedRows.Contains(index)) - { - CheckedRows.Add(index); - - Updated(); - - await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, true)); - } - - break; - - case "uncheck": - - index = int.Parse(s[1]); - - if (CheckedRows.Contains(index)) - { - CheckedRows.Remove(index); - - Updated(); - - await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, false)); - } - - break; - } - - - break; - - } + if (match != null) + { + await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.RawData, false), index, + match)); + result.Handled = true; + return; } - /// - /// This method checks of the amount of buttons - /// - private void CheckGrid() + //if (button != null) + //{ + // await OnButtonClicked(new ButtonClickedEventArgs(button, index)); + + // result.Handled = true; + // return; + //} + + switch (result.RawData) { - switch (_mEKeyboardType) - { - case EKeyboardType.InlineKeyBoard: + case "$previous$": - if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging) - { - throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; - } + if (CurrentPageIndex > 0) + { + CurrentPageIndex--; + } - if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols) - { - throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; - } + Updated(); - break; + break; + case "$next$": - case EKeyboardType.ReplyKeyboard: + if (CurrentPageIndex < PageCount - 1) + { + CurrentPageIndex++; + } - if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging) - { - throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows }; - } + Updated(); - if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols) - { - throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols }; - } + break; - break; - } + default: + + var s = result.RawData.Split('$'); + + + switch (s[0]) + { + case "check": + + index = int.Parse(s[1]); + + if (!CheckedRows.Contains(index)) + { + CheckedRows.Add(index); + + Updated(); + + await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, true)); + } + + break; + + case "uncheck": + + index = int.Parse(s[1]); + + if (CheckedRows.Contains(index)) + { + CheckedRows.Remove(index); + + Updated(); + + await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, false)); + } + + break; + } + + + break; + } + } + + /// + /// This method checks of the amount of buttons + /// + private void CheckGrid() + { + switch (_mEKeyboardType) + { + case EKeyboardType.InlineKeyBoard: + + if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging) + { + throw new MaximumRowsReachedException + { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; + } + + if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols) + { + throw new MaximumColsException + { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; + } + + break; + + case EKeyboardType.ReplyKeyboard: + + if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging) + { + throw new MaximumRowsReachedException + { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows }; + } + + if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols) + { + throw new MaximumColsException + { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols }; + } + + break; + } + } + + public override async Task Render(MessageResult result) + { + if (!_renderNecessary) + { + return; } - public override async Task Render(MessageResult result) + //Check for rows and column limits + CheckGrid(); + + _renderNecessary = false; + + Message m = null; + + var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage); + + //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") + //{ + // form = form.FilterDuplicate(this.SearchQuery, true); + //} + //else + //{ + //form = form.Duplicate(); + //} + + if (EnablePaging) { - if (!_renderNecessary) - return; + IntegratePagingView(form); + } + else + { + form = PrepareCheckableLayout(form); + } - //Check for rows and column limits - CheckGrid(); + if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) + { + form.InsertButtonRow(0, HeadLayoutButtonRow.ToArray()); + } - _renderNecessary = false; - - Message m = null; - - var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage); - - //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") - //{ - // form = form.FilterDuplicate(this.SearchQuery, true); - //} - //else - //{ - //form = form.Duplicate(); - //} - - if (EnablePaging) + if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) + { + if (IsNavigationBarVisible) { - IntegratePagingView(form); + form.InsertButtonRow(2, SubHeadLayoutButtonRow.ToArray()); } else { - form = PrepareCheckableLayout(form); + form.InsertButtonRow(1, SubHeadLayoutButtonRow.ToArray()); } + } - if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) - { - form.InsertButtonRow(0, HeadLayoutButtonRow.ToArray()); - } + switch (KeyboardType) + { + //Reply Keyboard could only be updated with a new keyboard. + case EKeyboardType.ReplyKeyboard: - if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) - { - if (IsNavigationBarVisible) + if (form.Count == 0) { - form.InsertButtonRow(2, SubHeadLayoutButtonRow.ToArray()); - } - else - { - form.InsertButtonRow(1, SubHeadLayoutButtonRow.ToArray()); - } - } - - switch (KeyboardType) - { - //Reply Keyboard could only be updated with a new keyboard. - case EKeyboardType.ReplyKeyboard: - - if (form.Count == 0) - { - if (MessageId != null) - { - await Device.HideReplyKeyboard(); - MessageId = null; - } - - return; - } - - //if (form.Count == 0) - // return; - - - var rkm = (ReplyKeyboardMarkup)form; - rkm.ResizeKeyboard = ResizeKeyboard; - rkm.OneTimeKeyboard = OneTimeKeyboard; - m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); - - //Prevent flicker of keyboard - if (DeletePreviousMessage && MessageId != null) - await Device.DeleteMessage(MessageId.Value); - - break; - - case EKeyboardType.InlineKeyBoard: - if (MessageId != null) { - m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form); - } - else - { - m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); + await Device.HideReplyKeyboard(); + MessageId = null; } - break; - } - - if (m != null) - { - MessageId = m.MessageId; - } - - - } - - private void IntegratePagingView(ButtonForm dataForm) - { - //No Items - if (dataForm.Rows == 0) - { - dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$")); - } - - var bf = new ButtonForm(); - - bf = PrepareCheckableLayout(dataForm); - - - if (IsNavigationBarVisible) - { - //🔍 - var row = new ButtonRow(); - row.Add(new ButtonBase(PreviousPageLabel, "$previous$")); - row.Add(new ButtonBase(string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), "$site$")); - row.Add(new ButtonBase(NextPageLabel, "$next$")); - - - dataForm.InsertButtonRow(0, row); - - dataForm.AddButtonRow(row); - } - } - - private ButtonForm PrepareCheckableLayout(ButtonForm dataForm) - { - var bf = new ButtonForm(); - for (var i = 0; i < dataForm.Rows; i++) - { - var it = (CurrentPageIndex * (MaximumRow - LayoutRows)) + i; - - //if (it > dataForm.Rows - 1) - // break; - - var r = dataForm[i]; - - var s = CheckedRows.Contains(it) ? CheckedIconLabel : UncheckedIconLabel; - - //On reply keyboards we need a unique text. - if (KeyboardType == EKeyboardType.ReplyKeyboard) - { - s = $"{it + 1}. " + s; + return; } - if (CheckedRows.Contains(it)) + //if (form.Count == 0) + // return; + + + var rkm = (ReplyKeyboardMarkup)form; + rkm.ResizeKeyboard = ResizeKeyboard; + rkm.OneTimeKeyboard = OneTimeKeyboard; + m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, + markdownV2AutoEscape: false); + + //Prevent flicker of keyboard + if (DeletePreviousMessage && MessageId != null) { - r.Insert(0, new ButtonBase(s, "uncheck$" + it)); + await Device.DeleteMessage(MessageId.Value); + } + + break; + + case EKeyboardType.InlineKeyBoard: + + if (MessageId != null) + { + m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form); } else { - r.Insert(0, new ButtonBase(s, "check$" + it)); + m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, + parseMode: MessageParseMode, markdownV2AutoEscape: false); } - bf.AddButtonRow(r); - } - - return bf; + break; } - public bool PagingNecessary + if (m != null) { - get + MessageId = m.MessageId; + } + } + + private void IntegratePagingView(ButtonForm dataForm) + { + //No Items + if (dataForm.Rows == 0) + { + dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$")); + } + + var bf = new ButtonForm(); + + bf = PrepareCheckableLayout(dataForm); + + + if (IsNavigationBarVisible) + { + //🔍 + var row = new ButtonRow(); + row.Add(new ButtonBase(PreviousPageLabel, "$previous$")); + row.Add(new ButtonBase( + string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), + "$site$")); + row.Add(new ButtonBase(NextPageLabel, "$next$")); + + + dataForm.InsertButtonRow(0, row); + + dataForm.AddButtonRow(row); + } + } + + private ButtonForm PrepareCheckableLayout(ButtonForm dataForm) + { + var bf = new ButtonForm(); + for (var i = 0; i < dataForm.Rows; i++) + { + var it = CurrentPageIndex * (MaximumRow - LayoutRows) + i; + + //if (it > dataForm.Rows - 1) + // break; + + var r = dataForm[i]; + + var s = CheckedRows.Contains(it) ? CheckedIconLabel : UncheckedIconLabel; + + //On reply keyboards we need a unique text. + if (KeyboardType == EKeyboardType.ReplyKeyboard) { - if (KeyboardType == EKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) - { - return true; - } - - if (KeyboardType == EKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows) - { - return true; - } - - return false; + s = $"{it + 1}. " + s; } - } - public bool IsNavigationBarVisible - { - get + if (CheckedRows.Contains(it)) { - if (NavigationBarVisibility == ENavigationBarVisibility.always | (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary)) - { - return true; - } - - return false; + r.Insert(0, new ButtonBase(s, "uncheck$" + it)); } - } - - /// - /// Returns the maximum number of rows - /// - public int MaximumRow - { - get + else { - return KeyboardType switch - { - EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows, - EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows, - _ => 0 - }; - } - } - - /// - /// Returns the number of all rows (layout + navigation + content); - /// - public int TotalRows => LayoutRows + DataSource.RowCount; - - - /// - /// Contains the Number of Rows which are used by the layout. - /// - private int LayoutRows - { - get - { - var layoutRows = 0; - - if (NavigationBarVisibility == ENavigationBarVisibility.always | NavigationBarVisibility == ENavigationBarVisibility.auto) - layoutRows += 2; - - if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) - layoutRows++; - - if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) - layoutRows++; - - return layoutRows; - } - } - - /// - /// Returns the number of item rows per page. - /// - public int ItemRowsPerPage => MaximumRow - LayoutRows; - - public int PageCount - { - get - { - if (DataSource.RowCount == 0) - return 1; - - //var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null); - - var max = DataSource.RowCount; - - //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") - //{ - // bf = bf.FilterDuplicate(this.SearchQuery); - //} - - if (max == 0) - return 1; - - return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage); - } - } - - public override Task Hidden(bool formClose) - { - //Prepare for opening Modal, and comming back - if (!formClose) - { - Updated(); + r.Insert(0, new ButtonBase(s, "check$" + it)); } - return Task.CompletedTask; + bf.AddButtonRow(r); } - public List CheckedItems + return bf; + } + + public override Task Hidden(bool formClose) + { + //Prepare for opening Modal, and comming back + if (!formClose) { - get - { - var lst = new List(); - - foreach (var c in CheckedRows) - { - lst.Add(ButtonsForm[c][0]); - } - - return lst; - } - } - - - /// - /// Tells the control that it has been updated. - /// - public void Updated() - { - _renderNecessary = true; - } - - public override async Task Cleanup() - { - if (MessageId == null) - return; - - switch (KeyboardType) - { - case EKeyboardType.InlineKeyBoard: - - await Device.DeleteMessage(MessageId.Value); - - MessageId = null; - - break; - case EKeyboardType.ReplyKeyboard: - - if (HideKeyboardOnCleanup) - { - await Device.HideReplyKeyboard(); - } - - MessageId = null; - - break; - } - - - - + Updated(); } + return Task.CompletedTask; } + /// + /// Tells the control that it has been updated. + /// + public void Updated() + { + _renderNecessary = true; + } + + public override async Task Cleanup() + { + if (MessageId == null) + { + return; + } + + switch (KeyboardType) + { + case EKeyboardType.InlineKeyBoard: + + await Device.DeleteMessage(MessageId.Value); + + MessageId = null; + + break; + case EKeyboardType.ReplyKeyboard: + + if (HideKeyboardOnCleanup) + { + await Device.HideReplyKeyboard(); + } + + MessageId = null; + + break; + } + } } diff --git a/TelegramBotBase/Controls/Hybrid/MultiView.cs b/TelegramBotBase/Controls/Hybrid/MultiView.cs index 5008b73..2c8b98d 100644 --- a/TelegramBotBase/Controls/Hybrid/MultiView.cs +++ b/TelegramBotBase/Controls/Hybrid/MultiView.cs @@ -3,124 +3,125 @@ using System.Threading.Tasks; using TelegramBotBase.Args; using TelegramBotBase.Base; -namespace TelegramBotBase.Controls.Hybrid +namespace TelegramBotBase.Controls.Hybrid; + +/// +/// This Control is for having a basic form content switching control. +/// +public abstract class MultiView : ControlBase { + private int _mISelectedViewIndex; /// - /// This Control is for having a basic form content switching control. + /// Hold if the View has been rendered already. /// - public abstract class MultiView : ControlBase + private bool _rendered; + + + public MultiView() { - /// - /// Index of the current View. - /// - public int SelectedViewIndex - { - get => _mISelectedViewIndex; - set - { - _mISelectedViewIndex = value; - - //Already rendered? Re-Render - if (_rendered) - ForceRender().Wait(); - } - } - - private int _mISelectedViewIndex; - - /// - /// Hold if the View has been rendered already. - /// - private bool _rendered; - - private List Messages { get; set; } - - - public MultiView() - { - Messages = new List(); - } - - - private Task Device_MessageSent(object sender, MessageSentEventArgs e) - { - if (e.Origin == null || !e.Origin.IsSubclassOf(typeof(MultiView))) - return Task.CompletedTask; - - Messages.Add(e.MessageId); - return Task.CompletedTask; - } - - public override void Init() - { - Device.MessageSent += Device_MessageSent; - } - - public override Task Load(MessageResult result) - { - _rendered = false; - return Task.CompletedTask; - } - - - public override async Task Render(MessageResult result) - { - //When already rendered, skip rendering - if (_rendered) - return; - - await CleanUpView(); - - await RenderView(new RenderViewEventArgs(SelectedViewIndex)); - - _rendered = true; - } - - - /// - /// Will get invoked on rendering the current controls view. - /// - /// - public virtual Task RenderView(RenderViewEventArgs e) - { - return Task.CompletedTask; - } - - private async Task CleanUpView() - { - - var tasks = new List(); - - foreach (var msg in Messages) - { - tasks.Add(Device.DeleteMessage(msg)); - } - - await Task.WhenAll(tasks); - - Messages.Clear(); - - } - - /// - /// Forces render of control contents. - /// - public async Task ForceRender() - { - await CleanUpView(); - - await RenderView(new RenderViewEventArgs(SelectedViewIndex)); - - _rendered = true; - } - - public override async Task Cleanup() - { - Device.MessageSent -= Device_MessageSent; - - await CleanUpView(); - } - + Messages = new List(); } -} + + /// + /// Index of the current View. + /// + public int SelectedViewIndex + { + get => _mISelectedViewIndex; + set + { + _mISelectedViewIndex = value; + + //Already rendered? Re-Render + if (_rendered) + { + ForceRender().Wait(); + } + } + } + + private List Messages { get; } + + + private Task Device_MessageSent(object sender, MessageSentEventArgs e) + { + if (e.Origin == null || !e.Origin.IsSubclassOf(typeof(MultiView))) + { + return Task.CompletedTask; + } + + Messages.Add(e.MessageId); + return Task.CompletedTask; + } + + public override void Init() + { + Device.MessageSent += Device_MessageSent; + } + + public override Task Load(MessageResult result) + { + _rendered = false; + return Task.CompletedTask; + } + + + public override async Task Render(MessageResult result) + { + //When already rendered, skip rendering + if (_rendered) + { + return; + } + + await CleanUpView(); + + await RenderView(new RenderViewEventArgs(SelectedViewIndex)); + + _rendered = true; + } + + + /// + /// Will get invoked on rendering the current controls view. + /// + /// + public virtual Task RenderView(RenderViewEventArgs e) + { + return Task.CompletedTask; + } + + private async Task CleanUpView() + { + var tasks = new List(); + + foreach (var msg in Messages) + { + tasks.Add(Device.DeleteMessage(msg)); + } + + await Task.WhenAll(tasks); + + Messages.Clear(); + } + + /// + /// Forces render of control contents. + /// + public async Task ForceRender() + { + await CleanUpView(); + + await RenderView(new RenderViewEventArgs(SelectedViewIndex)); + + _rendered = true; + } + + public override async Task Cleanup() + { + Device.MessageSent -= Device_MessageSent; + + await CleanUpView(); + } +} \ No newline at end of file diff --git a/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs b/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs index 1270b8f..b3ce36c 100644 --- a/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs +++ b/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs @@ -15,237 +15,373 @@ using TelegramBotBase.Form; using TelegramBotBase.Localizations; using static TelegramBotBase.Base.Async; -namespace TelegramBotBase.Controls.Hybrid +namespace TelegramBotBase.Controls.Hybrid; + +public class TaggedButtonGrid : MultiView { - public class TaggedButtonGrid : MultiView + private static readonly object EvButtonClicked = new(); + + private readonly EventHandlerList _events = new(); + + private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard; + + private bool _renderNecessary = true; + + public string BackLabel = Default.Language["ButtonGrid_Back"]; + + public string CheckAllLabel = Default.Language["ButtonGrid_CheckAll"]; + + public string NextPageLabel = Default.Language["ButtonGrid_NextPage"]; + + public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"]; + + public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"]; + + public string SearchLabel = Default.Language["ButtonGrid_SearchFeature"]; + + public string UncheckAllLabel = Default.Language["ButtonGrid_UncheckAll"]; + + public TaggedButtonGrid() { + DataSource = new ButtonFormDataSource(); - public string Title { get; set; } = Default.Language["ButtonGrid_Title"]; + SelectedViewIndex = 0; + } - public string ConfirmationText { get; set; } + public TaggedButtonGrid(EKeyboardType type) : this() + { + _mEKeyboardType = type; + } - private bool _renderNecessary = true; - private static readonly object EvButtonClicked = new object(); + public TaggedButtonGrid(ButtonForm form) + { + DataSource = new ButtonFormDataSource(form); + } - private readonly EventHandlerList _events = new EventHandlerList(); + public string Title { get; set; } = Default.Language["ButtonGrid_Title"]; - [Obsolete("This property is obsolete. Please use the DataSource property instead.")] - public ButtonForm ButtonsForm + public string ConfirmationText { get; set; } + + [Obsolete("This property is obsolete. Please use the DataSource property instead.")] + public ButtonForm ButtonsForm + { + get => DataSource.ButtonForm; + set => DataSource = new ButtonFormDataSource(value); + } + + /// + /// Data source of the items. + /// + public ButtonFormDataSource DataSource { get; set; } + + public int? MessageId { get; set; } + + + /// + /// Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if + /// there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same + /// height as the app's standard keyboard. + /// Source: https://core.telegram.org/bots/api#replykeyboardmarkup + /// + public bool ResizeKeyboard { get; set; } = false; + + public bool OneTimeKeyboard { get; set; } = false; + + public bool HideKeyboardOnCleanup { get; set; } = true; + + public bool DeletePreviousMessage { get; set; } = true; + + /// + /// Removes the reply message from a user. + /// + public bool DeleteReplyMessage { get; set; } = true; + + /// + /// Parsemode of the message. + /// + public ParseMode MessageParseMode { get; set; } = ParseMode.Markdown; + + /// + /// Enables automatic paging of buttons when the amount of rows is exceeding the limits. + /// + public bool EnablePaging { get; set; } = false; + + /// + /// Shows un-/check all tags options + /// + public bool EnableCheckAllTools { get; set; } = false; + + /// + /// Enabled a search function. + /// + public bool EnableSearch { get; set; } = false; + + public string SearchQuery { get; set; } + + public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always; + + + /// + /// Index of the current page + /// + public int CurrentPageIndex { get; set; } + + /// + /// Layout of the buttons which should be displayed always on top. + /// + public ButtonRow HeadLayoutButtonRow { get; set; } + + /// + /// Layout of columns which should be displayed below the header + /// + public ButtonRow SubHeadLayoutButtonRow { get; set; } + + /// + /// Layout of columns which should be displayed below the header + /// + private ButtonRow TagsSubHeadLayoutButtonRow { get; set; } + + /// + /// List of Tags which will be allowed to filter by. + /// + public List Tags { get; set; } + + /// + /// List of Tags selected by the User. + /// + public List SelectedTags { get; set; } + + /// + /// Defines which type of Button Keyboard should be rendered. + /// + public EKeyboardType KeyboardType + { + get => _mEKeyboardType; + set { - get => DataSource.ButtonForm; - set => DataSource = new ButtonFormDataSource(value); - } - - /// - /// Data source of the items. - /// - public ButtonFormDataSource DataSource { get; set; } - - public int? MessageId { get; set; } - - - /// - /// Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard. - /// Source: https://core.telegram.org/bots/api#replykeyboardmarkup - /// - public bool ResizeKeyboard { get; set; } = false; - - public bool OneTimeKeyboard { get; set; } = false; - - public bool HideKeyboardOnCleanup { get; set; } = true; - - public bool DeletePreviousMessage { get; set; } = true; - - /// - /// Removes the reply message from a user. - /// - public bool DeleteReplyMessage { get; set; } = true; - - /// - /// Parsemode of the message. - /// - public ParseMode MessageParseMode { get; set; } = ParseMode.Markdown; - - /// - /// Enables automatic paging of buttons when the amount of rows is exceeding the limits. - /// - public bool EnablePaging { get; set; } = false; - - /// - /// Shows un-/check all tags options - /// - public bool EnableCheckAllTools { get; set; } = false; - - /// - /// Enabled a search function. - /// - public bool EnableSearch { get; set; } = false; - - public string SearchQuery { get; set; } - - public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always; - - - /// - /// Index of the current page - /// - public int CurrentPageIndex { get; set; } - - public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"]; - - public string NextPageLabel = Default.Language["ButtonGrid_NextPage"]; - - public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"]; - - public string SearchLabel = Default.Language["ButtonGrid_SearchFeature"]; - - public string BackLabel = Default.Language["ButtonGrid_Back"]; - - public string CheckAllLabel = Default.Language["ButtonGrid_CheckAll"]; - - public string UncheckAllLabel = Default.Language["ButtonGrid_UncheckAll"]; - - /// - /// Layout of the buttons which should be displayed always on top. - /// - public ButtonRow HeadLayoutButtonRow { get; set; } - - /// - /// Layout of columns which should be displayed below the header - /// - public ButtonRow SubHeadLayoutButtonRow { get; set; } - - /// - /// Layout of columns which should be displayed below the header - /// - private ButtonRow TagsSubHeadLayoutButtonRow { get; set; } - - /// - /// List of Tags which will be allowed to filter by. - /// - public List Tags { get; set; } - - /// - /// List of Tags selected by the User. - /// - public List SelectedTags { get; set; } - - /// - /// Defines which type of Button Keyboard should be rendered. - /// - public EKeyboardType KeyboardType - { - get => _mEKeyboardType; - set + if (_mEKeyboardType != value) { - if (_mEKeyboardType != value) - { - _renderNecessary = true; + _renderNecessary = true; - Cleanup().Wait(); - - _mEKeyboardType = value; - } + Cleanup().Wait(); + _mEKeyboardType = value; } } + } - private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard; - public TaggedButtonGrid() + public bool PagingNecessary + { + get { - DataSource = new ButtonFormDataSource(); - - SelectedViewIndex = 0; - } - - public TaggedButtonGrid(EKeyboardType type) : this() - { - _mEKeyboardType = type; - } - - - public TaggedButtonGrid(ButtonForm form) - { - DataSource = new ButtonFormDataSource(form); - } - - - public event AsyncEventHandler ButtonClicked - { - add => _events.AddHandler(EvButtonClicked, value); - remove => _events.RemoveHandler(EvButtonClicked, value); - } - - public async Task OnButtonClicked(ButtonClickedEventArgs e) - { - var handler = _events[EvButtonClicked]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) + if (KeyboardType == EKeyboardType.InlineKeyBoard && + TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) { - await h.InvokeAllAsync(this, e); - } - } - - public override void Init() - { - Device.MessageDeleted += Device_MessageDeleted; - } - - private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e) - { - if (MessageId == null) - return; - - if (e.MessageId != MessageId) - return; - - MessageId = null; - } - - public override async Task Load(MessageResult result) - { - if (KeyboardType != EKeyboardType.ReplyKeyboard) - return; - - if (!result.IsFirstHandler) - return; - - if (result.MessageText == null || result.MessageText == "") - return; - - var matches = new List(); - ButtonRow match = null; - var index = -1; - - if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false) - { - match = HeadLayoutButtonRow; - goto check; + return true; } - if (SubHeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + if (KeyboardType == EKeyboardType.ReplyKeyboard && + TotalRows > Constants.Telegram.MaxReplyKeyboardRows) { - match = SubHeadLayoutButtonRow; - goto check; + return true; } - if (TagsSubHeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + return false; + } + } + + public bool IsNavigationBarVisible + { + get + { + if ((NavigationBarVisibility == ENavigationBarVisibility.always) | + (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary)) { - match = TagsSubHeadLayoutButtonRow; - goto check; + return true; } - var br = DataSource.FindRow(result.MessageText); - if (br != null) + return false; + } + } + + /// + /// Returns the maximum number of rows + /// + public int MaximumRow + { + get + { + return KeyboardType switch { - match = br.Item1; - index = br.Item2; + EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows, + EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows, + _ => 0 + }; + } + } + + /// + /// Returns the number of all rows (layout + navigation + content); + /// + public int TotalRows => LayoutRows + DataSource.RowCount; + + + /// + /// Contains the Number of Rows which are used by the layout. + /// + private int LayoutRows + { + get + { + var layoutRows = 0; + + if ((NavigationBarVisibility == ENavigationBarVisibility.always) | + (NavigationBarVisibility == ENavigationBarVisibility.auto)) + { + layoutRows += 2; } + if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) + { + layoutRows++; + } + + if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) + { + layoutRows++; + } + + if (EnableCheckAllTools && SelectedViewIndex == 1) + { + layoutRows++; + } + + return layoutRows; + } + } + + /// + /// Returns the number of item rows per page. + /// + public int ItemRowsPerPage => MaximumRow - LayoutRows; + + public int PageCount + { + get + { + if (DataSource.RowCount == 0) + { + return 1; + } + + //var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null); + + var max = DataSource.CalculateMax(EnableSearch ? SearchQuery : null); + + //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") + //{ + // bf = bf.FilterDuplicate(this.SearchQuery); + //} + + if (max == 0) + { + return 1; + } + + return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage); + } + } + + + public event AsyncEventHandler ButtonClicked + { + add => _events.AddHandler(EvButtonClicked, value); + remove => _events.RemoveHandler(EvButtonClicked, value); + } + + public async Task OnButtonClicked(ButtonClickedEventArgs e) + { + var handler = _events[EvButtonClicked]?.GetInvocationList() + .Cast>(); + if (handler == null) + { + return; + } + + foreach (var h in handler) + { + await h.InvokeAllAsync(this, e); + } + } + + public override void Init() + { + Device.MessageDeleted += Device_MessageDeleted; + } + + private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e) + { + if (MessageId == null) + { + return; + } + + if (e.MessageId != MessageId) + { + return; + } + + MessageId = null; + } + + public override async Task Load(MessageResult result) + { + if (KeyboardType != EKeyboardType.ReplyKeyboard) + { + return; + } + + if (!result.IsFirstHandler) + { + return; + } + + if (result.MessageText == null || result.MessageText == "") + { + return; + } + + var matches = new List(); + ButtonRow match = null; + var index = -1; + + if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + { + match = HeadLayoutButtonRow; + goto check; + } + + if (SubHeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + { + match = SubHeadLayoutButtonRow; + goto check; + } + + if (TagsSubHeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + { + match = TagsSubHeadLayoutButtonRow; + goto check; + } + + var br = DataSource.FindRow(result.MessageText); + if (br != null) + { + match = br.Item1; + index = br.Item2; + } + //var button = HeadLayoutButtonRow?. .FirstOrDefault(a => a.Text.Trim() == result.MessageText) // ?? SubHeadLayoutButtonRow?.FirstOrDefault(a => a.Text.Trim() == result.MessageText); @@ -257,172 +393,184 @@ namespace TelegramBotBase.Controls.Hybrid check: + switch (SelectedViewIndex) + { + case 0: - switch (SelectedViewIndex) - { - case 0: + //Remove button click message + if (DeleteReplyMessage) + { + await Device.DeleteMessage(result.MessageId); + } - //Remove button click message - if (DeleteReplyMessage) - await Device.DeleteMessage(result.MessageId); + if (match != null) + { + await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.MessageText), + index, match)); - if (match != null) + result.Handled = true; + return; + } + + if (result.MessageText == PreviousPageLabel) + { + if (CurrentPageIndex > 0) { - await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.MessageText), index, match)); - - result.Handled = true; - return; - } - - if (result.MessageText == PreviousPageLabel) - { - if (CurrentPageIndex > 0) - CurrentPageIndex--; - - Updated(); - result.Handled = true; - } - else if (result.MessageText == NextPageLabel) - { - if (CurrentPageIndex < PageCount - 1) - CurrentPageIndex++; - - Updated(); - result.Handled = true; - } - else if (EnableSearch) - { - if (result.MessageText.StartsWith("🔍")) - { - //Sent note about searching - if (SearchQuery == null) - { - await Device.Send(SearchLabel); - } - - SearchQuery = null; - Updated(); - result.Handled = true; - return; - } - - SearchQuery = result.MessageText; - - if (SearchQuery != null && SearchQuery != "") - { - CurrentPageIndex = 0; - Updated(); - result.Handled = true; - } - - } - else if (Tags != null) - { - if (result.MessageText == "📁") - { - //Remove button click message - if (DeletePreviousMessage) - await Device.DeleteMessage(result.MessageId); - - SelectedViewIndex = 1; - Updated(); - result.Handled = true; - } - } - - break; - case 1: - - //Remove button click message - if (DeleteReplyMessage) - await Device.DeleteMessage(result.MessageId); - - if (result.MessageText == BackLabel) - { - SelectedViewIndex = 0; - Updated(); - result.Handled = true; - return; - } - - if (result.MessageText == CheckAllLabel) - { - CheckAllTags(); - } - else if (result.MessageText == UncheckAllLabel) - { - UncheckAllTags(); - } - - var i = result.MessageText.LastIndexOf(" "); - if (i == -1) - i = result.MessageText.Length; - - var t = result.MessageText.Substring(0, i); - - if (SelectedTags.Contains(t)) - { - SelectedTags.Remove(t); - } - else - { - SelectedTags.Add(t); + CurrentPageIndex--; } Updated(); result.Handled = true; + } + else if (result.MessageText == NextPageLabel) + { + if (CurrentPageIndex < PageCount - 1) + { + CurrentPageIndex++; + } + + Updated(); + result.Handled = true; + } + else if (EnableSearch) + { + if (result.MessageText.StartsWith("🔍")) + { + //Sent note about searching + if (SearchQuery == null) + { + await Device.Send(SearchLabel); + } + + SearchQuery = null; + Updated(); + result.Handled = true; + return; + } + + SearchQuery = result.MessageText; + + if (SearchQuery != null && SearchQuery != "") + { + CurrentPageIndex = 0; + Updated(); + result.Handled = true; + } + } + else if (Tags != null) + { + if (result.MessageText == "📁") + { + //Remove button click message + if (DeletePreviousMessage) + { + await Device.DeleteMessage(result.MessageId); + } + + SelectedViewIndex = 1; + Updated(); + result.Handled = true; + } + } + + break; + case 1: + + //Remove button click message + if (DeleteReplyMessage) + { + await Device.DeleteMessage(result.MessageId); + } + + if (result.MessageText == BackLabel) + { + SelectedViewIndex = 0; + Updated(); + result.Handled = true; + return; + } + + if (result.MessageText == CheckAllLabel) + { + CheckAllTags(); + } + else if (result.MessageText == UncheckAllLabel) + { + UncheckAllTags(); + } + + var i = result.MessageText.LastIndexOf(" "); + if (i == -1) + { + i = result.MessageText.Length; + } + + var t = result.MessageText.Substring(0, i); + + if (SelectedTags.Contains(t)) + { + SelectedTags.Remove(t); + } + else + { + SelectedTags.Add(t); + } + + Updated(); + result.Handled = true; - break; - - } - - + break; + } + } + public override async Task Action(MessageResult result, string value = null) + { + if (result.Handled) + { + return; } - public override async Task Action(MessageResult result, string value = null) + if (!result.IsFirstHandler) { - if (result.Handled) - return; + return; + } - if (!result.IsFirstHandler) - return; + //Find clicked button depending on Text or Value (depending on markup type) + if (KeyboardType != EKeyboardType.InlineKeyBoard) + { + return; + } - //Find clicked button depending on Text or Value (depending on markup type) - if (KeyboardType != EKeyboardType.InlineKeyBoard) - return; + await result.ConfirmAction(ConfirmationText ?? ""); - await result.ConfirmAction(ConfirmationText ?? ""); + ButtonRow match = null; + var index = -1; - ButtonRow match = null; - var index = -1; + if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) + { + match = HeadLayoutButtonRow; + goto check; + } - if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) - { - match = HeadLayoutButtonRow; - goto check; - } + if (SubHeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) + { + match = SubHeadLayoutButtonRow; + goto check; + } - if (SubHeadLayoutButtonRow?.Matches(result.RawData, false) ?? false) - { - match = SubHeadLayoutButtonRow; - goto check; - } - - if (TagsSubHeadLayoutButtonRow?.Matches(result.RawData) ?? false) - { - match = TagsSubHeadLayoutButtonRow; - goto check; - } - - var br = DataSource.FindRow(result.RawData, false); - if (br != null) - { - match = br.Item1; - index = br.Item2; - } + if (TagsSubHeadLayoutButtonRow?.Matches(result.RawData) ?? false) + { + match = TagsSubHeadLayoutButtonRow; + goto check; + } + var br = DataSource.FindRow(result.RawData, false); + if (br != null) + { + match = br.Item1; + index = br.Item2; + } //var bf = DataSource.ButtonForm; @@ -434,537 +582,439 @@ namespace TelegramBotBase.Controls.Hybrid //var index = bf.FindRowByButton(button); check: - if (match != null) - { - await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.RawData, false), index, match)); - - result.Handled = true; - return; - } - - switch (result.RawData) - { - case "$previous$": - - if (CurrentPageIndex > 0) - CurrentPageIndex--; - - Updated(); - - break; - - case "$next$": - - if (CurrentPageIndex < PageCount - 1) - CurrentPageIndex++; - - Updated(); - - break; - - case "$filter$": - - SelectedViewIndex = 1; - Updated(); - - break; - - case "$back$": - - SelectedViewIndex = 0; - Updated(); - - break; - - case "$checkall$": - - CheckAllTags(); - - break; - - case "$uncheckall$": - - UncheckAllTags(); - - break; - } + if (match != null) + { + await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.RawData, false), index, + match)); + result.Handled = true; + return; } - /// - /// This method checks of the amount of buttons - /// - private void CheckGrid() + switch (result.RawData) { - switch (_mEKeyboardType) - { - case EKeyboardType.InlineKeyBoard: + case "$previous$": - if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging) - { - throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; - } - - if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols) - { - throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; - } - - break; - - case EKeyboardType.ReplyKeyboard: - - if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging) - { - throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows }; - } - - if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols) - { - throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols }; - } - - break; - } - } - - public override async Task Render(MessageResult result) - { - if (!_renderNecessary) - return; - - //Check for rows and column limits - CheckGrid(); - - _renderNecessary = false; - - switch (SelectedViewIndex) - { - case 0: - - await RenderDataView(); - - break; - - case 1: - - - await RenderTagView(); - - - - break; - - } - - - - } - - - #region "Data View" - - private async Task RenderDataView() - { - Message m = null; - - var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (EnableSearch ? SearchQuery : null)); - - //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") - //{ - // form = form.FilterDuplicate(this.SearchQuery, true); - //} - //else - //{ - // form = form.Duplicate(); - //} - - if (Tags != null && SelectedTags != null) - { - form = form.TagDuplicate(SelectedTags); - } - - if (EnablePaging) - { - IntegratePagingView(form); - } - - if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) - { - form.InsertButtonRow(0, HeadLayoutButtonRow.ToArray()); - } - - if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) - { - if (IsNavigationBarVisible) + if (CurrentPageIndex > 0) { - form.InsertButtonRow(2, SubHeadLayoutButtonRow.ToArray()); - } - else - { - form.InsertButtonRow(1, SubHeadLayoutButtonRow.ToArray()); - } - } - - switch (KeyboardType) - { - //Reply Keyboard could only be updated with a new keyboard. - case EKeyboardType.ReplyKeyboard: - - if (form.Count == 0) - { - if (MessageId != null) - { - await Device.HideReplyKeyboard(); - MessageId = null; - } - return; - } - - - var rkm = (ReplyKeyboardMarkup)form; - rkm.ResizeKeyboard = ResizeKeyboard; - rkm.OneTimeKeyboard = OneTimeKeyboard; - m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); - - //Prevent flicker of keyboard - if (DeletePreviousMessage && MessageId != null) - await Device.DeleteMessage(MessageId.Value); - - break; - - case EKeyboardType.InlineKeyBoard: - - - //Try to edit message if message id is available - //When the returned message is null then the message has been already deleted, resend it - if (MessageId != null) - { - m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form); - if (m != null) - { - MessageId = m.MessageId; - return; - } - } - - //When no message id is available or it has been deleted due the use of AutoCleanForm re-render automatically - m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); - break; - } - - if (m != null) - { - MessageId = m.MessageId; - } - } - - private void IntegratePagingView(ButtonForm dataForm) - { - //No Items - if (dataForm.Rows == 0) - { - dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$")); - } - - if (IsNavigationBarVisible) - { - //🔍 - var row = new ButtonRow(); - row.Add(new ButtonBase(PreviousPageLabel, "$previous$")); - row.Add(new ButtonBase(string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), "$site$")); - - if (Tags != null && Tags.Count > 0) - { - row.Add(new ButtonBase("📁", "$filter$")); + CurrentPageIndex--; } - row.Add(new ButtonBase(NextPageLabel, "$next$")); - - if (EnableSearch) - { - row.Insert(2, new ButtonBase("🔍 " + (SearchQuery ?? ""), "$search$")); - } - - dataForm.InsertButtonRow(0, row); - - dataForm.AddButtonRow(row); - } - } - - #endregion - - - #region "Tag View" - - - private async Task RenderTagView() - { - Message m = null; - var bf = new ButtonForm(); - - bf.AddButtonRow(BackLabel, "$back$"); - - if (EnableCheckAllTools) - { - TagsSubHeadLayoutButtonRow = new ButtonRow(new ButtonBase(CheckAllLabel, "$checkall$"), new ButtonBase(UncheckAllLabel, "$uncheckall$")); - bf.AddButtonRow(TagsSubHeadLayoutButtonRow); - } - - foreach (var t in Tags) - { - - var s = t; - - if (SelectedTags?.Contains(t) ?? false) - { - s += " ✅"; - } - - bf.AddButtonRow(s, t); - - } - - switch (KeyboardType) - { - //Reply Keyboard could only be updated with a new keyboard. - case EKeyboardType.ReplyKeyboard: - - if (bf.Count == 0) - { - if (MessageId != null) - { - await Device.HideReplyKeyboard(); - MessageId = null; - } - return; - } - - //if (bf.Count == 0) - // return; - - - var rkm = (ReplyKeyboardMarkup)bf; - rkm.ResizeKeyboard = ResizeKeyboard; - rkm.OneTimeKeyboard = OneTimeKeyboard; - m = await Device.Send("Choose category", rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); - - //Prevent flicker of keyboard - if (DeletePreviousMessage && MessageId != null) - await Device.DeleteMessage(MessageId.Value); - - break; - - case EKeyboardType.InlineKeyBoard: - - if (MessageId != null) - { - m = await Device.Edit(MessageId.Value, "Choose category", (InlineKeyboardMarkup)bf); - } - else - { - m = await Device.Send("Choose category", (InlineKeyboardMarkup)bf, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false); - } - - break; - } - - - - if (m != null) - MessageId = m.MessageId; - - } - - - #endregion - - - public bool PagingNecessary - { - get - { - if (KeyboardType == EKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) - { - return true; - } - - if (KeyboardType == EKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows) - { - return true; - } - - return false; - } - } - - public bool IsNavigationBarVisible - { - get - { - if (NavigationBarVisibility == ENavigationBarVisibility.always | (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary)) - { - return true; - } - - return false; - } - } - - /// - /// Returns the maximum number of rows - /// - public int MaximumRow - { - get - { - return KeyboardType switch - { - EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows, - EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows, - _ => 0 - }; - } - } - - /// - /// Returns the number of all rows (layout + navigation + content); - /// - public int TotalRows => LayoutRows + DataSource.RowCount; - - - /// - /// Contains the Number of Rows which are used by the layout. - /// - private int LayoutRows - { - get - { - var layoutRows = 0; - - if (NavigationBarVisibility == ENavigationBarVisibility.always | NavigationBarVisibility == ENavigationBarVisibility.auto) - layoutRows += 2; - - if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) - layoutRows++; - - if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) - layoutRows++; - - if (EnableCheckAllTools && SelectedViewIndex == 1) - { - layoutRows++; - } - - return layoutRows; - } - } - - /// - /// Returns the number of item rows per page. - /// - public int ItemRowsPerPage => MaximumRow - LayoutRows; - - public int PageCount - { - get - { - if (DataSource.RowCount == 0) - return 1; - - //var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null); - - var max = DataSource.CalculateMax(EnableSearch ? SearchQuery : null); - - //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") - //{ - // bf = bf.FilterDuplicate(this.SearchQuery); - //} - - if (max == 0) - return 1; - - return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage); - } - } - - public override Task Hidden(bool formClose) - { - //Prepare for opening Modal, and comming back - if (!formClose) - { Updated(); - } - else - { - //Remove event handler - Device.MessageDeleted -= Device_MessageDeleted; - } - return Task.CompletedTask; + break; + + case "$next$": + + if (CurrentPageIndex < PageCount - 1) + { + CurrentPageIndex++; + } + + Updated(); + + break; + + case "$filter$": + + SelectedViewIndex = 1; + Updated(); + + break; + + case "$back$": + + SelectedViewIndex = 0; + Updated(); + + break; + + case "$checkall$": + + CheckAllTags(); + + break; + + case "$uncheckall$": + + UncheckAllTags(); + + break; } + } - /// - /// Tells the control that it has been updated. - /// - public void Updated() + /// + /// This method checks of the amount of buttons + /// + private void CheckGrid() + { + switch (_mEKeyboardType) { - _renderNecessary = true; - } + case EKeyboardType.InlineKeyBoard: - public override async Task Cleanup() + if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging) + { + throw new MaximumRowsReachedException + { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; + } + + if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols) + { + throw new MaximumColsException + { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; + } + + break; + + case EKeyboardType.ReplyKeyboard: + + if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging) + { + throw new MaximumRowsReachedException + { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows }; + } + + if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols) + { + throw new MaximumColsException + { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols }; + } + + break; + } + } + + public override async Task Render(MessageResult result) + { + if (!_renderNecessary) { - if (MessageId == null) - return; - - switch (KeyboardType) - { - case EKeyboardType.InlineKeyBoard: - - await Device.DeleteMessage(MessageId.Value); - - MessageId = null; - - break; - case EKeyboardType.ReplyKeyboard: - - if (HideKeyboardOnCleanup) - { - await Device.HideReplyKeyboard(); - } - - MessageId = null; - - break; - } - + return; } + //Check for rows and column limits + CheckGrid(); - /// - /// Checks all tags for filtering. - /// - public void CheckAllTags() + _renderNecessary = false; + + switch (SelectedViewIndex) { - SelectedTags.Clear(); + case 0: - SelectedTags = Tags.Select(a => a).ToList(); + await RenderDataView(); - Updated(); + break; + case 1: + + + await RenderTagView(); + + + break; } - - /// - /// Unchecks all tags for filtering. - /// - public void UncheckAllTags() - { - SelectedTags.Clear(); - - Updated(); - } - } -} + #region "Tag View" + + private async Task RenderTagView() + { + Message m = null; + var bf = new ButtonForm(); + + bf.AddButtonRow(BackLabel, "$back$"); + + if (EnableCheckAllTools) + { + TagsSubHeadLayoutButtonRow = new ButtonRow(new ButtonBase(CheckAllLabel, "$checkall$"), + new ButtonBase(UncheckAllLabel, "$uncheckall$")); + bf.AddButtonRow(TagsSubHeadLayoutButtonRow); + } + + foreach (var t in Tags) + { + var s = t; + + if (SelectedTags?.Contains(t) ?? false) + { + s += " ✅"; + } + + bf.AddButtonRow(s, t); + } + + switch (KeyboardType) + { + //Reply Keyboard could only be updated with a new keyboard. + case EKeyboardType.ReplyKeyboard: + + if (bf.Count == 0) + { + if (MessageId != null) + { + await Device.HideReplyKeyboard(); + MessageId = null; + } + + return; + } + + //if (bf.Count == 0) + // return; + + + var rkm = (ReplyKeyboardMarkup)bf; + rkm.ResizeKeyboard = ResizeKeyboard; + rkm.OneTimeKeyboard = OneTimeKeyboard; + m = await Device.Send("Choose category", rkm, disableNotification: true, + parseMode: MessageParseMode, markdownV2AutoEscape: false); + + //Prevent flicker of keyboard + if (DeletePreviousMessage && MessageId != null) + { + await Device.DeleteMessage(MessageId.Value); + } + + break; + + case EKeyboardType.InlineKeyBoard: + + if (MessageId != null) + { + m = await Device.Edit(MessageId.Value, "Choose category", (InlineKeyboardMarkup)bf); + } + else + { + m = await Device.Send("Choose category", (InlineKeyboardMarkup)bf, disableNotification: true, + parseMode: MessageParseMode, markdownV2AutoEscape: false); + } + + break; + } + + + if (m != null) + { + MessageId = m.MessageId; + } + } + + #endregion + + public override Task Hidden(bool formClose) + { + //Prepare for opening Modal, and comming back + if (!formClose) + { + Updated(); + } + else + //Remove event handler + { + Device.MessageDeleted -= Device_MessageDeleted; + } + + return Task.CompletedTask; + } + + /// + /// Tells the control that it has been updated. + /// + public void Updated() + { + _renderNecessary = true; + } + + public override async Task Cleanup() + { + if (MessageId == null) + { + return; + } + + switch (KeyboardType) + { + case EKeyboardType.InlineKeyBoard: + + await Device.DeleteMessage(MessageId.Value); + + MessageId = null; + + break; + case EKeyboardType.ReplyKeyboard: + + if (HideKeyboardOnCleanup) + { + await Device.HideReplyKeyboard(); + } + + MessageId = null; + + break; + } + } + + + /// + /// Checks all tags for filtering. + /// + public void CheckAllTags() + { + SelectedTags.Clear(); + + SelectedTags = Tags.Select(a => a).ToList(); + + Updated(); + } + + /// + /// Unchecks all tags for filtering. + /// + public void UncheckAllTags() + { + SelectedTags.Clear(); + + Updated(); + } + + + #region "Data View" + + private async Task RenderDataView() + { + Message m = null; + + var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, + EnableSearch ? SearchQuery : null); + + //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") + //{ + // form = form.FilterDuplicate(this.SearchQuery, true); + //} + //else + //{ + // form = form.Duplicate(); + //} + + if (Tags != null && SelectedTags != null) + { + form = form.TagDuplicate(SelectedTags); + } + + if (EnablePaging) + { + IntegratePagingView(form); + } + + if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) + { + form.InsertButtonRow(0, HeadLayoutButtonRow.ToArray()); + } + + if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) + { + if (IsNavigationBarVisible) + { + form.InsertButtonRow(2, SubHeadLayoutButtonRow.ToArray()); + } + else + { + form.InsertButtonRow(1, SubHeadLayoutButtonRow.ToArray()); + } + } + + switch (KeyboardType) + { + //Reply Keyboard could only be updated with a new keyboard. + case EKeyboardType.ReplyKeyboard: + + if (form.Count == 0) + { + if (MessageId != null) + { + await Device.HideReplyKeyboard(); + MessageId = null; + } + + return; + } + + + var rkm = (ReplyKeyboardMarkup)form; + rkm.ResizeKeyboard = ResizeKeyboard; + rkm.OneTimeKeyboard = OneTimeKeyboard; + m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, + markdownV2AutoEscape: false); + + //Prevent flicker of keyboard + if (DeletePreviousMessage && MessageId != null) + { + await Device.DeleteMessage(MessageId.Value); + } + + break; + + case EKeyboardType.InlineKeyBoard: + + + //Try to edit message if message id is available + //When the returned message is null then the message has been already deleted, resend it + if (MessageId != null) + { + m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form); + if (m != null) + { + MessageId = m.MessageId; + return; + } + } + + //When no message id is available or it has been deleted due the use of AutoCleanForm re-render automatically + m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, + parseMode: MessageParseMode, markdownV2AutoEscape: false); + break; + } + + if (m != null) + { + MessageId = m.MessageId; + } + } + + private void IntegratePagingView(ButtonForm dataForm) + { + //No Items + if (dataForm.Rows == 0) + { + dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$")); + } + + if (IsNavigationBarVisible) + { + //🔍 + var row = new ButtonRow(); + row.Add(new ButtonBase(PreviousPageLabel, "$previous$")); + row.Add(new ButtonBase( + string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), + "$site$")); + + if (Tags != null && Tags.Count > 0) + { + row.Add(new ButtonBase("📁", "$filter$")); + } + + row.Add(new ButtonBase(NextPageLabel, "$next$")); + + if (EnableSearch) + { + row.Insert(2, new ButtonBase("🔍 " + (SearchQuery ?? ""), "$search$")); + } + + dataForm.InsertButtonRow(0, row); + + dataForm.AddButtonRow(row); + } + } + + #endregion +} \ No newline at end of file diff --git a/TelegramBotBase/Controls/Inline/CalendarPicker.cs b/TelegramBotBase/Controls/Inline/CalendarPicker.cs index ccdd1db..4420cc1 100644 --- a/TelegramBotBase/Controls/Inline/CalendarPicker.cs +++ b/TelegramBotBase/Controls/Inline/CalendarPicker.cs @@ -10,254 +10,257 @@ using TelegramBotBase.Localizations; using static TelegramBotBase.Tools.Arrays; using static TelegramBotBase.Tools.Time; -namespace TelegramBotBase.Controls.Inline +namespace TelegramBotBase.Controls.Inline; + +public class CalendarPicker : ControlBase { - public class CalendarPicker : ControlBase + public CalendarPicker(CultureInfo culture) { + SelectedDate = DateTime.Today; + VisibleMonth = DateTime.Today; + FirstDayOfWeek = DayOfWeek.Monday; + Culture = culture; + PickerMode = EMonthPickerMode.day; + } - public DateTime SelectedDate { get; set; } + public CalendarPicker() : this(new CultureInfo("en-en")) + { + } - public DateTime VisibleMonth { get; set; } + public DateTime SelectedDate { get; set; } - public DayOfWeek FirstDayOfWeek { get; set; } + public DateTime VisibleMonth { get; set; } - public CultureInfo Culture { get; set; } + public DayOfWeek FirstDayOfWeek { get; set; } + + public CultureInfo Culture { get; set; } - private int? MessageId { get; set; } + private int? MessageId { get; set; } - public string Title { get; set; } = Default.Language["CalendarPicker_Title"]; + public string Title { get; set; } = Default.Language["CalendarPicker_Title"]; - public EMonthPickerMode PickerMode { get; set; } + public EMonthPickerMode PickerMode { get; set; } - public bool EnableDayView { get; set; } = true; + public bool EnableDayView { get; set; } = true; - public bool EnableMonthView { get; set; } = true; + public bool EnableMonthView { get; set; } = true; - public bool EnableYearView { get; set; } = true; + public bool EnableYearView { get; set; } = true; - public CalendarPicker(CultureInfo culture) + + public override async Task Action(MessageResult result, string value = null) + { + await result.ConfirmAction(); + + switch (result.RawData) { - SelectedDate = DateTime.Today; - VisibleMonth = DateTime.Today; - FirstDayOfWeek = DayOfWeek.Monday; - Culture = culture; - PickerMode = EMonthPickerMode.day; - } + case "$next$": - public CalendarPicker() : this(new CultureInfo("en-en")) { } + VisibleMonth = PickerMode switch + { + EMonthPickerMode.day => VisibleMonth.AddMonths(1), + EMonthPickerMode.month => VisibleMonth.AddYears(1), + EMonthPickerMode.year => VisibleMonth.AddYears(10), + _ => VisibleMonth + }; + break; + case "$prev$": + VisibleMonth = PickerMode switch + { + EMonthPickerMode.day => VisibleMonth.AddMonths(-1), + EMonthPickerMode.month => VisibleMonth.AddYears(-1), + EMonthPickerMode.year => VisibleMonth.AddYears(-10), + _ => VisibleMonth + }; + break; - public override async Task Action(MessageResult result, string value = null) - { - await result.ConfirmAction(); + case "$monthtitle$": - switch (result.RawData) - { - case "$next$": + if (EnableMonthView) + { + PickerMode = EMonthPickerMode.month; + } - VisibleMonth = PickerMode switch - { - EMonthPickerMode.day => VisibleMonth.AddMonths(1), - EMonthPickerMode.month => VisibleMonth.AddYears(1), - EMonthPickerMode.year => VisibleMonth.AddYears(10), - _ => VisibleMonth - }; + break; - break; - case "$prev$": + case "$yeartitle$": - VisibleMonth = PickerMode switch - { - EMonthPickerMode.day => VisibleMonth.AddMonths(-1), - EMonthPickerMode.month => VisibleMonth.AddYears(-1), - EMonthPickerMode.year => VisibleMonth.AddYears(-10), - _ => VisibleMonth - }; + if (EnableYearView) + { + PickerMode = EMonthPickerMode.year; + } - break; + break; + case "$yearstitle$": - case "$monthtitle$": + if (EnableMonthView) + { + PickerMode = EMonthPickerMode.month; + } - if (EnableMonthView) - { - PickerMode = EMonthPickerMode.month; - } + VisibleMonth = SelectedDate; - break; + break; - case "$yeartitle$": + default: - if (EnableYearView) - { - PickerMode = EMonthPickerMode.year; - } - - break; - case "$yearstitle$": - - if (EnableMonthView) - { - PickerMode = EMonthPickerMode.month; - } + var day = 0; + if (result.RawData.StartsWith("d-") && + TryParseDay(result.RawData.Split('-')[1], SelectedDate, out day)) + { + SelectedDate = new DateTime(VisibleMonth.Year, VisibleMonth.Month, day); + } + var month = 0; + if (result.RawData.StartsWith("m-") && TryParseMonth(result.RawData.Split('-')[1], out month)) + { + SelectedDate = new DateTime(VisibleMonth.Year, month, 1); VisibleMonth = SelectedDate; - break; - - default: - - var day = 0; - if (result.RawData.StartsWith("d-") && TryParseDay(result.RawData.Split('-')[1], SelectedDate, out day)) + if (EnableDayView) { - SelectedDate = new DateTime(VisibleMonth.Year, VisibleMonth.Month, day); + PickerMode = EMonthPickerMode.day; } + } - var month = 0; - if (result.RawData.StartsWith("m-") && TryParseMonth(result.RawData.Split('-')[1], out month)) + var year = 0; + if (result.RawData.StartsWith("y-") && TryParseYear(result.RawData.Split('-')[1], out year)) + { + SelectedDate = new DateTime(year, SelectedDate.Month, SelectedDate.Day); + VisibleMonth = SelectedDate; + + if (EnableMonthView) { - SelectedDate = new DateTime(VisibleMonth.Year, month, 1); - VisibleMonth = SelectedDate; - - if (EnableDayView) - { - PickerMode = EMonthPickerMode.day; - } + PickerMode = EMonthPickerMode.month; } + } - var year = 0; - if (result.RawData.StartsWith("y-") && TryParseYear(result.RawData.Split('-')[1], out year)) - { - SelectedDate = new DateTime(year, SelectedDate.Month, SelectedDate.Day); - VisibleMonth = SelectedDate; - - if (EnableMonthView) - { - PickerMode = EMonthPickerMode.month; - } - - } - - break; - } - - - + break; } - - - - public override async Task Render(MessageResult result) - { - - - - var bf = new ButtonForm(); - - switch (PickerMode) - { - case EMonthPickerMode.day: - - var month = VisibleMonth; - - var dayNamesNormal = Culture.DateTimeFormat.ShortestDayNames; - var dayNamesShifted = Shift(dayNamesNormal, (int)FirstDayOfWeek); - - bf.AddButtonRow(new ButtonBase(Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase(Culture.DateTimeFormat.MonthNames[month.Month - 1] + " " + month.Year, "$monthtitle$"), new ButtonBase(Default.Language["CalendarPicker_NextPage"], "$next$")); - - bf.AddButtonRow(dayNamesShifted.Select(a => new ButtonBase(a, a)).ToList()); - - //First Day of month - var firstDay = new DateTime(month.Year, month.Month, 1); - - //Last Day of month - var lastDay = firstDay.LastDayOfMonth(); - - //Start of Week where first day of month is (left border) - var start = firstDay.StartOfWeek(FirstDayOfWeek); - - //End of week where last day of month is (right border) - var end = lastDay.EndOfWeek(FirstDayOfWeek); - - for (var i = 0; i <= ((end - start).Days / 7); i++) - { - var lst = new List(); - for (var id = 0; id < 7; id++) - { - var d = start.AddDays((i * 7) + id); - if (d < firstDay | d > lastDay) - { - lst.Add(new ButtonBase("-", "m-" + d.Day)); - continue; - } - - var day = d.Day.ToString(); - - if (d == DateTime.Today) - { - day = "(" + day + ")"; - } - - lst.Add(new ButtonBase((SelectedDate == d ? "[" + day + "]" : day), "d-" + d.Day)); - } - bf.AddButtonRow(lst); - } - - break; - - case EMonthPickerMode.month: - - bf.AddButtonRow(new ButtonBase(Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase(VisibleMonth.Year.ToString("0000"), "$yeartitle$"), new ButtonBase(Default.Language["CalendarPicker_NextPage"], "$next$")); - - var months = Culture.DateTimeFormat.MonthNames; - - var buttons = months.Select((a, b) => new ButtonBase((b == SelectedDate.Month - 1 && SelectedDate.Year == VisibleMonth.Year ? "[ " + a + " ]" : a), "m-" + (b + 1))); - - bf.AddSplitted(buttons); - - break; - - case EMonthPickerMode.year: - - bf.AddButtonRow(new ButtonBase(Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase("Year", "$yearstitle$"), new ButtonBase(Default.Language["CalendarPicker_NextPage"], "$next$")); - - var starti = Math.Floor(VisibleMonth.Year / 10f) * 10; - - for (var i = 0; i < 10; i++) - { - var m = starti + (i * 2); - bf.AddButtonRow(new ButtonBase((SelectedDate.Year == m ? "[ " + m + " ]" : m.ToString()), "y-" + m), new ButtonBase((SelectedDate.Year == (m + 1) ? "[ " + (m + 1) + " ]" : (m + 1).ToString()), "y-" + (m + 1))); - } - - break; - - } - - - if (MessageId != null) - { - var m = await Device.Edit(MessageId.Value, Title, bf); - } - else - { - var m = await Device.Send(Title, bf); - MessageId = m.MessageId; - } - } - - - - public override async Task Cleanup() - { - - if (MessageId != null) - { - await Device.DeleteMessage(MessageId.Value); - } - - } - } -} + + + public override async Task Render(MessageResult result) + { + var bf = new ButtonForm(); + + switch (PickerMode) + { + case EMonthPickerMode.day: + + var month = VisibleMonth; + + var dayNamesNormal = Culture.DateTimeFormat.ShortestDayNames; + var dayNamesShifted = Shift(dayNamesNormal, (int)FirstDayOfWeek); + + bf.AddButtonRow(new ButtonBase(Default.Language["CalendarPicker_PreviousPage"], "$prev$"), + new ButtonBase(Culture.DateTimeFormat.MonthNames[month.Month - 1] + " " + month.Year, + "$monthtitle$"), + new ButtonBase(Default.Language["CalendarPicker_NextPage"], "$next$")); + + bf.AddButtonRow(dayNamesShifted.Select(a => new ButtonBase(a, a)).ToList()); + + //First Day of month + var firstDay = new DateTime(month.Year, month.Month, 1); + + //Last Day of month + var lastDay = firstDay.LastDayOfMonth(); + + //Start of Week where first day of month is (left border) + var start = firstDay.StartOfWeek(FirstDayOfWeek); + + //End of week where last day of month is (right border) + var end = lastDay.EndOfWeek(FirstDayOfWeek); + + for (var i = 0; i <= (end - start).Days / 7; i++) + { + var lst = new List(); + for (var id = 0; id < 7; id++) + { + var d = start.AddDays(i * 7 + id); + if ((d < firstDay) | (d > lastDay)) + { + lst.Add(new ButtonBase("-", "m-" + d.Day)); + continue; + } + + var day = d.Day.ToString(); + + if (d == DateTime.Today) + { + day = "(" + day + ")"; + } + + lst.Add(new ButtonBase(SelectedDate == d ? "[" + day + "]" : day, "d-" + d.Day)); + } + + bf.AddButtonRow(lst); + } + + break; + + case EMonthPickerMode.month: + + bf.AddButtonRow(new ButtonBase(Default.Language["CalendarPicker_PreviousPage"], "$prev$"), + new ButtonBase(VisibleMonth.Year.ToString("0000"), "$yeartitle$"), + new ButtonBase(Default.Language["CalendarPicker_NextPage"], "$next$")); + + var months = Culture.DateTimeFormat.MonthNames; + + var buttons = months.Select((a, b) => + new ButtonBase( + b == SelectedDate.Month - 1 && + SelectedDate.Year == VisibleMonth.Year + ? "[ " + a + " ]" + : a, + "m-" + (b + 1))); + + bf.AddSplitted(buttons); + + break; + + case EMonthPickerMode.year: + + bf.AddButtonRow(new ButtonBase(Default.Language["CalendarPicker_PreviousPage"], "$prev$"), + new ButtonBase("Year", "$yearstitle$"), + new ButtonBase(Default.Language["CalendarPicker_NextPage"], "$next$")); + + var starti = Math.Floor(VisibleMonth.Year / 10f) * 10; + + for (var i = 0; i < 10; i++) + { + var m = starti + i * 2; + bf.AddButtonRow( + new ButtonBase(SelectedDate.Year == m ? "[ " + m + " ]" : m.ToString(), "y-" + m), + new ButtonBase(SelectedDate.Year == m + 1 ? "[ " + (m + 1) + " ]" : (m + 1).ToString(), + "y-" + (m + 1))); + } + + break; + } + + + if (MessageId != null) + { + var m = await Device.Edit(MessageId.Value, Title, bf); + } + else + { + var m = await Device.Send(Title, bf); + MessageId = m.MessageId; + } + } + + + public override async Task Cleanup() + { + if (MessageId != null) + { + await Device.DeleteMessage(MessageId.Value); + } + } +} \ No newline at end of file diff --git a/TelegramBotBase/Controls/Inline/MonthPicker.cs b/TelegramBotBase/Controls/Inline/MonthPicker.cs index a5032b1..d6b5fb1 100644 --- a/TelegramBotBase/Controls/Inline/MonthPicker.cs +++ b/TelegramBotBase/Controls/Inline/MonthPicker.cs @@ -1,18 +1,12 @@ using TelegramBotBase.Enums; -namespace TelegramBotBase.Controls.Inline +namespace TelegramBotBase.Controls.Inline; + +public class MonthPicker : CalendarPicker { - public class MonthPicker : CalendarPicker + public MonthPicker() { - - - - public MonthPicker() - { - PickerMode = EMonthPickerMode.month; - EnableDayView = false; - } - - + PickerMode = EMonthPickerMode.month; + EnableDayView = false; } -} +} \ No newline at end of file diff --git a/TelegramBotBase/Controls/Inline/MultiToggleButton.cs b/TelegramBotBase/Controls/Inline/MultiToggleButton.cs index fa8f159..488a5f1 100644 --- a/TelegramBotBase/Controls/Inline/MultiToggleButton.cs +++ b/TelegramBotBase/Controls/Inline/MultiToggleButton.cs @@ -6,152 +6,147 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; using TelegramBotBase.Localizations; -namespace TelegramBotBase.Controls.Inline +namespace TelegramBotBase.Controls.Inline; + +public class MultiToggleButton : ControlBase { - public class MultiToggleButton : ControlBase + private static readonly object EvToggled = new(); + + private readonly EventHandlerList _events = new(); + + private bool _renderNecessary = true; + + + public MultiToggleButton() { - /// - /// This contains the selected icon. - /// - public string SelectedIcon { get; set; } = Default.Language["MultiToggleButton_SelectedIcon"]; + Options = new List(); + } - /// - /// This will appear on the ConfirmAction message (if not empty) - /// - public string ChangedString { get; set; } = Default.Language["MultiToggleButton_Changed"]; + /// + /// This contains the selected icon. + /// + public string SelectedIcon { get; set; } = Default.Language["MultiToggleButton_SelectedIcon"]; - /// - /// This holds the title of the control. - /// - public string Title { get; set; } = Default.Language["MultiToggleButton_Title"]; + /// + /// This will appear on the ConfirmAction message (if not empty) + /// + public string ChangedString { get; set; } = Default.Language["MultiToggleButton_Changed"]; - public int? MessageId { get; set; } + /// + /// This holds the title of the control. + /// + public string Title { get; set; } = Default.Language["MultiToggleButton_Title"]; - private bool _renderNecessary = true; + public int? MessageId { get; set; } - private static readonly object EvToggled = new object(); + /// + /// This will hold all options available. + /// + public List Options { get; set; } - private readonly EventHandlerList _events = new EventHandlerList(); + /// + /// This will set if an empty selection (null) is allowed. + /// + public bool AllowEmptySelection { get; set; } = true; - /// - /// This will hold all options available. - /// - public List Options { get; set; } + public ButtonBase SelectedOption { get; set; } - /// - /// This will set if an empty selection (null) is allowed. - /// - public bool AllowEmptySelection { get; set; } = true; + public event EventHandler Toggled + { + add => _events.AddHandler(EvToggled, value); + remove => _events.RemoveHandler(EvToggled, value); + } + public void OnToggled(EventArgs e) + { + (_events[EvToggled] as EventHandler)?.Invoke(this, e); + } - public MultiToggleButton() + public override async Task Action(MessageResult result, string value = null) + { + if (result.Handled) { - Options = new List(); + return; } - public event EventHandler Toggled + await result.ConfirmAction(ChangedString); + + switch (value ?? "unknown") { - add => _events.AddHandler(EvToggled, value); - remove => _events.RemoveHandler(EvToggled, value); - } + default: - public void OnToggled(EventArgs e) - { - (_events[EvToggled] as EventHandler)?.Invoke(this, e); - } + var s = value.Split('$'); - public override async Task Action(MessageResult result, string value = null) - { - if (result.Handled) - return; - - await result.ConfirmAction(ChangedString); - - switch (value ?? "unknown") - { - default: - - var s = value.Split('$'); - - if (s[0] == "check" && s.Length > 1) + if (s[0] == "check" && s.Length > 1) + { + var index = 0; + if (!int.TryParse(s[1], out index)) { - var index = 0; - if (!int.TryParse(s[1], out index)) - { - return; - } - - if(SelectedOption== null || SelectedOption != Options[index]) - { - SelectedOption = Options[index]; - OnToggled(EventArgs.Empty); - } - else if(AllowEmptySelection) - { - SelectedOption = null; - OnToggled(EventArgs.Empty); - } - - _renderNecessary = true; - return; } + if (SelectedOption == null || SelectedOption != Options[index]) + { + SelectedOption = Options[index]; + OnToggled(EventArgs.Empty); + } + else if (AllowEmptySelection) + { + SelectedOption = null; + OnToggled(EventArgs.Empty); + } - _renderNecessary = false; + _renderNecessary = true; - break; - - } - - result.Handled = true; - - } - - public override async Task Render(MessageResult result) - { - if (!_renderNecessary) - return; - - var bf = new ButtonForm(this); - - var lst = new List(); - foreach (var o in Options) - { - var index = Options.IndexOf(o); - if (o == SelectedOption) - { - lst.Add(new ButtonBase(SelectedIcon + " " + o.Text, "check$" + index)); - continue; + return; } - lst.Add(new ButtonBase(o.Text, "check$" + index)); - } - - bf.AddButtonRow(lst); - - if (MessageId != null) - { - var m = await Device.Edit(MessageId.Value, Title, bf); - } - else - { - var m = await Device.Send(Title, bf, disableNotification: true); - if (m != null) - { - MessageId = m.MessageId; - } - } - - _renderNecessary = false; + _renderNecessary = false; + break; } - public ButtonBase SelectedOption - { - get; set; - } - + result.Handled = true; } -} + + public override async Task Render(MessageResult result) + { + if (!_renderNecessary) + { + return; + } + + var bf = new ButtonForm(this); + + var lst = new List(); + foreach (var o in Options) + { + var index = Options.IndexOf(o); + if (o == SelectedOption) + { + lst.Add(new ButtonBase(SelectedIcon + " " + o.Text, "check$" + index)); + continue; + } + + lst.Add(new ButtonBase(o.Text, "check$" + index)); + } + + bf.AddButtonRow(lst); + + if (MessageId != null) + { + var m = await Device.Edit(MessageId.Value, Title, bf); + } + else + { + var m = await Device.Send(Title, bf, disableNotification: true); + if (m != null) + { + MessageId = m.MessageId; + } + } + + _renderNecessary = false; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Controls/Inline/ProgressBar.cs b/TelegramBotBase/Controls/Inline/ProgressBar.cs index 2dde19a..ab2fc89 100644 --- a/TelegramBotBase/Controls/Inline/ProgressBar.cs +++ b/TelegramBotBase/Controls/Inline/ProgressBar.cs @@ -2,266 +2,255 @@ using System.Threading.Tasks; using TelegramBotBase.Base; -namespace TelegramBotBase.Controls.Inline +namespace TelegramBotBase.Controls.Inline; + +/// +/// A simple control for show and managing progress. +/// +public class ProgressBar : ControlBase { - /// - /// A simple control for show and managing progress. - /// - public class ProgressBar : ControlBase + public enum EProgressStyle { - public enum EProgressStyle - { - standard = 0, - squares = 1, - circles = 2, - lines = 3, - squaredLines = 4, - custom = 10 - } - - public EProgressStyle ProgressStyle - { - get => _mEStyle; - set - { - _mEStyle = value; - LoadStyle(); - } - } - - private EProgressStyle _mEStyle = EProgressStyle.standard; - - - public int Value - { - get => _mIValue; - set - { - if (value > Max) - { - return; - } - - if (_mIValue != value) - { - RenderNecessary = true; - } - _mIValue = value; - } - } - - private int _mIValue; - - public int Max - { - get => _mIMax; - set - { - if (_mIMax != value) - { - RenderNecessary = true; - } - _mIMax = value; - } - } - - private int _mIMax = 100; - - public int? MessageId { get; set; } - - private bool RenderNecessary { get; set; } - - public int Steps - { - get - { - return ProgressStyle switch - { - EProgressStyle.standard => 1, - EProgressStyle.squares => 10, - EProgressStyle.circles => 10, - EProgressStyle.lines => 5, - EProgressStyle.squaredLines => 5, - _ => 1 - }; - } - } - - /// - /// Filled block (reached percentage) - /// - public string BlockChar - { - get; set; - } - - /// - /// Unfilled block (not reached yet) - /// - public string EmptyBlockChar - { - get; set; - } - - /// - /// String at the beginning of the progress bar - /// - public string StartChar - { - get; set; - } - - /// - /// String at the end of the progress bar - /// - public string EndChar - { - get; set; - } - - public ProgressBar() - { - ProgressStyle = EProgressStyle.standard; - - Value = 0; - Max = 100; - - RenderNecessary = true; - } - - public ProgressBar(int value, int max, EProgressStyle style) - { - this.Value = value; - this.Max = max; - ProgressStyle = style; - - RenderNecessary = true; - } - - public override async Task Cleanup() - { - if (MessageId == null || MessageId == -1) - return; - - - await Device.DeleteMessage(MessageId.Value); - } - - public void LoadStyle() - { - StartChar = ""; - EndChar = ""; - - switch (ProgressStyle) - { - case EProgressStyle.circles: - - BlockChar = "⚫️ "; - EmptyBlockChar = "⚪️ "; - - break; - case EProgressStyle.squares: - - BlockChar = "⬛️ "; - EmptyBlockChar = "⬜️ "; - - break; - case EProgressStyle.lines: - - BlockChar = "█"; - EmptyBlockChar = "▁"; - - break; - case EProgressStyle.squaredLines: - - BlockChar = "▇"; - EmptyBlockChar = "—"; - - StartChar = "["; - EndChar = "]"; - - break; - case EProgressStyle.standard: - case EProgressStyle.custom: - - BlockChar = ""; - EmptyBlockChar = ""; - - break; - } - - } - - public override async Task Render(MessageResult result) - { - if (!RenderNecessary) - { - return; - } - - if (Device == null) - { - return; - } - - var message = ""; - var blocks = 0; - var maxBlocks = 0; - - switch (ProgressStyle) - { - case EProgressStyle.standard: - - message = Value.ToString("0") + "%"; - - break; - - case EProgressStyle.squares: - case EProgressStyle.circles: - case EProgressStyle.lines: - case EProgressStyle.squaredLines: - case EProgressStyle.custom: - - blocks = (int)Math.Floor((decimal)Value / Steps); - - maxBlocks = (Max / Steps); - - message += StartChar; - - for (var i = 0; i < blocks; i++) - { - message += BlockChar; - } - - for (var i = 0; i < (maxBlocks - blocks); i++) - { - message += EmptyBlockChar; - } - - message += EndChar; - - message += " " + Value.ToString("0") + "%"; - - break; - - default: - - return; - } - - if (MessageId == null) - { - var m = await Device.Send(message); - - MessageId = m.MessageId; - } - else - { - await Device.Edit(MessageId.Value, message); - } - - RenderNecessary = false; - } - + standard = 0, + squares = 1, + circles = 2, + lines = 3, + squaredLines = 4, + custom = 10 } -} + + private EProgressStyle _mEStyle = EProgressStyle.standard; + + private int _mIMax = 100; + + private int _mIValue; + + public ProgressBar() + { + ProgressStyle = EProgressStyle.standard; + + Value = 0; + Max = 100; + + RenderNecessary = true; + } + + public ProgressBar(int value, int max, EProgressStyle style) + { + Value = value; + Max = max; + ProgressStyle = style; + + RenderNecessary = true; + } + + public EProgressStyle ProgressStyle + { + get => _mEStyle; + set + { + _mEStyle = value; + LoadStyle(); + } + } + + + public int Value + { + get => _mIValue; + set + { + if (value > Max) + { + return; + } + + if (_mIValue != value) + { + RenderNecessary = true; + } + + _mIValue = value; + } + } + + public int Max + { + get => _mIMax; + set + { + if (_mIMax != value) + { + RenderNecessary = true; + } + + _mIMax = value; + } + } + + public int? MessageId { get; set; } + + private bool RenderNecessary { get; set; } + + public int Steps + { + get + { + return ProgressStyle switch + { + EProgressStyle.standard => 1, + EProgressStyle.squares => 10, + EProgressStyle.circles => 10, + EProgressStyle.lines => 5, + EProgressStyle.squaredLines => 5, + _ => 1 + }; + } + } + + /// + /// Filled block (reached percentage) + /// + public string BlockChar { get; set; } + + /// + /// Unfilled block (not reached yet) + /// + public string EmptyBlockChar { get; set; } + + /// + /// String at the beginning of the progress bar + /// + public string StartChar { get; set; } + + /// + /// String at the end of the progress bar + /// + public string EndChar { get; set; } + + public override async Task Cleanup() + { + if (MessageId == null || MessageId == -1) + { + return; + } + + + await Device.DeleteMessage(MessageId.Value); + } + + public void LoadStyle() + { + StartChar = ""; + EndChar = ""; + + switch (ProgressStyle) + { + case EProgressStyle.circles: + + BlockChar = "⚫️ "; + EmptyBlockChar = "⚪️ "; + + break; + case EProgressStyle.squares: + + BlockChar = "⬛️ "; + EmptyBlockChar = "⬜️ "; + + break; + case EProgressStyle.lines: + + BlockChar = "█"; + EmptyBlockChar = "▁"; + + break; + case EProgressStyle.squaredLines: + + BlockChar = "▇"; + EmptyBlockChar = "—"; + + StartChar = "["; + EndChar = "]"; + + break; + case EProgressStyle.standard: + case EProgressStyle.custom: + + BlockChar = ""; + EmptyBlockChar = ""; + + break; + } + } + + public override async Task Render(MessageResult result) + { + if (!RenderNecessary) + { + return; + } + + if (Device == null) + { + return; + } + + var message = ""; + var blocks = 0; + var maxBlocks = 0; + + switch (ProgressStyle) + { + case EProgressStyle.standard: + + message = Value.ToString("0") + "%"; + + break; + + case EProgressStyle.squares: + case EProgressStyle.circles: + case EProgressStyle.lines: + case EProgressStyle.squaredLines: + case EProgressStyle.custom: + + blocks = (int)Math.Floor((decimal)Value / Steps); + + maxBlocks = Max / Steps; + + message += StartChar; + + for (var i = 0; i < blocks; i++) + { + message += BlockChar; + } + + for (var i = 0; i < maxBlocks - blocks; i++) + { + message += EmptyBlockChar; + } + + message += EndChar; + + message += " " + Value.ToString("0") + "%"; + + break; + + default: + + return; + } + + if (MessageId == null) + { + var m = await Device.Send(message); + + MessageId = m.MessageId; + } + else + { + await Device.Edit(MessageId.Value, message); + } + + RenderNecessary = false; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Controls/Inline/ToggleButton.cs b/TelegramBotBase/Controls/Inline/ToggleButton.cs index 8f27415..4c7811e 100644 --- a/TelegramBotBase/Controls/Inline/ToggleButton.cs +++ b/TelegramBotBase/Controls/Inline/ToggleButton.cs @@ -5,135 +5,133 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; using TelegramBotBase.Localizations; -namespace TelegramBotBase.Controls.Inline +namespace TelegramBotBase.Controls.Inline; + +public class ToggleButton : ControlBase { - public class ToggleButton : ControlBase + private static readonly object EvToggled = new(); + + private readonly EventHandlerList _events = new(); + + private bool _renderNecessary = true; + + + public ToggleButton() { - - public string UncheckedIcon { get; set; } = Default.Language["ToggleButton_OffIcon"]; - - public string CheckedIcon { get; set; } = Default.Language["ToggleButton_OnIcon"]; - - public string CheckedString { get; set; } = Default.Language["ToggleButton_On"]; - - public string UncheckedString { get; set; } = Default.Language["ToggleButton_Off"]; - - public string ChangedString { get; set; } = Default.Language["ToggleButton_Changed"]; - - public string Title { get; set; } = Default.Language["ToggleButton_Title"]; - - public int? MessageId { get; set; } - - public bool Checked { get; set; } - - private bool _renderNecessary = true; - - private static readonly object EvToggled = new object(); - - private readonly EventHandlerList _events = new EventHandlerList(); - - - public ToggleButton() - { - - - } - - public ToggleButton(string checkedString, string uncheckedString) - { - this.CheckedString = checkedString; - this.UncheckedString = uncheckedString; - } - - public event EventHandler Toggled - { - add => _events.AddHandler(EvToggled, value); - remove => _events.RemoveHandler(EvToggled, value); - } - - public void OnToggled(EventArgs e) - { - (_events[EvToggled] as EventHandler)?.Invoke(this, e); - } - - public override async Task Action(MessageResult result, string value = null) - { - - if (result.Handled) - return; - - await result.ConfirmAction(ChangedString); - - switch (value ?? "unknown") - { - case "on": - - if (Checked) - return; - - _renderNecessary = true; - - Checked = true; - - OnToggled(EventArgs.Empty); - - break; - - case "off": - - if (!Checked) - return; - - _renderNecessary = true; - - Checked = false; - - OnToggled(EventArgs.Empty); - - break; - - default: - - _renderNecessary = false; - - break; - - } - - result.Handled = true; - - } - - public override async Task Render(MessageResult result) - { - if (!_renderNecessary) - return; - - var bf = new ButtonForm(this); - - var bOn = new ButtonBase((Checked ? CheckedIcon : UncheckedIcon) + " " + CheckedString, "on"); - - var bOff = new ButtonBase((!Checked ? CheckedIcon : UncheckedIcon) + " " + UncheckedString, "off"); - - bf.AddButtonRow(bOn, bOff); - - if (MessageId != null) - { - var m = await Device.Edit(MessageId.Value, Title, bf); - } - else - { - var m = await Device.Send(Title, bf, disableNotification: true); - if (m != null) - { - MessageId = m.MessageId; - } - } - - _renderNecessary = false; - - - } - } -} + + public ToggleButton(string checkedString, string uncheckedString) + { + CheckedString = checkedString; + UncheckedString = uncheckedString; + } + + public string UncheckedIcon { get; set; } = Default.Language["ToggleButton_OffIcon"]; + + public string CheckedIcon { get; set; } = Default.Language["ToggleButton_OnIcon"]; + + public string CheckedString { get; set; } = Default.Language["ToggleButton_On"]; + + public string UncheckedString { get; set; } = Default.Language["ToggleButton_Off"]; + + public string ChangedString { get; set; } = Default.Language["ToggleButton_Changed"]; + + public string Title { get; set; } = Default.Language["ToggleButton_Title"]; + + public int? MessageId { get; set; } + + public bool Checked { get; set; } + + public event EventHandler Toggled + { + add => _events.AddHandler(EvToggled, value); + remove => _events.RemoveHandler(EvToggled, value); + } + + public void OnToggled(EventArgs e) + { + (_events[EvToggled] as EventHandler)?.Invoke(this, e); + } + + public override async Task Action(MessageResult result, string value = null) + { + if (result.Handled) + { + return; + } + + await result.ConfirmAction(ChangedString); + + switch (value ?? "unknown") + { + case "on": + + if (Checked) + { + return; + } + + _renderNecessary = true; + + Checked = true; + + OnToggled(EventArgs.Empty); + + break; + + case "off": + + if (!Checked) + { + return; + } + + _renderNecessary = true; + + Checked = false; + + OnToggled(EventArgs.Empty); + + break; + + default: + + _renderNecessary = false; + + break; + } + + result.Handled = true; + } + + public override async Task Render(MessageResult result) + { + if (!_renderNecessary) + { + return; + } + + var bf = new ButtonForm(this); + + var bOn = new ButtonBase((Checked ? CheckedIcon : UncheckedIcon) + " " + CheckedString, "on"); + + var bOff = new ButtonBase((!Checked ? CheckedIcon : UncheckedIcon) + " " + UncheckedString, "off"); + + bf.AddButtonRow(bOn, bOff); + + if (MessageId != null) + { + var m = await Device.Edit(MessageId.Value, Title, bf); + } + else + { + var m = await Device.Send(Title, bf, disableNotification: true); + if (m != null) + { + MessageId = m.MessageId; + } + } + + _renderNecessary = false; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Controls/Inline/TreeView.cs b/TelegramBotBase/Controls/Inline/TreeView.cs index e3b6612..1aee568 100644 --- a/TelegramBotBase/Controls/Inline/TreeView.cs +++ b/TelegramBotBase/Controls/Inline/TreeView.cs @@ -5,117 +5,117 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; using TelegramBotBase.Localizations; -namespace TelegramBotBase.Controls.Inline +namespace TelegramBotBase.Controls.Inline; + +public class TreeView : ControlBase { - public class TreeView : ControlBase + public TreeView() { - public List Nodes { get; set; } + Nodes = new List(); + Title = Default.Language["TreeView_Title"]; + } - public TreeViewNode SelectedNode { get; set; } + public List Nodes { get; set; } - public TreeViewNode VisibleNode { get; set; } + public TreeViewNode SelectedNode { get; set; } - public string Title { get; set; } + public TreeViewNode VisibleNode { get; set; } - private int? MessageId { get; set; } + public string Title { get; set; } - public string MoveUpIcon { get; set; } = Default.Language["TreeView_LevelUp"]; + private int? MessageId { get; set; } - public TreeView() + public string MoveUpIcon { get; set; } = Default.Language["TreeView_LevelUp"]; + + + public override async Task Action(MessageResult result, string value = null) + { + await result.ConfirmAction(); + + if (result.Handled) { - Nodes = new List(); - Title = Default.Language["TreeView_Title"]; + return; } + var val = result.RawData; - public override async Task Action(MessageResult result, string value = null) + switch (val) { - await result.ConfirmAction(); + case "up": + case "parent": - if (result.Handled) - return; + VisibleNode = VisibleNode?.ParentNode; - var val = result.RawData; + result.Handled = true; - switch (val) - { - case "up": - case "parent": + break; + default: - VisibleNode = (VisibleNode?.ParentNode); + var n = VisibleNode != null + ? VisibleNode.FindNodeByValue(val) + : Nodes.FirstOrDefault(a => a.Value == val); - result.Handled = true; - - break; - default: - - var n = (VisibleNode != null ? VisibleNode.FindNodeByValue(val) : Nodes.FirstOrDefault(a => a.Value == val)); - - if (n == null) - return; - - - if (n.ChildNodes.Count > 0) - { - VisibleNode = n; - } - else - { - SelectedNode = (SelectedNode != n ? n : null); - } - - result.Handled = true; - - - break; - - } - - } - - - public override async Task Render(MessageResult result) - { - var startnode = VisibleNode; - - var nodes = (startnode?.ChildNodes ?? Nodes); - - var bf = new ButtonForm(); - - if (startnode != null) - { - bf.AddButtonRow(new ButtonBase(MoveUpIcon, "up"), new ButtonBase(startnode.Text, "parent")); - } - - foreach (var n in nodes) - { - var s = n.Text; - if (SelectedNode == n) + if (n == null) { - s = "[ " + s + " ]"; + return; } - bf.AddButtonRow(new ButtonBase(s, n.Value, n.Url)); - } + + if (n.ChildNodes.Count > 0) + { + VisibleNode = n; + } + else + { + SelectedNode = SelectedNode != n ? n : null; + } + + result.Handled = true; - - if (MessageId != null) - { - var m = await Device.Edit(MessageId.Value, Title, bf); - } - else - { - var m = await Device.Send(Title, bf); - MessageId = m.MessageId; - } + break; } - - public string GetPath() - { - return (VisibleNode?.GetPath() ?? "\\"); - } - - } -} + + + public override async Task Render(MessageResult result) + { + var startnode = VisibleNode; + + var nodes = startnode?.ChildNodes ?? Nodes; + + var bf = new ButtonForm(); + + if (startnode != null) + { + bf.AddButtonRow(new ButtonBase(MoveUpIcon, "up"), new ButtonBase(startnode.Text, "parent")); + } + + foreach (var n in nodes) + { + var s = n.Text; + if (SelectedNode == n) + { + s = "[ " + s + " ]"; + } + + bf.AddButtonRow(new ButtonBase(s, n.Value, n.Url)); + } + + + if (MessageId != null) + { + var m = await Device.Edit(MessageId.Value, Title, bf); + } + else + { + var m = await Device.Send(Title, bf); + MessageId = m.MessageId; + } + } + + public string GetPath() + { + return VisibleNode?.GetPath() ?? "\\"; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Controls/Inline/TreeViewNode.cs b/TelegramBotBase/Controls/Inline/TreeViewNode.cs index 4219f49..b714bbd 100644 --- a/TelegramBotBase/Controls/Inline/TreeViewNode.cs +++ b/TelegramBotBase/Controls/Inline/TreeViewNode.cs @@ -1,62 +1,61 @@ using System.Collections.Generic; using System.Linq; -namespace TelegramBotBase.Controls.Inline +namespace TelegramBotBase.Controls.Inline; + +public class TreeViewNode { - public class TreeViewNode + public TreeViewNode(string text, string value) { - public string Text { get; set; } - - public string Value { get; set; } - - public string Url { get; set; } - - public List ChildNodes { get; set; } = new List(); - - public TreeViewNode ParentNode { get; set; } - - public TreeViewNode(string text, string value) - { - this.Text = text; - this.Value = value; - } - - public TreeViewNode(string text, string value, string url) : this(text, value) - { - this.Url = url; - } - - public TreeViewNode(string text, string value, params TreeViewNode[] childnodes) : this(text, value) - { - foreach(var c in childnodes) - { - AddNode(c); - } - } - - - public void AddNode(TreeViewNode node) - { - node.ParentNode = this; - ChildNodes.Add(node); - } - - public TreeViewNode FindNodeByValue(string value) - { - return ChildNodes.FirstOrDefault(a => a.Value == value); - } - - public string GetPath() - { - var s = "\\" + Value; - var p = this; - while (p.ParentNode != null) - { - s = "\\" + p.ParentNode.Value + s; - p = p.ParentNode; - } - return s; - } - + Text = text; + Value = value; } -} + + public TreeViewNode(string text, string value, string url) : this(text, value) + { + Url = url; + } + + public TreeViewNode(string text, string value, params TreeViewNode[] childnodes) : this(text, value) + { + foreach (var c in childnodes) + { + AddNode(c); + } + } + + public string Text { get; set; } + + public string Value { get; set; } + + public string Url { get; set; } + + public List ChildNodes { get; set; } = new(); + + public TreeViewNode ParentNode { get; set; } + + + public void AddNode(TreeViewNode node) + { + node.ParentNode = this; + ChildNodes.Add(node); + } + + public TreeViewNode FindNodeByValue(string value) + { + return ChildNodes.FirstOrDefault(a => a.Value == value); + } + + public string GetPath() + { + var s = "\\" + Value; + var p = this; + while (p.ParentNode != null) + { + s = "\\" + p.ParentNode.Value + s; + p = p.ParentNode; + } + + return s; + } +} \ No newline at end of file diff --git a/TelegramBotBase/DataSources/ButtonFormDataSource.cs b/TelegramBotBase/DataSources/ButtonFormDataSource.cs index 3b90ec8..c14b7e3 100644 --- a/TelegramBotBase/DataSources/ButtonFormDataSource.cs +++ b/TelegramBotBase/DataSources/ButtonFormDataSource.cs @@ -4,132 +4,134 @@ using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Form; using TelegramBotBase.Interfaces; -namespace TelegramBotBase.DataSources +namespace TelegramBotBase.DataSources; + +public class ButtonFormDataSource : IDataSource { - public class ButtonFormDataSource : IDataSource + private ButtonForm _buttonform; + + public ButtonFormDataSource() { - public virtual ButtonForm ButtonForm - { - get => _buttonform; - set => _buttonform = value; - } - - private ButtonForm _buttonform; - - public ButtonFormDataSource() - { - _buttonform = new ButtonForm(); - } - - public ButtonFormDataSource(ButtonForm bf) - { - _buttonform = bf; - } - - - /// - /// Returns the amount of rows exisiting. - /// - /// - public virtual int Count => ButtonForm.Count; - - - /// - /// Returns the amount of rows. - /// - public virtual int RowCount => ButtonForm.Rows; - - /// - /// Returns the maximum amount of columns. - /// - public virtual int ColumnCount => ButtonForm.Cols; - - /// - /// Returns the row with the specific index. - /// - /// - /// - public virtual ButtonRow ItemAt(int index) - { - return ButtonForm[index]; - } - - public virtual List ItemRange(int start, int count) - { - return ButtonForm.GetRange(start, count); - } - - public virtual List AllItems() - { - return ButtonForm.ToArray(); - } - - public virtual ButtonForm PickItems(int start, int count, string filter = null) - { - var bf = new ButtonForm(); - ButtonForm dataForm = null; - - if (filter == null) - { - dataForm = ButtonForm.Duplicate(); - } - else - { - dataForm = ButtonForm.FilterDuplicate(filter, true); - } - - for (var i = 0; i < count; i++) - { - var it = start + i; - - if (it > dataForm.Rows - 1) - break; - - bf.AddButtonRow(dataForm[it]); - } - - return bf; - } - - public virtual ButtonForm PickAllItems(string filter = null) - { - if (filter == null) - return ButtonForm.Duplicate(); - - - return ButtonForm.FilterDuplicate(filter, true); - } - - public virtual Tuple FindRow(string text, bool useText = true) - { - return ButtonForm.FindRow(text, useText); - } - - /// - /// Returns the maximum items of this data source. - /// - /// - /// - public virtual int CalculateMax(string filter = null) - { - return PickAllItems(filter).Rows; - } - - public virtual ButtonRow Render(object data) - { - return data as ButtonRow; - } - - - public static implicit operator ButtonFormDataSource(ButtonForm bf) - { - return new ButtonFormDataSource(bf); - } - - public static implicit operator ButtonForm(ButtonFormDataSource ds) - { - return ds.ButtonForm; - } - + _buttonform = new ButtonForm(); } -} + + public ButtonFormDataSource(ButtonForm bf) + { + _buttonform = bf; + } + + public virtual ButtonForm ButtonForm + { + get => _buttonform; + set => _buttonform = value; + } + + + /// + /// Returns the amount of rows. + /// + public virtual int RowCount => ButtonForm.Rows; + + /// + /// Returns the maximum amount of columns. + /// + public virtual int ColumnCount => ButtonForm.Cols; + + + /// + /// Returns the amount of rows exisiting. + /// + /// + public virtual int Count => ButtonForm.Count; + + /// + /// Returns the row with the specific index. + /// + /// + /// + public virtual ButtonRow ItemAt(int index) + { + return ButtonForm[index]; + } + + public virtual List ItemRange(int start, int count) + { + return ButtonForm.GetRange(start, count); + } + + public virtual List AllItems() + { + return ButtonForm.ToArray(); + } + + public virtual ButtonForm PickItems(int start, int count, string filter = null) + { + var bf = new ButtonForm(); + ButtonForm dataForm = null; + + if (filter == null) + { + dataForm = ButtonForm.Duplicate(); + } + else + { + dataForm = ButtonForm.FilterDuplicate(filter, true); + } + + for (var i = 0; i < count; i++) + { + var it = start + i; + + if (it > dataForm.Rows - 1) + { + break; + } + + bf.AddButtonRow(dataForm[it]); + } + + return bf; + } + + public virtual ButtonForm PickAllItems(string filter = null) + { + if (filter == null) + { + return ButtonForm.Duplicate(); + } + + + return ButtonForm.FilterDuplicate(filter, true); + } + + public virtual Tuple FindRow(string text, bool useText = true) + { + return ButtonForm.FindRow(text, useText); + } + + /// + /// Returns the maximum items of this data source. + /// + /// + /// + public virtual int CalculateMax(string filter = null) + { + return PickAllItems(filter).Rows; + } + + public virtual ButtonRow Render(object data) + { + return data as ButtonRow; + } + + + public static implicit operator ButtonFormDataSource(ButtonForm bf) + { + return new ButtonFormDataSource(bf); + } + + public static implicit operator ButtonForm(ButtonFormDataSource ds) + { + return ds.ButtonForm; + } +} \ No newline at end of file diff --git a/TelegramBotBase/DataSources/StaticDataSource.cs b/TelegramBotBase/DataSources/StaticDataSource.cs index 59e400e..2cf1d50 100644 --- a/TelegramBotBase/DataSources/StaticDataSource.cs +++ b/TelegramBotBase/DataSources/StaticDataSource.cs @@ -2,38 +2,36 @@ using System.Linq; using TelegramBotBase.Interfaces; -namespace TelegramBotBase.DataSources +namespace TelegramBotBase.DataSources; + +public class StaticDataSource : IDataSource { - public class StaticDataSource : IDataSource + public StaticDataSource() { - private List Data { get; set; } - - public StaticDataSource() - { - - } - - public StaticDataSource(List data) - { - Data = data; - } - - - public int Count => Data.Count; - - public T ItemAt(int index) - { - return Data[index]; - } - - public List ItemRange(int start, int count) - { - return Data.Skip(start).Take(count).ToList(); - } - - public List AllItems() - { - return Data; - } } -} + + public StaticDataSource(List data) + { + Data = data; + } + + private List Data { get; } + + + public int Count => Data.Count; + + public T ItemAt(int index) + { + return Data[index]; + } + + public List ItemRange(int start, int count) + { + return Data.Skip(start).Take(count).ToList(); + } + + public List AllItems() + { + return Data; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Enums/eDeleteMode.cs b/TelegramBotBase/Enums/eDeleteMode.cs index b4d190a..4cd1421 100644 --- a/TelegramBotBase/Enums/eDeleteMode.cs +++ b/TelegramBotBase/Enums/eDeleteMode.cs @@ -1,18 +1,19 @@ -namespace TelegramBotBase.Enums +namespace TelegramBotBase.Enums; + +public enum EDeleteMode { - public enum EDeleteMode - { - /// - /// Don't delete any message. - /// - None = 0, - /// - /// Delete messages on every callback/action. - /// - OnEveryCall = 1, - /// - /// Delete on leaving this form. - /// - OnLeavingForm = 2 - } -} + /// + /// Don't delete any message. + /// + None = 0, + + /// + /// Delete messages on every callback/action. + /// + OnEveryCall = 1, + + /// + /// Delete on leaving this form. + /// + OnLeavingForm = 2 +} \ No newline at end of file diff --git a/TelegramBotBase/Enums/eDeleteSide.cs b/TelegramBotBase/Enums/eDeleteSide.cs index 1b91ea1..3c75443 100644 --- a/TelegramBotBase/Enums/eDeleteSide.cs +++ b/TelegramBotBase/Enums/eDeleteSide.cs @@ -1,18 +1,19 @@ -namespace TelegramBotBase.Enums +namespace TelegramBotBase.Enums; + +public enum EDeleteSide { - public enum EDeleteSide - { - /// - /// Delete only messages from this bot. - /// - BotOnly = 0, - /// - /// Delete only user messages. - /// - UserOnly = 1, - /// - /// Delete all messages in this context. - /// - Both = 2 - } -} + /// + /// Delete only messages from this bot. + /// + BotOnly = 0, + + /// + /// Delete only user messages. + /// + UserOnly = 1, + + /// + /// Delete all messages in this context. + /// + Both = 2 +} \ No newline at end of file diff --git a/TelegramBotBase/Enums/eKeyboardType.cs b/TelegramBotBase/Enums/eKeyboardType.cs index ed808a0..c4f2033 100644 --- a/TelegramBotBase/Enums/eKeyboardType.cs +++ b/TelegramBotBase/Enums/eKeyboardType.cs @@ -1,16 +1,14 @@ -namespace TelegramBotBase.Enums +namespace TelegramBotBase.Enums; + +public enum EKeyboardType { - public enum EKeyboardType - { - /// - /// Uses a ReplyKeyboardMarkup - /// - ReplyKeyboard = 0, + /// + /// Uses a ReplyKeyboardMarkup + /// + ReplyKeyboard = 0, - /// - /// Uses a InlineKeyboardMakup - /// - InlineKeyBoard = 1 - - } -} + /// + /// Uses a InlineKeyboardMakup + /// + InlineKeyBoard = 1 +} \ No newline at end of file diff --git a/TelegramBotBase/Enums/eMonthPickerMode.cs b/TelegramBotBase/Enums/eMonthPickerMode.cs index b5f318f..f61cd08 100644 --- a/TelegramBotBase/Enums/eMonthPickerMode.cs +++ b/TelegramBotBase/Enums/eMonthPickerMode.cs @@ -1,18 +1,19 @@ -namespace TelegramBotBase.Enums +namespace TelegramBotBase.Enums; + +public enum EMonthPickerMode { - public enum EMonthPickerMode - { - /// - /// Shows the calendar with day picker mode - /// - day = 0, - /// - /// Shows the calendar with month overview - /// - month = 1, - /// - /// Shows the calendar with year overview - /// - year = 2 - } -} + /// + /// Shows the calendar with day picker mode + /// + day = 0, + + /// + /// Shows the calendar with month overview + /// + month = 1, + + /// + /// Shows the calendar with year overview + /// + year = 2 +} \ No newline at end of file diff --git a/TelegramBotBase/Enums/eNavigationBarVisibility.cs b/TelegramBotBase/Enums/eNavigationBarVisibility.cs index 00b4d57..f9834c2 100644 --- a/TelegramBotBase/Enums/eNavigationBarVisibility.cs +++ b/TelegramBotBase/Enums/eNavigationBarVisibility.cs @@ -1,21 +1,19 @@ -namespace TelegramBotBase.Enums +namespace TelegramBotBase.Enums; + +public enum ENavigationBarVisibility { - public enum ENavigationBarVisibility - { - /// - /// Shows it depending on the amount of items. - /// - auto = 0, + /// + /// Shows it depending on the amount of items. + /// + auto = 0, - /// - /// Will not show it at any time. - /// - never = 1, + /// + /// Will not show it at any time. + /// + never = 1, - /// - /// Will show it at any time. - /// - always = 2 - - } -} + /// + /// Will show it at any time. + /// + always = 2 +} \ No newline at end of file diff --git a/TelegramBotBase/Enums/eSettings.cs b/TelegramBotBase/Enums/eSettings.cs index da63d21..cebc8f7 100644 --- a/TelegramBotBase/Enums/eSettings.cs +++ b/TelegramBotBase/Enums/eSettings.cs @@ -1,36 +1,34 @@ -namespace TelegramBotBase.Enums +namespace TelegramBotBase.Enums; + +public enum ESettings { - public enum ESettings - { - /// - /// How often could a form navigate to another (within one user action/call/message) - /// - NavigationMaximum = 1, + /// + /// How often could a form navigate to another (within one user action/call/message) + /// + NavigationMaximum = 1, - /// - /// Loggs all messages and sent them to the event handler - /// - LogAllMessages = 2, + /// + /// Loggs all messages and sent them to the event handler + /// + LogAllMessages = 2, - /// - /// Skips all messages during running (good for big delay updates) - /// - SkipAllMessages = 3, + /// + /// Skips all messages during running (good for big delay updates) + /// + SkipAllMessages = 3, - /// - /// Does stick to the console event handler and saves all sessions on exit. - /// - SaveSessionsOnConsoleExit = 4, + /// + /// Does stick to the console event handler and saves all sessions on exit. + /// + SaveSessionsOnConsoleExit = 4, - /// - /// Indicates the maximum number of times a request that received error - /// 429 will be sent again after a timeout until it receives code 200 or an error code not equal to 429. - /// - MaxNumberOfRetries = 5, - - } -} + /// + /// Indicates the maximum number of times a request that received error + /// 429 will be sent again after a timeout until it receives code 200 or an error code not equal to 429. + /// + MaxNumberOfRetries = 5 +} \ No newline at end of file diff --git a/TelegramBotBase/Exceptions/MaxLengthException.cs b/TelegramBotBase/Exceptions/MaxLengthException.cs index 86d811a..2e93214 100644 --- a/TelegramBotBase/Exceptions/MaxLengthException.cs +++ b/TelegramBotBase/Exceptions/MaxLengthException.cs @@ -1,13 +1,11 @@ using System; -namespace TelegramBotBase.Exceptions -{ - public class MaxLengthException : Exception - { - public MaxLengthException(int length) : base($"Your messages with a length of {length} is too long for telegram. Actually is {Constants.Telegram.MaxMessageLength} characters allowed. Please split it.") - { - - } +namespace TelegramBotBase.Exceptions; +public class MaxLengthException : Exception +{ + public MaxLengthException(int length) : base( + $"Your messages with a length of {length} is too long for telegram. Actually is {Constants.Telegram.MaxMessageLength} characters allowed. Please split it.") + { } -} +} \ No newline at end of file diff --git a/TelegramBotBase/Exceptions/MaximumColsException.cs b/TelegramBotBase/Exceptions/MaximumColsException.cs index 8ddf203..4209353 100644 --- a/TelegramBotBase/Exceptions/MaximumColsException.cs +++ b/TelegramBotBase/Exceptions/MaximumColsException.cs @@ -1,14 +1,14 @@ using System; -namespace TelegramBotBase.Exceptions +namespace TelegramBotBase.Exceptions; + +public class MaximumColsException : Exception { - public class MaximumColsException : Exception - { - public int Value { get; set; } + public int Value { get; set; } - public int Maximum { get; set; } + public int Maximum { get; set; } - public override string Message => $"You have exceeded the maximum of columns by {Value.ToString()} / {Maximum.ToString()}"; - } -} + public override string Message => + $"You have exceeded the maximum of columns by {Value.ToString()} / {Maximum.ToString()}"; +} \ No newline at end of file diff --git a/TelegramBotBase/Exceptions/MaximumRowsException.cs b/TelegramBotBase/Exceptions/MaximumRowsException.cs index 10f5140..be3ad7d 100644 --- a/TelegramBotBase/Exceptions/MaximumRowsException.cs +++ b/TelegramBotBase/Exceptions/MaximumRowsException.cs @@ -1,14 +1,14 @@ using System; -namespace TelegramBotBase.Exceptions +namespace TelegramBotBase.Exceptions; + +public class MaximumRowsReachedException : Exception { - public class MaximumRowsReachedException : Exception - { - public int Value { get; set; } + public int Value { get; set; } - public int Maximum { get; set; } + public int Maximum { get; set; } - public override string Message => $"You have exceeded the maximum of rows by {Value.ToString()} / {Maximum.ToString()}"; - } -} + public override string Message => + $"You have exceeded the maximum of rows by {Value.ToString()} / {Maximum.ToString()}"; +} \ No newline at end of file diff --git a/TelegramBotBase/Factories/DefaultStartFormFactory.cs b/TelegramBotBase/Factories/DefaultStartFormFactory.cs index 969d446..7ce2988 100644 --- a/TelegramBotBase/Factories/DefaultStartFormFactory.cs +++ b/TelegramBotBase/Factories/DefaultStartFormFactory.cs @@ -2,24 +2,25 @@ using TelegramBotBase.Form; using TelegramBotBase.Interfaces; -namespace TelegramBotBase.Factories +namespace TelegramBotBase.Factories; + +public class DefaultStartFormFactory : IStartFormFactory { - public class DefaultStartFormFactory : IStartFormFactory + private readonly Type _startFormClass; + + public DefaultStartFormFactory(Type startFormClass) { - private readonly Type _startFormClass; - - public DefaultStartFormFactory(Type startFormClass) + if (!typeof(FormBase).IsAssignableFrom(startFormClass)) { - if (!typeof(FormBase).IsAssignableFrom(startFormClass)) - throw new ArgumentException("startFormClass argument must be a FormBase type"); - - _startFormClass = startFormClass; + throw new ArgumentException("startFormClass argument must be a FormBase type"); } - - public FormBase CreateForm() - { - return _startFormClass.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as FormBase; - } + _startFormClass = startFormClass; } -} + + + public FormBase CreateForm() + { + return _startFormClass.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as FormBase; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Factories/LambdaStartFormFactory.cs b/TelegramBotBase/Factories/LambdaStartFormFactory.cs index 563e03e..2ca4c5c 100644 --- a/TelegramBotBase/Factories/LambdaStartFormFactory.cs +++ b/TelegramBotBase/Factories/LambdaStartFormFactory.cs @@ -1,22 +1,21 @@ using TelegramBotBase.Form; using TelegramBotBase.Interfaces; -namespace TelegramBotBase.Factories +namespace TelegramBotBase.Factories; + +public class LambdaStartFormFactory : IStartFormFactory { - public class LambdaStartFormFactory : IStartFormFactory + public delegate FormBase CreateFormDelegate(); + + private readonly CreateFormDelegate _lambda; + + public LambdaStartFormFactory(CreateFormDelegate lambda) { - public delegate FormBase CreateFormDelegate(); - - private readonly CreateFormDelegate _lambda; - - public LambdaStartFormFactory(CreateFormDelegate lambda) - { - _lambda = lambda; - } - - public FormBase CreateForm() - { - return _lambda(); - } + _lambda = lambda; } -} + + public FormBase CreateForm() + { + return _lambda(); + } +} \ No newline at end of file diff --git a/TelegramBotBase/Factories/ServiceProviderStartFormFactory.cs b/TelegramBotBase/Factories/ServiceProviderStartFormFactory.cs index 4f2a0ef..4ee81db 100644 --- a/TelegramBotBase/Factories/ServiceProviderStartFormFactory.cs +++ b/TelegramBotBase/Factories/ServiceProviderStartFormFactory.cs @@ -3,33 +3,34 @@ using Microsoft.Extensions.DependencyInjection; using TelegramBotBase.Form; using TelegramBotBase.Interfaces; -namespace TelegramBotBase.Factories +namespace TelegramBotBase.Factories; + +public class ServiceProviderStartFormFactory : IStartFormFactory { - public class ServiceProviderStartFormFactory : IStartFormFactory + private readonly IServiceProvider _serviceProvider; + private readonly Type _startFormClass; + + public ServiceProviderStartFormFactory(Type startFormClass, IServiceProvider serviceProvider) { - private readonly Type _startFormClass; - private readonly IServiceProvider _serviceProvider; - - public ServiceProviderStartFormFactory(Type startFormClass, IServiceProvider serviceProvider) + if (!typeof(FormBase).IsAssignableFrom(startFormClass)) { - if (!typeof(FormBase).IsAssignableFrom(startFormClass)) - throw new ArgumentException("startFormClass argument must be a FormBase type"); - - _startFormClass = startFormClass; - _serviceProvider = serviceProvider; + throw new ArgumentException("startFormClass argument must be a FormBase type"); } - public FormBase CreateForm() - { - return (FormBase)ActivatorUtilities.CreateInstance(_serviceProvider, _startFormClass); - } + _startFormClass = startFormClass; + _serviceProvider = serviceProvider; } - public class ServiceProviderStartFormFactory : ServiceProviderStartFormFactory - where T : FormBase + public FormBase CreateForm() { - public ServiceProviderStartFormFactory(IServiceProvider serviceProvider) : base(typeof(T), serviceProvider) - { - } + return (FormBase)ActivatorUtilities.CreateInstance(_serviceProvider, _startFormClass); } } + +public class ServiceProviderStartFormFactory : ServiceProviderStartFormFactory + where T : FormBase +{ + public ServiceProviderStartFormFactory(IServiceProvider serviceProvider) : base(typeof(T), serviceProvider) + { + } +} \ No newline at end of file diff --git a/TelegramBotBase/Form/AlertDialog.cs b/TelegramBotBase/Form/AlertDialog.cs index fe7f472..74f4f1c 100644 --- a/TelegramBotBase/Form/AlertDialog.cs +++ b/TelegramBotBase/Form/AlertDialog.cs @@ -1,21 +1,18 @@ using TelegramBotBase.Attributes; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +/// +/// A simple prompt dialog with one ok Button +/// +[IgnoreState] +public class AlertDialog : ConfirmDialog { - /// - /// A simple prompt dialog with one ok Button - /// - [IgnoreState] - public class AlertDialog : ConfirmDialog + public AlertDialog(string message, string buttonText) : base(message) { - public string ButtonText { get; set; } - - public AlertDialog(string message, string buttonText) : base(message) - { - Buttons.Add(new ButtonBase(buttonText, "ok")); - this.ButtonText = buttonText; - - } - + Buttons.Add(new ButtonBase(buttonText, "ok")); + ButtonText = buttonText; } -} + + public string ButtonText { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Form/ArrayPromptDialog.cs b/TelegramBotBase/Form/ArrayPromptDialog.cs index 4ce663c..7481563 100644 --- a/TelegramBotBase/Form/ArrayPromptDialog.cs +++ b/TelegramBotBase/Form/ArrayPromptDialog.cs @@ -1,113 +1,112 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using TelegramBotBase.Args; using TelegramBotBase.Attributes; using TelegramBotBase.Base; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +/// +/// A prompt with a lot of buttons +/// +[IgnoreState] +public class ArrayPromptDialog : FormBase { - /// - /// A prompt with a lot of buttons - /// - [IgnoreState] - public class ArrayPromptDialog : FormBase + public ArrayPromptDialog() { - /// - /// The message the users sees. - /// - public string Message { get; set; } + } - /// - /// An additional optional value. - /// - public object Tag { get; set; } + public ArrayPromptDialog(string message) + { + Message = message; + } - public ButtonBase[][] Buttons { get; set; } + public ArrayPromptDialog(string message, params ButtonBase[][] buttons) + { + Message = message; + Buttons = buttons; + } - [Obsolete] - public Dictionary ButtonForms { get; set; } = new Dictionary(); + /// + /// The message the users sees. + /// + public string Message { get; set; } - private static object EvButtonClicked { get; } = new object(); + /// + /// An additional optional value. + /// + public object Tag { get; set; } - public ArrayPromptDialog() + public ButtonBase[][] Buttons { get; set; } + + [Obsolete] public Dictionary ButtonForms { get; set; } = new(); + + private static object EvButtonClicked { get; } = new(); + + public override async Task Action(MessageResult message) + { + var call = message.GetData(); + + message.Handled = true; + + if (!message.IsAction) { - + return; } - public ArrayPromptDialog(string message) + await message.ConfirmAction(); + + await message.DeleteMessage(); + + var buttons = Buttons.Aggregate((a, b) => a.Union(b).ToArray()).ToList(); + + if (call == null) { - this.Message = message; + return; } - public ArrayPromptDialog(string message, params ButtonBase[][] buttons) + var button = buttons.FirstOrDefault(a => a.Value == call.Value); + + if (button == null) { - this.Message = message; - this.Buttons = buttons; + return; } - public override async Task Action(MessageResult message) + OnButtonClicked(new ButtonClickedEventArgs(button) { Tag = Tag }); + + var fb = ButtonForms.ContainsKey(call.Value) ? ButtonForms[call.Value] : null; + + if (fb != null) { - var call = message.GetData(); - - message.Handled = true; - - if (!message.IsAction) - return; - - await message.ConfirmAction(); - - await message.DeleteMessage(); - - var buttons = Buttons.Aggregate((a, b) => a.Union(b).ToArray()).ToList(); - - if(call==null) - { - return; - } - - var button = buttons.FirstOrDefault(a => a.Value == call.Value); - - if (button == null) - { - return; - } - - OnButtonClicked(new ButtonClickedEventArgs(button) { Tag = Tag }); - - var fb = ButtonForms.ContainsKey(call.Value) ? ButtonForms[call.Value] : null; - - if (fb != null) - { - await NavigateTo(fb); - } - } - - - public override async Task Render(MessageResult message) - { - var btn = new ButtonForm(); - - foreach(var bl in Buttons) - { - btn.AddButtonRow(bl.Select(a => new ButtonBase(a.Text, CallbackData.Create("action", a.Value))).ToList()); - } - - await Device.Send(Message, btn); - } - - - public event EventHandler ButtonClicked - { - add => Events.AddHandler(EvButtonClicked, value); - remove => Events.RemoveHandler(EvButtonClicked, value); - } - - public void OnButtonClicked(ButtonClickedEventArgs e) - { - (Events[EvButtonClicked] as EventHandler)?.Invoke(this, e); + await NavigateTo(fb); } } + + + public override async Task Render(MessageResult message) + { + var btn = new ButtonForm(); + + foreach (var bl in Buttons) + { + btn.AddButtonRow( + bl.Select(a => new ButtonBase(a.Text, CallbackData.Create("action", a.Value))).ToList()); + } + + await Device.Send(Message, btn); + } + + + public event EventHandler ButtonClicked + { + add => Events.AddHandler(EvButtonClicked, value); + remove => Events.RemoveHandler(EvButtonClicked, value); + } + + public void OnButtonClicked(ButtonClickedEventArgs e) + { + (Events[EvButtonClicked] as EventHandler)?.Invoke(this, e); + } } diff --git a/TelegramBotBase/Form/AutoCleanForm.cs b/TelegramBotBase/Form/AutoCleanForm.cs index be2ff1e..d920488 100644 --- a/TelegramBotBase/Form/AutoCleanForm.cs +++ b/TelegramBotBase/Form/AutoCleanForm.cs @@ -11,135 +11,143 @@ using TelegramBotBase.Attributes; using TelegramBotBase.Base; using TelegramBotBase.Enums; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +/// +/// A form which cleans up old messages sent within +/// +public class AutoCleanForm : FormBase { - /// - /// A form which cleans up old messages sent within - /// - public class AutoCleanForm : FormBase + public AutoCleanForm() { - [SaveState] - public List OldMessages { get; set; } + OldMessages = new List(); + DeleteMode = EDeleteMode.OnEveryCall; + DeleteSide = EDeleteSide.BotOnly; - [SaveState] - public EDeleteMode DeleteMode { get; set; } + Init += AutoCleanForm_Init; - [SaveState] - public EDeleteSide DeleteSide { get; set; } + Closed += AutoCleanForm_Closed; + } + [SaveState] public List OldMessages { get; set; } + [SaveState] public EDeleteMode DeleteMode { get; set; } - public AutoCleanForm() + [SaveState] public EDeleteSide DeleteSide { get; set; } + + private Task AutoCleanForm_Init(object sender, InitEventArgs e) + { + if (Device == null) { - OldMessages = new List(); - DeleteMode = EDeleteMode.OnEveryCall; - DeleteSide = EDeleteSide.BotOnly; - - Init += AutoCleanForm_Init; - - Closed += AutoCleanForm_Closed; - - } - - private Task AutoCleanForm_Init(object sender, InitEventArgs e) - { - if (Device == null) - return Task.CompletedTask; - - Device.MessageSent += Device_MessageSent; - - Device.MessageReceived += Device_MessageReceived; - - Device.MessageDeleted += Device_MessageDeleted; return Task.CompletedTask; } - private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e) + Device.MessageSent += Device_MessageSent; + + Device.MessageReceived += Device_MessageReceived; + + Device.MessageDeleted += Device_MessageDeleted; + return Task.CompletedTask; + } + + private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e) + { + if (OldMessages.Contains(e.MessageId)) { - if (OldMessages.Contains(e.MessageId)) - OldMessages.Remove(e.MessageId); + OldMessages.Remove(e.MessageId); + } + } + + private void Device_MessageReceived(object sender, MessageReceivedEventArgs e) + { + if (DeleteSide == EDeleteSide.BotOnly) + { + return; } - private void Device_MessageReceived(object sender, MessageReceivedEventArgs e) + OldMessages.Add(e.Message.MessageId); + } + + private Task Device_MessageSent(object sender, MessageSentEventArgs e) + { + if (DeleteSide == EDeleteSide.UserOnly) { - if (DeleteSide == EDeleteSide.BotOnly) - return; - - OldMessages.Add(e.Message.MessageId); - } - - private Task Device_MessageSent(object sender, MessageSentEventArgs e) - { - if (DeleteSide == EDeleteSide.UserOnly) - return Task.CompletedTask; - - OldMessages.Add(e.Message.MessageId); return Task.CompletedTask; } - public override async Task PreLoad(MessageResult message) - { - if (DeleteMode != EDeleteMode.OnEveryCall) - return; + OldMessages.Add(e.Message.MessageId); + return Task.CompletedTask; + } - await MessageCleanup(); + public override async Task PreLoad(MessageResult message) + { + if (DeleteMode != EDeleteMode.OnEveryCall) + { + return; } - /// - /// Adds a message to this of removable ones - /// - /// - public void AddMessage(Message m) + await MessageCleanup(); + } + + /// + /// Adds a message to this of removable ones + /// + /// + public void AddMessage(Message m) + { + OldMessages.Add(m.MessageId); + } + + + /// + /// Adds a message to this of removable ones + /// + /// + public void AddMessage(int messageId) + { + OldMessages.Add(messageId); + } + + /// + /// Keeps the message by removing it from the list + /// + /// + public void LeaveMessage(int id) + { + OldMessages.Remove(id); + } + + /// + /// Keeps the last sent message + /// + public void LeaveLastMessage() + { + if (OldMessages.Count == 0) { - OldMessages.Add(m.MessageId); + return; } + OldMessages.RemoveAt(OldMessages.Count - 1); + } - /// - /// Adds a message to this of removable ones - /// - /// - public void AddMessage(int messageId) + private Task AutoCleanForm_Closed(object sender, EventArgs e) + { + if (DeleteMode != EDeleteMode.OnLeavingForm) { - OldMessages.Add(messageId); - } - - /// - /// Keeps the message by removing it from the list - /// - /// - public void LeaveMessage(int id) - { - OldMessages.Remove(id); - } - - /// - /// Keeps the last sent message - /// - public void LeaveLastMessage() - { - if (OldMessages.Count == 0) - return; - - OldMessages.RemoveAt(OldMessages.Count - 1); - } - - private Task AutoCleanForm_Closed(object sender, EventArgs e) - { - if (DeleteMode != EDeleteMode.OnLeavingForm) - return Task.CompletedTask; - - MessageCleanup().Wait(); return Task.CompletedTask; } - /// - /// Cleans up all remembered messages. - /// - /// - public async Task MessageCleanup() - { - var oldMessages = OldMessages.AsEnumerable(); + MessageCleanup().Wait(); + return Task.CompletedTask; + } + + /// + /// Cleans up all remembered messages. + /// + /// + public async Task MessageCleanup() + { + var oldMessages = OldMessages.AsEnumerable(); #if !NETSTANDARD2_0 while (oldMessages.Any()) @@ -181,51 +189,51 @@ namespace TelegramBotBase.Form await retryAfterTask; } #else - while (oldMessages.Any()) + while (oldMessages.Any()) + { + using (var cts = new CancellationTokenSource()) { - using (var cts = new CancellationTokenSource()) + var deletedMessages = new ConcurrentBag(); + var parallelQuery = OldMessages.AsParallel() + .WithCancellation(cts.Token); + Task retryAfterTask = null; + try { - var deletedMessages = new ConcurrentBag(); - var parallelQuery = OldMessages.AsParallel() - .WithCancellation(cts.Token); - Task retryAfterTask = null; - try + parallelQuery.ForAll(i => { - parallelQuery.ForAll(i => + try { - try - { - Device.DeleteMessage(i).GetAwaiter().GetResult(); - deletedMessages.Add(i); - } - catch (ApiRequestException req) when (req.ErrorCode == 400) - { - deletedMessages.Add(i); - } - }); - } - catch (AggregateException ex) - { - cts.Cancel(); + Device.DeleteMessage(i).GetAwaiter().GetResult(); + deletedMessages.Add(i); + } + catch (ApiRequestException req) when (req.ErrorCode == 400) + { + deletedMessages.Add(i); + } + }); + } + catch (AggregateException ex) + { + cts.Cancel(); - var retryAfterSeconds = ex.InnerExceptions - .Where(e => e is ApiRequestException apiEx && apiEx.ErrorCode == 429) - .Max(e => ((ApiRequestException)e).Parameters.RetryAfter) ?? 0; - retryAfterTask = Task.Delay(retryAfterSeconds * 1000); - } + var retryAfterSeconds = ex.InnerExceptions + .Where(e => e is ApiRequestException apiEx && apiEx.ErrorCode == 429) + .Max(e => ((ApiRequestException)e).Parameters.RetryAfter) ?? 0; + retryAfterTask = Task.Delay(retryAfterSeconds * 1000); + } - //deletedMessages.AsParallel().ForAll(i => Device.OnMessageDeleted(new MessageDeletedEventArgs(i))); - - oldMessages = oldMessages.Where(x => !deletedMessages.Contains(x)); - if (retryAfterTask != null) - await retryAfterTask; + //deletedMessages.AsParallel().ForAll(i => Device.OnMessageDeleted(new MessageDeletedEventArgs(i))); + oldMessages = oldMessages.Where(x => !deletedMessages.Contains(x)); + if (retryAfterTask != null) + { + await retryAfterTask; } } + } #endif - OldMessages.Clear(); - } + OldMessages.Clear(); } -} +} \ No newline at end of file diff --git a/TelegramBotBase/Form/ButtonBase.cs b/TelegramBotBase/Form/ButtonBase.cs index a068774..c962dcb 100644 --- a/TelegramBotBase/Form/ButtonBase.cs +++ b/TelegramBotBase/Form/ButtonBase.cs @@ -1,66 +1,62 @@ using System.Diagnostics; using Telegram.Bot.Types.ReplyMarkups; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +[DebuggerDisplay("{Text}, {Value}")] +/// +/// Base class for button handling +/// +public class ButtonBase { - [DebuggerDisplay("{Text}, {Value}")] - /// - /// Base class for button handling - /// - public class ButtonBase + public ButtonBase() { - public virtual string Text { get; set; } - - public string Value { get; set; } - - public string Url { get; set; } - - public ButtonBase() - { - - } - - public ButtonBase(string text, string value, string url = null) - { - this.Text = text; - this.Value = value; - this.Url = url; - } - - - /// - /// Returns an inline Button - /// - /// - /// - public virtual InlineKeyboardButton ToInlineButton(ButtonForm form) - { - var id = (form.DependencyControl != null ? form.DependencyControl.ControlId + "_" : ""); - if (Url == null) - { - return InlineKeyboardButton.WithCallbackData(Text, id + Value); - } - - var ikb = new InlineKeyboardButton(Text) - { - //ikb.Text = this.Text; - Url = Url - }; - - return ikb; - - } - - - /// - /// Returns a KeyBoardButton - /// - /// - /// - public virtual KeyboardButton ToKeyboardButton(ButtonForm form) - { - return new KeyboardButton(Text); - } - } -} + + public ButtonBase(string text, string value, string url = null) + { + Text = text; + Value = value; + Url = url; + } + + public virtual string Text { get; set; } + + public string Value { get; set; } + + public string Url { get; set; } + + + /// + /// Returns an inline Button + /// + /// + /// + public virtual InlineKeyboardButton ToInlineButton(ButtonForm form) + { + var id = form.DependencyControl != null ? form.DependencyControl.ControlId + "_" : ""; + if (Url == null) + { + return InlineKeyboardButton.WithCallbackData(Text, id + Value); + } + + var ikb = new InlineKeyboardButton(Text) + { + //ikb.Text = this.Text; + Url = Url + }; + + return ikb; + } + + + /// + /// Returns a KeyBoardButton + /// + /// + /// + public virtual KeyboardButton ToKeyboardButton(ButtonForm form) + { + return new KeyboardButton(Text); + } +} \ No newline at end of file diff --git a/TelegramBotBase/Form/ButtonForm.cs b/TelegramBotBase/Form/ButtonForm.cs index fea7fb9..9591ddf 100644 --- a/TelegramBotBase/Form/ButtonForm.cs +++ b/TelegramBotBase/Form/ButtonForm.cs @@ -5,321 +5,337 @@ using Telegram.Bot.Types.ReplyMarkups; using TelegramBotBase.Base; using TelegramBotBase.Controls.Hybrid; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +/// +/// Base class for an buttons array +/// +public class ButtonForm { - /// - /// Base class for an buttons array - /// - public class ButtonForm + private readonly List _buttons = new(); + + public ButtonForm() { - private List _buttons = new List(); + } + + public ButtonForm(ControlBase control) + { + DependencyControl = control; + } - public IReplyMarkup Markup { get; set; } + public IReplyMarkup Markup { get; set; } - public ControlBase DependencyControl { get; set; } + public ControlBase DependencyControl { get; set; } - /// - /// Contains the number of rows. - /// - public int Rows => _buttons.Count; + /// + /// Contains the number of rows. + /// + public int Rows => _buttons.Count; - /// - /// Contains the highest number of columns in an row. - /// - public int Cols + /// + /// Contains the highest number of columns in an row. + /// + public int Cols + { + get { return _buttons.Select(a => a.Count).OrderByDescending(a => a).FirstOrDefault(); } + } + + + public ButtonRow this[int row] => _buttons[row]; + + public int Count + { + get { - get + if (_buttons.Count == 0) { - return _buttons.Select(a => a.Count).OrderByDescending(a => a).FirstOrDefault(); - } - } - - - public ButtonRow this[int row] => _buttons[row]; - - public ButtonForm() - { - - } - - public ButtonForm(ControlBase control) - { - DependencyControl = control; - } - - public void AddButtonRow(string text, string value, string url = null) - { - _buttons.Add(new List { new ButtonBase(text, value, url) }); - } - - //public void AddButtonRow(ButtonRow row) - //{ - // Buttons.Add(row.ToList()); - //} - - public void AddButtonRow(ButtonRow row) - { - _buttons.Add(row); - } - - public void AddButtonRow(params ButtonBase[] row) - { - AddButtonRow(row.ToList()); - } - - public void AddButtonRows(IEnumerable rows) - { - _buttons.AddRange(rows); - } - - public void InsertButtonRow(int index, IEnumerable row) - { - _buttons.Insert(index, row.ToList()); - } - - public void InsertButtonRow(int index, ButtonRow row) - { - _buttons.Insert(index, row); - } - - //public void InsertButtonRow(int index, params ButtonBase[] row) - //{ - // InsertButtonRow(index, row.ToList()); - //} - - public static T[][] SplitTo(IEnumerable items, int itemsPerRow = 2) - { - var splitted = default(T[][]); - - try - { - var t = items.Select((a, index) => new { a, index }) - .GroupBy(a => a.index / itemsPerRow) - .Select(a => a.Select(b => b.a).ToArray()).ToArray(); - - splitted = t; - } - catch - { - + return 0; } - return splitted; - } - - public int Count - { - get - { - if (_buttons.Count == 0) - return 0; - - return _buttons.Select(a => a.ToArray()).ToList().Aggregate((a, b) => a.Union(b).ToArray()).Length; - } - } - - /// - /// Add buttons splitted in the amount of columns (i.e. 2 per row...) - /// - /// - /// - public void AddSplitted(IEnumerable buttons, int buttonsPerRow = 2) - { - var sp = SplitTo(buttons, buttonsPerRow); - - foreach (var bl in sp) - { - AddButtonRow(bl); - } - } - - /// - /// Returns a range of rows from the buttons. - /// - /// - /// - /// - public List GetRange(int start, int count) - { - return _buttons.Skip(start).Take(count).ToList(); - } - - - public List ToList() - { - return _buttons.DefaultIfEmpty(new List()).Select(a => a.ToList()).Aggregate((a, b) => a.Union(b).ToList()); - } - - public InlineKeyboardButton[][] ToInlineButtonArray() - { - var ikb = _buttons.Select(a => a.ToArray().Select(b => b.ToInlineButton(this)).ToArray()).ToArray(); - - return ikb; - } - - public KeyboardButton[][] ToReplyButtonArray() - { - var ikb = _buttons.Select(a => a.ToArray().Select(b => b.ToKeyboardButton(this)).ToArray()).ToArray(); - - return ikb; - } - - public List ToArray() - { - return _buttons; - } - - public int FindRowByButton(ButtonBase button) - { - var row = _buttons.FirstOrDefault(a => a.ToArray().Count(b => b == button) > 0); - if (row == null) - return -1; - - return _buttons.IndexOf(row); - } - - public Tuple FindRow(string text, bool useText = true) - { - var r = _buttons.FirstOrDefault(a => a.Matches(text, useText)); - if (r == null) - return null; - - var i = _buttons.IndexOf(r); - return new Tuple(r, i); - } - - - /// - /// Returns the first Button with the given value. - /// - /// - /// - public ButtonBase GetButtonByValue(string value) - { - return ToList().Where(a => a.Value == value).FirstOrDefault(); - } - - public static implicit operator InlineKeyboardMarkup(ButtonForm form) - { - if (form == null) - return null; - - var ikm = new InlineKeyboardMarkup(form.ToInlineButtonArray()); - - return ikm; - } - - public static implicit operator ReplyKeyboardMarkup(ButtonForm form) - { - if (form == null) - return null; - - var ikm = new ReplyKeyboardMarkup(form.ToReplyButtonArray()); - - return ikm; - } - - /// - /// Creates a copy of this form. - /// - /// - public ButtonForm Duplicate() - { - var bf = new ButtonForm - { - Markup = Markup, - DependencyControl = DependencyControl - }; - - foreach (var b in _buttons) - { - var lst = new ButtonRow(); - foreach (var b2 in b) - { - lst.Add(b2); - } - bf._buttons.Add(lst); - } - - return bf; - } - - /// - /// Creates a copy of this form and filters by the parameter. - /// - /// - public ButtonForm FilterDuplicate(string filter, bool byRow = false) - { - var bf = new ButtonForm - { - Markup = Markup, - DependencyControl = DependencyControl - }; - - foreach (var b in _buttons) - { - var lst = new ButtonRow(); - foreach (var b2 in b) - { - if (b2.Text.IndexOf(filter, StringComparison.InvariantCultureIgnoreCase) == -1) - continue; - - //Copy full row, when at least one match has found. - if (byRow) - { - lst = b; - break; - } - - lst.Add(b2); - } - - if (lst.Count > 0) - bf._buttons.Add(lst); - } - - return bf; - } - - /// - /// Creates a copy of this form and filters by the parameter. - /// - /// - public ButtonForm TagDuplicate(List tags, bool byRow = false) - { - var bf = new ButtonForm - { - Markup = Markup, - DependencyControl = DependencyControl - }; - - foreach (var b in _buttons) - { - var lst = new ButtonRow(); - foreach (var b2 in b) - { - if (!(b2 is TagButtonBase tb)) - continue; - - if (!tags.Contains(tb.Tag)) - continue; - - //Copy full row, when at least one match has found. - if (byRow) - { - lst = b; - break; - } - - lst.Add(b2); - } - - if (lst.Count > 0) - bf._buttons.Add(lst); - } - - return bf; + return _buttons.Select(a => a.ToArray()).ToList().Aggregate((a, b) => a.Union(b).ToArray()).Length; } } -} + + public void AddButtonRow(string text, string value, string url = null) + { + _buttons.Add(new List { new(text, value, url) }); + } + + //public void AddButtonRow(ButtonRow row) + //{ + // Buttons.Add(row.ToList()); + //} + + public void AddButtonRow(ButtonRow row) + { + _buttons.Add(row); + } + + public void AddButtonRow(params ButtonBase[] row) + { + AddButtonRow(row.ToList()); + } + + public void AddButtonRows(IEnumerable rows) + { + _buttons.AddRange(rows); + } + + public void InsertButtonRow(int index, IEnumerable row) + { + _buttons.Insert(index, row.ToList()); + } + + public void InsertButtonRow(int index, ButtonRow row) + { + _buttons.Insert(index, row); + } + + //public void InsertButtonRow(int index, params ButtonBase[] row) + //{ + // InsertButtonRow(index, row.ToList()); + //} + + public static T[][] SplitTo(IEnumerable items, int itemsPerRow = 2) + { + var splitted = default(T[][]); + + try + { + var t = items.Select((a, index) => new { a, index }) + .GroupBy(a => a.index / itemsPerRow) + .Select(a => a.Select(b => b.a).ToArray()).ToArray(); + + splitted = t; + } + catch + { + } + + return splitted; + } + + /// + /// Add buttons splitted in the amount of columns (i.e. 2 per row...) + /// + /// + /// + public void AddSplitted(IEnumerable buttons, int buttonsPerRow = 2) + { + var sp = SplitTo(buttons, buttonsPerRow); + + foreach (var bl in sp) + { + AddButtonRow(bl); + } + } + + /// + /// Returns a range of rows from the buttons. + /// + /// + /// + /// + public List GetRange(int start, int count) + { + return _buttons.Skip(start).Take(count).ToList(); + } + + + public List ToList() + { + return _buttons.DefaultIfEmpty(new List()).Select(a => a.ToList()) + .Aggregate((a, b) => a.Union(b).ToList()); + } + + public InlineKeyboardButton[][] ToInlineButtonArray() + { + var ikb = _buttons.Select(a => a.ToArray().Select(b => b.ToInlineButton(this)).ToArray()).ToArray(); + + return ikb; + } + + public KeyboardButton[][] ToReplyButtonArray() + { + var ikb = _buttons.Select(a => a.ToArray().Select(b => b.ToKeyboardButton(this)).ToArray()).ToArray(); + + return ikb; + } + + public List ToArray() + { + return _buttons; + } + + public int FindRowByButton(ButtonBase button) + { + var row = _buttons.FirstOrDefault(a => a.ToArray().Count(b => b == button) > 0); + if (row == null) + { + return -1; + } + + return _buttons.IndexOf(row); + } + + public Tuple FindRow(string text, bool useText = true) + { + var r = _buttons.FirstOrDefault(a => a.Matches(text, useText)); + if (r == null) + { + return null; + } + + var i = _buttons.IndexOf(r); + return new Tuple(r, i); + } + + + /// + /// Returns the first Button with the given value. + /// + /// + /// + public ButtonBase GetButtonByValue(string value) + { + return ToList().Where(a => a.Value == value).FirstOrDefault(); + } + + public static implicit operator InlineKeyboardMarkup(ButtonForm form) + { + if (form == null) + { + return null; + } + + var ikm = new InlineKeyboardMarkup(form.ToInlineButtonArray()); + + return ikm; + } + + public static implicit operator ReplyKeyboardMarkup(ButtonForm form) + { + if (form == null) + { + return null; + } + + var ikm = new ReplyKeyboardMarkup(form.ToReplyButtonArray()); + + return ikm; + } + + /// + /// Creates a copy of this form. + /// + /// + public ButtonForm Duplicate() + { + var bf = new ButtonForm + { + Markup = Markup, + DependencyControl = DependencyControl + }; + + foreach (var b in _buttons) + { + var lst = new ButtonRow(); + foreach (var b2 in b) + { + lst.Add(b2); + } + + bf._buttons.Add(lst); + } + + return bf; + } + + /// + /// Creates a copy of this form and filters by the parameter. + /// + /// + public ButtonForm FilterDuplicate(string filter, bool byRow = false) + { + var bf = new ButtonForm + { + Markup = Markup, + DependencyControl = DependencyControl + }; + + foreach (var b in _buttons) + { + var lst = new ButtonRow(); + foreach (var b2 in b) + { + if (b2.Text.IndexOf(filter, StringComparison.InvariantCultureIgnoreCase) == -1) + { + continue; + } + + //Copy full row, when at least one match has found. + if (byRow) + { + lst = b; + break; + } + + lst.Add(b2); + } + + if (lst.Count > 0) + { + bf._buttons.Add(lst); + } + } + + return bf; + } + + /// + /// Creates a copy of this form and filters by the parameter. + /// + /// + public ButtonForm TagDuplicate(List tags, bool byRow = false) + { + var bf = new ButtonForm + { + Markup = Markup, + DependencyControl = DependencyControl + }; + + foreach (var b in _buttons) + { + var lst = new ButtonRow(); + foreach (var b2 in b) + { + if (!(b2 is TagButtonBase tb)) + { + continue; + } + + if (!tags.Contains(tb.Tag)) + { + continue; + } + + //Copy full row, when at least one match has found. + if (byRow) + { + lst = b; + break; + } + + lst.Add(b2); + } + + if (lst.Count > 0) + { + bf._buttons.Add(lst); + } + } + + return bf; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Form/CallbackData.cs b/TelegramBotBase/Form/CallbackData.cs index 9cca33d..d1cf35c 100644 --- a/TelegramBotBase/Form/CallbackData.cs +++ b/TelegramBotBase/Form/CallbackData.cs @@ -1,76 +1,67 @@ using Newtonsoft.Json; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +/// +/// Base class for serializing buttons and data +/// +public class CallbackData { - /// - /// Base class for serializing buttons and data - /// - public class CallbackData + public CallbackData() { - [JsonProperty("m")] - public string Method { get; set; } - - [JsonProperty("v")] - public string Value { get; set; } - - - public CallbackData() - { - - } - - public CallbackData(string method, string value) - { - Method = method; - Value = value; - } - - public static string Create(string method, string value) - { - return new CallbackData(method, value).Serialize(); - } - - /// - /// Serializes data to json string - /// - /// - public string Serialize() - { - var s = ""; - try - { - - s = JsonConvert.SerializeObject(this); - } - catch - { - - - } - return s; - } - - /// - /// Deserializes data from json string - /// - /// - /// - public static CallbackData Deserialize(string data) - { - CallbackData cd = null; - try - { - cd = JsonConvert.DeserializeObject(data); - - return cd; - } - catch - { - - } - - return null; - } - } -} + + public CallbackData(string method, string value) + { + Method = method; + Value = value; + } + + [JsonProperty("m")] public string Method { get; set; } + + [JsonProperty("v")] public string Value { get; set; } + + public static string Create(string method, string value) + { + return new CallbackData(method, value).Serialize(); + } + + /// + /// Serializes data to json string + /// + /// + public string Serialize() + { + var s = ""; + try + { + s = JsonConvert.SerializeObject(this); + } + catch + { + } + + return s; + } + + /// + /// Deserializes data from json string + /// + /// + /// + public static CallbackData Deserialize(string data) + { + CallbackData cd = null; + try + { + cd = JsonConvert.DeserializeObject(data); + + return cd; + } + catch + { + } + + return null; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Form/ConfirmDialog.cs b/TelegramBotBase/Form/ConfirmDialog.cs index 0621fcb..ebb62c3 100644 --- a/TelegramBotBase/Form/ConfirmDialog.cs +++ b/TelegramBotBase/Form/ConfirmDialog.cs @@ -1,115 +1,119 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using TelegramBotBase.Args; using TelegramBotBase.Attributes; using TelegramBotBase.Base; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +[IgnoreState] +public class ConfirmDialog : ModalDialog { - [IgnoreState] - public class ConfirmDialog : ModalDialog + public ConfirmDialog() { - /// - /// The message the users sees. - /// - public string Message { get; set; } - - /// - /// An additional optional value. - /// - public object Tag { get; set; } - - /// - /// Automatically close form on button click - /// - public bool AutoCloseOnClick { get; set; } = true; - - public List Buttons { get; set; } - - private static object EvButtonClicked { get; } = new object(); - - public ConfirmDialog() - { - - } - - public ConfirmDialog(string message) - { - this.Message = message; - Buttons = new List(); - } - - public ConfirmDialog(string message, params ButtonBase[] buttons) - { - this.Message = message; - this.Buttons = buttons.ToList(); - } - - /// - /// Adds one Button - /// - /// - public void AddButton(ButtonBase button) - { - Buttons.Add(button); - } - - public override async Task Action(MessageResult message) - { - if (message.Handled) - return; - - if (!message.IsFirstHandler) - return; - - var call = message.GetData(); - if (call == null) - return; - - message.Handled = true; - - await message.ConfirmAction(); - - await message.DeleteMessage(); - - var button = Buttons.FirstOrDefault(a => a.Value == call.Value); - - if (button == null) - { - return; - } - - OnButtonClicked(new ButtonClickedEventArgs(button) { Tag = Tag }); - - if (AutoCloseOnClick) - await CloseForm(); - } - - - public override async Task Render(MessageResult message) - { - var btn = new ButtonForm(); - - var buttons = Buttons.Select(a => new ButtonBase(a.Text, CallbackData.Create("action", a.Value))).ToList(); - btn.AddButtonRow(buttons); - - await Device.Send(Message, btn); - } - - - public event EventHandler ButtonClicked - { - add => Events.AddHandler(EvButtonClicked, value); - remove => Events.RemoveHandler(EvButtonClicked, value); - } - - public void OnButtonClicked(ButtonClickedEventArgs e) - { - (Events[EvButtonClicked] as EventHandler)?.Invoke(this, e); - } - } -} + + public ConfirmDialog(string message) + { + Message = message; + Buttons = new List(); + } + + public ConfirmDialog(string message, params ButtonBase[] buttons) + { + Message = message; + Buttons = buttons.ToList(); + } + + /// + /// The message the users sees. + /// + public string Message { get; set; } + + /// + /// An additional optional value. + /// + public object Tag { get; set; } + + /// + /// Automatically close form on button click + /// + public bool AutoCloseOnClick { get; set; } = true; + + public List Buttons { get; set; } + + private static object EvButtonClicked { get; } = new(); + + /// + /// Adds one Button + /// + /// + public void AddButton(ButtonBase button) + { + Buttons.Add(button); + } + + public override async Task Action(MessageResult message) + { + if (message.Handled) + { + return; + } + + if (!message.IsFirstHandler) + { + return; + } + + var call = message.GetData(); + if (call == null) + { + return; + } + + message.Handled = true; + + await message.ConfirmAction(); + + await message.DeleteMessage(); + + var button = Buttons.FirstOrDefault(a => a.Value == call.Value); + + if (button == null) + { + return; + } + + OnButtonClicked(new ButtonClickedEventArgs(button) { Tag = Tag }); + + if (AutoCloseOnClick) + { + await CloseForm(); + } + } + + + public override async Task Render(MessageResult message) + { + var btn = new ButtonForm(); + + var buttons = Buttons.Select(a => new ButtonBase(a.Text, CallbackData.Create("action", a.Value))).ToList(); + btn.AddButtonRow(buttons); + + await Device.Send(Message, btn); + } + + + public event EventHandler ButtonClicked + { + add => Events.AddHandler(EvButtonClicked, value); + remove => Events.RemoveHandler(EvButtonClicked, value); + } + + public void OnButtonClicked(ButtonClickedEventArgs e) + { + (Events[EvButtonClicked] as EventHandler)?.Invoke(this, e); + } +} \ No newline at end of file diff --git a/TelegramBotBase/Form/DynamicButton.cs b/TelegramBotBase/Form/DynamicButton.cs index 9dcc89b..129339d 100644 --- a/TelegramBotBase/Form/DynamicButton.cs +++ b/TelegramBotBase/Form/DynamicButton.cs @@ -1,33 +1,30 @@ using System; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +public class DynamicButton : ButtonBase { - public class DynamicButton : ButtonBase + private readonly Func _getText; + + private string _mText = ""; + + public DynamicButton(string text, string value, string url = null) { - public override string Text - { - get => _getText?.Invoke() ?? _mText; - set => _mText = value; - } - - private string _mText = ""; - - private Func _getText; - - public DynamicButton(string text, string value, string url = null) - { - this.Text = text; - this.Value = value; - this.Url = url; - } - - public DynamicButton(Func getText, string value, string url = null) - { - this._getText = getText; - this.Value = value; - this.Url = url; - } - - + Text = text; + Value = value; + Url = url; } -} + + public DynamicButton(Func getText, string value, string url = null) + { + _getText = getText; + Value = value; + Url = url; + } + + public override string Text + { + get => _getText?.Invoke() ?? _mText; + set => _mText = value; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Form/GroupForm.cs b/TelegramBotBase/Form/GroupForm.cs index 6134a43..14002f9 100644 --- a/TelegramBotBase/Form/GroupForm.cs +++ b/TelegramBotBase/Form/GroupForm.cs @@ -3,73 +3,73 @@ using Telegram.Bot.Types.Enums; using TelegramBotBase.Args; using TelegramBotBase.Base; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +public class GroupForm : FormBase { - public class GroupForm : FormBase + public override async Task Load(MessageResult message) { - public override async Task Load(MessageResult message) + switch (message.MessageType) { - switch (message.MessageType) - { - case MessageType.ChatMembersAdded: + case MessageType.ChatMembersAdded: - await OnMemberChanges(new MemberChangeEventArgs(MessageType.ChatMembersAdded, message, message.Message.NewChatMembers)); + await OnMemberChanges(new MemberChangeEventArgs(MessageType.ChatMembersAdded, message, + message.Message.NewChatMembers)); - break; - case MessageType.ChatMemberLeft: + break; + case MessageType.ChatMemberLeft: - await OnMemberChanges(new MemberChangeEventArgs(MessageType.ChatMemberLeft, message, message.Message.LeftChatMember)); + await OnMemberChanges(new MemberChangeEventArgs(MessageType.ChatMemberLeft, message, + message.Message.LeftChatMember)); - break; + break; - case MessageType.ChatPhotoChanged: - case MessageType.ChatPhotoDeleted: - case MessageType.ChatTitleChanged: - case MessageType.MigratedFromGroup: - case MessageType.MigratedToSupergroup: - case MessageType.MessagePinned: - case MessageType.GroupCreated: - case MessageType.SupergroupCreated: - case MessageType.ChannelCreated: + case MessageType.ChatPhotoChanged: + case MessageType.ChatPhotoDeleted: + case MessageType.ChatTitleChanged: + case MessageType.MigratedFromGroup: + case MessageType.MigratedToSupergroup: + case MessageType.MessagePinned: + case MessageType.GroupCreated: + case MessageType.SupergroupCreated: + case MessageType.ChannelCreated: - await OnGroupChanged(new GroupChangedEventArgs(message.MessageType, message)); + await OnGroupChanged(new GroupChangedEventArgs(message.MessageType, message)); - break; + break; - default: + default: - await OnMessage(message); + await OnMessage(message); - break; - } - - } - - public override async Task Edited(MessageResult message) - { - await OnMessageEdit(message); - } - - public virtual Task OnMemberChanges(MemberChangeEventArgs e) - { - return Task.CompletedTask; - } - - - public virtual Task OnGroupChanged(GroupChangedEventArgs e) - { - return Task.CompletedTask; - } - - - public virtual Task OnMessage(MessageResult e) - { - return Task.CompletedTask; - } - - public virtual Task OnMessageEdit(MessageResult e) - { - return Task.CompletedTask; + break; } } -} + + public override async Task Edited(MessageResult message) + { + await OnMessageEdit(message); + } + + public virtual Task OnMemberChanges(MemberChangeEventArgs e) + { + return Task.CompletedTask; + } + + + public virtual Task OnGroupChanged(GroupChangedEventArgs e) + { + return Task.CompletedTask; + } + + + public virtual Task OnMessage(MessageResult e) + { + return Task.CompletedTask; + } + + public virtual Task OnMessageEdit(MessageResult e) + { + return Task.CompletedTask; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Form/ModalDialog.cs b/TelegramBotBase/Form/ModalDialog.cs index 06d7b7b..06e2bbd 100644 --- a/TelegramBotBase/Form/ModalDialog.cs +++ b/TelegramBotBase/Form/ModalDialog.cs @@ -1,26 +1,25 @@ using System; using System.Threading.Tasks; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +public class ModalDialog : FormBase { - public class ModalDialog : FormBase + /// + /// Contains the parent from where the modal dialog has been opened. + /// + public FormBase ParentForm { get; set; } + + /// + /// This is a modal only function and does everything to close this form. + /// + public async Task CloseForm() { - /// - /// Contains the parent from where the modal dialog has been opened. - /// - public FormBase ParentForm { get; set; } + await CloseControls(); - /// - /// This is a modal only function and does everything to close this form. - /// - public async Task CloseForm() - { - await CloseControls(); - - await OnClosed(EventArgs.Empty); + await OnClosed(EventArgs.Empty); - await ParentForm?.ReturnFromModal(this); - } + await ParentForm?.ReturnFromModal(this); } -} +} \ No newline at end of file diff --git a/TelegramBotBase/Form/Navigation/NavigationController.cs b/TelegramBotBase/Form/Navigation/NavigationController.cs index 94461ab..01931e8 100644 --- a/TelegramBotBase/Form/Navigation/NavigationController.cs +++ b/TelegramBotBase/Form/Navigation/NavigationController.cs @@ -10,348 +10,356 @@ using TelegramBotBase.Base; using TelegramBotBase.Interfaces; using TelegramBotBase.Tools; -namespace TelegramBotBase.Form.Navigation +namespace TelegramBotBase.Form.Navigation; + +[DebuggerDisplay("{Index+1} Forms")] +public class NavigationController : FormBase, IStateForm { - [DebuggerDisplay("{Index+1} Forms")] - public class NavigationController : FormBase, IStateForm + public NavigationController() { + History = new List(); + Index = -1; + ForceCleanupOnLastPop = true; - [SaveState] - private List History { get; set; } + Init += NavigationController_Init; + Opened += NavigationController_Opened; + Closed += NavigationController_Closed; + } - [SaveState] - public int Index { get; set; } + public NavigationController(FormBase startForm, params FormBase[] forms) : this() + { + Client = startForm.Client; + Device = startForm.Device; + startForm.NavigationController = this; - /// - /// Will replace the controller when poping a form to the root form. - /// - [SaveState] - public bool ForceCleanupOnLastPop { get; set; } + History.Add(startForm); + Index = 0; - public NavigationController() + if (forms.Length > 0) { - History = new List(); - Index = -1; - ForceCleanupOnLastPop = true; - - Init += NavigationController_Init; - Opened += NavigationController_Opened; - Closed += NavigationController_Closed; + History.AddRange(forms); + Index = History.Count - 1; } + } - public NavigationController(FormBase startForm, params FormBase[] forms) : this() - { - Client = startForm.Client; - Device = startForm.Device; - startForm.NavigationController = this; + [SaveState] private List History { get; } - History.Add(startForm); - Index = 0; + [SaveState] public int Index { get; set; } - if (forms.Length > 0) - { - History.AddRange(forms); - Index = History.Count - 1; - } - } + /// + /// Will replace the controller when poping a form to the root form. + /// + [SaveState] + public bool ForceCleanupOnLastPop { get; set; } - private async Task NavigationController_Init(object sender, InitEventArgs e) - { - if (CurrentForm == null) - return; - - await CurrentForm.OnInit(e); - } - - private async Task NavigationController_Opened(object sender, EventArgs e) - { - if (CurrentForm == null) - return; - - await CurrentForm.OnOpened(e); - } - - private async Task NavigationController_Closed(object sender, EventArgs e) - { - if (CurrentForm == null) - return; - - await CurrentForm.OnClosed(e); - } - - - - /// - /// Remove the current active form on the stack. - /// - /// - public virtual async Task PopAsync() + /// + /// Returns the current form from the stack. + /// + public FormBase CurrentForm + { + get { if (History.Count == 0) - return; - - var form = History[Index]; - - form.NavigationController = null; - History.Remove(form); - Index--; - - Device.FormSwitched = true; - - await form.OnClosed(EventArgs.Empty); - - //Leave NavigationController and move to the last one - if (ForceCleanupOnLastPop && History.Count == 1) { - var lastForm = History[0]; - lastForm.NavigationController = null; - await NavigateTo(lastForm); - return; + return null; } - if (History.Count > 0) - { - form = History[Index]; - await form.OnOpened(EventArgs.Empty); - } + return History[Index]; + } + } + + + public void LoadState(LoadStateEventArgs e) + { + if (e.Get("$controller.history.count") == null) + { + return; } - /// - /// Pop's through all forms back to the root form. - /// - /// - public virtual async Task PopToRootAsync() - { - while (Index > 0) - { - await PopAsync(); - } - } - /// - /// Pushing the given form to the stack and renders it. - /// - /// - /// - public virtual async Task PushAsync(FormBase form, params object[] args) + var historyCount = e.GetInt("$controller.history.count"); + + for (var i = 0; i < historyCount; i++) { - form.Client = Client; + var c = e.GetObject($"$controller.history[{i}]") as Dictionary; + + + var qname = e.Get($"$controller.history[{i}].type"); + + if (qname == null) + { + continue; + } + + var t = Type.GetType(qname); + if (t == null || !t.IsSubclassOf(typeof(FormBase))) + { + continue; + } + + //No default constructor, fallback + if (t.GetConstructor(new Type[] { })?.Invoke(new object[] { }) is not FormBase form) + { + continue; + } + + var properties = c.Where(a => a.Key.StartsWith("$")); + + var fields = form.GetType() + .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) + .Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); + + foreach (var p in properties) + { + var f = fields.FirstOrDefault(a => a.Name == p.Key.Substring(1)); + if (f == null) + { + continue; + } + + try + { + if (f.PropertyType.IsEnum) + { + var ent = Enum.Parse(f.PropertyType, p.Value.ToString()); + + f.SetValue(form, ent); + + continue; + } + + + f.SetValue(form, p.Value); + } + catch (ArgumentException) + { + Conversion.CustomConversionChecks(form, p, f); + } + catch + { + } + } + form.Device = Device; + form.Client = Client; form.NavigationController = this; + form.OnInit(new InitEventArgs()); + History.Add(form); - Index++; + } + } - Device.FormSwitched = true; + public void SaveState(SaveStateEventArgs e) + { + e.Set("$controller.history.count", History.Count.ToString()); - if (Index < 2) - return; + var i = 0; + foreach (var form in History) + { + var fields = form.GetType() + .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) + .Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); - await form.OnInit(new InitEventArgs(args)); + var dt = new Dictionary(); + foreach (var f in fields) + { + var val = f.GetValue(form); + dt.Add("$" + f.Name, val); + } + + e.Set($"$controller.history[{i}].type", form.GetType().AssemblyQualifiedName); + + e.SetObject($"$controller.history[{i}]", dt); + + i++; + } + } + + private async Task NavigationController_Init(object sender, InitEventArgs e) + { + if (CurrentForm == null) + { + return; + } + + await CurrentForm.OnInit(e); + } + + private async Task NavigationController_Opened(object sender, EventArgs e) + { + if (CurrentForm == null) + { + return; + } + + await CurrentForm.OnOpened(e); + } + + private async Task NavigationController_Closed(object sender, EventArgs e) + { + if (CurrentForm == null) + { + return; + } + + await CurrentForm.OnClosed(e); + } + + + /// + /// Remove the current active form on the stack. + /// + /// + public virtual async Task PopAsync() + { + if (History.Count == 0) + { + return; + } + + var form = History[Index]; + + form.NavigationController = null; + History.Remove(form); + Index--; + + Device.FormSwitched = true; + + await form.OnClosed(EventArgs.Empty); + + //Leave NavigationController and move to the last one + if (ForceCleanupOnLastPop && History.Count == 1) + { + var lastForm = History[0]; + lastForm.NavigationController = null; + await NavigateTo(lastForm); + return; + } + + if (History.Count > 0) + { + form = History[Index]; await form.OnOpened(EventArgs.Empty); } + } - /// - /// Pops the current form and pushes a new one. - /// Will help to remove forms so you can not navigate back to them. - /// - /// - /// - /// - public virtual async Task PushAndReplaceAsync(FormBase form, params object[] args) + /// + /// Pop's through all forms back to the root form. + /// + /// + public virtual async Task PopToRootAsync() + { + while (Index > 0) { await PopAsync(); - - await PushAsync(form, args); } - - /// - /// Returns the current form from the stack. - /// - public FormBase CurrentForm - { - get - { - if (History.Count == 0) - return null; - - return History[Index]; - } - } - - public List GetAllForms() - { - return History.ToList(); - } - - - public void LoadState(LoadStateEventArgs e) - { - if (e.Get("$controller.history.count") == null) - return; - - - var historyCount = e.GetInt("$controller.history.count"); - - for (var i = 0; i < historyCount; i++) - { - - var c = e.GetObject($"$controller.history[{i}]") as Dictionary; - - - - var qname = e.Get($"$controller.history[{i}].type"); - - if (qname == null) - continue; - - var t = Type.GetType(qname); - if (t == null || !t.IsSubclassOf(typeof(FormBase))) - { - continue; - } - - //No default constructor, fallback - if (t.GetConstructor(new Type[] { })?.Invoke(new object[] { }) is not FormBase form) - { - continue; - } - - var properties = c.Where(a => a.Key.StartsWith("$")); - - var fields = form.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); - - foreach (var p in properties) - { - var f = fields.FirstOrDefault(a => a.Name == p.Key.Substring(1)); - if (f == null) - continue; - - try - { - if (f.PropertyType.IsEnum) - { - var ent = Enum.Parse(f.PropertyType, p.Value.ToString()); - - f.SetValue(form, ent); - - continue; - } - - - f.SetValue(form, p.Value); - } - catch (ArgumentException) - { - - Conversion.CustomConversionChecks(form, p, f); - - } - catch - { - - } - } - - form.Device = Device; - form.Client = Client; - form.NavigationController = this; - - form.OnInit(new InitEventArgs()); - - History.Add(form); - } - - } - - public void SaveState(SaveStateEventArgs e) - { - e.Set("$controller.history.count", History.Count.ToString()); - - var i = 0; - foreach (var form in History) - { - var fields = form.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); - - var dt = new Dictionary(); - foreach (var f in fields) - { - var val = f.GetValue(form); - - dt.Add("$" + f.Name, val); - } - - e.Set($"$controller.history[{i}].type", form.GetType().AssemblyQualifiedName); - - e.SetObject($"$controller.history[{i}]", dt); - - i++; - } - } - - - #region "Methods passthrough" - - public override async Task NavigateTo(FormBase newForm, params object[] args) - { - await CurrentForm.NavigateTo(newForm, args); - } - - public override async Task LoadControls(MessageResult message) - { - await CurrentForm.LoadControls(message); - } - - public override async Task Load(MessageResult message) - { - await CurrentForm.Load(message); - } - - public override async Task ActionControls(MessageResult message) - { - await CurrentForm.ActionControls(message); - } - - public override async Task Action(MessageResult message) - { - await CurrentForm.Action(message); - } - - - - public override async Task Edited(MessageResult message) - { - await CurrentForm.Edited(message); - } - - public override async Task Render(MessageResult message) - { - await CurrentForm.Render(message); - } - - public override async Task RenderControls(MessageResult message) - { - await CurrentForm.RenderControls(message); - } - - public override async Task PreLoad(MessageResult message) - { - await CurrentForm.PreLoad(message); - } - - public override async Task ReturnFromModal(ModalDialog modal) - { - await CurrentForm.ReturnFromModal(modal); - } - - public override async Task SentData(DataResult message) - { - await CurrentForm.SentData(message); - } - - - #endregion - } + + /// + /// Pushing the given form to the stack and renders it. + /// + /// + /// + public virtual async Task PushAsync(FormBase form, params object[] args) + { + form.Client = Client; + form.Device = Device; + form.NavigationController = this; + + History.Add(form); + Index++; + + Device.FormSwitched = true; + + if (Index < 2) + { + return; + } + + await form.OnInit(new InitEventArgs(args)); + + await form.OnOpened(EventArgs.Empty); + } + + /// + /// Pops the current form and pushes a new one. + /// Will help to remove forms so you can not navigate back to them. + /// + /// + /// + /// + public virtual async Task PushAndReplaceAsync(FormBase form, params object[] args) + { + await PopAsync(); + + await PushAsync(form, args); + } + + public List GetAllForms() + { + return History.ToList(); + } + + + #region "Methods passthrough" + + public override async Task NavigateTo(FormBase newForm, params object[] args) + { + await CurrentForm.NavigateTo(newForm, args); + } + + public override async Task LoadControls(MessageResult message) + { + await CurrentForm.LoadControls(message); + } + + public override async Task Load(MessageResult message) + { + await CurrentForm.Load(message); + } + + public override async Task ActionControls(MessageResult message) + { + await CurrentForm.ActionControls(message); + } + + public override async Task Action(MessageResult message) + { + await CurrentForm.Action(message); + } + + + public override async Task Edited(MessageResult message) + { + await CurrentForm.Edited(message); + } + + public override async Task Render(MessageResult message) + { + await CurrentForm.Render(message); + } + + public override async Task RenderControls(MessageResult message) + { + await CurrentForm.RenderControls(message); + } + + public override async Task PreLoad(MessageResult message) + { + await CurrentForm.PreLoad(message); + } + + public override async Task ReturnFromModal(ModalDialog modal) + { + await CurrentForm.ReturnFromModal(modal); + } + + public override async Task SentData(DataResult message) + { + await CurrentForm.SentData(message); + } + + #endregion } diff --git a/TelegramBotBase/Form/PromptDialog.cs b/TelegramBotBase/Form/PromptDialog.cs index 61a28bf..a2d4c56 100644 --- a/TelegramBotBase/Form/PromptDialog.cs +++ b/TelegramBotBase/Form/PromptDialog.cs @@ -1,5 +1,4 @@ using System; -using System.ComponentModel; using System.Threading.Tasks; using Telegram.Bot.Types; using Telegram.Bot.Types.ReplyMarkups; @@ -8,108 +7,106 @@ using TelegramBotBase.Attributes; using TelegramBotBase.Base; using TelegramBotBase.Localizations; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +[IgnoreState] +public class PromptDialog : ModalDialog { - [IgnoreState] - public class PromptDialog : ModalDialog + public PromptDialog() { - /// - /// The message the users sees. - /// - public string Message { get; set; } - - /// - /// The returned text value by the user. - /// - public string Value { get; set; } - - /// - /// An additional optional value. - /// - public object Tag { get; set; } - - private static object EvCompleted { get; } = new object(); - - public bool ShowBackButton { get; set; } = false; - - public string BackLabel { get; set; } = Default.Language["PromptDialog_Back"]; - - /// - /// Contains the RAW received message. - /// - public Message ReceivedMessage { get; set; } - - public PromptDialog() - { - - } - - public PromptDialog(string message) - { - this.Message = message; - } - - public override async Task Load(MessageResult message) - { - if (message.Handled) - return; - - if (!message.IsFirstHandler) - return; - - if (ShowBackButton && message.MessageText == BackLabel) - { - await CloseForm(); - - return; - } - - if (Value == null) - { - Value = message.MessageText; - - ReceivedMessage = message.Message; - } - - - } - - public override async Task Render(MessageResult message) - { - - if (Value == null) - { - if (ShowBackButton) - { - var bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase(BackLabel, "back")); - await Device.Send(Message, (ReplyMarkupBase)bf); - return; - } - - await Device.Send(Message); - return; - } - - - message.Handled = true; - - OnCompleted(new PromptDialogCompletedEventArgs { Tag = Tag, Value = Value }); - - await CloseForm(); - } - - - public event EventHandler Completed - { - add => Events.AddHandler(EvCompleted, value); - remove => Events.RemoveHandler(EvCompleted, value); - } - - public void OnCompleted(PromptDialogCompletedEventArgs e) - { - (Events[EvCompleted] as EventHandler)?.Invoke(this, e); - } - } -} + + public PromptDialog(string message) + { + Message = message; + } + + /// + /// The message the users sees. + /// + public string Message { get; set; } + + /// + /// The returned text value by the user. + /// + public string Value { get; set; } + + /// + /// An additional optional value. + /// + public object Tag { get; set; } + + private static object EvCompleted { get; } = new(); + + public bool ShowBackButton { get; set; } = false; + + public string BackLabel { get; set; } = Default.Language["PromptDialog_Back"]; + + /// + /// Contains the RAW received message. + /// + public Message ReceivedMessage { get; set; } + + public override async Task Load(MessageResult message) + { + if (message.Handled) + { + return; + } + + if (!message.IsFirstHandler) + { + return; + } + + if (ShowBackButton && message.MessageText == BackLabel) + { + await CloseForm(); + + return; + } + + if (Value == null) + { + Value = message.MessageText; + + ReceivedMessage = message.Message; + } + } + + public override async Task Render(MessageResult message) + { + if (Value == null) + { + if (ShowBackButton) + { + var bf = new ButtonForm(); + bf.AddButtonRow(new ButtonBase(BackLabel, "back")); + await Device.Send(Message, (ReplyMarkupBase)bf); + return; + } + + await Device.Send(Message); + return; + } + + + message.Handled = true; + + OnCompleted(new PromptDialogCompletedEventArgs { Tag = Tag, Value = Value }); + + await CloseForm(); + } + + + public event EventHandler Completed + { + add => Events.AddHandler(EvCompleted, value); + remove => Events.RemoveHandler(EvCompleted, value); + } + + public void OnCompleted(PromptDialogCompletedEventArgs e) + { + (Events[EvCompleted] as EventHandler)?.Invoke(this, e); + } +} \ No newline at end of file diff --git a/TelegramBotBase/Form/SplitterForm.cs b/TelegramBotBase/Form/SplitterForm.cs index bfb9818..4d8d668 100644 --- a/TelegramBotBase/Form/SplitterForm.cs +++ b/TelegramBotBase/Form/SplitterForm.cs @@ -2,95 +2,92 @@ using Telegram.Bot.Types.Enums; using TelegramBotBase.Base; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +/// +/// This is used to split incomming requests depending on the chat type. +/// +public class SplitterForm : FormBase { - /// - /// This is used to split incomming requests depending on the chat type. - /// - public class SplitterForm : FormBase + private static object __evOpenSupergroup = new(); + private static object __evOpenGroup = new(); + private static object __evOpenChannel = new(); + private static object __evOpen = new(); + + + public override async Task Load(MessageResult message) { - - private static object __evOpenSupergroup = new object(); - private static object __evOpenGroup = new object(); - private static object __evOpenChannel = new object(); - private static object __evOpen = new object(); - - - public override async Task Load(MessageResult message) + if (message.Message.Chat.Type == ChatType.Channel) { + if (await OpenChannel(message)) + { + return; + } + } - if (message.Message.Chat.Type == ChatType.Channel) + if (message.Message.Chat.Type == ChatType.Supergroup) + { + if (await OpenSupergroup(message)) { - if (await OpenChannel(message)) - { - return; - } - } - if (message.Message.Chat.Type == ChatType.Supergroup) - { - if (await OpenSupergroup(message)) - { - return; - } - if (await OpenGroup(message)) - { - return; - } - } - if (message.Message.Chat.Type == ChatType.Group) - { - if (await OpenGroup(message)) - { - return; - } + return; } - await Open(message); + if (await OpenGroup(message)) + { + return; + } } - - public virtual Task OpenSupergroup(MessageResult e) + if (message.Message.Chat.Type == ChatType.Group) { - return Task.FromResult(false); - } - - public virtual Task OpenChannel(MessageResult e) - { - return Task.FromResult(false); - } - - public virtual Task Open(MessageResult e) - { - return Task.FromResult(false); - } - - public virtual Task OpenGroup(MessageResult e) - { - return Task.FromResult(false); - } - - - - - public override Task Action(MessageResult message) - { - return base.Action(message); - } - - public override Task PreLoad(MessageResult message) - { - return base.PreLoad(message); - } - - public override Task Render(MessageResult message) - { - return base.Render(message); - } - - public override Task SentData(DataResult message) - { - return base.SentData(message); + if (await OpenGroup(message)) + { + return; + } } + await Open(message); } -} + + + public virtual Task OpenSupergroup(MessageResult e) + { + return Task.FromResult(false); + } + + public virtual Task OpenChannel(MessageResult e) + { + return Task.FromResult(false); + } + + public virtual Task Open(MessageResult e) + { + return Task.FromResult(false); + } + + public virtual Task OpenGroup(MessageResult e) + { + return Task.FromResult(false); + } + + + public override Task Action(MessageResult message) + { + return base.Action(message); + } + + public override Task PreLoad(MessageResult message) + { + return base.PreLoad(message); + } + + public override Task Render(MessageResult message) + { + return base.Render(message); + } + + public override Task SentData(DataResult message) + { + return base.SentData(message); + } +} \ No newline at end of file diff --git a/TelegramBotBase/Form/TagButtonBase.cs b/TelegramBotBase/Form/TagButtonBase.cs index fd6f545..8a6cb9e 100644 --- a/TelegramBotBase/Form/TagButtonBase.cs +++ b/TelegramBotBase/Form/TagButtonBase.cs @@ -1,50 +1,46 @@ using Telegram.Bot.Types.ReplyMarkups; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +/// +/// Base class for button handling +/// +public class TagButtonBase : ButtonBase { - /// - /// Base class for button handling - /// - public class TagButtonBase : ButtonBase + public TagButtonBase() { - public string Tag { get; set; } - - public TagButtonBase() - { - - } - - public TagButtonBase(string text, string value, string tag) - { - this.Text = text; - this.Value = value; - this.Tag = tag; - } - - - /// - /// Returns an inline Button - /// - /// - /// - public override InlineKeyboardButton ToInlineButton(ButtonForm form) - { - var id = (form.DependencyControl != null ? form.DependencyControl.ControlId + "_" : ""); - - return InlineKeyboardButton.WithCallbackData(Text, id + Value); - - } - - - /// - /// Returns a KeyBoardButton - /// - /// - /// - public override KeyboardButton ToKeyboardButton(ButtonForm form) - { - return new KeyboardButton(Text); - } - } -} + + public TagButtonBase(string text, string value, string tag) + { + Text = text; + Value = value; + Tag = tag; + } + + public string Tag { get; set; } + + + /// + /// Returns an inline Button + /// + /// + /// + public override InlineKeyboardButton ToInlineButton(ButtonForm form) + { + var id = form.DependencyControl != null ? form.DependencyControl.ControlId + "_" : ""; + + return InlineKeyboardButton.WithCallbackData(Text, id + Value); + } + + + /// + /// Returns a KeyBoardButton + /// + /// + /// + public override KeyboardButton ToKeyboardButton(ButtonForm form) + { + return new KeyboardButton(Text); + } +} \ No newline at end of file diff --git a/TelegramBotBase/Interfaces/IDataSource.cs b/TelegramBotBase/Interfaces/IDataSource.cs index 7934972..fe759ee 100644 --- a/TelegramBotBase/Interfaces/IDataSource.cs +++ b/TelegramBotBase/Interfaces/IDataSource.cs @@ -1,40 +1,36 @@ using System.Collections.Generic; -namespace TelegramBotBase.Interfaces +namespace TelegramBotBase.Interfaces; + +public interface IDataSource { - public interface IDataSource - { - - /// - /// Returns the amount of items within this source. - /// - /// - int Count { get; } + /// + /// Returns the amount of items within this source. + /// + /// + int Count { get; } - /// - /// Returns the item at the specific index. - /// - /// - /// - T ItemAt(int index); + /// + /// Returns the item at the specific index. + /// + /// + /// + T ItemAt(int index); - /// - /// Get all items from this source within this range. - /// - /// - /// - /// - List ItemRange(int start, int count); + /// + /// Get all items from this source within this range. + /// + /// + /// + /// + List ItemRange(int start, int count); - /// - /// Gets a list of all items of this datasource. - /// - /// - List AllItems(); - - - } -} + /// + /// Gets a list of all items of this datasource. + /// + /// + List AllItems(); +} \ No newline at end of file diff --git a/TelegramBotBase/Interfaces/IDeviceSession.cs b/TelegramBotBase/Interfaces/IDeviceSession.cs index 05ae969..8e0d95a 100644 --- a/TelegramBotBase/Interfaces/IDeviceSession.cs +++ b/TelegramBotBase/Interfaces/IDeviceSession.cs @@ -1,40 +1,38 @@ using System; using TelegramBotBase.Form; -namespace TelegramBotBase.Interfaces +namespace TelegramBotBase.Interfaces; + +internal interface IDeviceSession { - internal interface IDeviceSession - { - /// - /// Device or chat id - /// - long DeviceId { get; set; } + /// + /// Device or chat id + /// + long DeviceId { get; set; } - /// - /// Username of user or group - /// - string ChatTitle { get; set; } + /// + /// Username of user or group + /// + string ChatTitle { get; set; } - /// - /// When did any last action happend (message received or button clicked) - /// - DateTime LastAction { get; set; } + /// + /// When did any last action happend (message received or button clicked) + /// + DateTime LastAction { get; set; } - /// - /// Returns the form where the user/group is at the moment. - /// - FormBase ActiveForm { get; set; } + /// + /// Returns the form where the user/group is at the moment. + /// + FormBase ActiveForm { get; set; } - /// - /// Returns the previous shown form - /// - FormBase PreviousForm { get; set; } + /// + /// Returns the previous shown form + /// + FormBase PreviousForm { get; set; } - /// - /// contains if the form has been switched (navigated) - /// - bool FormSwitched { get; set; } - - } -} + /// + /// contains if the form has been switched (navigated) + /// + bool FormSwitched { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Interfaces/IMessageLoopFactory.cs b/TelegramBotBase/Interfaces/IMessageLoopFactory.cs index 937e37a..951b7fa 100644 --- a/TelegramBotBase/Interfaces/IMessageLoopFactory.cs +++ b/TelegramBotBase/Interfaces/IMessageLoopFactory.cs @@ -4,15 +4,11 @@ using TelegramBotBase.Args; using TelegramBotBase.Base; using TelegramBotBase.Sessions; -namespace TelegramBotBase.Interfaces +namespace TelegramBotBase.Interfaces; + +public interface IMessageLoopFactory { - public interface IMessageLoopFactory - { + Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult e); - Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult e); - - event EventHandler UnhandledCall; - - - } -} + event EventHandler UnhandledCall; +} \ No newline at end of file diff --git a/TelegramBotBase/Interfaces/IStartFormFactory.cs b/TelegramBotBase/Interfaces/IStartFormFactory.cs index e300928..28a2df2 100644 --- a/TelegramBotBase/Interfaces/IStartFormFactory.cs +++ b/TelegramBotBase/Interfaces/IStartFormFactory.cs @@ -1,9 +1,8 @@ using TelegramBotBase.Form; -namespace TelegramBotBase.Interfaces +namespace TelegramBotBase.Interfaces; + +public interface IStartFormFactory { - public interface IStartFormFactory - { - FormBase CreateForm(); - } -} + FormBase CreateForm(); +} \ No newline at end of file diff --git a/TelegramBotBase/Interfaces/IStateForm.cs b/TelegramBotBase/Interfaces/IStateForm.cs index f9346d7..7e42cc4 100644 --- a/TelegramBotBase/Interfaces/IStateForm.cs +++ b/TelegramBotBase/Interfaces/IStateForm.cs @@ -1,16 +1,13 @@ using TelegramBotBase.Args; -namespace TelegramBotBase.Interfaces +namespace TelegramBotBase.Interfaces; + +/// +/// Is used to save specific fields into a session state to survive restarts or unhandled exceptions and crashes. +/// +public interface IStateForm { - /// - /// Is used to save specific fields into a session state to survive restarts or unhandled exceptions and crashes. - /// - public interface IStateForm - { + void LoadState(LoadStateEventArgs e); - void LoadState(LoadStateEventArgs e); - - void SaveState(SaveStateEventArgs e); - - } -} + void SaveState(SaveStateEventArgs e); +} \ No newline at end of file diff --git a/TelegramBotBase/Interfaces/IStateMachine.cs b/TelegramBotBase/Interfaces/IStateMachine.cs index 2c9c656..221fc77 100644 --- a/TelegramBotBase/Interfaces/IStateMachine.cs +++ b/TelegramBotBase/Interfaces/IStateMachine.cs @@ -2,14 +2,13 @@ using TelegramBotBase.Args; using TelegramBotBase.Base; -namespace TelegramBotBase.Interfaces +namespace TelegramBotBase.Interfaces; + +public interface IStateMachine { - public interface IStateMachine - { - Type FallbackStateForm { get; } + Type FallbackStateForm { get; } - void SaveFormStates(SaveStatesEventArgs e); + void SaveFormStates(SaveStatesEventArgs e); - StateContainer LoadFormStates(); - } -} + StateContainer LoadFormStates(); +} \ No newline at end of file diff --git a/TelegramBotBase/Localizations/Default.cs b/TelegramBotBase/Localizations/Default.cs index 27fb412..0582b8a 100644 --- a/TelegramBotBase/Localizations/Default.cs +++ b/TelegramBotBase/Localizations/Default.cs @@ -1,10 +1,6 @@ -namespace TelegramBotBase.Localizations +namespace TelegramBotBase.Localizations; + +public static class Default { - public static class Default - { - - public static Localization Language = new English(); - - - } -} + public static Localization Language = new English(); +} \ No newline at end of file diff --git a/TelegramBotBase/Localizations/English.cs b/TelegramBotBase/Localizations/English.cs index 2ba5fed..fb5b948 100644 --- a/TelegramBotBase/Localizations/English.cs +++ b/TelegramBotBase/Localizations/English.cs @@ -1,37 +1,35 @@ -namespace TelegramBotBase.Localizations +namespace TelegramBotBase.Localizations; + +public class English : Localization { - public class English : Localization + public English() { - public English() - { - Values["Language"] = "English"; - Values["ButtonGrid_Title"] = "Menu"; - Values["ButtonGrid_NoItems"] = "There are no items."; - Values["ButtonGrid_PreviousPage"] = "◀️"; - Values["ButtonGrid_NextPage"] = "▶️"; - Values["ButtonGrid_CurrentPage"] = "Page {0} of {1}"; - Values["ButtonGrid_SearchFeature"] = "💡 Send a message to filter the list. Click the 🔍 to reset the filter."; - Values["ButtonGrid_Back"] = "Back"; - Values["ButtonGrid_CheckAll"] = "Check all"; - Values["ButtonGrid_UncheckAll"] = "Uncheck all"; - Values["CalendarPicker_Title"] = "Pick date"; - Values["CalendarPicker_PreviousPage"] = "◀️"; - Values["CalendarPicker_NextPage"] = "▶️"; - Values["TreeView_Title"] = "Select node"; - Values["TreeView_LevelUp"] = "🔼 level up"; - Values["ToggleButton_On"] = "On"; - Values["ToggleButton_Off"] = "Off"; - Values["ToggleButton_OnIcon"] = "⚫"; - Values["ToggleButton_OffIcon"] = "⚪"; - Values["ToggleButton_Title"] = "Toggle"; - Values["ToggleButton_Changed"] = "Choosen"; - Values["MultiToggleButton_SelectedIcon"] = "✅"; - Values["MultiToggleButton_Title"] = "Multi-Toggle"; - Values["MultiToggleButton_Changed"] = "Choosen"; - Values["PromptDialog_Back"] = "Back"; - Values["ToggleButton_Changed"] = "Setting changed"; - } - - + Values["Language"] = "English"; + Values["ButtonGrid_Title"] = "Menu"; + Values["ButtonGrid_NoItems"] = "There are no items."; + Values["ButtonGrid_PreviousPage"] = "◀️"; + Values["ButtonGrid_NextPage"] = "▶️"; + Values["ButtonGrid_CurrentPage"] = "Page {0} of {1}"; + Values["ButtonGrid_SearchFeature"] = + "💡 Send a message to filter the list. Click the 🔍 to reset the filter."; + Values["ButtonGrid_Back"] = "Back"; + Values["ButtonGrid_CheckAll"] = "Check all"; + Values["ButtonGrid_UncheckAll"] = "Uncheck all"; + Values["CalendarPicker_Title"] = "Pick date"; + Values["CalendarPicker_PreviousPage"] = "◀️"; + Values["CalendarPicker_NextPage"] = "▶️"; + Values["TreeView_Title"] = "Select node"; + Values["TreeView_LevelUp"] = "🔼 level up"; + Values["ToggleButton_On"] = "On"; + Values["ToggleButton_Off"] = "Off"; + Values["ToggleButton_OnIcon"] = "⚫"; + Values["ToggleButton_OffIcon"] = "⚪"; + Values["ToggleButton_Title"] = "Toggle"; + Values["ToggleButton_Changed"] = "Choosen"; + Values["MultiToggleButton_SelectedIcon"] = "✅"; + Values["MultiToggleButton_Title"] = "Multi-Toggle"; + Values["MultiToggleButton_Changed"] = "Choosen"; + Values["PromptDialog_Back"] = "Back"; + Values["ToggleButton_Changed"] = "Setting changed"; } -} +} \ No newline at end of file diff --git a/TelegramBotBase/Localizations/German.cs b/TelegramBotBase/Localizations/German.cs index d34240a..52afbf7 100644 --- a/TelegramBotBase/Localizations/German.cs +++ b/TelegramBotBase/Localizations/German.cs @@ -1,37 +1,35 @@ -namespace TelegramBotBase.Localizations +namespace TelegramBotBase.Localizations; + +public class German : Localization { - public class German : Localization + public German() { - public German() - { - Values["Language"] = "Deutsch (German)"; - Values["ButtonGrid_Title"] = "Menü"; - Values["ButtonGrid_NoItems"] = "Es sind keine Einträge vorhanden."; - Values["ButtonGrid_PreviousPage"] = "◀️"; - Values["ButtonGrid_NextPage"] = "▶️"; - Values["ButtonGrid_CurrentPage"] = "Seite {0} von {1}"; - Values["ButtonGrid_SearchFeature"] = "💡 Sende eine Nachricht um die Liste zu filtern. Klicke die 🔍 um den Filter zurückzusetzen."; - Values["ButtonGrid_Back"] = "Zurück"; - Values["ButtonGrid_CheckAll"] = "Alle auswählen"; - Values["ButtonGrid_UncheckAll"] = "Keine auswählen"; - Values["CalendarPicker_Title"] = "Datum auswählen"; - Values["CalendarPicker_PreviousPage"] = "◀️"; - Values["CalendarPicker_NextPage"] = "▶️"; - Values["TreeView_Title"] = "Knoten auswählen"; - Values["TreeView_LevelUp"] = "🔼 Stufe hoch"; - Values["ToggleButton_On"] = "An"; - Values["ToggleButton_Off"] = "Aus"; - Values["ToggleButton_OnIcon"] = "⚫"; - Values["ToggleButton_OffIcon"] = "⚪"; - Values["ToggleButton_Title"] = "Schalter"; - Values["ToggleButton_Changed"] = "Ausgewählt"; - Values["MultiToggleButton_SelectedIcon"] = "✅"; - Values["MultiToggleButton_Title"] = "Mehrfach-Schalter"; - Values["MultiToggleButton_Changed"] = "Ausgewählt"; - Values["PromptDialog_Back"] = "Zurück"; - Values["ToggleButton_Changed"] = "Einstellung geändert"; - } - - + Values["Language"] = "Deutsch (German)"; + Values["ButtonGrid_Title"] = "Menü"; + Values["ButtonGrid_NoItems"] = "Es sind keine Einträge vorhanden."; + Values["ButtonGrid_PreviousPage"] = "◀️"; + Values["ButtonGrid_NextPage"] = "▶️"; + Values["ButtonGrid_CurrentPage"] = "Seite {0} von {1}"; + Values["ButtonGrid_SearchFeature"] = + "💡 Sende eine Nachricht um die Liste zu filtern. Klicke die 🔍 um den Filter zurückzusetzen."; + Values["ButtonGrid_Back"] = "Zurück"; + Values["ButtonGrid_CheckAll"] = "Alle auswählen"; + Values["ButtonGrid_UncheckAll"] = "Keine auswählen"; + Values["CalendarPicker_Title"] = "Datum auswählen"; + Values["CalendarPicker_PreviousPage"] = "◀️"; + Values["CalendarPicker_NextPage"] = "▶️"; + Values["TreeView_Title"] = "Knoten auswählen"; + Values["TreeView_LevelUp"] = "🔼 Stufe hoch"; + Values["ToggleButton_On"] = "An"; + Values["ToggleButton_Off"] = "Aus"; + Values["ToggleButton_OnIcon"] = "⚫"; + Values["ToggleButton_OffIcon"] = "⚪"; + Values["ToggleButton_Title"] = "Schalter"; + Values["ToggleButton_Changed"] = "Ausgewählt"; + Values["MultiToggleButton_SelectedIcon"] = "✅"; + Values["MultiToggleButton_Title"] = "Mehrfach-Schalter"; + Values["MultiToggleButton_Changed"] = "Ausgewählt"; + Values["PromptDialog_Back"] = "Zurück"; + Values["ToggleButton_Changed"] = "Einstellung geändert"; } -} +} \ No newline at end of file diff --git a/TelegramBotBase/Localizations/Localization.cs b/TelegramBotBase/Localizations/Localization.cs index b34fb88..3efddff 100644 --- a/TelegramBotBase/Localizations/Localization.cs +++ b/TelegramBotBase/Localizations/Localization.cs @@ -1,12 +1,10 @@ using System.Collections.Generic; -namespace TelegramBotBase.Localizations +namespace TelegramBotBase.Localizations; + +public abstract class Localization { - public abstract class Localization - { - public Dictionary Values = new Dictionary(); - - public string this[string key] => Values[key]; - } -} + public Dictionary Values = new(); + public string this[string key] => Values[key]; +} \ No newline at end of file diff --git a/TelegramBotBase/Markdown/Generator.cs b/TelegramBotBase/Markdown/Generator.cs index 748f62d..333c6cf 100644 --- a/TelegramBotBase/Markdown/Generator.cs +++ b/TelegramBotBase/Markdown/Generator.cs @@ -1,159 +1,159 @@ using System.Linq; using Telegram.Bot.Types.Enums; -namespace TelegramBotBase.Markdown +namespace TelegramBotBase.Markdown; + +/// +/// https://core.telegram.org/bots/api#markdownv2-style +/// +public static class Generator { + public static ParseMode OutputMode { get; set; } = ParseMode.Markdown; + /// - /// https://core.telegram.org/bots/api#markdownv2-style + /// Generates a link with title in Markdown or HTML /// - public static class Generator + /// + /// + /// + /// + public static string Link(this string url, string title = null, string tooltip = null) { - public static ParseMode OutputMode { get; set; } = ParseMode.Markdown; - - /// - /// Generates a link with title in Markdown or HTML - /// - /// - /// - /// - /// - public static string Link(this string url, string title = null, string tooltip = null) + return OutputMode switch { - return OutputMode switch - { - ParseMode.Markdown => "[" + (title ?? url) + "](" + url + " " + (tooltip ?? "") + ")", - ParseMode.Html => $"{title ?? ""}", - _ => url - }; - } - - /// - /// Returns a Link to the User, title is optional. - /// - /// - /// - /// - public static string MentionUser(this int userId, string title = null) - { - return Link("tg://user?id=" + userId, title); - } - - /// - /// Returns a Link to the User, title is optional. - /// - /// - /// - /// - public static string MentionUser(this string username, string title = null) - { - return Link("tg://user?id=" + username, title); - } - - /// - /// Returns a bold text in Markdown or HTML - /// - /// - /// - public static string Bold(this string text) - { - return OutputMode switch - { - ParseMode.Markdown => "*" + text + "*", - ParseMode.Html => "" + text + "", - _ => text - }; - } - - /// - /// Returns a strike through in Markdown or HTML - /// - /// - /// - public static string Strikesthrough(this string text) - { - return OutputMode switch - { - ParseMode.Markdown => "~" + text + "~", - ParseMode.Html => "" + text + "", - _ => text - }; - } - - /// - /// Returns a italic text in Markdown or HTML - /// - /// - /// - public static string Italic(this string text) - { - return OutputMode switch - { - ParseMode.Markdown => "_" + text + "_", - ParseMode.Html => "" + text + "", - _ => text - }; - } - - /// - /// Returns a underline text in Markdown or HTML - /// - /// - /// - public static string Underline(this string text) - { - return OutputMode switch - { - ParseMode.Markdown => "__" + text + "__", - ParseMode.Html => "" + text + "", - _ => text - }; - } - - /// - /// Returns a monospace text in Markdown or HTML - /// - /// - /// - public static string Monospace(this string text) - { - return OutputMode switch - { - ParseMode.Markdown => "`" + text + "`", - ParseMode.Html => "" + text + "", - _ => text - }; - } - - /// - /// Returns a multi monospace text in Markdown or HTML - /// - /// - /// - public static string MultiMonospace(this string text) - { - return OutputMode switch - { - ParseMode.Markdown => "```" + text + "```", - ParseMode.Html => "
" + text + "
", - _ => text - }; - } - - /// - /// Escapes all characters as stated in the documentation: https://core.telegram.org/bots/api#markdownv2-style - /// - /// - /// - public static string MarkdownV2Escape(this string text, params char[] toKeep) - { - var toEscape = new[] { '_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!' }; - - return text.EscapeAll(toEscape.Where(a => !toKeep.Contains(a)).Select(a => a.ToString()).ToArray()); - } - - public static string EscapeAll(this string seed, string[] chars, char escapeCharacter = '\\') - { - return chars.Aggregate(seed, (str, cItem) => str.Replace(cItem, escapeCharacter + cItem)); - } + ParseMode.Markdown => "[" + (title ?? url) + "](" + url + " " + (tooltip ?? "") + ")", + ParseMode.Html => $"
{title ?? ""}", + _ => url + }; } -} + + /// + /// Returns a Link to the User, title is optional. + /// + /// + /// + /// + public static string MentionUser(this int userId, string title = null) + { + return Link("tg://user?id=" + userId, title); + } + + /// + /// Returns a Link to the User, title is optional. + /// + /// + /// + /// + public static string MentionUser(this string username, string title = null) + { + return Link("tg://user?id=" + username, title); + } + + /// + /// Returns a bold text in Markdown or HTML + /// + /// + /// + public static string Bold(this string text) + { + return OutputMode switch + { + ParseMode.Markdown => "*" + text + "*", + ParseMode.Html => "" + text + "", + _ => text + }; + } + + /// + /// Returns a strike through in Markdown or HTML + /// + /// + /// + public static string Strikesthrough(this string text) + { + return OutputMode switch + { + ParseMode.Markdown => "~" + text + "~", + ParseMode.Html => "" + text + "", + _ => text + }; + } + + /// + /// Returns a italic text in Markdown or HTML + /// + /// + /// + public static string Italic(this string text) + { + return OutputMode switch + { + ParseMode.Markdown => "_" + text + "_", + ParseMode.Html => "" + text + "", + _ => text + }; + } + + /// + /// Returns a underline text in Markdown or HTML + /// + /// + /// + public static string Underline(this string text) + { + return OutputMode switch + { + ParseMode.Markdown => "__" + text + "__", + ParseMode.Html => "" + text + "", + _ => text + }; + } + + /// + /// Returns a monospace text in Markdown or HTML + /// + /// + /// + public static string Monospace(this string text) + { + return OutputMode switch + { + ParseMode.Markdown => "`" + text + "`", + ParseMode.Html => "" + text + "", + _ => text + }; + } + + /// + /// Returns a multi monospace text in Markdown or HTML + /// + /// + /// + public static string MultiMonospace(this string text) + { + return OutputMode switch + { + ParseMode.Markdown => "```" + text + "```", + ParseMode.Html => "
" + text + "
", + _ => text + }; + } + + /// + /// Escapes all characters as stated in the documentation: https://core.telegram.org/bots/api#markdownv2-style + /// + /// + /// + public static string MarkdownV2Escape(this string text, params char[] toKeep) + { + var toEscape = new[] + { '_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!' }; + + return text.EscapeAll(toEscape.Where(a => !toKeep.Contains(a)).Select(a => a.ToString()).ToArray()); + } + + public static string EscapeAll(this string seed, string[] chars, char escapeCharacter = '\\') + { + return chars.Aggregate(seed, (str, cItem) => str.Replace(cItem, escapeCharacter + cItem)); + } +} \ No newline at end of file diff --git a/TelegramBotBase/MessageLoops/FormBaseMessageLoop.cs b/TelegramBotBase/MessageLoops/FormBaseMessageLoop.cs index bfd6d81..7a06466 100644 --- a/TelegramBotBase/MessageLoops/FormBaseMessageLoop.cs +++ b/TelegramBotBase/MessageLoops/FormBaseMessageLoop.cs @@ -7,116 +7,116 @@ using TelegramBotBase.Base; using TelegramBotBase.Interfaces; using TelegramBotBase.Sessions; -namespace TelegramBotBase.MessageLoops +namespace TelegramBotBase.MessageLoops; + +/// +/// Thats the default message loop which reacts to Message, EditMessage and CallbackQuery. +/// +public class FormBaseMessageLoop : IMessageLoopFactory { - /// - /// Thats the default message loop which reacts to Message, EditMessage and CallbackQuery. - /// - public class FormBaseMessageLoop : IMessageLoopFactory + private static readonly object EvUnhandledCall = new(); + + private readonly EventHandlerList _events = new(); + + public async Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult mr) { - private static readonly object EvUnhandledCall = new object(); + var update = ur.RawData; - private readonly EventHandlerList _events = new EventHandlerList(); - public async Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult mr) + if (update.Type != UpdateType.Message + && update.Type != UpdateType.EditedMessage + && update.Type != UpdateType.CallbackQuery) { - var update = ur.RawData; + return; + } + //Is this a bot command ? + if (mr.IsFirstHandler && mr.IsBotCommand && bot.IsKnownBotCommand(mr.BotCommand)) + { + var sce = new BotCommandEventArgs(mr.BotCommand, mr.BotCommandParameters, mr.Message, session.DeviceId, + session); + await bot.OnBotCommand(sce); - if (update.Type != UpdateType.Message - && update.Type != UpdateType.EditedMessage - && update.Type != UpdateType.CallbackQuery) + if (sce.Handled) { return; } + } - //Is this a bot command ? - if (mr.IsFirstHandler && mr.IsBotCommand && bot.IsKnownBotCommand(mr.BotCommand)) + mr.Device = session; + + var activeForm = session.ActiveForm; + + //Pre Loading Event + await activeForm.PreLoad(mr); + + //Send Load event to controls + await activeForm.LoadControls(mr); + + //Loading Event + await activeForm.Load(mr); + + + //Is Attachment ? (Photo, Audio, Video, Contact, Location, Document) (Ignore Callback Queries) + if (update.Type == UpdateType.Message) + { + if ((mr.MessageType == MessageType.Contact) + | (mr.MessageType == MessageType.Document) + | (mr.MessageType == MessageType.Location) + | (mr.MessageType == MessageType.Photo) + | (mr.MessageType == MessageType.Video) + | (mr.MessageType == MessageType.Audio)) { - var sce = new BotCommandEventArgs(mr.BotCommand, mr.BotCommandParameters, mr.Message, session.DeviceId, session); - await bot.OnBotCommand(sce); - - if (sce.Handled) - return; + await activeForm.SentData(new DataResult(ur)); } + } - mr.Device = session; + //Action Event + if (!session.FormSwitched && mr.IsAction) + { + //Send Action event to controls + await activeForm.ActionControls(mr); - var activeForm = session.ActiveForm; + //Send Action event to form itself + await activeForm.Action(mr); - //Pre Loading Event - await activeForm.PreLoad(mr); - - //Send Load event to controls - await activeForm.LoadControls(mr); - - //Loading Event - await activeForm.Load(mr); - - - //Is Attachment ? (Photo, Audio, Video, Contact, Location, Document) (Ignore Callback Queries) - if (update.Type == UpdateType.Message) + if (!mr.Handled) { - if (mr.MessageType == MessageType.Contact - | mr.MessageType == MessageType.Document - | mr.MessageType == MessageType.Location - | mr.MessageType == MessageType.Photo - | mr.MessageType == MessageType.Video - | mr.MessageType == MessageType.Audio) + var uhc = new UnhandledCallEventArgs(ur.Message.Text, mr.RawData, session.DeviceId, mr.MessageId, + ur.Message, session); + OnUnhandledCall(uhc); + + if (uhc.Handled) { - await activeForm.SentData(new DataResult(ur)); - } - } - - //Action Event - if (!session.FormSwitched && mr.IsAction) - { - //Send Action event to controls - await activeForm.ActionControls(mr); - - //Send Action event to form itself - await activeForm.Action(mr); - - if (!mr.Handled) - { - var uhc = new UnhandledCallEventArgs(ur.Message.Text, mr.RawData, session.DeviceId, mr.MessageId, ur.Message, session); - OnUnhandledCall(uhc); - - if (uhc.Handled) + mr.Handled = true; + if (!session.FormSwitched) { - mr.Handled = true; - if (!session.FormSwitched) - { - return; - } + return; } } - } - - if (!session.FormSwitched) - { - //Render Event - await activeForm.RenderControls(mr); - - await activeForm.Render(mr); - } - } - /// - /// Will be called if no form handeled this call - /// - public event EventHandler UnhandledCall + if (!session.FormSwitched) { - add => _events.AddHandler(EvUnhandledCall, value); - remove => _events.RemoveHandler(EvUnhandledCall, value); - } - - public void OnUnhandledCall(UnhandledCallEventArgs e) - { - (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); + //Render Event + await activeForm.RenderControls(mr); + await activeForm.Render(mr); } } -} + + /// + /// Will be called if no form handeled this call + /// + public event EventHandler UnhandledCall + { + add => _events.AddHandler(EvUnhandledCall, value); + remove => _events.RemoveHandler(EvUnhandledCall, value); + } + + public void OnUnhandledCall(UnhandledCallEventArgs e) + { + (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); + } +} \ No newline at end of file diff --git a/TelegramBotBase/MessageLoops/FullMessageLoop.cs b/TelegramBotBase/MessageLoops/FullMessageLoop.cs index 1277094..69c2105 100644 --- a/TelegramBotBase/MessageLoops/FullMessageLoop.cs +++ b/TelegramBotBase/MessageLoops/FullMessageLoop.cs @@ -7,109 +7,109 @@ using TelegramBotBase.Base; using TelegramBotBase.Interfaces; using TelegramBotBase.Sessions; -namespace TelegramBotBase.MessageLoops +namespace TelegramBotBase.MessageLoops; + +/// +/// This message loop reacts to all update types. +/// +public class FullMessageLoop : IMessageLoopFactory { - /// - /// This message loop reacts to all update types. - /// - public class FullMessageLoop : IMessageLoopFactory + private static readonly object EvUnhandledCall = new(); + + private readonly EventHandlerList _events = new(); + + public async Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult mr) { - private static readonly object EvUnhandledCall = new object(); + var update = ur.RawData; - private readonly EventHandlerList _events = new EventHandlerList(); - public async Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult mr) + //Is this a bot command ? + if (mr.IsFirstHandler && mr.IsBotCommand && bot.IsKnownBotCommand(mr.BotCommand)) { - var update = ur.RawData; + var sce = new BotCommandEventArgs(mr.BotCommand, mr.BotCommandParameters, mr.Message, session.DeviceId, + session); + await bot.OnBotCommand(sce); - - //Is this a bot command ? - if (mr.IsFirstHandler && mr.IsBotCommand && bot.IsKnownBotCommand(mr.BotCommand)) + if (sce.Handled) { - var sce = new BotCommandEventArgs(mr.BotCommand, mr.BotCommandParameters, mr.Message, session.DeviceId, session); - await bot.OnBotCommand(sce); - - if (sce.Handled) - return; + return; } + } - mr.Device = session; + mr.Device = session; - var activeForm = session.ActiveForm; + var activeForm = session.ActiveForm; - //Pre Loading Event - await activeForm.PreLoad(mr); + //Pre Loading Event + await activeForm.PreLoad(mr); - //Send Load event to controls - await activeForm.LoadControls(mr); + //Send Load event to controls + await activeForm.LoadControls(mr); - //Loading Event - await activeForm.Load(mr); + //Loading Event + await activeForm.Load(mr); - //Is Attachment ? (Photo, Audio, Video, Contact, Location, Document) (Ignore Callback Queries) - if (update.Type == UpdateType.Message) + //Is Attachment ? (Photo, Audio, Video, Contact, Location, Document) (Ignore Callback Queries) + if (update.Type == UpdateType.Message) + { + if ((mr.MessageType == MessageType.Contact) + | (mr.MessageType == MessageType.Document) + | (mr.MessageType == MessageType.Location) + | (mr.MessageType == MessageType.Photo) + | (mr.MessageType == MessageType.Video) + | (mr.MessageType == MessageType.Audio)) { - if (mr.MessageType == MessageType.Contact - | mr.MessageType == MessageType.Document - | mr.MessageType == MessageType.Location - | mr.MessageType == MessageType.Photo - | mr.MessageType == MessageType.Video - | mr.MessageType == MessageType.Audio) - { - await activeForm.SentData(new DataResult(ur)); - } + await activeForm.SentData(new DataResult(ur)); } + } - //Action Event - if (!session.FormSwitched && mr.IsAction) + //Action Event + if (!session.FormSwitched && mr.IsAction) + { + //Send Action event to controls + await activeForm.ActionControls(mr); + + //Send Action event to form itself + await activeForm.Action(mr); + + if (!mr.Handled) { - //Send Action event to controls - await activeForm.ActionControls(mr); + var uhc = new UnhandledCallEventArgs(ur.Message.Text, mr.RawData, session.DeviceId, mr.MessageId, + ur.Message, session); + OnUnhandledCall(uhc); - //Send Action event to form itself - await activeForm.Action(mr); - - if (!mr.Handled) + if (uhc.Handled) { - var uhc = new UnhandledCallEventArgs(ur.Message.Text, mr.RawData, session.DeviceId, mr.MessageId, ur.Message, session); - OnUnhandledCall(uhc); - - if (uhc.Handled) + mr.Handled = true; + if (!session.FormSwitched) { - mr.Handled = true; - if (!session.FormSwitched) - { - return; - } + return; } } - } - - if (!session.FormSwitched) - { - //Render Event - await activeForm.RenderControls(mr); - - await activeForm.Render(mr); - } - } - /// - /// Will be called if no form handeled this call - /// - public event EventHandler UnhandledCall + if (!session.FormSwitched) { - add => _events.AddHandler(EvUnhandledCall, value); - remove => _events.RemoveHandler(EvUnhandledCall, value); - } - - public void OnUnhandledCall(UnhandledCallEventArgs e) - { - (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); + //Render Event + await activeForm.RenderControls(mr); + await activeForm.Render(mr); } } -} + + /// + /// Will be called if no form handeled this call + /// + public event EventHandler UnhandledCall + { + add => _events.AddHandler(EvUnhandledCall, value); + remove => _events.RemoveHandler(EvUnhandledCall, value); + } + + public void OnUnhandledCall(UnhandledCallEventArgs e) + { + (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); + } +} \ No newline at end of file diff --git a/TelegramBotBase/MessageLoops/MinimalMessageLoop.cs b/TelegramBotBase/MessageLoops/MinimalMessageLoop.cs index 2483668..74b5c83 100644 --- a/TelegramBotBase/MessageLoops/MinimalMessageLoop.cs +++ b/TelegramBotBase/MessageLoops/MinimalMessageLoop.cs @@ -6,44 +6,41 @@ using TelegramBotBase.Base; using TelegramBotBase.Interfaces; using TelegramBotBase.Sessions; -namespace TelegramBotBase.MessageLoops +namespace TelegramBotBase.MessageLoops; + +/// +/// This is a minimal message loop which will react to all update types and just calling the Load method. +/// +public class MinimalMessageLoop : IMessageLoopFactory { - /// - /// This is a minimal message loop which will react to all update types and just calling the Load method. - /// - public class MinimalMessageLoop : IMessageLoopFactory + private static readonly object EvUnhandledCall = new(); + + private readonly EventHandlerList _events = new(); + + public async Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult mr) { - private static readonly object EvUnhandledCall = new object(); - - private readonly EventHandlerList _events = new EventHandlerList(); - - public async Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult mr) - { - var update = ur.RawData; + var update = ur.RawData; - mr.Device = session; + mr.Device = session; - var activeForm = session.ActiveForm; + var activeForm = session.ActiveForm; - //Loading Event - await activeForm.Load(mr); - - } - - /// - /// Will be called if no form handeled this call - /// - public event EventHandler UnhandledCall - { - add => _events.AddHandler(EvUnhandledCall, value); - remove => _events.RemoveHandler(EvUnhandledCall, value); - } - - public void OnUnhandledCall(UnhandledCallEventArgs e) - { - (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); - - } + //Loading Event + await activeForm.Load(mr); } -} + + /// + /// Will be called if no form handeled this call + /// + public event EventHandler UnhandledCall + { + add => _events.AddHandler(EvUnhandledCall, value); + remove => _events.RemoveHandler(EvUnhandledCall, value); + } + + public void OnUnhandledCall(UnhandledCallEventArgs e) + { + (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); + } +} \ No newline at end of file diff --git a/TelegramBotBase/Properties/AssemblyInfo.cs b/TelegramBotBase/Properties/AssemblyInfo.cs index 14bc370..7f6a35f 100644 --- a/TelegramBotBase/Properties/AssemblyInfo.cs +++ b/TelegramBotBase/Properties/AssemblyInfo.cs @@ -32,4 +32,4 @@ using System.Runtime.InteropServices; // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.1.0.0")] -[assembly: AssemblyFileVersion("3.1.0.0")] +[assembly: AssemblyFileVersion("3.1.0.0")] \ No newline at end of file diff --git a/TelegramBotBase/SessionBase.cs b/TelegramBotBase/SessionBase.cs index 66ac76d..e7036cd 100644 --- a/TelegramBotBase/SessionBase.cs +++ b/TelegramBotBase/SessionBase.cs @@ -11,330 +11,338 @@ using TelegramBotBase.Interfaces; using TelegramBotBase.Sessions; using TelegramBotBase.Tools; -namespace TelegramBotBase +namespace TelegramBotBase; + +/// +/// Base class for managing all active sessions +/// +public class SessionBase { - /// - /// Base class for managing all active sessions - /// - public class SessionBase + public SessionBase() { - /// - /// The Basic message client. - /// - public MessageClient Client { get; set; } + SessionList = new Dictionary(); + } - /// - /// A list of all active sessions. - /// - public Dictionary SessionList { get; set; } + /// + /// The Basic message client. + /// + public MessageClient Client { get; set; } + + /// + /// A list of all active sessions. + /// + public Dictionary SessionList { get; set; } - /// - /// Reference to the Main BotBase instance for later use. - /// - public BotBase BotBase { get; set; } + /// + /// Reference to the Main BotBase instance for later use. + /// + public BotBase BotBase { get; set; } + /// + /// Get device session from Device/ChatId + /// + /// + /// + public DeviceSession this[long key] + { + get => SessionList[key]; + set => SessionList[key] = value; + } - public SessionBase() + /// + /// Get device session from Device/ChatId + /// + /// + /// + public DeviceSession GetSession(long deviceId) + { + var ds = SessionList.FirstOrDefault(a => a.Key == deviceId).Value ?? null; + return ds; + } + + /// + /// Start a new session + /// + /// + /// + /// + public async Task StartSession(long deviceId) + { + var start = BotBase.StartFormFactory.CreateForm(); + + start.Client = Client; + + var ds = new DeviceSession(deviceId, start); + + start.Device = ds; + await start.OnInit(new InitEventArgs()); + + await start.OnOpened(EventArgs.Empty); + + this[deviceId] = ds; + return ds; + } + + /// + /// End session + /// + /// + public void EndSession(long deviceId) + { + var d = this[deviceId]; + if (d != null) { - SessionList = new Dictionary(); + SessionList.Remove(deviceId); + } + } + + /// + /// Returns all active User Sessions. + /// + /// + public List GetUserSessions() + { + return SessionList.Where(a => a.Key > 0).Select(a => a.Value).ToList(); + } + + /// + /// Returns all active Group Sessions. + /// + /// + public List GetGroupSessions() + { + return SessionList.Where(a => a.Key < 0).Select(a => a.Value).ToList(); + } + + /// + /// Loads the previously saved states from the machine. + /// + public async void LoadSessionStates() + { + if (BotBase.StateMachine == null) + { + return; } - /// - /// Get device session from Device/ChatId - /// - /// - /// - public DeviceSession this[long key] + LoadSessionStates(BotBase.StateMachine); + } + + + /// + /// Loads the previously saved states from the machine. + /// + public async void LoadSessionStates(IStateMachine statemachine) + { + if (statemachine == null) { - get => SessionList[key]; - set => SessionList[key] = value; + throw new ArgumentNullException("StateMachine", + "No StateMachine defined. Please set one to property BotBase.StateMachine"); } - /// - /// Get device session from Device/ChatId - /// - /// - /// - public DeviceSession GetSession(long deviceId) + var container = statemachine.LoadFormStates(); + + foreach (var s in container.States) { - var ds = SessionList.FirstOrDefault(a => a.Key == deviceId).Value ?? null; - return ds; - } - - /// - /// Start a new session - /// - /// - /// - /// - public async Task StartSession(long deviceId) - { - var start = BotBase.StartFormFactory.CreateForm(); - - start.Client = Client; - - var ds = new DeviceSession(deviceId, start); - - start.Device = ds; - await start.OnInit(new InitEventArgs()); - - await start.OnOpened(EventArgs.Empty); - - this[deviceId] = ds; - return ds; - } - - /// - /// End session - /// - /// - public void EndSession(long deviceId) - { - var d = this[deviceId]; - if (d != null) + var t = Type.GetType(s.QualifiedName); + if (t == null || !t.IsSubclassOf(typeof(FormBase))) { - SessionList.Remove(deviceId); - - } - } - - /// - /// Returns all active User Sessions. - /// - /// - public List GetUserSessions() - { - return SessionList.Where(a => a.Key > 0).Select(a => a.Value).ToList(); - } - - /// - /// Returns all active Group Sessions. - /// - /// - public List GetGroupSessions() - { - return SessionList.Where(a => a.Key < 0).Select(a => a.Value).ToList(); - } - - /// - /// Loads the previously saved states from the machine. - /// - public async void LoadSessionStates() - { - if (BotBase.StateMachine == null) - { - return; + continue; } - LoadSessionStates(BotBase.StateMachine); - } - - - /// - /// Loads the previously saved states from the machine. - /// - public async void LoadSessionStates(IStateMachine statemachine) - { - if (statemachine == null) + //Key already existing + if (SessionList.ContainsKey(s.DeviceId)) { - throw new ArgumentNullException("StateMachine", "No StateMachine defined. Please set one to property BotBase.StateMachine"); + continue; } - var container = statemachine.LoadFormStates(); - - foreach (var s in container.States) + //No default constructor, fallback + if (!(t.GetConstructor(new Type[] { })?.Invoke(new object[] { }) is FormBase form)) { - var t = Type.GetType(s.QualifiedName); - if (t == null || !t.IsSubclassOf(typeof(FormBase))) + if (!statemachine.FallbackStateForm.IsSubclassOf(typeof(FormBase))) { continue; } - //Key already existing - if (SessionList.ContainsKey(s.DeviceId)) + form = + statemachine.FallbackStateForm.GetConstructor(new Type[] { }) + ?.Invoke(new object[] { }) as FormBase; + + //Fallback failed, due missing default constructor + if (form == null) + { continue; - - //No default constructor, fallback - if (!(t.GetConstructor(new Type[] { })?.Invoke(new object[] { }) is FormBase form)) - { - if (!statemachine.FallbackStateForm.IsSubclassOf(typeof(FormBase))) - continue; - - form = statemachine.FallbackStateForm.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as FormBase; - - //Fallback failed, due missing default constructor - if (form == null) - continue; - } + } - if (s.Values != null && s.Values.Count > 0) + if (s.Values != null && s.Values.Count > 0) + { + var properties = s.Values.Where(a => a.Key.StartsWith("$")); + var fields = form.GetType() + .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) + .Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); + + foreach (var p in properties) { - var properties = s.Values.Where(a => a.Key.StartsWith("$")); - var fields = form.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); - - foreach (var p in properties) + var f = fields.FirstOrDefault(a => a.Name == p.Key.Substring(1)); + if (f == null) { - var f = fields.FirstOrDefault(a => a.Name == p.Key.Substring(1)); - if (f == null) + continue; + } + + try + { + if (f.PropertyType.IsEnum) + { + var ent = Enum.Parse(f.PropertyType, p.Value.ToString()); + + f.SetValue(form, ent); + continue; - - try - { - if (f.PropertyType.IsEnum) - { - var ent = Enum.Parse(f.PropertyType, p.Value.ToString()); - - f.SetValue(form, ent); - - continue; - } - - - f.SetValue(form, p.Value); } - catch (ArgumentException) - { - Conversion.CustomConversionChecks(form, p, f); - } - catch - { - - } + f.SetValue(form, p.Value); + } + catch (ArgumentException) + { + Conversion.CustomConversionChecks(form, p, f); + } + catch + { } } + } - form.Client = Client; - var device = new DeviceSession(s.DeviceId, form) + form.Client = Client; + var device = new DeviceSession(s.DeviceId, form) + { + ChatTitle = s.ChatTitle + }; + + SessionList.Add(s.DeviceId, device); + + //Is Subclass of IStateForm + if (form is IStateForm iform) + { + var ls = new LoadStateEventArgs { - ChatTitle = s.ChatTitle + Values = s.Values + }; + iform.LoadState(ls); + } + + try + { + await form.OnInit(new InitEventArgs()); + + await form.OnOpened(EventArgs.Empty); + } + catch + { + //Skip on exception + SessionList.Remove(s.DeviceId); + } + } + } + + + /// + /// Saves all open states into the machine. + /// + public void SaveSessionStates(IStateMachine statemachine) + { + if (statemachine == null) + { + throw new ArgumentNullException("StateMachine", + "No StateMachine defined. Please set one to property BotBase.StateMachine"); + } + + var states = new List(); + + foreach (var s in SessionList) + { + if (s.Value == null) + { + continue; + } + + var form = s.Value.ActiveForm; + + try + { + var se = new StateEntry + { + DeviceId = s.Key, + ChatTitle = s.Value.GetChatTitle(), + FormUri = form.GetType().FullName, + QualifiedName = form.GetType().AssemblyQualifiedName }; - SessionList.Add(s.DeviceId, device); + //Skip classes where IgnoreState attribute is existing + if (form.GetType().GetCustomAttributes(typeof(IgnoreState), true).Length != 0) + { + //Skip this form, when there is no fallback state form + if (statemachine.FallbackStateForm == null) + { + continue; + } + + //Replace form by default State one. + se.FormUri = statemachine.FallbackStateForm.FullName; + se.QualifiedName = statemachine.FallbackStateForm.AssemblyQualifiedName; + } //Is Subclass of IStateForm if (form is IStateForm iform) { - var ls = new LoadStateEventArgs - { - Values = s.Values - }; - iform.LoadState(ls); + //Loading Session states + var ssea = new SaveStateEventArgs(); + iform.SaveState(ssea); + + se.Values = ssea.Values; } - try - { - await form.OnInit(new InitEventArgs()); + //Search for public properties with SaveState attribute + var fields = form.GetType() + .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) + .Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); - await form.OnOpened(EventArgs.Empty); - } - catch + foreach (var f in fields) { - //Skip on exception - SessionList.Remove(s.DeviceId); + var val = f.GetValue(form); + + se.Values.Add("$" + f.Name, val); } + + states.Add(se); + } + catch + { + //Continue on error (skip this form) } - } - - - - /// - /// Saves all open states into the machine. - /// - public void SaveSessionStates(IStateMachine statemachine) + var sc = new StateContainer { - if (statemachine == null) - { - throw new ArgumentNullException("StateMachine", "No StateMachine defined. Please set one to property BotBase.StateMachine"); - } + States = states + }; - var states = new List(); + statemachine.SaveFormStates(new SaveStatesEventArgs(sc)); + } - foreach (var s in SessionList) - { - if (s.Value == null) - { - continue; - } - - var form = s.Value.ActiveForm; - - try - { - var se = new StateEntry - { - DeviceId = s.Key, - ChatTitle = s.Value.GetChatTitle(), - FormUri = form.GetType().FullName, - QualifiedName = form.GetType().AssemblyQualifiedName - }; - - //Skip classes where IgnoreState attribute is existing - if (form.GetType().GetCustomAttributes(typeof(IgnoreState), true).Length != 0) - { - //Skip this form, when there is no fallback state form - if (statemachine.FallbackStateForm == null) - { - continue; - } - - //Replace form by default State one. - se.FormUri = statemachine.FallbackStateForm.FullName; - se.QualifiedName = statemachine.FallbackStateForm.AssemblyQualifiedName; - } - - //Is Subclass of IStateForm - if (form is IStateForm iform) - { - //Loading Session states - var ssea = new SaveStateEventArgs(); - iform.SaveState(ssea); - - se.Values = ssea.Values; - } - - //Search for public properties with SaveState attribute - var fields = form.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList(); - - foreach (var f in fields) - { - var val = f.GetValue(form); - - se.Values.Add("$" + f.Name, val); - } - - states.Add(se); - } - catch - { - //Continue on error (skip this form) - } - } - - var sc = new StateContainer - { - States = states - }; - - statemachine.SaveFormStates(new SaveStatesEventArgs(sc)); - } - - /// - /// Saves all open states into the machine. - /// - public void SaveSessionStates() + /// + /// Saves all open states into the machine. + /// + public void SaveSessionStates() + { + if (BotBase.StateMachine == null) { - if (BotBase.StateMachine == null) - return; - - - SaveSessionStates(BotBase.StateMachine); + return; } + + + SaveSessionStates(BotBase.StateMachine); } } diff --git a/TelegramBotBase/Sessions/DeviceSession.cs b/TelegramBotBase/Sessions/DeviceSession.cs index 5c017c0..2ece87c 100644 --- a/TelegramBotBase/Sessions/DeviceSession.cs +++ b/TelegramBotBase/Sessions/DeviceSession.cs @@ -18,914 +18,978 @@ using TelegramBotBase.Form; using TelegramBotBase.Interfaces; using TelegramBotBase.Markdown; -namespace TelegramBotBase.Sessions +namespace TelegramBotBase.Sessions; + +/// +/// Base class for a device/chat session +/// +public class DeviceSession : IDeviceSession { - /// - /// Base class for a device/chat session - /// - public class DeviceSession : IDeviceSession + private static readonly object EvMessageSent = new(); + private static readonly object EvMessageReceived = new(); + private static readonly object EvMessageDeleted = new(); + + private readonly EventHandlerList _events = new(); + + public DeviceSession() { - /// - /// Device or chat id - /// - public long DeviceId { get; set; } + } - /// - /// Username of user or group - /// - public string ChatTitle { get; set; } + public DeviceSession(long deviceId) + { + DeviceId = deviceId; + } - /// - /// Returns the ChatTitle depending on groups/channels or users - /// - /// - public string GetChatTitle() + public DeviceSession(long deviceId, FormBase startForm) + { + DeviceId = deviceId; + ActiveForm = startForm; + ActiveForm.Device = this; + } + + /// + /// Returns the ID of the last received message. + /// + public int LastMessageId => LastMessage?.MessageId ?? -1; + + /// + /// Returns the last received message. + /// + public Message LastMessage { get; set; } + + public MessageClient Client => ActiveForm.Client; + + /// + /// Returns if the messages is posted within a group. + /// + public bool IsGroup => LastMessage != null && + (LastMessage.Chat.Type == ChatType.Group) | + (LastMessage.Chat.Type == ChatType.Supergroup); + + /// + /// Returns if the messages is posted within a channel. + /// + public bool IsChannel => LastMessage != null && LastMessage.Chat.Type == ChatType.Channel; + + #region "Static" + + /// + /// Indicates the maximum number of times a request that received error + /// 429 will be sent again after a timeout until it receives code 200 or an error code not equal to 429. + /// + public static uint MaxNumberOfRetries { get; set; } + + #endregion "Static" + + /// + /// Device or chat id + /// + public long DeviceId { get; set; } + + /// + /// Username of user or group + /// + public string ChatTitle { get; set; } + + /// + /// When did any last action happend (message received or button clicked) + /// + public DateTime LastAction { get; set; } + + /// + /// Returns the form where the user/group is at the moment. + /// + public FormBase ActiveForm { get; set; } + + /// + /// Returns the previous shown form + /// + public FormBase PreviousForm { get; set; } + + /// + /// contains if the form has been switched (navigated) + /// + public bool FormSwitched { get; set; } = false; + + /// + /// Returns the ChatTitle depending on groups/channels or users + /// + /// + public string GetChatTitle() + { + return LastMessage?.Chat.Title + ?? LastMessage?.Chat.Username + ?? LastMessage?.Chat.FirstName + ?? ChatTitle; + } + + + /// + /// Confirm incomming action (i.e. Button click) + /// + /// + /// + public async Task ConfirmAction(string callbackQueryId, string message = "", bool showAlert = false, + string urlToOpen = null) + { + try { - return LastMessage?.Chat.Title - ?? LastMessage?.Chat.Username - ?? LastMessage?.Chat.FirstName - ?? ChatTitle; + await Client.TelegramClient.AnswerCallbackQueryAsync(callbackQueryId, message, showAlert, urlToOpen); + } + catch + { + } + } + + /// + /// Edits the text message + /// + /// + /// + /// + /// + public async Task Edit(int messageId, string text, ButtonForm buttons = null, + ParseMode parseMode = ParseMode.Markdown) + { + InlineKeyboardMarkup markup = buttons; + + if (text.Length > Constants.Telegram.MaxMessageLength) + { + throw new MaxLengthException(text.Length); } - /// - /// When did any last action happend (message received or button clicked) - /// - public DateTime LastAction { get; set; } - - /// - /// Returns the form where the user/group is at the moment. - /// - public FormBase ActiveForm { get; set; } - - /// - /// Returns the previous shown form - /// - public FormBase PreviousForm { get; set; } - - /// - /// contains if the form has been switched (navigated) - /// - public bool FormSwitched { get; set; } = false; - - /// - /// Returns the ID of the last received message. - /// - public int LastMessageId => LastMessage?.MessageId ?? -1; - - /// - /// Returns the last received message. - /// - public Message LastMessage { get; set; } - - public MessageClient Client => ActiveForm.Client; - - /// - /// Returns if the messages is posted within a group. - /// - public bool IsGroup => LastMessage != null && (LastMessage.Chat.Type == ChatType.Group | LastMessage.Chat.Type == ChatType.Supergroup); - - /// - /// Returns if the messages is posted within a channel. - /// - public bool IsChannel => LastMessage != null && LastMessage.Chat.Type == ChatType.Channel; - - private readonly EventHandlerList _events = new EventHandlerList(); - - private static readonly object EvMessageSent = new object(); - private static readonly object EvMessageReceived = new object(); - private static readonly object EvMessageDeleted = new object(); - - public DeviceSession() + try { - + return await Api(a => + a.EditMessageTextAsync(DeviceId, messageId, text, parseMode, replyMarkup: markup)); } - - public DeviceSession(long deviceId) + catch { - this.DeviceId = deviceId; - } - - public DeviceSession(long deviceId, FormBase startForm) - { - this.DeviceId = deviceId; - ActiveForm = startForm; - ActiveForm.Device = this; } - /// - /// Confirm incomming action (i.e. Button click) - /// - /// - /// - public async Task ConfirmAction(string callbackQueryId, string message = "", bool showAlert = false, string urlToOpen = null) - { - try - { - await Client.TelegramClient.AnswerCallbackQueryAsync(callbackQueryId, message, showAlert, urlToOpen); - } - catch - { + return null; + } - } + /// + /// Edits the text message + /// + /// + /// + /// + /// + public async Task Edit(int messageId, string text, InlineKeyboardMarkup markup, + ParseMode parseMode = ParseMode.Markdown) + { + if (text.Length > Constants.Telegram.MaxMessageLength) + { + throw new MaxLengthException(text.Length); } - /// - /// Edits the text message - /// - /// - /// - /// - /// - public async Task Edit(int messageId, string text, ButtonForm buttons = null, ParseMode parseMode = ParseMode.Markdown) + try { - InlineKeyboardMarkup markup = buttons; - - if (text.Length > Constants.Telegram.MaxMessageLength) - { - throw new MaxLengthException(text.Length); - } - - try - { - return await Api(a => a.EditMessageTextAsync(DeviceId, messageId, text, parseMode, replyMarkup: markup)); - } - catch - { - - } + return await Api(a => + a.EditMessageTextAsync(DeviceId, messageId, text, parseMode, replyMarkup: markup)); + } + catch + { + } + return null; + } + + /// + /// Edits the text message + /// + /// + /// + /// + /// + public async Task Edit(Message message, ButtonForm buttons = null, + ParseMode parseMode = ParseMode.Markdown) + { + InlineKeyboardMarkup markup = buttons; + + if (message.Text.Length > Constants.Telegram.MaxMessageLength) + { + throw new MaxLengthException(message.Text.Length); + } + + try + { + return await Api(a => + a.EditMessageTextAsync(DeviceId, message.MessageId, message.Text, parseMode, + replyMarkup: markup)); + } + catch + { + } + + + return null; + } + + /// + /// Edits the reply keyboard markup (buttons) + /// + /// + /// + /// + public async Task EditReplyMarkup(int messageId, ButtonForm bf) + { + try + { + return await Api(a => a.EditMessageReplyMarkupAsync(DeviceId, messageId, bf)); + } + catch + { + } + + return null; + } + + /// + /// Sends a simple text message + /// + /// + /// + /// + /// + /// + public async Task Send(long deviceId, string text, ButtonForm buttons = null, int replyTo = 0, + bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, + bool markdownV2AutoEscape = true) + { + if (ActiveForm == null) + { return null; } - /// - /// Edits the text message - /// - /// - /// - /// - /// - public async Task Edit(int messageId, string text, InlineKeyboardMarkup markup, ParseMode parseMode = ParseMode.Markdown) + InlineKeyboardMarkup markup = buttons; + + if (text.Length > Constants.Telegram.MaxMessageLength) { - if (text.Length > Constants.Telegram.MaxMessageLength) - { - throw new MaxLengthException(text.Length); - } + throw new MaxLengthException(text.Length); + } - try - { - return await Api(a => a.EditMessageTextAsync(DeviceId, messageId, text, parseMode, replyMarkup: markup)); - } - catch - { + if (parseMode == ParseMode.MarkdownV2 && markdownV2AutoEscape) + { + text = text.MarkdownV2Escape(); + } - } + try + { + var t = Api(a => a.SendTextMessageAsync(deviceId, text, parseMode, replyToMessageId: replyTo, + replyMarkup: markup, disableNotification: disableNotification)); + var o = GetOrigin(new StackTrace()); + await OnMessageSent(new MessageSentEventArgs(await t, o)); + + return await t; + } + catch + { + return null; + } + } + + /// + /// Sends a simple text message + /// + /// + /// + /// + /// + /// + public async Task Send(string text, ButtonForm buttons = null, int replyTo = 0, + bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, + bool markdownV2AutoEscape = true) + { + return await Send(DeviceId, text, buttons, replyTo, disableNotification, parseMode, markdownV2AutoEscape); + } + + /// + /// Sends a simple text message + /// + /// + /// + /// + /// + /// + public async Task Send(string text, InlineKeyboardMarkup markup, int replyTo = 0, + bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, + bool markdownV2AutoEscape = true) + { + if (ActiveForm == null) + { return null; } - /// - /// Edits the text message - /// - /// - /// - /// - /// - public async Task Edit(Message message, ButtonForm buttons = null, ParseMode parseMode = ParseMode.Markdown) + if (text.Length > Constants.Telegram.MaxMessageLength) { - InlineKeyboardMarkup markup = buttons; + throw new MaxLengthException(text.Length); + } - if (message.Text.Length > Constants.Telegram.MaxMessageLength) - { - throw new MaxLengthException(message.Text.Length); - } + if (parseMode == ParseMode.MarkdownV2 && markdownV2AutoEscape) + { + text = text.MarkdownV2Escape(); + } - try - { - return await Api(a => a.EditMessageTextAsync(DeviceId, message.MessageId, message.Text, parseMode, replyMarkup: markup)); - } - catch - { + try + { + var t = Api(a => a.SendTextMessageAsync(DeviceId, text, parseMode, replyToMessageId: replyTo, + replyMarkup: markup, disableNotification: disableNotification)); - } + var o = GetOrigin(new StackTrace()); + await OnMessageSent(new MessageSentEventArgs(await t, o)); + return await t; + } + catch + { + return null; + } + } + /// + /// Sends a simple text message + /// + /// + /// + /// + /// + /// + public async Task Send(string text, ReplyMarkupBase markup, int replyTo = 0, + bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, + bool markdownV2AutoEscape = true) + { + if (ActiveForm == null) + { return null; } - /// - /// Edits the reply keyboard markup (buttons) - /// - /// - /// - /// - public async Task EditReplyMarkup(int messageId, ButtonForm bf) + if (text.Length > Constants.Telegram.MaxMessageLength) { + throw new MaxLengthException(text.Length); + } - try - { - return await Api(a => a.EditMessageReplyMarkupAsync(DeviceId, messageId, bf)); - } - catch - { + if (parseMode == ParseMode.MarkdownV2 && markdownV2AutoEscape) + { + text = text.MarkdownV2Escape(); + } - } + try + { + var t = Api(a => a.SendTextMessageAsync(DeviceId, text, parseMode, replyToMessageId: replyTo, + replyMarkup: markup, disableNotification: disableNotification)); + var o = GetOrigin(new StackTrace()); + await OnMessageSent(new MessageSentEventArgs(await t, o)); + + return await t; + } + catch + { + return null; + } + } + + /// + /// Sends an image + /// + /// + /// + /// + /// + /// + public async Task SendPhoto(InputOnlineFile file, string caption = null, ButtonForm buttons = null, + int replyTo = 0, bool disableNotification = false, + ParseMode parseMode = ParseMode.Markdown) + { + if (ActiveForm == null) + { return null; } - /// - /// Sends a simple text message - /// - /// - /// - /// - /// - /// - public async Task Send(long deviceId, string text, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool markdownV2AutoEscape = true) + InlineKeyboardMarkup markup = buttons; + + try { - if (ActiveForm == null) - return null; + var t = Api(a => a.SendPhotoAsync(DeviceId, file, caption, parseMode, replyToMessageId: replyTo, + replyMarkup: markup, disableNotification: disableNotification)); - InlineKeyboardMarkup markup = buttons; + var o = GetOrigin(new StackTrace()); + await OnMessageSent(new MessageSentEventArgs(await t, o)); - if (text.Length > Constants.Telegram.MaxMessageLength) - { - throw new MaxLengthException(text.Length); - } + return await t; + } + catch + { + return null; + } + } - if (parseMode == ParseMode.MarkdownV2 && markdownV2AutoEscape) - { - text = text.MarkdownV2Escape(); - } - - try - { - var t = Api(a => a.SendTextMessageAsync(deviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); - - var o = GetOrigin(new StackTrace()); - - await OnMessageSent(new MessageSentEventArgs(await t, o)); - - return await t; - } - catch - { - return null; - } + /// + /// Sends an video + /// + /// + /// + /// + /// + /// + public async Task SendVideo(InputOnlineFile file, string caption = null, ButtonForm buttons = null, + int replyTo = 0, bool disableNotification = false, + ParseMode parseMode = ParseMode.Markdown) + { + if (ActiveForm == null) + { + return null; } - /// - /// Sends a simple text message - /// - /// - /// - /// - /// - /// - public async Task Send(string text, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool markdownV2AutoEscape = true) + InlineKeyboardMarkup markup = buttons; + + try { - return await Send(DeviceId, text, buttons, replyTo, disableNotification, parseMode, markdownV2AutoEscape); + var t = Api(a => a.SendVideoAsync(DeviceId, file, caption: caption, parseMode: parseMode, + replyToMessageId: replyTo, replyMarkup: markup, + disableNotification: disableNotification)); + + var o = GetOrigin(new StackTrace()); + await OnMessageSent(new MessageSentEventArgs(await t, o)); + + return await t; + } + catch + { + return null; + } + } + + /// + /// Sends an video + /// + /// + /// + /// + /// + /// + public async Task SendVideo(string url, ButtonForm buttons = null, int replyTo = 0, + bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) + { + if (ActiveForm == null) + { + return null; } - /// - /// Sends a simple text message - /// - /// - /// - /// - /// - /// - public async Task Send(string text, InlineKeyboardMarkup markup, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool markdownV2AutoEscape = true) + InlineKeyboardMarkup markup = buttons; + + try { - if (ActiveForm == null) - return null; + var t = Api(a => a.SendVideoAsync(DeviceId, new InputOnlineFile(url), parseMode: parseMode, + replyToMessageId: replyTo, replyMarkup: markup, + disableNotification: disableNotification)); - if (text.Length > Constants.Telegram.MaxMessageLength) - { - throw new MaxLengthException(text.Length); - } + var o = GetOrigin(new StackTrace()); + await OnMessageSent(new MessageSentEventArgs(await t, o)); - if (parseMode == ParseMode.MarkdownV2 && markdownV2AutoEscape) - { - text = text.MarkdownV2Escape(); - } + return await t; + } + catch + { + return null; + } + } - try - { - var t = Api(a => a.SendTextMessageAsync(DeviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); - - var o = GetOrigin(new StackTrace()); - await OnMessageSent(new MessageSentEventArgs(await t, o)); - - return await t; - } - catch - { - return null; - } + /// + /// Sends an video + /// + /// + /// + /// + /// + /// + /// + public async Task SendVideo(string filename, byte[] video, ButtonForm buttons = null, int replyTo = 0, + bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) + { + if (ActiveForm == null) + { + return null; } - /// - /// Sends a simple text message - /// - /// - /// - /// - /// - /// - public async Task Send(string text, ReplyMarkupBase markup, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool markdownV2AutoEscape = true) + InlineKeyboardMarkup markup = buttons; + + try { - if (ActiveForm == null) - return null; - - if (text.Length > Constants.Telegram.MaxMessageLength) - { - throw new MaxLengthException(text.Length); - } - - if (parseMode == ParseMode.MarkdownV2 && markdownV2AutoEscape) - { - text = text.MarkdownV2Escape(); - } - - try - { - var t = Api(a => a.SendTextMessageAsync(DeviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); - - var o = GetOrigin(new StackTrace()); - await OnMessageSent(new MessageSentEventArgs(await t, o)); - - return await t; - } - catch - { - return null; - } - } - - /// - /// Sends an image - /// - /// - /// - /// - /// - /// - public async Task SendPhoto(InputOnlineFile file, string caption = null, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) - { - if (ActiveForm == null) - return null; - - InlineKeyboardMarkup markup = buttons; - - try - { - var t = Api(a => a.SendPhotoAsync(DeviceId, file, caption: caption, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); - - var o = GetOrigin(new StackTrace()); - await OnMessageSent(new MessageSentEventArgs(await t, o)); - - return await t; - } - catch - { - return null; - } - } - - /// - /// Sends an video - /// - /// - /// - /// - /// - /// - public async Task SendVideo(InputOnlineFile file, string caption = null, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) - { - if (ActiveForm == null) - return null; - - InlineKeyboardMarkup markup = buttons; - - try - { - var t = Api(a => a.SendVideoAsync(DeviceId, file, caption: caption, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); - - var o = GetOrigin(new StackTrace()); - await OnMessageSent(new MessageSentEventArgs(await t, o)); - - return await t; - } - catch - { - return null; - } - } - - /// - /// Sends an video - /// - /// - /// - /// - /// - /// - public async Task SendVideo(string url, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) - { - if (ActiveForm == null) - return null; - - InlineKeyboardMarkup markup = buttons; - - try - { - var t = Api(a => a.SendVideoAsync(DeviceId, new InputOnlineFile(url), parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); - - var o = GetOrigin(new StackTrace()); - await OnMessageSent(new MessageSentEventArgs(await t, o)); - - return await t; - } - catch - { - return null; - } - } - - /// - /// Sends an video - /// - /// - /// - /// - /// - /// - /// - public async Task SendVideo(string filename, byte[] video, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) - { - if (ActiveForm == null) - return null; - - InlineKeyboardMarkup markup = buttons; - - try - { - var ms = new MemoryStream(video); - - var fts = new InputOnlineFile(ms, filename); - - var t = Api(a => a.SendVideoAsync(DeviceId, fts, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); - - var o = GetOrigin(new StackTrace()); - await OnMessageSent(new MessageSentEventArgs(await t, o)); - - return await t; - } - catch - { - return null; - } - } - - /// - /// Sends an local file as video - /// - /// - /// - /// - /// - /// - /// - public async Task SendLocalVideo(string filepath, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown) - { - if (ActiveForm == null) - return null; - - InlineKeyboardMarkup markup = buttons; - - try - { - var fs = new FileStream(filepath, FileMode.Open); - - var filename = Path.GetFileName(filepath); - - var fts = new InputOnlineFile(fs, filename); - - var t = Api(a => a.SendVideoAsync(DeviceId, fts, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification)); - - var o = GetOrigin(new StackTrace()); - await OnMessageSent(new MessageSentEventArgs(await t, o)); - - return await t; - } - catch - { - return null; - } - } - - /// - /// Sends an document - /// - /// - /// - /// - /// - /// - /// - /// - public async Task SendDocument(string filename, byte[] document, string caption = "", ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) - { - var ms = new MemoryStream(document); + var ms = new MemoryStream(video); var fts = new InputOnlineFile(ms, filename); - return await SendDocument(fts, caption, buttons, replyTo, disableNotification); + var t = Api(a => a.SendVideoAsync(DeviceId, fts, parseMode: parseMode, replyToMessageId: replyTo, + replyMarkup: markup, disableNotification: disableNotification)); + + var o = GetOrigin(new StackTrace()); + await OnMessageSent(new MessageSentEventArgs(await t, o)); + + return await t; } - - /// - /// Generates a Textfile from scratch with the specified encoding. (Default is UTF8) - /// - /// - /// - /// Default is UTF8 - /// - /// - /// - /// - /// - public async Task SendTextFile(string filename, string textcontent, Encoding encoding = null, string caption = "", ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) + catch { - encoding = encoding ?? Encoding.UTF8; - - var ms = new MemoryStream(); - var sw = new StreamWriter(ms, encoding); - - sw.Write(textcontent); - sw.Flush(); - - var content = ms.ToArray(); - - return await SendDocument(filename, content, caption, buttons, replyTo, disableNotification); - } - - /// - /// Sends an document - /// - /// - /// - /// - /// - /// - /// - public async Task SendDocument(InputOnlineFile document, string caption = "", ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false) - { - InlineKeyboardMarkup markup = null; - if (buttons != null) - { - markup = buttons; - } - - try - { - var t = Api(a => a.SendDocumentAsync(DeviceId, document, caption, replyMarkup: markup, disableNotification: disableNotification, replyToMessageId: replyTo)); - - var o = GetOrigin(new StackTrace()); - await OnMessageSent(new MessageSentEventArgs(await t, o)); - - return await t; - } - catch - { - return null; - } - } - - /// - /// Set a chat action (showed to the user) - /// - /// - /// - public async Task SetAction(ChatAction action) - { - await Api(a => a.SendChatActionAsync(DeviceId, action)); - } - - /// - /// Requests the contact from the user. - /// - /// - /// - /// - /// - public async Task RequestContact(string buttonText = "Send your contact", string requestMessage = "Give me your phone number!", bool oneTimeOnly = true) - { - var rck = new ReplyKeyboardMarkup(KeyboardButton.WithRequestContact(buttonText)) - { - OneTimeKeyboard = oneTimeOnly - }; - return await Api(a => a.SendTextMessageAsync(DeviceId, requestMessage, replyMarkup: rck)); - } - - /// - /// Requests the location from the user. - /// - /// - /// - /// - /// - public async Task RequestLocation(string buttonText = "Send your location", string requestMessage = "Give me your location!", bool oneTimeOnly = true) - { - var rcl = new ReplyKeyboardMarkup(KeyboardButton.WithRequestLocation(buttonText)) - { - OneTimeKeyboard = oneTimeOnly - }; - return await Api(a => a.SendTextMessageAsync(DeviceId, requestMessage, replyMarkup: rcl)); - } - - public async Task HideReplyKeyboard(string closedMsg = "Closed", bool autoDeleteResponse = true) - { - try - { - var m = await Send(closedMsg, new ReplyKeyboardRemove()); - - if (autoDeleteResponse && m != null) - { - await DeleteMessage(m); - } - - return m; - } - catch - { - - } return null; } - - /// - /// Deletes a message - /// - /// - /// - public virtual async Task DeleteMessage(int messageId = -1) - { - - await Raw(a => a.DeleteMessageAsync(DeviceId, messageId)); - - OnMessageDeleted(new MessageDeletedEventArgs(messageId)); - - return true; - } - - /// - /// Deletes the given message - /// - /// - /// - public virtual async Task DeleteMessage(Message message) - { - return await DeleteMessage(message.MessageId); - } - - - public virtual async Task ChangeChatPermissions(ChatPermissions permissions) - { - try - { - await Api(a => a.SetChatPermissionsAsync(DeviceId, permissions)); - } - catch - { - - } - } - - private Type GetOrigin(StackTrace stackTrace) - { - for (var i = 0; i < stackTrace.FrameCount; i++) - { - var methodBase = stackTrace.GetFrame(i).GetMethod(); - - //Debug.WriteLine(methodBase.Name); - - if (methodBase.DeclaringType.IsSubclassOf(typeof(FormBase)) | methodBase.DeclaringType.IsSubclassOf(typeof(ControlBase))) - { - return methodBase.DeclaringType; - } - } - - return null; - } - - #region "Users" - - public virtual async Task RestrictUser(long userId, ChatPermissions permissions, DateTime until = default(DateTime)) - { - try - { - await Api(a => a.RestrictChatMemberAsync(DeviceId, userId, permissions, until)); - } - catch - { - - } - } - - public virtual async Task GetChatUser(long userId) - { - try - { - return await Api(a => a.GetChatMemberAsync(DeviceId, userId)); - } - catch - { - - } - return null; - } - - [Obsolete("User BanUser instead.")] - public virtual async Task KickUser(long userId, DateTime until = default(DateTime)) - { - try - { - await Api(a => a.BanChatMemberAsync(DeviceId, userId, until)); - } - catch - { - - } - } - - public virtual async Task BanUser(long userId, DateTime until = default(DateTime)) - { - try - { - await Api(a => a.BanChatMemberAsync(DeviceId, userId, until)); - } - catch - { - - } - } - - public virtual async Task UnbanUser(long userId) - { - try - { - await Api(a => a.UnbanChatMemberAsync(DeviceId, userId)); - } - catch - { - - } - } - - #endregion - - /// - /// Gives access to the original TelegramClient without any Exception catchings. - /// - /// - /// - /// - public T Raw(Func call) - { - return call(Client.TelegramClient); - } - - /// - /// This will call a function on the TelegramClient and automatically Retry if an limit has been exceeded. - /// - /// - /// - /// - public async Task Api(Func> call) - { - var numberOfTries = 0; - while (numberOfTries < MaxNumberOfRetries) - { - try - { - return await call(Client.TelegramClient); - } - catch (ApiRequestException ex) - { - if (ex.ErrorCode != 429) - throw; - - if (ex.Parameters != null && ex.Parameters.RetryAfter != null) - await Task.Delay(ex.Parameters.RetryAfter.Value * 1000); - - numberOfTries++; - } - } - return default(T); - } - - /// - /// This will call a function on the TelegramClient and automatically Retry if an limit has been exceeded. - /// - /// - /// - public async Task Api(Func call) - { - var numberOfTries = 0; - while (numberOfTries < MaxNumberOfRetries) - { - try - { - await call(Client.TelegramClient); - return; - } - catch (ApiRequestException ex) - { - if (ex.ErrorCode != 429) - throw; - - if (ex.Parameters != null && ex.Parameters.RetryAfter != null) - await Task.Delay(ex.Parameters.RetryAfter.Value * 1000); - - numberOfTries++; - } - } - } - - - #region "Events" - - /// - /// Eventhandler for sent messages - /// - public event Async.AsyncEventHandler MessageSent - { - add => _events.AddHandler(EvMessageSent, value); - remove => _events.RemoveHandler(EvMessageSent, value); - } - - - public async Task OnMessageSent(MessageSentEventArgs e) - { - if (e.Message == null) - return; - - var handler = _events[EvMessageSent]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) - { - await h.InvokeAllAsync(this, e); - } - - //(this.__Events[__evMessageSent] as EventHandler)?.Invoke(this, e); - } - - /// - /// Eventhandler for received messages - /// - public event EventHandler MessageReceived - { - add => _events.AddHandler(EvMessageReceived, value); - remove => _events.RemoveHandler(EvMessageReceived, value); - } - - - public void OnMessageReceived(MessageReceivedEventArgs e) - { - (_events[EvMessageReceived] as EventHandler)?.Invoke(this, e); - } - - /// - /// Eventhandler for deleting messages - /// - public event EventHandler MessageDeleted - { - add => _events.AddHandler(EvMessageDeleted, value); - remove => _events.RemoveHandler(EvMessageDeleted, value); - } - - - public void OnMessageDeleted(MessageDeletedEventArgs e) - { - (_events[EvMessageDeleted] as EventHandler)?.Invoke(this, e); - } - - #endregion - - #region "Static" - - /// - /// Indicates the maximum number of times a request that received error - /// 429 will be sent again after a timeout until it receives code 200 or an error code not equal to 429. - /// - public static uint MaxNumberOfRetries { get; set; } - - #endregion "Static" } -} + + /// + /// Sends an local file as video + /// + /// + /// + /// + /// + /// + /// + public async Task SendLocalVideo(string filepath, ButtonForm buttons = null, int replyTo = 0, + bool disableNotification = false, + ParseMode parseMode = ParseMode.Markdown) + { + if (ActiveForm == null) + { + return null; + } + + InlineKeyboardMarkup markup = buttons; + + try + { + var fs = new FileStream(filepath, FileMode.Open); + + var filename = Path.GetFileName(filepath); + + var fts = new InputOnlineFile(fs, filename); + + var t = Api(a => a.SendVideoAsync(DeviceId, fts, parseMode: parseMode, replyToMessageId: replyTo, + replyMarkup: markup, disableNotification: disableNotification)); + + var o = GetOrigin(new StackTrace()); + await OnMessageSent(new MessageSentEventArgs(await t, o)); + + return await t; + } + catch + { + return null; + } + } + + /// + /// Sends an document + /// + /// + /// + /// + /// + /// + /// + /// + public async Task SendDocument(string filename, byte[] document, string caption = "", + ButtonForm buttons = null, int replyTo = 0, + bool disableNotification = false) + { + var ms = new MemoryStream(document); + + var fts = new InputOnlineFile(ms, filename); + + return await SendDocument(fts, caption, buttons, replyTo, disableNotification); + } + + /// + /// Generates a Textfile from scratch with the specified encoding. (Default is UTF8) + /// + /// + /// + /// Default is UTF8 + /// + /// + /// + /// + /// + public async Task SendTextFile(string filename, string textcontent, Encoding encoding = null, + string caption = "", ButtonForm buttons = null, int replyTo = 0, + bool disableNotification = false) + { + encoding = encoding ?? Encoding.UTF8; + + var ms = new MemoryStream(); + var sw = new StreamWriter(ms, encoding); + + sw.Write(textcontent); + sw.Flush(); + + var content = ms.ToArray(); + + return await SendDocument(filename, content, caption, buttons, replyTo, disableNotification); + } + + /// + /// Sends an document + /// + /// + /// + /// + /// + /// + /// + public async Task SendDocument(InputOnlineFile document, string caption = "", + ButtonForm buttons = null, int replyTo = 0, + bool disableNotification = false) + { + InlineKeyboardMarkup markup = null; + if (buttons != null) + { + markup = buttons; + } + + try + { + var t = Api(a => a.SendDocumentAsync(DeviceId, document, caption, replyMarkup: markup, + disableNotification: disableNotification, replyToMessageId: replyTo)); + + var o = GetOrigin(new StackTrace()); + await OnMessageSent(new MessageSentEventArgs(await t, o)); + + return await t; + } + catch + { + return null; + } + } + + /// + /// Set a chat action (showed to the user) + /// + /// + /// + public async Task SetAction(ChatAction action) + { + await Api(a => a.SendChatActionAsync(DeviceId, action)); + } + + /// + /// Requests the contact from the user. + /// + /// + /// + /// + /// + public async Task RequestContact(string buttonText = "Send your contact", + string requestMessage = "Give me your phone number!", + bool oneTimeOnly = true) + { + var rck = new ReplyKeyboardMarkup(KeyboardButton.WithRequestContact(buttonText)) + { + OneTimeKeyboard = oneTimeOnly + }; + return await Api(a => a.SendTextMessageAsync(DeviceId, requestMessage, replyMarkup: rck)); + } + + /// + /// Requests the location from the user. + /// + /// + /// + /// + /// + public async Task RequestLocation(string buttonText = "Send your location", + string requestMessage = "Give me your location!", + bool oneTimeOnly = true) + { + var rcl = new ReplyKeyboardMarkup(KeyboardButton.WithRequestLocation(buttonText)) + { + OneTimeKeyboard = oneTimeOnly + }; + return await Api(a => a.SendTextMessageAsync(DeviceId, requestMessage, replyMarkup: rcl)); + } + + public async Task HideReplyKeyboard(string closedMsg = "Closed", bool autoDeleteResponse = true) + { + try + { + var m = await Send(closedMsg, new ReplyKeyboardRemove()); + + if (autoDeleteResponse && m != null) + { + await DeleteMessage(m); + } + + return m; + } + catch + { + } + + return null; + } + + /// + /// Deletes a message + /// + /// + /// + public virtual async Task DeleteMessage(int messageId = -1) + { + await Raw(a => a.DeleteMessageAsync(DeviceId, messageId)); + + OnMessageDeleted(new MessageDeletedEventArgs(messageId)); + + return true; + } + + /// + /// Deletes the given message + /// + /// + /// + public virtual async Task DeleteMessage(Message message) + { + return await DeleteMessage(message.MessageId); + } + + + public virtual async Task ChangeChatPermissions(ChatPermissions permissions) + { + try + { + await Api(a => a.SetChatPermissionsAsync(DeviceId, permissions)); + } + catch + { + } + } + + private Type GetOrigin(StackTrace stackTrace) + { + for (var i = 0; i < stackTrace.FrameCount; i++) + { + var methodBase = stackTrace.GetFrame(i).GetMethod(); + + //Debug.WriteLine(methodBase.Name); + + if (methodBase.DeclaringType.IsSubclassOf(typeof(FormBase)) | + methodBase.DeclaringType.IsSubclassOf(typeof(ControlBase))) + { + return methodBase.DeclaringType; + } + } + + return null; + } + + /// + /// Gives access to the original TelegramClient without any Exception catchings. + /// + /// + /// + /// + public T Raw(Func call) + { + return call(Client.TelegramClient); + } + + /// + /// This will call a function on the TelegramClient and automatically Retry if an limit has been exceeded. + /// + /// + /// + /// + public async Task Api(Func> call) + { + var numberOfTries = 0; + while (numberOfTries < MaxNumberOfRetries) + { + try + { + return await call(Client.TelegramClient); + } + catch (ApiRequestException ex) + { + if (ex.ErrorCode != 429) + { + throw; + } + + if (ex.Parameters != null && ex.Parameters.RetryAfter != null) + { + await Task.Delay(ex.Parameters.RetryAfter.Value * 1000); + } + + numberOfTries++; + } + } + + return default; + } + + /// + /// This will call a function on the TelegramClient and automatically Retry if an limit has been exceeded. + /// + /// + /// + public async Task Api(Func call) + { + var numberOfTries = 0; + while (numberOfTries < MaxNumberOfRetries) + { + try + { + await call(Client.TelegramClient); + return; + } + catch (ApiRequestException ex) + { + if (ex.ErrorCode != 429) + { + throw; + } + + if (ex.Parameters != null && ex.Parameters.RetryAfter != null) + { + await Task.Delay(ex.Parameters.RetryAfter.Value * 1000); + } + + numberOfTries++; + } + } + } + + #region "Users" + + public virtual async Task RestrictUser(long userId, ChatPermissions permissions, DateTime until = default) + { + try + { + await Api(a => a.RestrictChatMemberAsync(DeviceId, userId, permissions, until)); + } + catch + { + } + } + + public virtual async Task GetChatUser(long userId) + { + try + { + return await Api(a => a.GetChatMemberAsync(DeviceId, userId)); + } + catch + { + } + + return null; + } + + [Obsolete("User BanUser instead.")] + public virtual async Task KickUser(long userId, DateTime until = default) + { + try + { + await Api(a => a.BanChatMemberAsync(DeviceId, userId, until)); + } + catch + { + } + } + + public virtual async Task BanUser(long userId, DateTime until = default) + { + try + { + await Api(a => a.BanChatMemberAsync(DeviceId, userId, until)); + } + catch + { + } + } + + public virtual async Task UnbanUser(long userId) + { + try + { + await Api(a => a.UnbanChatMemberAsync(DeviceId, userId)); + } + catch + { + } + } + + #endregion + + + #region "Events" + + /// + /// Eventhandler for sent messages + /// + public event Async.AsyncEventHandler MessageSent + { + add => _events.AddHandler(EvMessageSent, value); + remove => _events.RemoveHandler(EvMessageSent, value); + } + + + public async Task OnMessageSent(MessageSentEventArgs e) + { + if (e.Message == null) + { + return; + } + + var handler = _events[EvMessageSent]?.GetInvocationList() + .Cast>(); + if (handler == null) + { + return; + } + + foreach (var h in handler) + { + await h.InvokeAllAsync(this, e); + } + + //(this.__Events[__evMessageSent] as EventHandler)?.Invoke(this, e); + } + + /// + /// Eventhandler for received messages + /// + public event EventHandler MessageReceived + { + add => _events.AddHandler(EvMessageReceived, value); + remove => _events.RemoveHandler(EvMessageReceived, value); + } + + + public void OnMessageReceived(MessageReceivedEventArgs e) + { + (_events[EvMessageReceived] as EventHandler)?.Invoke(this, e); + } + + /// + /// Eventhandler for deleting messages + /// + public event EventHandler MessageDeleted + { + add => _events.AddHandler(EvMessageDeleted, value); + remove => _events.RemoveHandler(EvMessageDeleted, value); + } + + + public void OnMessageDeleted(MessageDeletedEventArgs e) + { + (_events[EvMessageDeleted] as EventHandler)?.Invoke(this, e); + } + + #endregion +} \ No newline at end of file diff --git a/TelegramBotBase/States/JSONStateMachine.cs b/TelegramBotBase/States/JSONStateMachine.cs index 944caf0..ada7fe4 100644 --- a/TelegramBotBase/States/JSONStateMachine.cs +++ b/TelegramBotBase/States/JSONStateMachine.cs @@ -6,87 +6,87 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; using TelegramBotBase.Interfaces; -namespace TelegramBotBase.States +namespace TelegramBotBase.States; + +/// +/// Is used for all complex data types. Use if other default machines are not working. +/// +public class JsonStateMachine : IStateMachine { /// - /// Is used for all complex data types. Use if other default machines are not working. + /// Will initialize the state machine. /// - public class JsonStateMachine : IStateMachine + /// Path of the file and name where to save the session details. + /// + /// Type of Form which will be saved instead of Form which has + /// attribute declared. Needs to be subclass of + /// . + /// + /// Declares of the file could be overwritten. + public JsonStateMachine(string file, Type fallbackStateForm = null, bool overwrite = true) { - public string FilePath { get; set; } + FallbackStateForm = fallbackStateForm; - public bool Overwrite { get; set; } - - public Type FallbackStateForm { get; private set; } - - /// - /// Will initialize the state machine. - /// - /// Path of the file and name where to save the session details. - /// Type of Form which will be saved instead of Form which has attribute declared. Needs to be subclass of . - /// Declares of the file could be overwritten. - public JsonStateMachine(string file, Type fallbackStateForm = null, bool overwrite = true) + if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase))) { - FallbackStateForm = fallbackStateForm; - - if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase))) - { - throw new ArgumentException("FallbackStateForm is not a subclass of FormBase"); - } - - FilePath = file ?? throw new ArgumentNullException(nameof(file)); - Overwrite = overwrite; + throw new ArgumentException("FallbackStateForm is not a subclass of FormBase"); } - public StateContainer LoadFormStates() + FilePath = file ?? throw new ArgumentNullException(nameof(file)); + Overwrite = overwrite; + } + + public string FilePath { get; set; } + + public bool Overwrite { get; set; } + + public Type FallbackStateForm { get; } + + public StateContainer LoadFormStates() + { + try { - try + var content = File.ReadAllText(FilePath); + + var sc = JsonConvert.DeserializeObject(content, new JsonSerializerSettings { - var content = File.ReadAllText(FilePath); + TypeNameHandling = TypeNameHandling.All, + TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple + }); - var sc = JsonConvert.DeserializeObject(content, new JsonSerializerSettings - { - TypeNameHandling = TypeNameHandling.All, - TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple - }); - - return sc; - } - catch - { - - } - - return new StateContainer(); + return sc; + } + catch + { } - public void SaveFormStates(SaveStatesEventArgs e) + return new StateContainer(); + } + + public void SaveFormStates(SaveStatesEventArgs e) + { + if (File.Exists(FilePath)) { - if (File.Exists(FilePath)) + if (!Overwrite) { - if (!Overwrite) - { - throw new Exception("File exists already."); - } - - File.Delete(FilePath); + throw new Exception("File exists already."); } - try + File.Delete(FilePath); + } + + try + { + var content = JsonConvert.SerializeObject(e.States, Formatting.Indented, new JsonSerializerSettings { - var content = JsonConvert.SerializeObject(e.States, Formatting.Indented, new JsonSerializerSettings - { - TypeNameHandling = TypeNameHandling.All, - TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple - }); - - File.WriteAllText(FilePath, content); - } - catch - { - - } + TypeNameHandling = TypeNameHandling.All, + TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple + }); + File.WriteAllText(FilePath, content); + } + catch + { } } -} +} \ No newline at end of file diff --git a/TelegramBotBase/States/SimpleJSONStateMachine.cs b/TelegramBotBase/States/SimpleJSONStateMachine.cs index 5c84456..7e8fa58 100644 --- a/TelegramBotBase/States/SimpleJSONStateMachine.cs +++ b/TelegramBotBase/States/SimpleJSONStateMachine.cs @@ -6,79 +6,80 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; using TelegramBotBase.Interfaces; -namespace TelegramBotBase.States +namespace TelegramBotBase.States; + +/// +/// Is used for simple object structures like classes, lists or basic datatypes without generics and other compiler +/// based data types. +/// +public class SimpleJsonStateMachine : IStateMachine { /// - /// Is used for simple object structures like classes, lists or basic datatypes without generics and other compiler based data types. + /// Will initialize the state machine. /// - public class SimpleJsonStateMachine : IStateMachine + /// Path of the file and name where to save the session details. + /// + /// Type of Form which will be saved instead of Form which has + /// attribute declared. Needs to be subclass of + /// . + /// + /// Declares of the file could be overwritten. + public SimpleJsonStateMachine(string file, Type fallbackStateForm = null, bool overwrite = true) { - public string FilePath { get; set; } + FallbackStateForm = fallbackStateForm; - public bool Overwrite { get; set; } - - public Type FallbackStateForm { get; private set; } - - /// - /// Will initialize the state machine. - /// - /// Path of the file and name where to save the session details. - /// Type of Form which will be saved instead of Form which has attribute declared. Needs to be subclass of . - /// Declares of the file could be overwritten. - public SimpleJsonStateMachine(string file, Type fallbackStateForm = null, bool overwrite = true) + if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase))) { - FallbackStateForm = fallbackStateForm; - - if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase))) - { - throw new ArgumentException("FallbackStateForm is not a subclass of FormBase"); - } - - FilePath = file ?? throw new ArgumentNullException(nameof(file)); - Overwrite = overwrite; + throw new ArgumentException("FallbackStateForm is not a subclass of FormBase"); } - public StateContainer LoadFormStates() + FilePath = file ?? throw new ArgumentNullException(nameof(file)); + Overwrite = overwrite; + } + + public string FilePath { get; set; } + + public bool Overwrite { get; set; } + + public Type FallbackStateForm { get; } + + public StateContainer LoadFormStates() + { + try { - try - { - var content = File.ReadAllText(FilePath); + var content = File.ReadAllText(FilePath); - var sc = JsonConvert.DeserializeObject(content); + var sc = JsonConvert.DeserializeObject(content); - return sc; - } - catch - { - - } - - return new StateContainer(); + return sc; + } + catch + { } - public void SaveFormStates(SaveStatesEventArgs e) + return new StateContainer(); + } + + public void SaveFormStates(SaveStatesEventArgs e) + { + if (File.Exists(FilePath)) { - if (File.Exists(FilePath)) + if (!Overwrite) { - if (!Overwrite) - { - throw new Exception("File exists already."); - } - - File.Delete(FilePath); + throw new Exception("File exists already."); } - try - { - var content = JsonConvert.SerializeObject(e.States, Formatting.Indented); + File.Delete(FilePath); + } - File.WriteAllText(FilePath, content); - } - catch - { - - } + try + { + var content = JsonConvert.SerializeObject(e.States, Formatting.Indented); + File.WriteAllText(FilePath, content); + } + catch + { } } -} +} \ No newline at end of file diff --git a/TelegramBotBase/States/XMLStateMachine.cs b/TelegramBotBase/States/XMLStateMachine.cs index b472d27..1a569eb 100644 --- a/TelegramBotBase/States/XMLStateMachine.cs +++ b/TelegramBotBase/States/XMLStateMachine.cs @@ -7,90 +7,89 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; using TelegramBotBase.Interfaces; -namespace TelegramBotBase.States +namespace TelegramBotBase.States; + +public class XmlStateMachine : IStateMachine { - public class XmlStateMachine : IStateMachine + /// + /// Will initialize the state machine. + /// + /// Path of the file and name where to save the session details. + /// + /// Type of Form which will be saved instead of Form which has + /// attribute declared. Needs to be subclass of + /// . + /// + /// Declares of the file could be overwritten. + public XmlStateMachine(string file, Type fallbackStateForm = null, bool overwrite = true) { - public string FilePath { get; set; } + FallbackStateForm = fallbackStateForm; - public bool Overwrite { get; set; } - - public Type FallbackStateForm { get; private set; } - - /// - /// Will initialize the state machine. - /// - /// Path of the file and name where to save the session details. - /// Type of Form which will be saved instead of Form which has attribute declared. Needs to be subclass of . - /// Declares of the file could be overwritten. - public XmlStateMachine(string file, Type fallbackStateForm = null, bool overwrite = true) + if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase))) { - FallbackStateForm = fallbackStateForm; - - if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase))) - { - throw new ArgumentException("FallbackStateForm is not a subclass of FormBase"); - } - - FilePath = file ?? throw new ArgumentNullException(nameof(file)); - Overwrite = overwrite; + throw new ArgumentException("FallbackStateForm is not a subclass of FormBase"); } - public StateContainer LoadFormStates() - { - try - { - var serializer = new DataContractSerializer(typeof(StateContainer)); - - using (var reader = new StreamReader(FilePath)) - { - using (var xml = new XmlTextReader(reader)) - { - var sc = serializer.ReadObject(xml) as StateContainer; - return sc; - } - } - } - catch - { - - } - - return new StateContainer(); - } - - public void SaveFormStates(SaveStatesEventArgs e) - { - if (File.Exists(FilePath)) - { - if (!Overwrite) - { - throw new Exception("File exists already."); - } - - File.Delete(FilePath); - } - - try - { - var serializer = new DataContractSerializer(typeof(StateContainer)); - - using (var sw = new StreamWriter(FilePath)) - { - using (var writer = new XmlTextWriter(sw)) - { - writer.Formatting = Formatting.Indented; // indent the Xml so it’s human readable - serializer.WriteObject(writer, e.States); - writer.Flush(); - } - } - } - catch - { - - } - - } + FilePath = file ?? throw new ArgumentNullException(nameof(file)); + Overwrite = overwrite; } -} + public string FilePath { get; set; } + + public bool Overwrite { get; set; } + + public Type FallbackStateForm { get; } + + public StateContainer LoadFormStates() + { + try + { + var serializer = new DataContractSerializer(typeof(StateContainer)); + + using (var reader = new StreamReader(FilePath)) + { + using (var xml = new XmlTextReader(reader)) + { + var sc = serializer.ReadObject(xml) as StateContainer; + return sc; + } + } + } + catch + { + } + + return new StateContainer(); + } + + public void SaveFormStates(SaveStatesEventArgs e) + { + if (File.Exists(FilePath)) + { + if (!Overwrite) + { + throw new Exception("File exists already."); + } + + File.Delete(FilePath); + } + + try + { + var serializer = new DataContractSerializer(typeof(StateContainer)); + + using (var sw = new StreamWriter(FilePath)) + { + using (var writer = new XmlTextWriter(sw)) + { + writer.Formatting = Formatting.Indented; // indent the Xml so it’s human readable + serializer.WriteObject(writer, e.States); + writer.Flush(); + } + } + } + catch + { + } + } +} \ No newline at end of file diff --git a/TelegramBotBase/TelegramBotBase.csproj b/TelegramBotBase/TelegramBotBase.csproj index 4203025..3879e73 100644 --- a/TelegramBotBase/TelegramBotBase.csproj +++ b/TelegramBotBase/TelegramBotBase.csproj @@ -1,64 +1,64 @@  - - netstandard2.0;net5;netcoreapp3.1;net6 - 9 - false - False - true - https://github.com/MajMcCloud/TelegramBotFramework - https://github.com/MajMcCloud/TelegramBotFramework - - Dependency update. Removing .Net Framework target and replacing with .Net Standard 2.0 - Debug;Release; - MIT - false - false - true - true - true - snupkg - $(VersionPrefix) - portable - + + netstandard2.0;net5;netcoreapp3.1;net6 + 10 + false + False + true + https://github.com/MajMcCloud/TelegramBotFramework + https://github.com/MajMcCloud/TelegramBotFramework + - Dependency update. Removing .Net Framework target and replacing with .Net Standard 2.0 + Debug;Release; + MIT + false + false + true + true + true + snupkg + $(VersionPrefix) + portable + - - - - + + + + - - true - full - false - bin\Debug\ - TRACE;DEBUG - prompt - 4 - + + true + full + false + bin\Debug\ + TRACE;DEBUG + prompt + 4 + - - portable - true - bin\Release\ - TRACE - prompt - 4 - bin\Release\TelegramBotBase.xml - + + portable + true + bin\Release\ + TRACE + prompt + 4 + bin\Release\TelegramBotBase.xml + - - - - - + + + + + - - - - + + + + diff --git a/TelegramBotBase/TelegramBotBase.nuspec b/TelegramBotBase/TelegramBotBase.nuspec index 22df758..12c8077 100644 --- a/TelegramBotBase/TelegramBotBase.nuspec +++ b/TelegramBotBase/TelegramBotBase.nuspec @@ -1,27 +1,29 @@  - - TelegramBotBase - 2.1.0 - TelegramBotBase - TelegramBotBase - false - MIT - https://github.com/MajMcCloud/TelegramBotFramework - Package Description - - moving from .Net Framework 4.7.2 to .Net Standard 2.1 for the Library and .Net Core 3.0 for the test project! - - - - - - - - - - - - - - - \ No newline at end of file + + TelegramBotBase + 2.1.0 + TelegramBotBase + TelegramBotBase + false + MIT + https://github.com/MajMcCloud/TelegramBotFramework + Package Description + - moving from .Net Framework 4.7.2 to .Net Standard 2.1 for the Library and .Net Core 3.0 for the + test project! + + + + + + + + + + + + + + + + diff --git a/TelegramBotBase/Tools/Arrays.cs b/TelegramBotBase/Tools/Arrays.cs index b3814b1..9ad3993 100644 --- a/TelegramBotBase/Tools/Arrays.cs +++ b/TelegramBotBase/Tools/Arrays.cs @@ -1,15 +1,14 @@ using System; -namespace TelegramBotBase.Tools +namespace TelegramBotBase.Tools; + +public static class Arrays { - public static class Arrays + public static T[] Shift(T[] array, int positions) { - public static T[] Shift(T[] array, int positions) - { - var copy = new T[array.Length]; - Array.Copy(array, 0, copy, array.Length - positions, positions); - Array.Copy(array, positions, copy, 0, array.Length - positions); - return copy; - } + var copy = new T[array.Length]; + Array.Copy(array, 0, copy, array.Length - positions, positions); + Array.Copy(array, positions, copy, 0, array.Length - positions); + return copy; } -} +} \ No newline at end of file diff --git a/TelegramBotBase/Tools/Console.cs b/TelegramBotBase/Tools/Console.cs index 7baa187..31af172 100644 --- a/TelegramBotBase/Tools/Console.cs +++ b/TelegramBotBase/Tools/Console.cs @@ -2,64 +2,63 @@ using System.Collections.Generic; using System.Runtime.InteropServices; -namespace TelegramBotBase.Tools +namespace TelegramBotBase.Tools; + +public static class Console { - public static class Console + private static EventHandler __handler; + + private static readonly List __actions = new(); + + static Console() { - [DllImport("Kernel32")] - private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add); - - private delegate bool EventHandler(CtrlType sig); - - private static EventHandler __handler; - - private static List __actions = new List(); - - private enum CtrlType - { - CtrlCEvent = 0, - CtrlBreakEvent = 1, - CtrlCloseEvent = 2, - CtrlLogoffEvent = 5, - CtrlShutdownEvent = 6 - } - - static Console() - { - - } - - public static void SetHandler(Action action) - { - __actions.Add(action); - - if (__handler != null) - return; - - __handler += Handler; - SetConsoleCtrlHandler(__handler, true); - } - - private static bool Handler(CtrlType sig) - { - switch (sig) - { - case CtrlType.CtrlCEvent: - case CtrlType.CtrlLogoffEvent: - case CtrlType.CtrlShutdownEvent: - case CtrlType.CtrlCloseEvent: - - foreach (var a in __actions) - { - a(); - } - - return false; - - default: - return false; - } - } - } -} + + [DllImport("Kernel32")] + private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add); + + public static void SetHandler(Action action) + { + __actions.Add(action); + + if (__handler != null) + { + return; + } + + __handler += Handler; + SetConsoleCtrlHandler(__handler, true); + } + + private static bool Handler(CtrlType sig) + { + switch (sig) + { + case CtrlType.CtrlCEvent: + case CtrlType.CtrlLogoffEvent: + case CtrlType.CtrlShutdownEvent: + case CtrlType.CtrlCloseEvent: + + foreach (var a in __actions) + { + a(); + } + + return false; + + default: + return false; + } + } + + private delegate bool EventHandler(CtrlType sig); + + private enum CtrlType + { + CtrlCEvent = 0, + CtrlBreakEvent = 1, + CtrlCloseEvent = 2, + CtrlLogoffEvent = 5, + CtrlShutdownEvent = 6 + } +} \ No newline at end of file diff --git a/TelegramBotBase/Tools/Conversion.cs b/TelegramBotBase/Tools/Conversion.cs index 9993cd5..00ffc47 100644 --- a/TelegramBotBase/Tools/Conversion.cs +++ b/TelegramBotBase/Tools/Conversion.cs @@ -2,34 +2,31 @@ using System.Reflection; using TelegramBotBase.Form; -namespace TelegramBotBase.Tools +namespace TelegramBotBase.Tools; + +public static class Conversion { - public static class Conversion + public static void CustomConversionChecks(FormBase form, KeyValuePair p, PropertyInfo f) { - public static void CustomConversionChecks(FormBase form, KeyValuePair p, PropertyInfo f) + //Newtonsoft Int64/Int32 converter issue + if (f.PropertyType == typeof(int)) { - //Newtonsoft Int64/Int32 converter issue - if (f.PropertyType == typeof(int)) + if (int.TryParse(p.Value.ToString(), out var i)) { - if (int.TryParse(p.Value.ToString(), out var i)) - { - f.SetValue(form, i); - } - return; + f.SetValue(form, i); } - //Newtonsoft Double/Decimal converter issue - if (f.PropertyType == typeof(decimal) | f.PropertyType == typeof(decimal?)) - { - decimal d = 0; - if (decimal.TryParse(p.Value.ToString(), out d)) - { - f.SetValue(form, d); - } - } - - + return; } + //Newtonsoft Double/Decimal converter issue + if ((f.PropertyType == typeof(decimal)) | (f.PropertyType == typeof(decimal?))) + { + decimal d = 0; + if (decimal.TryParse(p.Value.ToString(), out d)) + { + f.SetValue(form, d); + } + } } -} +} \ No newline at end of file diff --git a/TelegramBotBase/Tools/Time.cs b/TelegramBotBase/Tools/Time.cs index f11733b..28d73c4 100644 --- a/TelegramBotBase/Tools/Time.cs +++ b/TelegramBotBase/Tools/Time.cs @@ -1,47 +1,48 @@ using System; -namespace TelegramBotBase.Tools +namespace TelegramBotBase.Tools; + +public static class Time { - public static class Time + public static bool TryParseDay(string src, DateTime currentDate, out int resultDay) { - public static bool TryParseDay(string src, DateTime currentDate, out int resultDay) - { - return int.TryParse(src, out resultDay) && resultDay >= 1 && resultDay <= DateTime.DaysInMonth(currentDate.Year, currentDate.Month); - } - - public static bool TryParseMonth(string src, out int resultMonth) - { - return int.TryParse(src, out resultMonth) && resultMonth >= 1 && resultMonth <= 12; - } - - public static bool TryParseYear(string src, out int resultYear) - { - return int.TryParse(src, out resultYear) && resultYear >= 0 && resultYear <= DateTime.MaxValue.Year; - } - - public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek) - { - var diff = dt.DayOfWeek - startOfWeek; - if (diff < 0) - { - diff += 7; - } - return dt.AddDays(-1 * diff).Date; - } - - public static DateTime EndOfWeek(this DateTime dt, DayOfWeek startOfWeek) - { - return StartOfWeek(dt, startOfWeek).AddDays(6); - } - - public static DateTime FirstDayOfMonth(this DateTime date) - { - return new DateTime(date.Year, date.Month, 1); - } - - public static DateTime LastDayOfMonth(this DateTime date) - { - return FirstDayOfMonth(date).AddMonths(1).AddDays(-1); - } + return int.TryParse(src, out resultDay) && resultDay >= 1 && + resultDay <= DateTime.DaysInMonth(currentDate.Year, currentDate.Month); } -} + + public static bool TryParseMonth(string src, out int resultMonth) + { + return int.TryParse(src, out resultMonth) && resultMonth >= 1 && resultMonth <= 12; + } + + public static bool TryParseYear(string src, out int resultYear) + { + return int.TryParse(src, out resultYear) && resultYear >= 0 && resultYear <= DateTime.MaxValue.Year; + } + + public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek) + { + var diff = dt.DayOfWeek - startOfWeek; + if (diff < 0) + { + diff += 7; + } + + return dt.AddDays(-1 * diff).Date; + } + + public static DateTime EndOfWeek(this DateTime dt, DayOfWeek startOfWeek) + { + return StartOfWeek(dt, startOfWeek).AddDays(6); + } + + public static DateTime FirstDayOfMonth(this DateTime date) + { + return new DateTime(date.Year, date.Month, 1); + } + + public static DateTime LastDayOfMonth(this DateTime date) + { + return FirstDayOfMonth(date).AddMonths(1).AddDays(-1); + } +} \ No newline at end of file From f41fdf90ed0246a669f867c9478b5ebfabf65d62 Mon Sep 17 00:00:00 2001 From: ZavaruKitsu Date: Sat, 8 Oct 2022 19:37:00 +0300 Subject: [PATCH 04/22] fix!: get rid of `async void` --- Examples/EFCoreBot/Program.cs | 4 ++-- TelegramBotBase/BotBase.cs | 15 ++++++-------- .../Form/Navigation/NavigationController.cs | 8 +++++--- TelegramBotBase/Interfaces/IStateForm.cs | 9 +++++---- TelegramBotBase/SessionBase.cs | 20 +++++++++---------- 5 files changed, 28 insertions(+), 28 deletions(-) diff --git a/Examples/EFCoreBot/Program.cs b/Examples/EFCoreBot/Program.cs index 3d983e1..37f5587 100644 --- a/Examples/EFCoreBot/Program.cs +++ b/Examples/EFCoreBot/Program.cs @@ -20,5 +20,5 @@ var bot = BotBaseBuilder.Create() .DefaultLanguage() .Build(); -bot.Start(); -await Task.Delay(-1); \ No newline at end of file +await bot.Start(); +await Task.Delay(-1); diff --git a/TelegramBotBase/BotBase.cs b/TelegramBotBase/BotBase.cs index bac92e3..3ac4f52 100644 --- a/TelegramBotBase/BotBase.cs +++ b/TelegramBotBase/BotBase.cs @@ -80,7 +80,7 @@ public class BotBase /// /// Start your Bot /// - public void Start() + public async Task Start() { if (Client == null) { @@ -89,16 +89,15 @@ public class BotBase Client.MessageLoop += Client_MessageLoop; - if (StateMachine != null) { - Sessions.LoadSessionStates(StateMachine); + await Sessions.LoadSessionStates(StateMachine); } //Enable auto session saving if (GetSetting(ESettings.SaveSessionsOnConsoleExit, false)) { - Console.SetHandler(() => { Sessions.SaveSessionStates(); }); + Console.SetHandler(() => { Sessions.SaveSessionStates().GetAwaiter().GetResult(); }); } DeviceSession.MaxNumberOfRetries = GetSetting(ESettings.MaxNumberOfRetries, 5); @@ -141,7 +140,7 @@ public class BotBase /// /// Stop your Bot /// - public void Stop() + public async Task Stop() { if (Client == null) { @@ -149,11 +148,9 @@ public class BotBase } Client.MessageLoop -= Client_MessageLoop; - - Client.StopReceiving(); - Sessions.SaveSessionStates(); + await Sessions.SaveSessionStates(); } /// @@ -407,4 +404,4 @@ public class BotBase } #endregion -} \ No newline at end of file +} diff --git a/TelegramBotBase/Form/Navigation/NavigationController.cs b/TelegramBotBase/Form/Navigation/NavigationController.cs index 01931e8..b29e203 100644 --- a/TelegramBotBase/Form/Navigation/NavigationController.cs +++ b/TelegramBotBase/Form/Navigation/NavigationController.cs @@ -69,7 +69,7 @@ public class NavigationController : FormBase, IStateForm } - public void LoadState(LoadStateEventArgs e) + public async Task LoadState(LoadStateEventArgs e) { if (e.Get("$controller.history.count") == null) { @@ -144,13 +144,13 @@ public class NavigationController : FormBase, IStateForm form.Client = Client; form.NavigationController = this; - form.OnInit(new InitEventArgs()); + await form.OnInit(new InitEventArgs()); History.Add(form); } } - public void SaveState(SaveStateEventArgs e) + public Task SaveState(SaveStateEventArgs e) { e.Set("$controller.history.count", History.Count.ToString()); @@ -175,6 +175,8 @@ public class NavigationController : FormBase, IStateForm i++; } + + return Task.CompletedTask; } private async Task NavigationController_Init(object sender, InitEventArgs e) diff --git a/TelegramBotBase/Interfaces/IStateForm.cs b/TelegramBotBase/Interfaces/IStateForm.cs index 7e42cc4..0a713cb 100644 --- a/TelegramBotBase/Interfaces/IStateForm.cs +++ b/TelegramBotBase/Interfaces/IStateForm.cs @@ -1,4 +1,5 @@ -using TelegramBotBase.Args; +using System.Threading.Tasks; +using TelegramBotBase.Args; namespace TelegramBotBase.Interfaces; @@ -7,7 +8,7 @@ namespace TelegramBotBase.Interfaces; /// public interface IStateForm { - void LoadState(LoadStateEventArgs e); + Task LoadState(LoadStateEventArgs e); - void SaveState(SaveStateEventArgs e); -} \ No newline at end of file + Task SaveState(SaveStateEventArgs e); +} diff --git a/TelegramBotBase/SessionBase.cs b/TelegramBotBase/SessionBase.cs index e7036cd..bd4f2bb 100644 --- a/TelegramBotBase/SessionBase.cs +++ b/TelegramBotBase/SessionBase.cs @@ -118,25 +118,25 @@ public class SessionBase /// /// Loads the previously saved states from the machine. /// - public async void LoadSessionStates() + public async Task LoadSessionStates() { if (BotBase.StateMachine == null) { return; } - LoadSessionStates(BotBase.StateMachine); + await LoadSessionStates(BotBase.StateMachine); } /// /// Loads the previously saved states from the machine. /// - public async void LoadSessionStates(IStateMachine statemachine) + public async Task LoadSessionStates(IStateMachine statemachine) { if (statemachine == null) { - throw new ArgumentNullException("StateMachine", + throw new ArgumentNullException(nameof(statemachine), "No StateMachine defined. Please set one to property BotBase.StateMachine"); } @@ -230,7 +230,7 @@ public class SessionBase { Values = s.Values }; - iform.LoadState(ls); + await iform.LoadState(ls); } try @@ -251,11 +251,11 @@ public class SessionBase /// /// Saves all open states into the machine. /// - public void SaveSessionStates(IStateMachine statemachine) + public async Task SaveSessionStates(IStateMachine statemachine) { if (statemachine == null) { - throw new ArgumentNullException("StateMachine", + throw new ArgumentNullException(nameof(statemachine), "No StateMachine defined. Please set one to property BotBase.StateMachine"); } @@ -299,7 +299,7 @@ public class SessionBase { //Loading Session states var ssea = new SaveStateEventArgs(); - iform.SaveState(ssea); + await iform.SaveState(ssea); se.Values = ssea.Values; } @@ -335,7 +335,7 @@ public class SessionBase /// /// Saves all open states into the machine. /// - public void SaveSessionStates() + public async Task SaveSessionStates() { if (BotBase.StateMachine == null) { @@ -343,6 +343,6 @@ public class SessionBase } - SaveSessionStates(BotBase.StateMachine); + await SaveSessionStates(BotBase.StateMachine); } } From f9d25dfb83d4d0bfd276d06c452174e0b93b1e0a Mon Sep 17 00:00:00 2001 From: ZavaruKitsu Date: Sat, 8 Oct 2022 20:00:21 +0300 Subject: [PATCH 05/22] fix!: prevent exceptions from being muted happens by not awaiting tasks --- Examples/EFCoreBot/StartForm.cs | 2 +- TelegramBotBase/Base/Async.cs | 4 +- TelegramBotBase/Base/MessageClient.cs | 14 +++-- TelegramBotBase/BotBase.cs | 54 +++++++++++-------- TelegramBotBase/Builder/BotBaseBuilder.cs | 26 ++++----- TelegramBotBase/Form/AutoCleanForm.cs | 4 +- .../MessageLoops/FormBaseMessageLoop.cs | 4 +- .../MessageLoops/FullMessageLoop.cs | 4 +- .../MessageLoops/MinimalMessageLoop.cs | 4 +- 9 files changed, 61 insertions(+), 55 deletions(-) diff --git a/Examples/EFCoreBot/StartForm.cs b/Examples/EFCoreBot/StartForm.cs index 7081c1a..1bfee77 100644 --- a/Examples/EFCoreBot/StartForm.cs +++ b/Examples/EFCoreBot/StartForm.cs @@ -33,4 +33,4 @@ public class StartForm : FormBase user.LastMessage = string.IsNullOrWhiteSpace(message.MessageText) ? "" : message.MessageText; await _dbContext.SaveChangesAsync(); } -} \ No newline at end of file +} diff --git a/TelegramBotBase/Base/Async.cs b/TelegramBotBase/Base/Async.cs index 9efe5be..260c7a1 100644 --- a/TelegramBotBase/Base/Async.cs +++ b/TelegramBotBase/Base/Async.cs @@ -7,7 +7,7 @@ namespace TelegramBotBase.Base; public static class Async { - public delegate Task AsyncEventHandler(object sender, TEventArgs e) where TEventArgs : EventArgs; + public delegate Task AsyncEventHandler(object sender, TEventArgs e) where TEventArgs : EventArgs; public static IEnumerable> GetHandlers( this AsyncEventHandler handler) @@ -24,4 +24,4 @@ public static class Async handler.GetHandlers() .Select(handleAsync => handleAsync(sender, e))); } -} \ No newline at end of file +} diff --git a/TelegramBotBase/Base/MessageClient.cs b/TelegramBotBase/Base/MessageClient.cs index a47ea16..99c45db 100644 --- a/TelegramBotBase/Base/MessageClient.cs +++ b/TelegramBotBase/Base/MessageClient.cs @@ -41,7 +41,6 @@ public class MessageClient ApiKey = apiKey; TelegramClient = new TelegramBotClient(apiKey, proxy); - Prepare(); } @@ -124,11 +123,9 @@ public class MessageClient } - public Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) + public async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) { - OnMessageLoop(new UpdateResult(update, null)); - - return Task.CompletedTask; + await OnMessageLoop(new UpdateResult(update, null)); } public Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, @@ -161,6 +158,7 @@ public class MessageClient /// This will set your bot commands to the given list. ///
/// + /// /// public async Task SetBotCommands(List botcommands, BotCommandScope scope = null, string languageCode = null) @@ -186,10 +184,10 @@ public class MessageClient remove => Events.RemoveHandler(EvOnMessageLoop, value); } - public void OnMessageLoop(UpdateResult update) + public async Task OnMessageLoop(UpdateResult update) { - (Events[EvOnMessageLoop] as Async.AsyncEventHandler)?.Invoke(this, update); + await (Events[EvOnMessageLoop] as Async.AsyncEventHandler)?.Invoke(this, update); } #endregion -} \ No newline at end of file +} diff --git a/TelegramBotBase/BotBase.cs b/TelegramBotBase/BotBase.cs index 3ac4f52..8e6fcad 100644 --- a/TelegramBotBase/BotBase.cs +++ b/TelegramBotBase/BotBase.cs @@ -108,32 +108,40 @@ public class BotBase private async Task Client_MessageLoop(object sender, UpdateResult e) { - var ds = Sessions.GetSession(e.DeviceId); - if (ds == null) + try { - ds = Sessions.StartSession(e.DeviceId).GetAwaiter().GetResult(); - e.Device = ds; - ds.LastMessage = e.RawData.Message; + var ds = Sessions.GetSession(e.DeviceId); + if (ds == null) + { + ds = await Sessions.StartSession(e.DeviceId); + e.Device = ds; + ds.LastMessage = e.RawData.Message; - OnSessionBegins(new SessionBeginEventArgs(e.DeviceId, ds)); + OnSessionBegins(new SessionBeginEventArgs(e.DeviceId, ds)); + } + + var mr = new MessageResult(e.RawData); + + var i = 0; + + //Should formulars get navigated (allow maximum of 10, to dont get loops) + do + { + i++; + + //Reset navigation + ds.FormSwitched = false; + + await MessageLoopFactory.MessageLoop(this, ds, e, mr); + + mr.IsFirstHandler = false; + } while (ds.FormSwitched && i < GetSetting(ESettings.NavigationMaximum, 10)); } - - var mr = new MessageResult(e.RawData); - - var i = 0; - - //Should formulars get navigated (allow maximum of 10, to dont get loops) - do + catch (Exception ex) { - i++; - - //Reset navigation - ds.FormSwitched = false; - - await MessageLoopFactory.MessageLoop(this, ds, e, mr); - - mr.IsFirstHandler = false; - } while (ds.FormSwitched && i < GetSetting(ESettings.NavigationMaximum, 10)); + var ds = Sessions.GetSession(e.DeviceId); + OnException(new SystemExceptionEventArgs(e.Message.Text, e.DeviceId, ds, ex)); + } } @@ -390,7 +398,7 @@ public class BotBase } /// - /// Will be called if no form handeled this call + /// Will be called if no form handled this call /// public event EventHandler UnhandledCall { diff --git a/TelegramBotBase/Builder/BotBaseBuilder.cs b/TelegramBotBase/Builder/BotBaseBuilder.cs index ffd2d58..c20368e 100644 --- a/TelegramBotBase/Builder/BotBaseBuilder.cs +++ b/TelegramBotBase/Builder/BotBaseBuilder.cs @@ -41,24 +41,24 @@ public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, public BotBase Build() { - var bb = new BotBase + var bot = new BotBase { ApiKey = _apiKey, StartFormFactory = _factory, Client = _client }; - bb.Sessions.Client = bb.Client; + bot.Sessions.Client = bot.Client; - bb.BotCommandScopes = BotCommandScopes; + bot.BotCommandScopes = BotCommandScopes; - bb.StateMachine = _statemachine; + bot.StateMachine = _statemachine; - bb.MessageLoopFactory = _messageLoopFactory; + bot.MessageLoopFactory = _messageLoopFactory; - bb.MessageLoopFactory.UnhandledCall += bb.MessageLoopFactory_UnhandledCall; + bot.MessageLoopFactory.UnhandledCall += bot.MessageLoopFactory_UnhandledCall; - return bb; + return bot; } public static IAPIKeySelectionStage Create() @@ -75,10 +75,10 @@ public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, } - public IBuildingStage QuickStart(string apiKey, Type StartForm) + public IBuildingStage QuickStart(string apiKey, Type startForm) { _apiKey = apiKey; - _factory = new DefaultStartFormFactory(StartForm); + _factory = new DefaultStartFormFactory(startForm); DefaultMessageLoop(); @@ -113,10 +113,10 @@ public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, return this; } - public IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory) + public IBuildingStage QuickStart(string apiKey, IStartFormFactory startFormFactory) { _apiKey = apiKey; - _factory = StartFormFactory; + _factory = startFormFactory; DefaultMessageLoop(); @@ -218,7 +218,7 @@ public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, TelegramClient = { Timeout = new TimeSpan(0, 1, 0) - } + }, }; return this; } @@ -369,4 +369,4 @@ public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, } #endregion -} \ No newline at end of file +} diff --git a/TelegramBotBase/Form/AutoCleanForm.cs b/TelegramBotBase/Form/AutoCleanForm.cs index d920488..e994ef3 100644 --- a/TelegramBotBase/Form/AutoCleanForm.cs +++ b/TelegramBotBase/Form/AutoCleanForm.cs @@ -219,7 +219,7 @@ public class AutoCleanForm : FormBase var retryAfterSeconds = ex.InnerExceptions .Where(e => e is ApiRequestException apiEx && apiEx.ErrorCode == 429) .Max(e => ((ApiRequestException)e).Parameters.RetryAfter) ?? 0; - retryAfterTask = Task.Delay(retryAfterSeconds * 1000); + retryAfterTask = Task.Delay(retryAfterSeconds * 1000, cts.Token); } //deletedMessages.AsParallel().ForAll(i => Device.OnMessageDeleted(new MessageDeletedEventArgs(i))); @@ -236,4 +236,4 @@ public class AutoCleanForm : FormBase OldMessages.Clear(); } -} \ No newline at end of file +} diff --git a/TelegramBotBase/MessageLoops/FormBaseMessageLoop.cs b/TelegramBotBase/MessageLoops/FormBaseMessageLoop.cs index 7a06466..f1a2d39 100644 --- a/TelegramBotBase/MessageLoops/FormBaseMessageLoop.cs +++ b/TelegramBotBase/MessageLoops/FormBaseMessageLoop.cs @@ -107,7 +107,7 @@ public class FormBaseMessageLoop : IMessageLoopFactory } /// - /// Will be called if no form handeled this call + /// Will be called if no form handled this call /// public event EventHandler UnhandledCall { @@ -119,4 +119,4 @@ public class FormBaseMessageLoop : IMessageLoopFactory { (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); } -} \ No newline at end of file +} diff --git a/TelegramBotBase/MessageLoops/FullMessageLoop.cs b/TelegramBotBase/MessageLoops/FullMessageLoop.cs index 69c2105..b7855c6 100644 --- a/TelegramBotBase/MessageLoops/FullMessageLoop.cs +++ b/TelegramBotBase/MessageLoops/FullMessageLoop.cs @@ -100,7 +100,7 @@ public class FullMessageLoop : IMessageLoopFactory } /// - /// Will be called if no form handeled this call + /// Will be called if no form handled this call /// public event EventHandler UnhandledCall { @@ -112,4 +112,4 @@ public class FullMessageLoop : IMessageLoopFactory { (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); } -} \ No newline at end of file +} diff --git a/TelegramBotBase/MessageLoops/MinimalMessageLoop.cs b/TelegramBotBase/MessageLoops/MinimalMessageLoop.cs index 74b5c83..8f72f15 100644 --- a/TelegramBotBase/MessageLoops/MinimalMessageLoop.cs +++ b/TelegramBotBase/MessageLoops/MinimalMessageLoop.cs @@ -31,7 +31,7 @@ public class MinimalMessageLoop : IMessageLoopFactory } /// - /// Will be called if no form handeled this call + /// Will be called if no form handled this call /// public event EventHandler UnhandledCall { @@ -43,4 +43,4 @@ public class MinimalMessageLoop : IMessageLoopFactory { (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); } -} \ No newline at end of file +} From d566cf858e3534b9eaa57184a17aede41efef053 Mon Sep 17 00:00:00 2001 From: ZavaruKitsu Date: Sat, 8 Oct 2022 20:01:23 +0300 Subject: [PATCH 06/22] fix(readme): update docs --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 7f067ad..f4d0fb1 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ var bot = BotBaseBuilder await bot.UploadBotCommands(); // Start your Bot -bot.Start(); +await bot.Start(); ``` The `BotBase` class will manage a lot of things for you, like bot commands, action events and so on. @@ -174,7 +174,7 @@ var bot = BotBaseBuilder .QuickStart("{YOUR API KEY}") .Build(); -bot.Start(); +await bot.Start(); ``` ## Features @@ -236,7 +236,7 @@ bot.BotCommand += async (s, en) => await bot.UploadBotCommands() -bot.Start(); +await bot.Start(); ``` On every input the user is sending back to the bot, the `Action` event gets raised. So here we could manage to send @@ -808,7 +808,7 @@ var bot = BotBaseBuilder .UseEnglish() .Build(); -bot.Start(); +await bot.Start(); ``` #### JSONStateMachine @@ -831,7 +831,7 @@ var bot = BotBaseBuilder .UseEnglish() .Build(); -bot.Start(); +await bot.Start(); ``` #### XMLStateMachine @@ -853,7 +853,7 @@ var bot = BotBaseBuilder .UseEnglish() .Build(); -bot.Start(); +await bot.Start(); ``` ### Interfaces From 8d02b54b05ab829d9e959d9b44fc4760a807d412 Mon Sep 17 00:00:00 2001 From: ZavaruKitsu Date: Sat, 8 Oct 2022 20:37:21 +0300 Subject: [PATCH 07/22] fix: remove obsolete properties & fix NRE --- TelegramBotBase.Test/Program.cs | 8 +++----- .../Tests/Controls/ButtonGridForm.cs | 4 ++-- .../Tests/Controls/ButtonGridPagingForm.cs | 4 ++-- .../Tests/Controls/MultiViewForm.cs | 7 ++++--- TelegramBotBase/Base/MessageResult.cs | 9 ++++++++- TelegramBotBase/Base/ResultBase.cs | 4 ++-- TelegramBotBase/Controls/Hybrid/ButtonGrid.cs | 11 +---------- .../Controls/Hybrid/CheckedButtonList.cs | 17 +++++------------ .../Controls/Hybrid/TaggedButtonGrid.cs | 9 +-------- 9 files changed, 28 insertions(+), 45 deletions(-) diff --git a/TelegramBotBase.Test/Program.cs b/TelegramBotBase.Test/Program.cs index 044dba2..6809cb7 100644 --- a/TelegramBotBase.Test/Program.cs +++ b/TelegramBotBase.Test/Program.cs @@ -11,7 +11,7 @@ namespace TelegramBotBaseTest; internal class Program { - private static void Main(string[] args) + private static async Task Main(string[] args) { var apiKey = ""; @@ -48,16 +48,14 @@ internal class Program Console.WriteLine(en.DeviceId + " " + en.Message.MessageText + " " + (en.Message.RawData ?? "")); }; - bb.Start(); + await bb.Start(); Console.WriteLine("Telegram Bot started..."); - Console.WriteLine("Press q to quit application."); - Console.ReadLine(); - bb.Stop(); + await bb.Stop(); } private static async Task Bb_BotCommand(object sender, BotCommandEventArgs en) diff --git a/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs b/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs index 0669d2e..e0492ec 100644 --- a/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs @@ -32,7 +32,7 @@ public class ButtonGridForm : AutoCleanForm bf.AddButtonRow(new ButtonBase("Button3", "b3"), new ButtonBase("Button4", "b4")); - _mButtons.ButtonsForm = bf; + _mButtons.DataSource.ButtonForm = bf; _mButtons.ButtonClicked += Bg_ButtonClicked; @@ -66,4 +66,4 @@ public class ButtonGridForm : AutoCleanForm await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); } } -} \ No newline at end of file +} diff --git a/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs b/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs index 47d6205..3ce477a 100644 --- a/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs @@ -38,7 +38,7 @@ public class ButtonGridPagingForm : AutoCleanForm bf.AddButtonRow(new ButtonBase(c.EnglishName, c.EnglishName)); } - _mButtons.ButtonsForm = bf; + _mButtons.DataSource.ButtonForm = bf; _mButtons.ButtonClicked += Bg_ButtonClicked; @@ -63,4 +63,4 @@ public class ButtonGridPagingForm : AutoCleanForm await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); } } -} \ No newline at end of file +} diff --git a/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs b/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs index 0511cb6..7e4bba2 100644 --- a/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs @@ -1,6 +1,7 @@ using System.Threading.Tasks; using TelegramBotBase.Args; using TelegramBotBase.Controls.Hybrid; +using TelegramBotBase.DataSources; using TelegramBotBase.Enums; using TelegramBotBase.Form; using TelegramBotBaseTest.Tests.Controls.Subclass; @@ -26,9 +27,9 @@ public class MultiViewForm : AutoCleanForm _bg = new ButtonGrid { - ButtonsForm = new ButtonForm() + DataSource = new ButtonFormDataSource() }; - _bg.ButtonsForm.AddButtonRow("Back", "$back$"); + _bg.DataSource.ButtonForm.AddButtonRow("Back", "$back$"); _bg.ButtonClicked += Bg_ButtonClicked; _bg.KeyboardType = EKeyboardType.ReplyKeyboard; AddControl(_bg); @@ -47,4 +48,4 @@ public class MultiViewForm : AutoCleanForm break; } } -} \ No newline at end of file +} diff --git a/TelegramBotBase/Base/MessageResult.cs b/TelegramBotBase/Base/MessageResult.cs index 531edf4..c6579ef 100644 --- a/TelegramBotBase/Base/MessageResult.cs +++ b/TelegramBotBase/Base/MessageResult.cs @@ -33,7 +33,7 @@ public class MessageResult : ResultBase /// /// The message id /// - public new int MessageId => + public override int MessageId => UpdateData?.Message?.MessageId ?? Message?.MessageId ?? UpdateData?.CallbackQuery?.Message?.MessageId @@ -45,6 +45,13 @@ public class MessageResult : ResultBase public MessageType MessageType => Message?.Type ?? MessageType.Unknown; + public override Message Message => + UpdateData?.Message + ?? UpdateData?.EditedMessage + ?? UpdateData?.ChannelPost + ?? UpdateData?.EditedChannelPost + ?? UpdateData?.CallbackQuery?.Message; + /// /// Is this an action ? (i.e. button click) /// diff --git a/TelegramBotBase/Base/ResultBase.cs b/TelegramBotBase/Base/ResultBase.cs index 2845237..69a4f74 100644 --- a/TelegramBotBase/Base/ResultBase.cs +++ b/TelegramBotBase/Base/ResultBase.cs @@ -12,7 +12,7 @@ public class ResultBase : EventArgs public virtual long DeviceId { get; set; } - public int MessageId => Message.MessageId; + public virtual int MessageId => Message.MessageId; public virtual Message Message { get; set; } @@ -42,4 +42,4 @@ public class ResultBase : EventArgs { } } -} \ No newline at end of file +} diff --git a/TelegramBotBase/Controls/Hybrid/ButtonGrid.cs b/TelegramBotBase/Controls/Hybrid/ButtonGrid.cs index e2871d9..ca0a895 100644 --- a/TelegramBotBase/Controls/Hybrid/ButtonGrid.cs +++ b/TelegramBotBase/Controls/Hybrid/ButtonGrid.cs @@ -55,15 +55,6 @@ public class ButtonGrid : ControlBase public string ConfirmationText { get; set; } = ""; - /// - /// - [Obsolete("This property is obsolete. Please use the DataSource property instead.")] - public ButtonForm ButtonsForm - { - get => DataSource.ButtonForm; - set => DataSource = new ButtonFormDataSource(value); - } - /// /// Data source of the items. /// @@ -746,4 +737,4 @@ public class ButtonGrid : ControlBase break; } } -} \ No newline at end of file +} diff --git a/TelegramBotBase/Controls/Hybrid/CheckedButtonList.cs b/TelegramBotBase/Controls/Hybrid/CheckedButtonList.cs index 6e49ebe..ed44fc0 100644 --- a/TelegramBotBase/Controls/Hybrid/CheckedButtonList.cs +++ b/TelegramBotBase/Controls/Hybrid/CheckedButtonList.cs @@ -55,13 +55,6 @@ public class CheckedButtonList : ControlBase public string ConfirmationText { get; set; } = ""; - [Obsolete("This property is obsolete. Please use the DataSource property instead.")] - public ButtonForm ButtonsForm - { - get => DataSource.ButtonForm; - set => DataSource = new ButtonFormDataSource(value); - } - /// /// Data source of the items. /// @@ -277,7 +270,7 @@ public class CheckedButtonList : ControlBase foreach (var c in CheckedRows) { - lst.Add(ButtonsForm[c][0]); + lst.Add(DataSource.ButtonForm[c][0]); } return lst; @@ -418,7 +411,7 @@ public class CheckedButtonList : ControlBase Updated(); - await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, false)); + await OnCheckedChanged(new CheckedChangedEventArgs(DataSource.ButtonForm[index], index, false)); } else if (result.MessageText.EndsWith(UncheckedIconLabel)) { @@ -435,7 +428,7 @@ public class CheckedButtonList : ControlBase Updated(); - await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, true)); + await OnCheckedChanged(new CheckedChangedEventArgs(DataSource.ButtonForm[index], index, true)); } //else if (this.EnableSearch) //{ @@ -589,7 +582,7 @@ public class CheckedButtonList : ControlBase Updated(); - await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, true)); + await OnCheckedChanged(new CheckedChangedEventArgs(DataSource.ButtonForm[index], index, true)); } break; @@ -604,7 +597,7 @@ public class CheckedButtonList : ControlBase Updated(); - await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, false)); + await OnCheckedChanged(new CheckedChangedEventArgs(DataSource.ButtonForm[index], index, false)); } break; diff --git a/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs b/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs index b3ce36c..c12aced 100644 --- a/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs +++ b/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs @@ -63,13 +63,6 @@ public class TaggedButtonGrid : MultiView public string ConfirmationText { get; set; } - [Obsolete("This property is obsolete. Please use the DataSource property instead.")] - public ButtonForm ButtonsForm - { - get => DataSource.ButtonForm; - set => DataSource = new ButtonFormDataSource(value); - } - /// /// Data source of the items. /// @@ -1017,4 +1010,4 @@ public class TaggedButtonGrid : MultiView } #endregion -} \ No newline at end of file +} From 77242a200fead54e3857d133eca093488740d6c6 Mon Sep 17 00:00:00 2001 From: ZavaruKitsu Date: Sat, 15 Oct 2022 18:16:22 +0300 Subject: [PATCH 08/22] upstream: apply changes --- .../AsyncFormUpdates/AsyncFormUpdates.csproj | 77 +++---------------- Examples/AsyncFormUpdates/Program.cs | 12 +-- .../Properties/AssemblyInfo.cs | 35 --------- TelegramBotBase/Base/MessageResult.cs | 2 +- TelegramBotBase/BotBase.cs | 18 ++--- TelegramBotBase/Builder/BotBaseBuilder.cs | 2 - .../DataSources/ButtonFormDataSource.cs | 4 +- TelegramBotBase/Form/SplitterForm.cs | 4 +- TelegramBotBase/Localizations/English.cs | 6 +- .../{SessionBase.cs => SessionManager.cs} | 24 ++---- TelegramBotBase/Sessions/DeviceSession.cs | 4 +- TelegramBotBase/TelegramBotBase.csproj | 14 ++-- 12 files changed, 48 insertions(+), 154 deletions(-) delete mode 100644 Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs rename TelegramBotBase/{SessionBase.cs => SessionManager.cs} (95%) diff --git a/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj b/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj index 6c2fe0b..95f3bea 100644 --- a/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj +++ b/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj @@ -1,74 +1,19 @@ - - - + + - Debug - AnyCPU - {673A56F5-6110-4AED-A68D-562FD6ED3EA6} Exe - AsyncFormUpdates - AsyncFormUpdates - v4.8 - 512 - true - true - - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 + net6.0 + enable + disable + - - - - - - - - - - - ..\..\packages\Telegram.Bot.17.0.0\lib\netstandard2.0\Telegram.Bot.dll - + + + - - - - - + - - - - - - {0bd16fb9-7ed4-4ccb-83eb-5cee538e1b6c} - TelegramBotBase - - - - - - - - - - + diff --git a/Examples/AsyncFormUpdates/Program.cs b/Examples/AsyncFormUpdates/Program.cs index facc257..63ecc9d 100644 --- a/Examples/AsyncFormUpdates/Program.cs +++ b/Examples/AsyncFormUpdates/Program.cs @@ -1,8 +1,8 @@ -using System; -using System.Timers; +using System.Timers; using AsyncFormUpdates.forms; using TelegramBotBase; using TelegramBotBase.Builder; +using Timer = System.Timers.Timer; namespace AsyncFormUpdates { @@ -10,7 +10,7 @@ namespace AsyncFormUpdates { private static BotBase __bot; - private static void Main(string[] args) + private static async Task Main(string[] args) { var apiKey = "APIKey"; @@ -18,7 +18,7 @@ namespace AsyncFormUpdates .QuickStart(apiKey) .Build(); - __bot.Start(); + await __bot.Start(); var timer = new Timer(5000); @@ -28,7 +28,7 @@ namespace AsyncFormUpdates Console.ReadLine(); timer.Stop(); - __bot.Stop(); + await __bot.Stop(); } private static async void Timer_Elapsed(object sender, ElapsedEventArgs e) @@ -46,4 +46,4 @@ namespace AsyncFormUpdates } } } -} \ No newline at end of file +} diff --git a/Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs b/Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs deleted file mode 100644 index f89e22b..0000000 --- a/Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Reflection; -using System.Runtime.InteropServices; - -// Allgemeine Informationen über eine Assembly werden über die folgenden -// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, -// die einer Assembly zugeordnet sind. -[assembly: AssemblyTitle("AsyncFormUpdates")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("AsyncFormUpdates")] -[assembly: AssemblyCopyright("Copyright © 2021")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly -// für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von -// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. -[assembly: ComVisible(false)] - -// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird -[assembly: Guid("673a56f5-6110-4aed-a68d-562fd6ed3ea6")] - -// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: -// -// Hauptversion -// Nebenversion -// Buildnummer -// Revision -// -// Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden, -// indem Sie "*" wie unten gezeigt eingeben: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/TelegramBotBase/Base/MessageResult.cs b/TelegramBotBase/Base/MessageResult.cs index c6579ef..11e33d7 100644 --- a/TelegramBotBase/Base/MessageResult.cs +++ b/TelegramBotBase/Base/MessageResult.cs @@ -123,7 +123,7 @@ public class MessageResult : ResultBase } /// - /// Confirm incomming action (i.e. Button click) + /// Confirm incoming action (i.e. Button click) /// /// /// diff --git a/TelegramBotBase/BotBase.cs b/TelegramBotBase/BotBase.cs index 8e6fcad..14fe7ba 100644 --- a/TelegramBotBase/BotBase.cs +++ b/TelegramBotBase/BotBase.cs @@ -18,9 +18,9 @@ namespace TelegramBotBase; /// Bot base class for full Device/Context and Messagehandling ///
/// -public class BotBase +public sealed class BotBase { - public BotBase() + internal BotBase() { SystemSettings = new Dictionary(); @@ -32,10 +32,7 @@ public class BotBase BotCommandScopes = new Dictionary>(); - Sessions = new SessionBase - { - BotBase = this - }; + Sessions = new SessionManager(this); } public MessageClient Client { get; set; } @@ -48,7 +45,7 @@ public class BotBase /// /// List of all running/active sessions /// - public SessionBase Sessions { get; set; } + public SessionManager Sessions { get; set; } /// /// Contains System commands which will be available at everytime and didnt get passed to forms, i.e. /start @@ -94,9 +91,10 @@ public class BotBase await Sessions.LoadSessionStates(StateMachine); } - //Enable auto session saving + // Enable auto session saving if (GetSetting(ESettings.SaveSessionsOnConsoleExit, false)) { + // should be waited until finish Console.SetHandler(() => { Sessions.SaveSessionStates().GetAwaiter().GetResult(); }); } @@ -329,8 +327,6 @@ public class BotBase private static readonly object EvMessage = new(); - private static object __evSystemCall = new(); - public delegate Task BotCommandEventHandler(object sender, BotCommandEventArgs e); private static readonly object EvException = new(); @@ -356,7 +352,7 @@ public class BotBase } /// - /// Will be called on incomming message + /// Will be called on incoming message /// public event EventHandler Message { diff --git a/TelegramBotBase/Builder/BotBaseBuilder.cs b/TelegramBotBase/Builder/BotBaseBuilder.cs index c20368e..f73e27d 100644 --- a/TelegramBotBase/Builder/BotBaseBuilder.cs +++ b/TelegramBotBase/Builder/BotBaseBuilder.cs @@ -48,8 +48,6 @@ public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, Client = _client }; - bot.Sessions.Client = bot.Client; - bot.BotCommandScopes = BotCommandScopes; bot.StateMachine = _statemachine; diff --git a/TelegramBotBase/DataSources/ButtonFormDataSource.cs b/TelegramBotBase/DataSources/ButtonFormDataSource.cs index c14b7e3..e91668c 100644 --- a/TelegramBotBase/DataSources/ButtonFormDataSource.cs +++ b/TelegramBotBase/DataSources/ButtonFormDataSource.cs @@ -39,7 +39,7 @@ public class ButtonFormDataSource : IDataSource /// - /// Returns the amount of rows exisiting. + /// Returns the amount of rows existing. /// /// public virtual int Count => ButtonForm.Count; @@ -134,4 +134,4 @@ public class ButtonFormDataSource : IDataSource { return ds.ButtonForm; } -} \ No newline at end of file +} diff --git a/TelegramBotBase/Form/SplitterForm.cs b/TelegramBotBase/Form/SplitterForm.cs index 4d8d668..99c0d85 100644 --- a/TelegramBotBase/Form/SplitterForm.cs +++ b/TelegramBotBase/Form/SplitterForm.cs @@ -5,7 +5,7 @@ using TelegramBotBase.Base; namespace TelegramBotBase.Form; /// -/// This is used to split incomming requests depending on the chat type. +/// This is used to split incoming requests depending on the chat type. /// public class SplitterForm : FormBase { @@ -90,4 +90,4 @@ public class SplitterForm : FormBase { return base.SentData(message); } -} \ No newline at end of file +} diff --git a/TelegramBotBase/Localizations/English.cs b/TelegramBotBase/Localizations/English.cs index fb5b948..5a7c362 100644 --- a/TelegramBotBase/Localizations/English.cs +++ b/TelegramBotBase/Localizations/English.cs @@ -25,11 +25,11 @@ public class English : Localization Values["ToggleButton_OnIcon"] = "⚫"; Values["ToggleButton_OffIcon"] = "⚪"; Values["ToggleButton_Title"] = "Toggle"; - Values["ToggleButton_Changed"] = "Choosen"; + Values["ToggleButton_Changed"] = "Chosen"; Values["MultiToggleButton_SelectedIcon"] = "✅"; Values["MultiToggleButton_Title"] = "Multi-Toggle"; - Values["MultiToggleButton_Changed"] = "Choosen"; + Values["MultiToggleButton_Changed"] = "Chosen"; Values["PromptDialog_Back"] = "Back"; Values["ToggleButton_Changed"] = "Setting changed"; } -} \ No newline at end of file +} diff --git a/TelegramBotBase/SessionBase.cs b/TelegramBotBase/SessionManager.cs similarity index 95% rename from TelegramBotBase/SessionBase.cs rename to TelegramBotBase/SessionManager.cs index bd4f2bb..7e9d257 100644 --- a/TelegramBotBase/SessionBase.cs +++ b/TelegramBotBase/SessionManager.cs @@ -16,17 +16,18 @@ namespace TelegramBotBase; /// /// Base class for managing all active sessions /// -public class SessionBase +public class SessionManager { - public SessionBase() + public SessionManager(BotBase botBase) { + BotBase = botBase; SessionList = new Dictionary(); } /// /// The Basic message client. /// - public MessageClient Client { get; set; } + public MessageClient Client => BotBase.Client; /// /// A list of all active sessions. @@ -37,18 +38,7 @@ public class SessionBase /// /// Reference to the Main BotBase instance for later use. /// - public BotBase BotBase { get; set; } - - /// - /// Get device session from Device/ChatId - /// - /// - /// - public DeviceSession this[long key] - { - get => SessionList[key]; - set => SessionList[key] = value; - } + public BotBase BotBase { get; } /// /// Get device session from Device/ChatId @@ -80,7 +70,7 @@ public class SessionBase await start.OnOpened(EventArgs.Empty); - this[deviceId] = ds; + SessionList[deviceId] = ds; return ds; } @@ -90,7 +80,7 @@ public class SessionBase /// public void EndSession(long deviceId) { - var d = this[deviceId]; + var d = SessionList[deviceId]; if (d != null) { SessionList.Remove(deviceId); diff --git a/TelegramBotBase/Sessions/DeviceSession.cs b/TelegramBotBase/Sessions/DeviceSession.cs index 2ece87c..5da18ab 100644 --- a/TelegramBotBase/Sessions/DeviceSession.cs +++ b/TelegramBotBase/Sessions/DeviceSession.cs @@ -125,7 +125,7 @@ public class DeviceSession : IDeviceSession /// - /// Confirm incomming action (i.e. Button click) + /// Confirm incoming action (i.e. Button click) /// /// /// @@ -992,4 +992,4 @@ public class DeviceSession : IDeviceSession } #endregion -} \ No newline at end of file +} diff --git a/TelegramBotBase/TelegramBotBase.csproj b/TelegramBotBase/TelegramBotBase.csproj index 3879e73..12c0a79 100644 --- a/TelegramBotBase/TelegramBotBase.csproj +++ b/TelegramBotBase/TelegramBotBase.csproj @@ -22,8 +22,8 @@ - - + + @@ -50,15 +50,15 @@ - - - + + + - - + + From b9a177c1528b08e333d4c52f300c09f0146c02a5 Mon Sep 17 00:00:00 2001 From: ZavaruKitsu Date: Sat, 15 Oct 2022 18:28:15 +0300 Subject: [PATCH 09/22] fix: merge conflict --- .../Datasources/ButtonFormDataSource.cs | 137 ------------------ 1 file changed, 137 deletions(-) delete mode 100644 TelegramBotBase/Datasources/ButtonFormDataSource.cs diff --git a/TelegramBotBase/Datasources/ButtonFormDataSource.cs b/TelegramBotBase/Datasources/ButtonFormDataSource.cs deleted file mode 100644 index e91668c..0000000 --- a/TelegramBotBase/Datasources/ButtonFormDataSource.cs +++ /dev/null @@ -1,137 +0,0 @@ -using System; -using System.Collections.Generic; -using TelegramBotBase.Controls.Hybrid; -using TelegramBotBase.Form; -using TelegramBotBase.Interfaces; - -namespace TelegramBotBase.DataSources; - -public class ButtonFormDataSource : IDataSource -{ - private ButtonForm _buttonform; - - public ButtonFormDataSource() - { - _buttonform = new ButtonForm(); - } - - public ButtonFormDataSource(ButtonForm bf) - { - _buttonform = bf; - } - - public virtual ButtonForm ButtonForm - { - get => _buttonform; - set => _buttonform = value; - } - - - /// - /// Returns the amount of rows. - /// - public virtual int RowCount => ButtonForm.Rows; - - /// - /// Returns the maximum amount of columns. - /// - public virtual int ColumnCount => ButtonForm.Cols; - - - /// - /// Returns the amount of rows existing. - /// - /// - public virtual int Count => ButtonForm.Count; - - /// - /// Returns the row with the specific index. - /// - /// - /// - public virtual ButtonRow ItemAt(int index) - { - return ButtonForm[index]; - } - - public virtual List ItemRange(int start, int count) - { - return ButtonForm.GetRange(start, count); - } - - public virtual List AllItems() - { - return ButtonForm.ToArray(); - } - - public virtual ButtonForm PickItems(int start, int count, string filter = null) - { - var bf = new ButtonForm(); - ButtonForm dataForm = null; - - if (filter == null) - { - dataForm = ButtonForm.Duplicate(); - } - else - { - dataForm = ButtonForm.FilterDuplicate(filter, true); - } - - for (var i = 0; i < count; i++) - { - var it = start + i; - - if (it > dataForm.Rows - 1) - { - break; - } - - bf.AddButtonRow(dataForm[it]); - } - - return bf; - } - - public virtual ButtonForm PickAllItems(string filter = null) - { - if (filter == null) - { - return ButtonForm.Duplicate(); - } - - - return ButtonForm.FilterDuplicate(filter, true); - } - - public virtual Tuple FindRow(string text, bool useText = true) - { - return ButtonForm.FindRow(text, useText); - } - - /// - /// Returns the maximum items of this data source. - /// - /// - /// - public virtual int CalculateMax(string filter = null) - { - return PickAllItems(filter).Rows; - } - - public virtual ButtonRow Render(object data) - { - return data as ButtonRow; - } - - - public static implicit operator ButtonFormDataSource(ButtonForm bf) - { - return new ButtonFormDataSource(bf); - } - - public static implicit operator ButtonForm(ButtonFormDataSource ds) - { - return ds.ButtonForm; - } -} From a2b75654d8d476607d0096f5d04409002c903ba4 Mon Sep 17 00:00:00 2001 From: ZavaruKitsu Date: Sat, 15 Oct 2022 18:51:26 +0300 Subject: [PATCH 10/22] refactor: example projects --- Examples/AsyncFormUpdates/App.config | 426 ------------------ .../AsyncFormUpdates/AsyncFormUpdates.csproj | 7 +- .../AsyncFormUpdates/Forms/AsyncFormEdit.cs | 48 ++ .../AsyncFormUpdates/Forms/AsyncFormUpdate.cs | 38 ++ Examples/AsyncFormUpdates/Forms/Start.cs | 42 ++ Examples/AsyncFormUpdates/Program.cs | 68 ++- .../AsyncFormUpdates/forms/AsyncFormEdit.cs | 51 --- .../AsyncFormUpdates/forms/AsyncFormUpdate.cs | 42 -- Examples/AsyncFormUpdates/forms/Start.cs | 44 -- .../{forms => Forms}/GroupManageForm.cs | 7 +- .../JoinHiderBot/{forms => Forms}/Start.cs | 5 +- Examples/JoinHiderBot/JoinHiderBot.csproj | 4 +- Examples/JoinHiderBot/Program.cs | 14 +- .../{commands/Commando.cs => Command.cs} | 6 +- .../SystemCommandsBot/{config => }/Config.cs | 19 +- .../{forms => Forms}/CmdForm.cs | 8 +- .../{forms => Forms}/StartForm.cs | 2 +- Examples/SystemCommandsBot/Program.cs | 14 +- .../SystemCommandsBot.csproj | 5 +- TelegramBotBase.Test/App.config | 14 - TelegramBotBase.Test/Program.cs | 23 +- .../Properties/AssemblyInfo.cs | 35 -- .../TelegramBotBase.Example.csproj | 15 + .../TelegramBotBaseTest.csproj | 35 -- TelegramBotBase.Test/Tests/ButtonTestForm.cs | 2 +- .../Tests/Controls/ButtonGridForm.cs | 2 +- .../Tests/Controls/ButtonGridPagingForm.cs | 2 +- .../Tests/Controls/ButtonGridTagForm.cs | 2 +- .../Tests/Controls/CalendarPickerForm.cs | 2 +- .../Tests/Controls/CheckedButtonListForm.cs | 2 +- .../Tests/Controls/MonthPickerForm.cs | 2 +- .../Tests/Controls/MultiToggleButtons.cs | 2 +- .../Tests/Controls/MultiViewForm.cs | 4 +- .../Tests/Controls/Subclass/MultiViewTest.cs | 2 +- .../Tests/Controls/ToggleButtons.cs | 2 +- .../Tests/Controls/TreeViewForms.cs | 2 +- TelegramBotBase.Test/Tests/DataForm.cs | 2 +- .../Tests/DataSources/CustomDataSource.cs | 2 +- .../Tests/DataSources/List.cs | 2 +- .../Tests/Groups/GroupChange.cs | 2 +- .../Tests/Groups/LinkReplaceTest.cs | 6 +- .../Tests/Groups/WelcomeUser.cs | 2 +- TelegramBotBase.Test/Tests/Menu.cs | 8 +- .../Tests/Navigation/CustomController.cs | 2 +- .../Tests/Navigation/Form1.cs | 2 +- .../Tests/Navigation/Start.cs | 2 +- .../Tests/Notifications/Start.cs | 2 +- TelegramBotBase.Test/Tests/ProgressTest.cs | 2 +- .../Tests/Register/PerForm.cs | 2 +- .../Tests/Register/PerStep.cs | 4 +- TelegramBotBase.Test/Tests/Register/Start.cs | 2 +- .../Tests/Register/Steps/Data.cs | 2 +- .../Tests/Register/Steps/Step1.cs | 2 +- .../Tests/Register/Steps/Step2.cs | 2 +- .../Tests/Register/Steps/Step3.cs | 2 +- TelegramBotBase.Test/Tests/SimpleForm.cs | 2 +- TelegramBotBase.Test/Tests/Start.cs | 4 +- TelegramBotBase.Test/Tests/TestForm.cs | 2 +- TelegramBotBase.Test/Tests/TestForm2.cs | 2 +- TelegramBotBase.Test/packages.config | 6 - TelegramBotFramework.sln | 2 +- 61 files changed, 271 insertions(+), 795 deletions(-) delete mode 100644 Examples/AsyncFormUpdates/App.config create mode 100644 Examples/AsyncFormUpdates/Forms/AsyncFormEdit.cs create mode 100644 Examples/AsyncFormUpdates/Forms/AsyncFormUpdate.cs create mode 100644 Examples/AsyncFormUpdates/Forms/Start.cs delete mode 100644 Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs delete mode 100644 Examples/AsyncFormUpdates/forms/AsyncFormUpdate.cs delete mode 100644 Examples/AsyncFormUpdates/forms/Start.cs rename Examples/JoinHiderBot/{forms => Forms}/GroupManageForm.cs (80%) rename Examples/JoinHiderBot/{forms => Forms}/Start.cs (80%) rename Examples/SystemCommandsBot/{commands/Commando.cs => Command.cs} (84%) rename Examples/SystemCommandsBot/{config => }/Config.cs (82%) rename Examples/SystemCommandsBot/{forms => Forms}/CmdForm.cs (94%) rename Examples/SystemCommandsBot/{forms => Forms}/StartForm.cs (95%) delete mode 100644 TelegramBotBase.Test/App.config delete mode 100644 TelegramBotBase.Test/Properties/AssemblyInfo.cs create mode 100644 TelegramBotBase.Test/TelegramBotBase.Example.csproj delete mode 100644 TelegramBotBase.Test/TelegramBotBaseTest.csproj delete mode 100644 TelegramBotBase.Test/packages.config diff --git a/Examples/AsyncFormUpdates/App.config b/Examples/AsyncFormUpdates/App.config deleted file mode 100644 index e784e10..0000000 --- a/Examples/AsyncFormUpdates/App.config +++ /dev/null @@ -1,426 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj b/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj index 95f3bea..5e6ad70 100644 --- a/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj +++ b/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj @@ -8,12 +8,7 @@ - - - - - - + diff --git a/Examples/AsyncFormUpdates/Forms/AsyncFormEdit.cs b/Examples/AsyncFormUpdates/Forms/AsyncFormEdit.cs new file mode 100644 index 0000000..a83fc63 --- /dev/null +++ b/Examples/AsyncFormUpdates/Forms/AsyncFormEdit.cs @@ -0,0 +1,48 @@ +using TelegramBotBase.Attributes; +using TelegramBotBase.Base; +using TelegramBotBase.Form; + +namespace AsyncFormUpdates.Forms; + +public class AsyncFormEdit : FormBase +{ + [SaveState] private int _counter; + + private int _messageId; + + public override Task Load(MessageResult message) + { + _counter++; + return Task.CompletedTask; + } + + public override async Task Action(MessageResult message) + { + await message.ConfirmAction(); + + switch (message.RawData ?? "") + { + case "back": + var st = new Start(); + await NavigateTo(st); + + break; + } + } + + public override async Task Render(MessageResult message) + { + var bf = new ButtonForm(); + bf.AddButtonRow("Back", "back"); + + if (_messageId != 0) + { + await Device.Edit(_messageId, $"Your current count is at: {_counter}", bf); + } + else + { + var m = await Device.Send($"Your current count is at: {_counter}", bf, disableNotification: true); + _messageId = m.MessageId; + } + } +} diff --git a/Examples/AsyncFormUpdates/Forms/AsyncFormUpdate.cs b/Examples/AsyncFormUpdates/Forms/AsyncFormUpdate.cs new file mode 100644 index 0000000..f2fb5dd --- /dev/null +++ b/Examples/AsyncFormUpdates/Forms/AsyncFormUpdate.cs @@ -0,0 +1,38 @@ +using TelegramBotBase.Attributes; +using TelegramBotBase.Base; +using TelegramBotBase.Form; + +namespace AsyncFormUpdates.Forms; + +public class AsyncFormUpdate : AutoCleanForm +{ + [SaveState] private int _counter; + + public override Task Load(MessageResult message) + { + _counter++; + return Task.CompletedTask; + } + + public override async Task Action(MessageResult message) + { + await message.ConfirmAction(); + + switch (message.RawData ?? "") + { + case "back": + var st = new Start(); + await NavigateTo(st); + + break; + } + } + + public override async Task Render(MessageResult message) + { + var bf = new ButtonForm(); + bf.AddButtonRow("Back", "back"); + + await Device.Send($"Your current count is at: {_counter}", bf, disableNotification: true); + } +} diff --git a/Examples/AsyncFormUpdates/Forms/Start.cs b/Examples/AsyncFormUpdates/Forms/Start.cs new file mode 100644 index 0000000..3756722 --- /dev/null +++ b/Examples/AsyncFormUpdates/Forms/Start.cs @@ -0,0 +1,42 @@ +using TelegramBotBase.Base; +using TelegramBotBase.Form; + +namespace AsyncFormUpdates.Forms; + +public class Start : AutoCleanForm +{ + public override async Task Action(MessageResult message) + { + await message.ConfirmAction(); + + switch (message.RawData ?? "") + { + case "async": + + var afe = new AsyncFormEdit(); + await NavigateTo(afe); + + + break; + + case "async_del": + + var afu = new AsyncFormUpdate(); + await NavigateTo(afu); + + + break; + } + } + + public override async Task Render(MessageResult message) + { + var bf = new ButtonForm(); + + bf.AddButtonRow("Open Async Form with AutoCleanupForm", "async_del"); + + bf.AddButtonRow("Open Async Form with Edit", "async"); + + await Device.Send("Choose your option", bf); + } +} diff --git a/Examples/AsyncFormUpdates/Program.cs b/Examples/AsyncFormUpdates/Program.cs index 63ecc9d..cc7404d 100644 --- a/Examples/AsyncFormUpdates/Program.cs +++ b/Examples/AsyncFormUpdates/Program.cs @@ -1,49 +1,47 @@ using System.Timers; -using AsyncFormUpdates.forms; +using AsyncFormUpdates.Forms; using TelegramBotBase; using TelegramBotBase.Builder; using Timer = System.Timers.Timer; -namespace AsyncFormUpdates +namespace AsyncFormUpdates; + +internal class Program { - internal class Program + private static BotBase __bot; + + private static async Task Main(string[] args) { - private static BotBase __bot; + __bot = BotBaseBuilder.Create() + .QuickStart(Environment.GetEnvironmentVariable("API_KEY") ?? + throw new Exception("API_KEY is not set")) + .Build(); - private static async Task Main(string[] args) + await __bot.Start(); + + var timer = new Timer(5000); + + timer.Elapsed += Timer_Elapsed; + timer.Start(); + + Console.ReadLine(); + + timer.Stop(); + await __bot.Stop(); + } + + private static async void Timer_Elapsed(object sender, ElapsedEventArgs e) + { + foreach (var s in __bot.Sessions.SessionList) { - var apiKey = "APIKey"; - - __bot = BotBaseBuilder.Create() - .QuickStart(apiKey) - .Build(); - - await __bot.Start(); - - var timer = new Timer(5000); - - timer.Elapsed += Timer_Elapsed; - timer.Start(); - - Console.ReadLine(); - - timer.Stop(); - await __bot.Stop(); - } - - private static async void Timer_Elapsed(object sender, ElapsedEventArgs e) - { - foreach (var s in __bot.Sessions.SessionList) + //Only for AsyncUpdateForm + if (s.Value.ActiveForm.GetType() != typeof(AsyncFormUpdate) && + s.Value.ActiveForm.GetType() != typeof(AsyncFormEdit)) { - //Only for AsyncUpdateForm - if (s.Value.ActiveForm.GetType() != typeof(AsyncFormUpdate) && - s.Value.ActiveForm.GetType() != typeof(AsyncFormEdit)) - { - continue; - } - - await __bot.InvokeMessageLoop(s.Key); + continue; } + + await __bot.InvokeMessageLoop(s.Key); } } } diff --git a/Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs b/Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs deleted file mode 100644 index 2ad3694..0000000 --- a/Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System.Threading.Tasks; -using TelegramBotBase.Attributes; -using TelegramBotBase.Base; -using TelegramBotBase.Form; - -namespace AsyncFormUpdates.forms -{ - public class AsyncFormEdit : FormBase - { - [SaveState] private int _counter; - - private int _messageId; - - public override Task Load(MessageResult message) - { - _counter++; - return Task.CompletedTask; - } - - public override async Task Action(MessageResult message) - { - await message.ConfirmAction(); - - switch (message.RawData ?? "") - { - case "back": - - var st = new Start(); - await NavigateTo(st); - - break; - } - } - - public override async Task Render(MessageResult message) - { - var bf = new ButtonForm(); - bf.AddButtonRow("Back", "back"); - - if (_messageId != 0) - { - await Device.Edit(_messageId, $"Your current count is at: {_counter}", bf); - } - else - { - var m = await Device.Send($"Your current count is at: {_counter}", bf, disableNotification: true); - _messageId = m.MessageId; - } - } - } -} \ No newline at end of file diff --git a/Examples/AsyncFormUpdates/forms/AsyncFormUpdate.cs b/Examples/AsyncFormUpdates/forms/AsyncFormUpdate.cs deleted file mode 100644 index 8a3b0b1..0000000 --- a/Examples/AsyncFormUpdates/forms/AsyncFormUpdate.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System.Threading.Tasks; -using TelegramBotBase.Attributes; -using TelegramBotBase.Base; -using TelegramBotBase.Form; - -namespace AsyncFormUpdates.forms -{ - public class AsyncFormUpdate : AutoCleanForm - { - [SaveState] private int _counter; - - - public override Task Load(MessageResult message) - { - _counter++; - return Task.CompletedTask; - } - - public override async Task Action(MessageResult message) - { - await message.ConfirmAction(); - - switch (message.RawData ?? "") - { - case "back": - - var st = new Start(); - await NavigateTo(st); - - break; - } - } - - public override async Task Render(MessageResult message) - { - var bf = new ButtonForm(); - bf.AddButtonRow("Back", "back"); - - await Device.Send($"Your current count is at: {_counter}", bf, disableNotification: true); - } - } -} \ No newline at end of file diff --git a/Examples/AsyncFormUpdates/forms/Start.cs b/Examples/AsyncFormUpdates/forms/Start.cs deleted file mode 100644 index 8713a04..0000000 --- a/Examples/AsyncFormUpdates/forms/Start.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System.Threading.Tasks; -using TelegramBotBase.Base; -using TelegramBotBase.Form; - -namespace AsyncFormUpdates.forms -{ - public class Start : AutoCleanForm - { - public override async Task Action(MessageResult message) - { - await message.ConfirmAction(); - - switch (message.RawData ?? "") - { - case "async": - - var afe = new AsyncFormEdit(); - await NavigateTo(afe); - - - break; - - case "async_del": - - var afu = new AsyncFormUpdate(); - await NavigateTo(afu); - - - break; - } - } - - public override async Task Render(MessageResult message) - { - var bf = new ButtonForm(); - - bf.AddButtonRow("Open Async Form with AutoCleanupForm", "async_del"); - - bf.AddButtonRow("Open Async Form with Edit", "async"); - - await Device.Send("Choose your option", bf); - } - } -} \ No newline at end of file diff --git a/Examples/JoinHiderBot/forms/GroupManageForm.cs b/Examples/JoinHiderBot/Forms/GroupManageForm.cs similarity index 80% rename from Examples/JoinHiderBot/forms/GroupManageForm.cs rename to Examples/JoinHiderBot/Forms/GroupManageForm.cs index 6ccf246..5d3915e 100644 --- a/Examples/JoinHiderBot/forms/GroupManageForm.cs +++ b/Examples/JoinHiderBot/Forms/GroupManageForm.cs @@ -1,9 +1,8 @@ -using System.Threading.Tasks; -using Telegram.Bot.Types.Enums; +using Telegram.Bot.Types.Enums; using TelegramBotBase.Args; using TelegramBotBase.Form; -namespace JoinHiderBot.forms; +namespace JoinHiderBot.Forms; public class GroupManageForm : GroupForm { @@ -19,4 +18,4 @@ public class GroupManageForm : GroupForm await Device.DeleteMessage(m); } -} \ No newline at end of file +} diff --git a/Examples/JoinHiderBot/forms/Start.cs b/Examples/JoinHiderBot/Forms/Start.cs similarity index 80% rename from Examples/JoinHiderBot/forms/Start.cs rename to Examples/JoinHiderBot/Forms/Start.cs index 0b868b6..c94b60a 100644 --- a/Examples/JoinHiderBot/forms/Start.cs +++ b/Examples/JoinHiderBot/Forms/Start.cs @@ -1,8 +1,7 @@ -using System.Threading.Tasks; -using TelegramBotBase.Base; +using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace JoinHiderBot.forms; +namespace JoinHiderBot.Forms; public class Start : SplitterForm { diff --git a/Examples/JoinHiderBot/JoinHiderBot.csproj b/Examples/JoinHiderBot/JoinHiderBot.csproj index 76dddc9..5e6ad70 100644 --- a/Examples/JoinHiderBot/JoinHiderBot.csproj +++ b/Examples/JoinHiderBot/JoinHiderBot.csproj @@ -3,10 +3,12 @@ Exe net6.0 + enable + disable - + diff --git a/Examples/JoinHiderBot/Program.cs b/Examples/JoinHiderBot/Program.cs index 9c0bfff..054c761 100644 --- a/Examples/JoinHiderBot/Program.cs +++ b/Examples/JoinHiderBot/Program.cs @@ -1,21 +1,19 @@ -using System; -using JoinHiderBot.forms; +using JoinHiderBot.Forms; using TelegramBotBase.Builder; namespace JoinHiderBot; internal class Program { - private static void Main(string[] args) + private static async Task Main(string[] args) { - var apiKey = ""; - var bot = BotBaseBuilder.Create() - .QuickStart(apiKey) + .QuickStart(Environment.GetEnvironmentVariable("API_KEY") ?? + throw new Exception("API_KEY is not set")) .Build(); - bot.Start(); + await bot.Start(); Console.ReadLine(); } -} \ No newline at end of file +} diff --git a/Examples/SystemCommandsBot/commands/Commando.cs b/Examples/SystemCommandsBot/Command.cs similarity index 84% rename from Examples/SystemCommandsBot/commands/Commando.cs rename to Examples/SystemCommandsBot/Command.cs index 8eb56d1..cd58074 100644 --- a/Examples/SystemCommandsBot/commands/Commando.cs +++ b/Examples/SystemCommandsBot/Command.cs @@ -1,6 +1,6 @@ -namespace SystemCommandsBot.commands; +namespace SystemCommandsBot; -public class Commando +public class Command { public int Id { get; set; } @@ -18,4 +18,4 @@ public class Commando public int? MaxInstances { get; set; } public string ProcName { get; set; } -} \ No newline at end of file +} diff --git a/Examples/SystemCommandsBot/config/Config.cs b/Examples/SystemCommandsBot/Config.cs similarity index 82% rename from Examples/SystemCommandsBot/config/Config.cs rename to Examples/SystemCommandsBot/Config.cs index 3125790..3a74502 100644 --- a/Examples/SystemCommandsBot/config/Config.cs +++ b/Examples/SystemCommandsBot/Config.cs @@ -1,30 +1,27 @@ -using System; -using System.Collections.Generic; -using System.IO; -using Newtonsoft.Json; -using SystemCommandsBot.commands; +using Newtonsoft.Json; -namespace SystemCommandsBot.config; +namespace SystemCommandsBot; public class Config { public Config() { - Commandos = new List(); + Commands = new List(); } public string Password { get; set; } public string ApiKey { get; set; } - public List Commandos { get; set; } + public List Commands { get; set; } public void LoadDefaultValues() { ApiKey = ""; - Commandos.Add(new Commando + Commands.Add(new Command { - Id = 0, Enabled = true, Title = "Test Befehl", ShellCmd = "explorer.exe", Action = "start", MaxInstances = 2 + Id = 0, Enabled = true, Title = "Test Befehl", ShellCmd = "explorer.exe", Action = "start", + MaxInstances = 2 }); } @@ -90,4 +87,4 @@ public class Config { } } -} \ No newline at end of file +} diff --git a/Examples/SystemCommandsBot/forms/CmdForm.cs b/Examples/SystemCommandsBot/Forms/CmdForm.cs similarity index 94% rename from Examples/SystemCommandsBot/forms/CmdForm.cs rename to Examples/SystemCommandsBot/Forms/CmdForm.cs index a5660fe..58a0674 100644 --- a/Examples/SystemCommandsBot/forms/CmdForm.cs +++ b/Examples/SystemCommandsBot/Forms/CmdForm.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace SystemCommandsBot.forms; +namespace SystemCommandsBot.Forms; public class CmdForm : AutoCleanForm { @@ -30,7 +30,7 @@ public class CmdForm : AutoCleanForm return; } - var cmd = Program.BotConfig.Commandos.Where(a => a.Enabled && a.Id == id).FirstOrDefault(); + var cmd = Program.BotConfig.Commands.Where(a => a.Enabled && a.Id == id).FirstOrDefault(); if (cmd == null) { await Device.Send("Cmd nicht verfügbar."); @@ -145,7 +145,7 @@ public class CmdForm : AutoCleanForm { if (MessageId == null) { - var buttons = Program.BotConfig.Commandos.Where(a => a.Enabled) + var buttons = Program.BotConfig.Commands.Where(a => a.Enabled) .Select(a => new ButtonBase(a.Title, a.Id.ToString())); var bf = new ButtonForm(); @@ -153,4 +153,4 @@ public class CmdForm : AutoCleanForm await Device.Send("Deine Optionen", bf); } } -} \ No newline at end of file +} diff --git a/Examples/SystemCommandsBot/forms/StartForm.cs b/Examples/SystemCommandsBot/Forms/StartForm.cs similarity index 95% rename from Examples/SystemCommandsBot/forms/StartForm.cs rename to Examples/SystemCommandsBot/Forms/StartForm.cs index 7b34f4d..885f4d2 100644 --- a/Examples/SystemCommandsBot/forms/StartForm.cs +++ b/Examples/SystemCommandsBot/Forms/StartForm.cs @@ -3,7 +3,7 @@ using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace SystemCommandsBot.forms; +namespace SystemCommandsBot.Forms; public class StartForm : FormBase { diff --git a/Examples/SystemCommandsBot/Program.cs b/Examples/SystemCommandsBot/Program.cs index b5330ac..4d44afe 100644 --- a/Examples/SystemCommandsBot/Program.cs +++ b/Examples/SystemCommandsBot/Program.cs @@ -1,6 +1,6 @@ using System; -using SystemCommandsBot.config; -using SystemCommandsBot.forms; +using System.Threading.Tasks; +using SystemCommandsBot.Forms; using TelegramBotBase.Builder; namespace SystemCommandsBot; @@ -9,8 +9,7 @@ internal class Program { public static Config BotConfig { get; set; } - - private static void Main(string[] args) + private static async Task Main(string[] args) { BotConfig = Config.Load(); @@ -25,13 +24,12 @@ internal class Program .QuickStart(BotConfig.ApiKey) .Build(); - bot.Start(); + await bot.Start(); Console.WriteLine("Bot started"); - Console.ReadLine(); - bot.Stop(); + await bot.Stop(); } -} \ No newline at end of file +} diff --git a/Examples/SystemCommandsBot/SystemCommandsBot.csproj b/Examples/SystemCommandsBot/SystemCommandsBot.csproj index 95990e5..7423d4a 100644 --- a/Examples/SystemCommandsBot/SystemCommandsBot.csproj +++ b/Examples/SystemCommandsBot/SystemCommandsBot.csproj @@ -3,11 +3,12 @@ Exe net6.0 + enable + disable - - + diff --git a/TelegramBotBase.Test/App.config b/TelegramBotBase.Test/App.config deleted file mode 100644 index 94f3e49..0000000 --- a/TelegramBotBase.Test/App.config +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/TelegramBotBase.Test/Program.cs b/TelegramBotBase.Test/Program.cs index 6809cb7..9276cbd 100644 --- a/TelegramBotBase.Test/Program.cs +++ b/TelegramBotBase.Test/Program.cs @@ -5,19 +5,18 @@ using TelegramBotBase.Args; using TelegramBotBase.Builder; using TelegramBotBase.Commands; using TelegramBotBase.Enums; -using TelegramBotBaseTest.Tests; +using TelegramBotBase.Example.Tests; -namespace TelegramBotBaseTest; +namespace TelegramBotBase.Example; internal class Program { private static async Task Main(string[] args) { - var apiKey = ""; - - var bb = BotBaseBuilder + var bot = BotBaseBuilder .Create() - .WithAPIKey(apiKey) + .WithAPIKey(Environment.GetEnvironmentVariable("API_KEY") ?? + throw new Exception("API_KEY is not set")) .DefaultMessageLoop() .WithStartForm() .NoProxy() @@ -36,26 +35,26 @@ internal class Program .Build(); - bb.BotCommand += Bb_BotCommand; + bot.BotCommand += Bb_BotCommand; //Update Bot commands to botfather - bb.UploadBotCommands().Wait(); + bot.UploadBotCommands().Wait(); - bb.SetSetting(ESettings.LogAllMessages, true); + bot.SetSetting(ESettings.LogAllMessages, true); - bb.Message += (s, en) => + bot.Message += (s, en) => { Console.WriteLine(en.DeviceId + " " + en.Message.MessageText + " " + (en.Message.RawData ?? "")); }; - await bb.Start(); + await bot.Start(); Console.WriteLine("Telegram Bot started..."); Console.WriteLine("Press q to quit application."); Console.ReadLine(); - await bb.Stop(); + await bot.Stop(); } private static async Task Bb_BotCommand(object sender, BotCommandEventArgs en) diff --git a/TelegramBotBase.Test/Properties/AssemblyInfo.cs b/TelegramBotBase.Test/Properties/AssemblyInfo.cs deleted file mode 100644 index af85f77..0000000 --- a/TelegramBotBase.Test/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Reflection; -using System.Runtime.InteropServices; - -// Allgemeine Informationen über eine Assembly werden über die folgenden -// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, -// die einer Assembly zugeordnet sind. -[assembly: AssemblyTitle("TelegramBotBaseTest")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("TelegramBotBaseTest")] -[assembly: AssemblyCopyright("Copyright © 2017")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar -// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von -// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. -[assembly: ComVisible(false)] - -// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird -[assembly: Guid("5817184c-0d59-4924-ac6c-6b943967811c")] - -// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: -// -// Hauptversion -// Nebenversion -// Buildnummer -// Revision -// -// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern -// übernehmen, indem Sie "*" eingeben: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/TelegramBotBase.Test/TelegramBotBase.Example.csproj b/TelegramBotBase.Test/TelegramBotBase.Example.csproj new file mode 100644 index 0000000..3e534ad --- /dev/null +++ b/TelegramBotBase.Test/TelegramBotBase.Example.csproj @@ -0,0 +1,15 @@ + + + + Exe + net6.0 + enable + disable + + + + + + + + diff --git a/TelegramBotBase.Test/TelegramBotBaseTest.csproj b/TelegramBotBase.Test/TelegramBotBaseTest.csproj deleted file mode 100644 index c40ee57..0000000 --- a/TelegramBotBase.Test/TelegramBotBaseTest.csproj +++ /dev/null @@ -1,35 +0,0 @@ - - - - Exe - netcoreapp3.1;net5;net6 - 10 - false - Debug;Release - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - - - - diff --git a/TelegramBotBase.Test/Tests/ButtonTestForm.cs b/TelegramBotBase.Test/Tests/ButtonTestForm.cs index f19b7d0..3bfab76 100644 --- a/TelegramBotBase.Test/Tests/ButtonTestForm.cs +++ b/TelegramBotBase.Test/Tests/ButtonTestForm.cs @@ -3,7 +3,7 @@ using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests; +namespace TelegramBotBase.Example.Tests; public class ButtonTestForm : AutoCleanForm { diff --git a/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs b/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs index e0492ec..47e7763 100644 --- a/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs @@ -4,7 +4,7 @@ using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls; +namespace TelegramBotBase.Example.Tests.Controls; public class ButtonGridForm : AutoCleanForm { diff --git a/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs b/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs index 3ce477a..f12b6a4 100644 --- a/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs @@ -6,7 +6,7 @@ using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls; +namespace TelegramBotBase.Example.Tests.Controls; public class ButtonGridPagingForm : AutoCleanForm { diff --git a/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs b/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs index 23b4b1d..78bc356 100644 --- a/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs @@ -8,7 +8,7 @@ using TelegramBotBase.DataSources; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls; +namespace TelegramBotBase.Example.Tests.Controls; public class ButtonGridTagForm : AutoCleanForm { diff --git a/TelegramBotBase.Test/Tests/Controls/CalendarPickerForm.cs b/TelegramBotBase.Test/Tests/Controls/CalendarPickerForm.cs index 69de30f..fedde60 100644 --- a/TelegramBotBase.Test/Tests/Controls/CalendarPickerForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/CalendarPickerForm.cs @@ -5,7 +5,7 @@ using TelegramBotBase.Controls.Inline; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls; +namespace TelegramBotBase.Example.Tests.Controls; public class CalendarPickerForm : AutoCleanForm { diff --git a/TelegramBotBase.Test/Tests/Controls/CheckedButtonListForm.cs b/TelegramBotBase.Test/Tests/Controls/CheckedButtonListForm.cs index 33849ae..55662e3 100644 --- a/TelegramBotBase.Test/Tests/Controls/CheckedButtonListForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/CheckedButtonListForm.cs @@ -6,7 +6,7 @@ using TelegramBotBase.DataSources; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls; +namespace TelegramBotBase.Example.Tests.Controls; public class CheckedButtonListForm : AutoCleanForm { diff --git a/TelegramBotBase.Test/Tests/Controls/MonthPickerForm.cs b/TelegramBotBase.Test/Tests/Controls/MonthPickerForm.cs index c44021f..8c5acda 100644 --- a/TelegramBotBase.Test/Tests/Controls/MonthPickerForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/MonthPickerForm.cs @@ -5,7 +5,7 @@ using TelegramBotBase.Controls.Inline; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls; +namespace TelegramBotBase.Example.Tests.Controls; public class MonthPickerForm : AutoCleanForm { diff --git a/TelegramBotBase.Test/Tests/Controls/MultiToggleButtons.cs b/TelegramBotBase.Test/Tests/Controls/MultiToggleButtons.cs index c75c065..fb46af5 100644 --- a/TelegramBotBase.Test/Tests/Controls/MultiToggleButtons.cs +++ b/TelegramBotBase.Test/Tests/Controls/MultiToggleButtons.cs @@ -7,7 +7,7 @@ using TelegramBotBase.Controls.Inline; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls; +namespace TelegramBotBase.Example.Tests.Controls; public class MultiToggleButtons : AutoCleanForm { diff --git a/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs b/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs index 7e4bba2..fbf8aa8 100644 --- a/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs @@ -3,10 +3,10 @@ using TelegramBotBase.Args; using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.DataSources; using TelegramBotBase.Enums; +using TelegramBotBase.Example.Tests.Controls.Subclass; using TelegramBotBase.Form; -using TelegramBotBaseTest.Tests.Controls.Subclass; -namespace TelegramBotBaseTest.Tests.Controls; +namespace TelegramBotBase.Example.Tests.Controls; public class MultiViewForm : AutoCleanForm { diff --git a/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs b/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs index 08c7649..c985d54 100644 --- a/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs +++ b/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs @@ -4,7 +4,7 @@ using TelegramBotBase.Base; using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls.Subclass; +namespace TelegramBotBase.Example.Tests.Controls.Subclass; public class MultiViewTest : MultiView { diff --git a/TelegramBotBase.Test/Tests/Controls/ToggleButtons.cs b/TelegramBotBase.Test/Tests/Controls/ToggleButtons.cs index 67db7e7..77c2e96 100644 --- a/TelegramBotBase.Test/Tests/Controls/ToggleButtons.cs +++ b/TelegramBotBase.Test/Tests/Controls/ToggleButtons.cs @@ -5,7 +5,7 @@ using TelegramBotBase.Controls.Inline; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls; +namespace TelegramBotBase.Example.Tests.Controls; public class ToggleButtons : AutoCleanForm { diff --git a/TelegramBotBase.Test/Tests/Controls/TreeViewForms.cs b/TelegramBotBase.Test/Tests/Controls/TreeViewForms.cs index b5d7465..0cf9549 100644 --- a/TelegramBotBase.Test/Tests/Controls/TreeViewForms.cs +++ b/TelegramBotBase.Test/Tests/Controls/TreeViewForms.cs @@ -5,7 +5,7 @@ using TelegramBotBase.Controls.Inline; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls; +namespace TelegramBotBase.Example.Tests.Controls; public class TreeViewForms : AutoCleanForm { diff --git a/TelegramBotBase.Test/Tests/DataForm.cs b/TelegramBotBase.Test/Tests/DataForm.cs index 7811d33..49554d0 100644 --- a/TelegramBotBase.Test/Tests/DataForm.cs +++ b/TelegramBotBase.Test/Tests/DataForm.cs @@ -7,7 +7,7 @@ using Telegram.Bot.Types.ReplyMarkups; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests; +namespace TelegramBotBase.Example.Tests; public class DataForm : AutoCleanForm { diff --git a/TelegramBotBase.Test/Tests/DataSources/CustomDataSource.cs b/TelegramBotBase.Test/Tests/DataSources/CustomDataSource.cs index 0246920..079d448 100644 --- a/TelegramBotBase.Test/Tests/DataSources/CustomDataSource.cs +++ b/TelegramBotBase.Test/Tests/DataSources/CustomDataSource.cs @@ -8,7 +8,7 @@ using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.DataSources; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.DataSources; +namespace TelegramBotBase.Example.Tests.DataSources; public class CustomDataSource : ButtonFormDataSource { diff --git a/TelegramBotBase.Test/Tests/DataSources/List.cs b/TelegramBotBase.Test/Tests/DataSources/List.cs index 35c55d7..cde1a85 100644 --- a/TelegramBotBase.Test/Tests/DataSources/List.cs +++ b/TelegramBotBase.Test/Tests/DataSources/List.cs @@ -4,7 +4,7 @@ using TelegramBotBase.Controls.Hybrid; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.DataSources; +namespace TelegramBotBase.Example.Tests.DataSources; public class List : FormBase { diff --git a/TelegramBotBase.Test/Tests/Groups/GroupChange.cs b/TelegramBotBase.Test/Tests/Groups/GroupChange.cs index fd984b6..9359998 100644 --- a/TelegramBotBase.Test/Tests/Groups/GroupChange.cs +++ b/TelegramBotBase.Test/Tests/Groups/GroupChange.cs @@ -4,7 +4,7 @@ using TelegramBotBase.Args; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Groups; +namespace TelegramBotBase.Example.Tests.Groups; public class GroupChange : GroupForm { diff --git a/TelegramBotBase.Test/Tests/Groups/LinkReplaceTest.cs b/TelegramBotBase.Test/Tests/Groups/LinkReplaceTest.cs index dd36756..69bc1ad 100644 --- a/TelegramBotBase.Test/Tests/Groups/LinkReplaceTest.cs +++ b/TelegramBotBase.Test/Tests/Groups/LinkReplaceTest.cs @@ -7,7 +7,7 @@ using Telegram.Bot.Types.Enums; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Groups; +namespace TelegramBotBase.Example.Tests.Groups; public class LinkReplaceTest : GroupForm { @@ -121,7 +121,7 @@ public class LinkReplaceTest : GroupForm if (Counter[from] >= 3) { - await e.Device.KickUser(from); + await e.Device.BanUser(from); await e.Device.Send(e.Message.From.FirstName + " " + e.Message.From.LastName + " has been removed from the group"); @@ -162,4 +162,4 @@ public class LinkReplaceTest : GroupForm return matches.Count > 0; } -} \ No newline at end of file +} diff --git a/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs b/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs index 3dc8048..6a6d09e 100644 --- a/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs +++ b/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs @@ -6,7 +6,7 @@ using TelegramBotBase.Args; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Groups; +namespace TelegramBotBase.Example.Tests.Groups; public class WelcomeUser : GroupForm { diff --git a/TelegramBotBase.Test/Tests/Menu.cs b/TelegramBotBase.Test/Tests/Menu.cs index 3b161db..740cfd7 100644 --- a/TelegramBotBase.Test/Tests/Menu.cs +++ b/TelegramBotBase.Test/Tests/Menu.cs @@ -2,12 +2,12 @@ using Telegram.Bot.Types.Enums; using TelegramBotBase.Base; using TelegramBotBase.Enums; +using TelegramBotBase.Example.Tests.Controls; +using TelegramBotBase.Example.Tests.DataSources; +using TelegramBotBase.Example.Tests.Groups; using TelegramBotBase.Form; -using TelegramBotBaseTest.Tests.Controls; -using TelegramBotBaseTest.Tests.DataSources; -using TelegramBotBaseTest.Tests.Groups; -namespace TelegramBotBaseTest.Tests; +namespace TelegramBotBase.Example.Tests; public class Menu : AutoCleanForm { diff --git a/TelegramBotBase.Test/Tests/Navigation/CustomController.cs b/TelegramBotBase.Test/Tests/Navigation/CustomController.cs index 28d7015..4f2a9a2 100644 --- a/TelegramBotBase.Test/Tests/Navigation/CustomController.cs +++ b/TelegramBotBase.Test/Tests/Navigation/CustomController.cs @@ -3,7 +3,7 @@ using System.Threading.Tasks; using TelegramBotBase.Form; using TelegramBotBase.Form.Navigation; -namespace TelegramBotBaseTest.Tests.Navigation; +namespace TelegramBotBase.Example.Tests.Navigation; internal class CustomController : NavigationController { diff --git a/TelegramBotBase.Test/Tests/Navigation/Form1.cs b/TelegramBotBase.Test/Tests/Navigation/Form1.cs index c000fe7..db4641f 100644 --- a/TelegramBotBase.Test/Tests/Navigation/Form1.cs +++ b/TelegramBotBase.Test/Tests/Navigation/Form1.cs @@ -4,7 +4,7 @@ using Telegram.Bot.Types; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Navigation; +namespace TelegramBotBase.Example.Tests.Navigation; public class Form1 : FormBase { diff --git a/TelegramBotBase.Test/Tests/Navigation/Start.cs b/TelegramBotBase.Test/Tests/Navigation/Start.cs index 034a653..cc53b47 100644 --- a/TelegramBotBase.Test/Tests/Navigation/Start.cs +++ b/TelegramBotBase.Test/Tests/Navigation/Start.cs @@ -3,7 +3,7 @@ using Telegram.Bot.Types; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Navigation; +namespace TelegramBotBase.Example.Tests.Navigation; public class Start : FormBase { diff --git a/TelegramBotBase.Test/Tests/Notifications/Start.cs b/TelegramBotBase.Test/Tests/Notifications/Start.cs index a04b770..a95ae74 100644 --- a/TelegramBotBase.Test/Tests/Notifications/Start.cs +++ b/TelegramBotBase.Test/Tests/Notifications/Start.cs @@ -3,7 +3,7 @@ using TelegramBotBase.Base; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Notifications; +namespace TelegramBotBase.Example.Tests.Notifications; public class Start : AutoCleanForm { diff --git a/TelegramBotBase.Test/Tests/ProgressTest.cs b/TelegramBotBase.Test/Tests/ProgressTest.cs index a8dcf70..5fa059d 100644 --- a/TelegramBotBase.Test/Tests/ProgressTest.cs +++ b/TelegramBotBase.Test/Tests/ProgressTest.cs @@ -6,7 +6,7 @@ using TelegramBotBase.Controls.Inline; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests; +namespace TelegramBotBase.Example.Tests; public class ProgressTest : AutoCleanForm { diff --git a/TelegramBotBase.Test/Tests/Register/PerForm.cs b/TelegramBotBase.Test/Tests/Register/PerForm.cs index fde7e05..40ad4bc 100644 --- a/TelegramBotBase.Test/Tests/Register/PerForm.cs +++ b/TelegramBotBase.Test/Tests/Register/PerForm.cs @@ -2,7 +2,7 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Register; +namespace TelegramBotBase.Example.Tests.Register; public class PerForm : AutoCleanForm { diff --git a/TelegramBotBase.Test/Tests/Register/PerStep.cs b/TelegramBotBase.Test/Tests/Register/PerStep.cs index 437dbce..8249ec4 100644 --- a/TelegramBotBase.Test/Tests/Register/PerStep.cs +++ b/TelegramBotBase.Test/Tests/Register/PerStep.cs @@ -1,9 +1,9 @@ using System.Threading.Tasks; using TelegramBotBase.Base; +using TelegramBotBase.Example.Tests.Register.Steps; using TelegramBotBase.Form; -using TelegramBotBaseTest.Tests.Register.Steps; -namespace TelegramBotBaseTest.Tests.Register; +namespace TelegramBotBase.Example.Tests.Register; public class PerStep : AutoCleanForm { diff --git a/TelegramBotBase.Test/Tests/Register/Start.cs b/TelegramBotBase.Test/Tests/Register/Start.cs index 09b3516..8f1071c 100644 --- a/TelegramBotBase.Test/Tests/Register/Start.cs +++ b/TelegramBotBase.Test/Tests/Register/Start.cs @@ -2,7 +2,7 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Register; +namespace TelegramBotBase.Example.Tests.Register; public class Start : AutoCleanForm { diff --git a/TelegramBotBase.Test/Tests/Register/Steps/Data.cs b/TelegramBotBase.Test/Tests/Register/Steps/Data.cs index 63a56ff..af8c471 100644 --- a/TelegramBotBase.Test/Tests/Register/Steps/Data.cs +++ b/TelegramBotBase.Test/Tests/Register/Steps/Data.cs @@ -1,4 +1,4 @@ -namespace TelegramBotBaseTest.Tests.Register.Steps; +namespace TelegramBotBase.Example.Tests.Register.Steps; public class Data { diff --git a/TelegramBotBase.Test/Tests/Register/Steps/Step1.cs b/TelegramBotBase.Test/Tests/Register/Steps/Step1.cs index 3cf1570..13e61b6 100644 --- a/TelegramBotBase.Test/Tests/Register/Steps/Step1.cs +++ b/TelegramBotBase.Test/Tests/Register/Steps/Step1.cs @@ -3,7 +3,7 @@ using TelegramBotBase.Args; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Register.Steps; +namespace TelegramBotBase.Example.Tests.Register.Steps; public class Step1 : AutoCleanForm { diff --git a/TelegramBotBase.Test/Tests/Register/Steps/Step2.cs b/TelegramBotBase.Test/Tests/Register/Steps/Step2.cs index fffd190..c5a0752 100644 --- a/TelegramBotBase.Test/Tests/Register/Steps/Step2.cs +++ b/TelegramBotBase.Test/Tests/Register/Steps/Step2.cs @@ -2,7 +2,7 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Register.Steps; +namespace TelegramBotBase.Example.Tests.Register.Steps; public class Step2 : AutoCleanForm { diff --git a/TelegramBotBase.Test/Tests/Register/Steps/Step3.cs b/TelegramBotBase.Test/Tests/Register/Steps/Step3.cs index 45eaea8..afe5989 100644 --- a/TelegramBotBase.Test/Tests/Register/Steps/Step3.cs +++ b/TelegramBotBase.Test/Tests/Register/Steps/Step3.cs @@ -2,7 +2,7 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Register.Steps; +namespace TelegramBotBase.Example.Tests.Register.Steps; public class Step3 : AutoCleanForm { diff --git a/TelegramBotBase.Test/Tests/SimpleForm.cs b/TelegramBotBase.Test/Tests/SimpleForm.cs index d776936..71669bf 100644 --- a/TelegramBotBase.Test/Tests/SimpleForm.cs +++ b/TelegramBotBase.Test/Tests/SimpleForm.cs @@ -4,7 +4,7 @@ using TelegramBotBase.Base; using TelegramBotBase.Enums; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests; +namespace TelegramBotBase.Example.Tests; public class SimpleForm : AutoCleanForm { diff --git a/TelegramBotBase.Test/Tests/Start.cs b/TelegramBotBase.Test/Tests/Start.cs index bbe1783..08a14d6 100644 --- a/TelegramBotBase.Test/Tests/Start.cs +++ b/TelegramBotBase.Test/Tests/Start.cs @@ -1,9 +1,9 @@ using System.Threading.Tasks; using TelegramBotBase.Base; +using TelegramBotBase.Example.Tests.Groups; using TelegramBotBase.Form; -using TelegramBotBaseTest.Tests.Groups; -namespace TelegramBotBaseTest.Tests; +namespace TelegramBotBase.Example.Tests; public class Start : SplitterForm { diff --git a/TelegramBotBase.Test/Tests/TestForm.cs b/TelegramBotBase.Test/Tests/TestForm.cs index 30cb824..d7d7873 100644 --- a/TelegramBotBase.Test/Tests/TestForm.cs +++ b/TelegramBotBase.Test/Tests/TestForm.cs @@ -3,7 +3,7 @@ using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests; +namespace TelegramBotBase.Example.Tests; public class TestForm : FormBase { diff --git a/TelegramBotBase.Test/Tests/TestForm2.cs b/TelegramBotBase.Test/Tests/TestForm2.cs index 2cff462..161fbcc 100644 --- a/TelegramBotBase.Test/Tests/TestForm2.cs +++ b/TelegramBotBase.Test/Tests/TestForm2.cs @@ -6,7 +6,7 @@ using TelegramBotBase.Base; using TelegramBotBase.Extensions.Images; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests; +namespace TelegramBotBase.Example.Tests; public class TestForm2 : FormBase { diff --git a/TelegramBotBase.Test/packages.config b/TelegramBotBase.Test/packages.config deleted file mode 100644 index f74d058..0000000 --- a/TelegramBotBase.Test/packages.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/TelegramBotFramework.sln b/TelegramBotFramework.sln index 34eec3f..e79a78c 100644 --- a/TelegramBotFramework.sln +++ b/TelegramBotFramework.sln @@ -5,7 +5,7 @@ VisualStudioVersion = 17.0.31912.275 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TelegramBotBase", "TelegramBotBase\TelegramBotBase.csproj", "{0BD16FB9-7ED4-4CCB-83EB-5CEE538E1B6C}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TelegramBotBaseTest", "TelegramBotBase.Test\TelegramBotBaseTest.csproj", "{88EC0E02-583D-4B9D-956C-81D63C8CFCFA}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TelegramBotBase.Example", "TelegramBotBase.Test\TelegramBotBase.Example.csproj", "{88EC0E02-583D-4B9D-956C-81D63C8CFCFA}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{3856B3FB-63E3-444A-9FF0-34171BE7AC5D}" ProjectSection(SolutionItems) = preProject From fb51677429c812b3c52232a6d982703a4e607ba8 Mon Sep 17 00:00:00 2001 From: ZavaruKitsu Date: Sat, 15 Oct 2022 19:01:29 +0300 Subject: [PATCH 11/22] refactor: make properties readonly --- TelegramBotBase/Base/MessageClient.cs | 2 +- TelegramBotBase/BotBase.cs | 24 ++++++++++++----------- TelegramBotBase/Builder/BotBaseBuilder.cs | 23 +++++++++------------- 3 files changed, 23 insertions(+), 26 deletions(-) diff --git a/TelegramBotBase/Base/MessageClient.cs b/TelegramBotBase/Base/MessageClient.cs index 99c45db..db7e27b 100644 --- a/TelegramBotBase/Base/MessageClient.cs +++ b/TelegramBotBase/Base/MessageClient.cs @@ -94,7 +94,7 @@ public class MessageClient } - public string ApiKey { get; set; } + public string ApiKey { get; } public ITelegramBotClient TelegramClient { get; set; } diff --git a/TelegramBotBase/BotBase.cs b/TelegramBotBase/BotBase.cs index 14fe7ba..05f8053 100644 --- a/TelegramBotBase/BotBase.cs +++ b/TelegramBotBase/BotBase.cs @@ -15,13 +15,16 @@ using Console = TelegramBotBase.Tools.Console; namespace TelegramBotBase; /// -/// Bot base class for full Device/Context and Messagehandling +/// Bot base class for full Device/Context and message handling /// /// public sealed class BotBase { - internal BotBase() + internal BotBase(string apiKey, MessageClient client) { + ApiKey = apiKey; + Client = client; + SystemSettings = new Dictionary(); SetSetting(ESettings.MaxNumberOfRetries, 5); @@ -35,38 +38,38 @@ public sealed class BotBase Sessions = new SessionManager(this); } - public MessageClient Client { get; set; } + public MessageClient Client { get; } /// /// Your TelegramBot APIKey /// - public string ApiKey { get; set; } = ""; + public string ApiKey { get; } /// /// List of all running/active sessions /// - public SessionManager Sessions { get; set; } + public SessionManager Sessions { get; } /// /// Contains System commands which will be available at everytime and didnt get passed to forms, i.e. /start /// - public Dictionary> BotCommandScopes { get; set; } = new(); + public Dictionary> BotCommandScopes { get; internal set; } /// /// Enable the SessionState (you need to implement on call forms the IStateForm interface) /// - public IStateMachine StateMachine { get; set; } + public IStateMachine StateMachine { get; internal set; } /// /// Offers functionality to manage the creation process of the start form. /// - public IStartFormFactory StartFormFactory { get; set; } + public IStartFormFactory StartFormFactory { get; internal set; } /// /// Contains the message loop factory, which cares about "message-management." /// - public IMessageLoopFactory MessageLoopFactory { get; set; } + public IMessageLoopFactory MessageLoopFactory { get; internal set; } /// /// All internal used settings. @@ -210,7 +213,6 @@ public sealed class BotBase e.Device = ds; await MessageLoopFactory.MessageLoop(this, ds, new UpdateResult(e.UpdateData, ds), e); - //await Client_Loop(this, e); } catch (Exception ex) { @@ -315,7 +317,7 @@ public sealed class BotBase return defaultValue; } - return SystemSettings[set] == 0u ? false : true; + return SystemSettings[set] != 0u; } diff --git a/TelegramBotBase/Builder/BotBaseBuilder.cs b/TelegramBotBase/Builder/BotBaseBuilder.cs index f73e27d..dc22976 100644 --- a/TelegramBotBase/Builder/BotBaseBuilder.cs +++ b/TelegramBotBase/Builder/BotBaseBuilder.cs @@ -27,7 +27,7 @@ public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, private IMessageLoopFactory _messageLoopFactory; - private IStateMachine _statemachine; + private IStateMachine _stateMachine; private BotBaseBuilder() { @@ -41,19 +41,14 @@ public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, public BotBase Build() { - var bot = new BotBase + var bot = new BotBase(_apiKey, _client) { - ApiKey = _apiKey, StartFormFactory = _factory, - Client = _client + BotCommandScopes = BotCommandScopes, + StateMachine = _stateMachine, + MessageLoopFactory = _messageLoopFactory }; - bot.BotCommandScopes = BotCommandScopes; - - bot.StateMachine = _statemachine; - - bot.MessageLoopFactory = _messageLoopFactory; - bot.MessageLoopFactory.UnhandledCall += bot.MessageLoopFactory_UnhandledCall; return bot; @@ -315,26 +310,26 @@ public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, public ILanguageSelectionStage UseSerialization(IStateMachine machine) { - _statemachine = machine; + _stateMachine = machine; return this; } public ILanguageSelectionStage UseJSON(string path) { - _statemachine = new JsonStateMachine(path); + _stateMachine = new JsonStateMachine(path); return this; } public ILanguageSelectionStage UseSimpleJSON(string path) { - _statemachine = new SimpleJsonStateMachine(path); + _stateMachine = new SimpleJsonStateMachine(path); return this; } public ILanguageSelectionStage UseXML(string path) { - _statemachine = new XmlStateMachine(path); + _stateMachine = new XmlStateMachine(path); return this; } From 9400cfc74ef88cfa0af0bead03cd124a96a81515 Mon Sep 17 00:00:00 2001 From: ZavaruKitsu Date: Sat, 15 Oct 2022 21:59:12 +0300 Subject: [PATCH 12/22] refactor: rename MaxLengthException & fix naming --- .../DataSources/ButtonFormDataSource.cs | 10 +++++----- TelegramBotBase/Exceptions/MaxLengthException.cs | 11 ----------- .../Exceptions/MaximumColsException.cs | 8 +++----- .../Exceptions/MaximumRowsException.cs | 6 +++--- .../Exceptions/MessageTooLongException.cs | 16 ++++++++++++++++ TelegramBotBase/Sessions/DeviceSession.cs | 12 ++++++------ 6 files changed, 33 insertions(+), 30 deletions(-) delete mode 100644 TelegramBotBase/Exceptions/MaxLengthException.cs create mode 100644 TelegramBotBase/Exceptions/MessageTooLongException.cs diff --git a/TelegramBotBase/DataSources/ButtonFormDataSource.cs b/TelegramBotBase/DataSources/ButtonFormDataSource.cs index e91668c..c92a55a 100644 --- a/TelegramBotBase/DataSources/ButtonFormDataSource.cs +++ b/TelegramBotBase/DataSources/ButtonFormDataSource.cs @@ -8,22 +8,22 @@ namespace TelegramBotBase.DataSources; public class ButtonFormDataSource : IDataSource { - private ButtonForm _buttonform; + private ButtonForm _buttonForm; public ButtonFormDataSource() { - _buttonform = new ButtonForm(); + _buttonForm = new ButtonForm(); } public ButtonFormDataSource(ButtonForm bf) { - _buttonform = bf; + _buttonForm = bf; } public virtual ButtonForm ButtonForm { - get => _buttonform; - set => _buttonform = value; + get => _buttonForm; + set => _buttonForm = value; } diff --git a/TelegramBotBase/Exceptions/MaxLengthException.cs b/TelegramBotBase/Exceptions/MaxLengthException.cs deleted file mode 100644 index 2e93214..0000000 --- a/TelegramBotBase/Exceptions/MaxLengthException.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; - -namespace TelegramBotBase.Exceptions; - -public class MaxLengthException : Exception -{ - public MaxLengthException(int length) : base( - $"Your messages with a length of {length} is too long for telegram. Actually is {Constants.Telegram.MaxMessageLength} characters allowed. Please split it.") - { - } -} \ No newline at end of file diff --git a/TelegramBotBase/Exceptions/MaximumColsException.cs b/TelegramBotBase/Exceptions/MaximumColsException.cs index 4209353..781ab40 100644 --- a/TelegramBotBase/Exceptions/MaximumColsException.cs +++ b/TelegramBotBase/Exceptions/MaximumColsException.cs @@ -2,13 +2,11 @@ namespace TelegramBotBase.Exceptions; -public class MaximumColsException : Exception +public sealed class MaximumColsException : Exception { public int Value { get; set; } - public int Maximum { get; set; } - public override string Message => - $"You have exceeded the maximum of columns by {Value.ToString()} / {Maximum.ToString()}"; -} \ No newline at end of file + $"You have exceeded the maximum of columns by {Value}/{Maximum}"; +} diff --git a/TelegramBotBase/Exceptions/MaximumRowsException.cs b/TelegramBotBase/Exceptions/MaximumRowsException.cs index be3ad7d..9b1beb8 100644 --- a/TelegramBotBase/Exceptions/MaximumRowsException.cs +++ b/TelegramBotBase/Exceptions/MaximumRowsException.cs @@ -2,7 +2,7 @@ namespace TelegramBotBase.Exceptions; -public class MaximumRowsReachedException : Exception +public sealed class MaximumRowsReachedException : Exception { public int Value { get; set; } @@ -10,5 +10,5 @@ public class MaximumRowsReachedException : Exception public override string Message => - $"You have exceeded the maximum of rows by {Value.ToString()} / {Maximum.ToString()}"; -} \ No newline at end of file + $"You have exceeded the maximum of rows by {Value}/{Maximum}"; +} diff --git a/TelegramBotBase/Exceptions/MessageTooLongException.cs b/TelegramBotBase/Exceptions/MessageTooLongException.cs new file mode 100644 index 0000000..44626db --- /dev/null +++ b/TelegramBotBase/Exceptions/MessageTooLongException.cs @@ -0,0 +1,16 @@ +using System; + +namespace TelegramBotBase.Exceptions; + +public sealed class MessageTooLongException : Exception +{ + public MessageTooLongException(int length) + { + Length = length; + } + + public int Length { get; set; } + + public override string Message => + $"You have exceeded the maximum of message length by {Length}/{Constants.Telegram.MaxMessageLength}"; +} diff --git a/TelegramBotBase/Sessions/DeviceSession.cs b/TelegramBotBase/Sessions/DeviceSession.cs index 5da18ab..f823c59 100644 --- a/TelegramBotBase/Sessions/DeviceSession.cs +++ b/TelegramBotBase/Sessions/DeviceSession.cs @@ -155,7 +155,7 @@ public class DeviceSession : IDeviceSession if (text.Length > Constants.Telegram.MaxMessageLength) { - throw new MaxLengthException(text.Length); + throw new MessageTooLongException(text.Length); } try @@ -183,7 +183,7 @@ public class DeviceSession : IDeviceSession { if (text.Length > Constants.Telegram.MaxMessageLength) { - throw new MaxLengthException(text.Length); + throw new MessageTooLongException(text.Length); } try @@ -213,7 +213,7 @@ public class DeviceSession : IDeviceSession if (message.Text.Length > Constants.Telegram.MaxMessageLength) { - throw new MaxLengthException(message.Text.Length); + throw new MessageTooLongException(message.Text.Length); } try @@ -270,7 +270,7 @@ public class DeviceSession : IDeviceSession if (text.Length > Constants.Telegram.MaxMessageLength) { - throw new MaxLengthException(text.Length); + throw new MessageTooLongException(text.Length); } if (parseMode == ParseMode.MarkdownV2 && markdownV2AutoEscape) @@ -329,7 +329,7 @@ public class DeviceSession : IDeviceSession if (text.Length > Constants.Telegram.MaxMessageLength) { - throw new MaxLengthException(text.Length); + throw new MessageTooLongException(text.Length); } if (parseMode == ParseMode.MarkdownV2 && markdownV2AutoEscape) @@ -372,7 +372,7 @@ public class DeviceSession : IDeviceSession if (text.Length > Constants.Telegram.MaxMessageLength) { - throw new MaxLengthException(text.Length); + throw new MessageTooLongException(text.Length); } if (parseMode == ParseMode.MarkdownV2 && markdownV2AutoEscape) From c86ce7a9e04a1aea948806eb293f62738c817cee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexei=20Ag=C3=BCero=20Alba?= Date: Thu, 1 Dec 2022 09:45:43 -0500 Subject: [PATCH 13/22] Call Serialize implicitly when assigning to a string --- TelegramBotBase/Form/CallbackData.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/TelegramBotBase/Form/CallbackData.cs b/TelegramBotBase/Form/CallbackData.cs index 3b50e31..c36bc01 100644 --- a/TelegramBotBase/Form/CallbackData.cs +++ b/TelegramBotBase/Form/CallbackData.cs @@ -77,6 +77,7 @@ namespace TelegramBotBase.Form return null; } - + + public static implicit operator string(CallbackData callbackData) => callbackData.Serialize(); } } From 138199e8114e55cafeefefe57afd4e6153412574 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexei=20Ag=C3=BCero=20Alba?= Date: Mon, 5 Dec 2022 17:12:53 -0500 Subject: [PATCH 14/22] Correctly implement Dispose pattern in FormBase for use on derived classes --- TelegramBotBase/Base/FormBase.cs | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/TelegramBotBase/Base/FormBase.cs b/TelegramBotBase/Base/FormBase.cs index 291e733..d3c2cba 100644 --- a/TelegramBotBase/Base/FormBase.cs +++ b/TelegramBotBase/Base/FormBase.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.ComponentModel; using System.Linq; -using System.Text; using System.Threading.Tasks; using TelegramBotBase.Args; using TelegramBotBase.Base; @@ -17,7 +16,6 @@ namespace TelegramBotBase.Form /// public class FormBase : IDisposable { - public NavigationController NavigationController { get; set; } public DeviceSession Device { get; set; } @@ -432,14 +430,29 @@ namespace TelegramBotBase.Form } } + protected virtual void Dispose(bool disposing) + { + if (this.IsDisposed) + { + return; + } + + if (disposing) + { + this.Client = null; + this.Device = null; + } + + this.IsDisposed = true; + } + /// /// Cleanup /// public void Dispose() { - this.Client = null; - this.Device = null; - this.IsDisposed = true; + Dispose(true); + GC.SuppressFinalize(this); } } } From e12e21845fdc98a4c578ad06041ba881d2365732 Mon Sep 17 00:00:00 2001 From: ZavaruKitsu Date: Wed, 4 Jan 2023 16:04:36 +0300 Subject: [PATCH 15/22] docs(readme): improve grammar --- README.md | 45 +++++++++++++++++++++++---------------------- 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index f4d0fb1..01b4cf0 100644 --- a/README.md +++ b/README.md @@ -108,9 +108,11 @@ The `BotBase` class will manage a lot of things for you, like bot commands, acti `StartForm` is your first form which every user will get internally redirected to, *just like a start page*. It needs to be a subclass of `FormBase` you will find in namespace `TelegramBotBase.Base` -Every `Form` has some events which will get raised at specific times. On every form you are able to get notes about +Every `Form` has some events which will get raised at specific times. +In every form, you are able to get notes about the *Remote Device*, -like ChatId and other stuff your carrying. From there you build up your bots: +like ChatId and other stuff your carrying. +From there you build up your bots: ```csharp public class StartForm : FormBase @@ -182,7 +184,7 @@ await bot.Start(); ### System calls & bot commands Using BotFather you can add *Commands* to your bot. The user will see them as popups in a dialog. -Before start (and later for sure) you could add them to your BotBase. +Before starting (and later, for sure), you could add them to your BotBase. If the message contains a command, a special *event handler* will get raised. Below we have 4 commands. @@ -357,7 +359,7 @@ public class ButtonTestForm : AutoCleanForm ### Custom controls -There are a bunch of ready to use controls. For example, progress bar. +There is a bunch of ready to use controls. For example, progress bar. @@ -552,7 +554,7 @@ public class PerForm : AutoCleanForm } ``` -[Another case](TelegramBotBase.Test/Tests/Register/PerStep.cs), where every of these 3 inputs gets requested by a +[Another case](TelegramBotBase.Test/Tests/Register/PerStep.cs), where every of these 3 inputs gets requested by different forms. Just for imagination of the possibilities. @@ -594,7 +596,7 @@ await this.NavigateTo(ad); ### AutoCleanForm -Just try it by youself. +Just try it by yourself. ### Prompt Dialog @@ -679,7 +681,7 @@ await this.NavigateTo(cd); ## Groups -For groups, there are multiple different tools which helps to work with and allows bot also to manage +For groups, there are multiple different tools which help to work with and allows bot also to manage "Single-User" chats and group chats. ### Splitter Form @@ -780,9 +782,9 @@ public class GroupForm : FormBase ## Statemachine and Sessions -Depending on the use-cases and the overall structure of a Telegram Bot it is essential to have some kind of session +Depending on the use-cases and the overall structure of a Telegram Bot, it is essential to have some kind of session serialization or state machine to keep the user context after bot restarts (i.e. due to updates) or crashes. -For this we have some structures which fits into the current environment. +For this, we have some structures which fit into the current environment. ### Statemachines @@ -813,8 +815,8 @@ await bot.Start(); #### JSONStateMachine -Is easy to use too, but works for complex datatypes, because it saves there namespaces and additional type info -into the JSON file too. +It is easy to use too, but it works for complex datatypes, because it saves their namespaces and additional type info +into the JSON file. ```csharp var bot = BotBaseBuilder @@ -836,7 +838,7 @@ await bot.Start(); #### XMLStateMachine -The last one, should work like the others. +The last one should work like the others. ```csharp var bot = BotBaseBuilder @@ -898,7 +900,7 @@ keep and restore, use the following attributes. #### SaveState -This will let the engine know, that you want too keep and restore this field automatically. Unlike the IStateForm +This will let the engine know that you want to keep and restore this field automatically. Unlike the IStateForm methods, you have no option to manipulate data. ```csharp @@ -908,9 +910,9 @@ public long UserId { get; set; } #### IgnoreState -Due to the fact that Attribute implementation and interaction is optional, you want to let the engine maybe know, that +Due to the fact that Attribute implementation and interaction is optional, you want to let the engine maybe know that you don't want to keep a specific form. So it should get *lost*. This attribute will help you here, add it to the form -class and it will not get serialized, even if it implements IStateForm or the SaveState attributes. +class, and it will not get serialized, even if it implements IStateForm or the SaveState attributes. ```csharp [IgnoreState] @@ -931,21 +933,20 @@ var f = new FormBase(); await this.NavigateTo(f); ``` -Depending on the model and structure of your bot it can make sense, to have more linear navigation instead of *cross* -navigation. +Depending on the model and structure of your bot, it can make sense, to have more linear navigation instead of *cross*-navigation. -For example, you have a bot which shows a list of football teams. And when clicking on it you want to open the team -details and latest matches. +For example, you have a bot which shows a list of football teams. And when clicking on it, you want to open the team +details and the latest matches. After the matches, you want to maybe switch to different teams and take a look at their statistics and matches. -At some point, you *just* want to get back to the first team so like on Android you're clicking the "back" button +At some point, you *just* want to get back to the first team, so like on Android you're clicking the "back" button multiple times. This can become really complicated, when not having some controller below which handle these "Push/Pop" calls. -Thats why we hace a NavigationController class which manages these situations and the stack. +That's why we have a NavigationController class which manages these situations and the stack. ### Usage @@ -955,7 +956,7 @@ navigation. You will use the current FormBase instance as a root class within the constructor, so you can later come back to this one. -**Tip**: *You can add also a completely new instance of i.e. a main menu form here to get back to it then. So you are +**Tip**: *You can also add a completely new instance of i.e. a main menu form here to get back to it then. So you are free to choose.* We are using the same `FormBase` instance as above. From 6343a8a719b094cf188df736d7e33c1fcf273bf4 Mon Sep 17 00:00:00 2001 From: Palash Jhabak Date: Sat, 21 Jan 2023 09:47:28 +0530 Subject: [PATCH 16/22] Add Web App Inline Keyboard Button --- TelegramBotBase/Form/WebAppButtonBase.cs | 48 ++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 TelegramBotBase/Form/WebAppButtonBase.cs diff --git a/TelegramBotBase/Form/WebAppButtonBase.cs b/TelegramBotBase/Form/WebAppButtonBase.cs new file mode 100644 index 0000000..7bd0de1 --- /dev/null +++ b/TelegramBotBase/Form/WebAppButtonBase.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Telegram.Bot.Types; +using Telegram.Bot.Types.ReplyMarkups; + +namespace TelegramBotBase.Form +{ + public class WebAppButtonBase : ButtonBase + { + public WebAppInfo WebAppInfo { get; set; } + + public WebAppButtonBase() + { + + } + + public WebAppButtonBase(String Text, WebAppInfo WebAppInfo) + { + this.Text = Text; + this.WebAppInfo = WebAppInfo; + } + + /// + /// Returns an inline Button + /// + /// + /// + public override InlineKeyboardButton ToInlineButton(ButtonForm form) + { + return InlineKeyboardButton.WithWebApp(this.Text, this.WebAppInfo); + } + + + /// + /// Returns a KeyBoardButton + /// + /// + /// + public override KeyboardButton ToKeyboardButton(ButtonForm form) + { + return KeyboardButton.WithWebApp(this.Text, this.WebAppInfo); + } + + } +} From c0e67d626242ee9a2011fe32e7b349df1243ef1e Mon Sep 17 00:00:00 2001 From: FlorianDahn Date: Fri, 27 Jan 2023 20:11:45 +0100 Subject: [PATCH 17/22] Fixing AutoCleanForm and NavigationController - AutoCleanForm does not work properly inside a NavigationController (Some messages wont get deleted) --- TelegramBotBase/Form/Navigation/NavigationController.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/TelegramBotBase/Form/Navigation/NavigationController.cs b/TelegramBotBase/Form/Navigation/NavigationController.cs index d1858b9..3f4c927 100644 --- a/TelegramBotBase/Form/Navigation/NavigationController.cs +++ b/TelegramBotBase/Form/Navigation/NavigationController.cs @@ -134,6 +134,9 @@ namespace TelegramBotBase.Form.Navigation /// public virtual async Task PushAsync(FormBase form, params object[] args) { + //Leave current form (needed for AutoCleanForm to work properly) + await CurrentForm.OnClosed(new EventArgs()); + form.Client = this.Client; form.Device = this.Device; form.NavigationController = this; From cd752759508378d84e40a9d5f6acdc64d82e39fa Mon Sep 17 00:00:00 2001 From: FlorianDahn Date: Sun, 4 Jun 2023 16:49:15 +0200 Subject: [PATCH 18/22] Fix in example project --- TelegramBotBase.Test/Tests/TestForm2.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/TelegramBotBase.Test/Tests/TestForm2.cs b/TelegramBotBase.Test/Tests/TestForm2.cs index 161fbcc..302a953 100644 --- a/TelegramBotBase.Test/Tests/TestForm2.cs +++ b/TelegramBotBase.Test/Tests/TestForm2.cs @@ -53,7 +53,7 @@ public class TestForm2 : FormBase await NavigateTo(fto); }; - await NavigateTo(ad); + await OpenModal(ad); } else if (call.Value == "confirm") { @@ -67,7 +67,7 @@ public class TestForm2 : FormBase await pd.NavigateTo(tf); }; - await NavigateTo(pd); + await OpenModal(pd); } else if (call.Value == "prompt") { From 6ae92b0b29c2e0c62800cff1d8e1ac9a99224140 Mon Sep 17 00:00:00 2001 From: FlorianDahn Date: Sun, 4 Jun 2023 17:15:30 +0200 Subject: [PATCH 19/22] Bugfix for TaggedButtonGrid in combination with AutoCleanForm --- TelegramBotBase/Base/FormBase.cs | 6 ++++++ TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/TelegramBotBase/Base/FormBase.cs b/TelegramBotBase/Base/FormBase.cs index 7557348..4b22b1c 100644 --- a/TelegramBotBase/Base/FormBase.cs +++ b/TelegramBotBase/Base/FormBase.cs @@ -447,4 +447,10 @@ public class FormBase : IDisposable Controls.Remove(c); } } + + /// + /// Returns if this instance is a subclass of AutoCleanForm. Necessary to prevent message deletion if not necessary. + /// + public bool IsAutoCleanForm() => this.GetType().IsSubclassOf(typeof(AutoCleanForm)); + } \ No newline at end of file diff --git a/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs b/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs index c12aced..9db6a87 100644 --- a/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs +++ b/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs @@ -455,7 +455,7 @@ public class TaggedButtonGrid : MultiView if (result.MessageText == "📁") { //Remove button click message - if (DeletePreviousMessage) + if (DeletePreviousMessage && !Device.ActiveForm.IsAutoCleanForm()) { await Device.DeleteMessage(result.MessageId); } From 54513c021410264b7602c2006a91ebaa0180a381 Mon Sep 17 00:00:00 2001 From: FlorianDahn Date: Sun, 4 Jun 2023 17:17:15 +0200 Subject: [PATCH 20/22] Moving TaggedButtonGrid icons into localization file --- TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs | 12 ++++++++---- TelegramBotBase/Localizations/English.cs | 5 +++-- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs b/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs index 9db6a87..7fac716 100644 --- a/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs +++ b/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs @@ -41,6 +41,10 @@ public class TaggedButtonGrid : MultiView public string UncheckAllLabel = Default.Language["ButtonGrid_UncheckAll"]; + public string SearchIcon = Default.Language["ButtonGrid_SearchIcon"]; + + public string TagIcon = Default.Language["ButtonGrid_TagIcon"]; + public TaggedButtonGrid() { DataSource = new ButtonFormDataSource(); @@ -427,7 +431,7 @@ public class TaggedButtonGrid : MultiView } else if (EnableSearch) { - if (result.MessageText.StartsWith("🔍")) + if (result.MessageText.StartsWith(SearchIcon)) { //Sent note about searching if (SearchQuery == null) @@ -452,7 +456,7 @@ public class TaggedButtonGrid : MultiView } else if (Tags != null) { - if (result.MessageText == "📁") + if (result.MessageText == TagIcon) { //Remove button click message if (DeletePreviousMessage && !Device.ActiveForm.IsAutoCleanForm()) @@ -993,14 +997,14 @@ public class TaggedButtonGrid : MultiView if (Tags != null && Tags.Count > 0) { - row.Add(new ButtonBase("📁", "$filter$")); + row.Add(new ButtonBase(TagIcon, "$filter$")); } row.Add(new ButtonBase(NextPageLabel, "$next$")); if (EnableSearch) { - row.Insert(2, new ButtonBase("🔍 " + (SearchQuery ?? ""), "$search$")); + row.Insert(2, new ButtonBase($"{SearchIcon} {(SearchQuery ?? "")}", "$search$")); } dataForm.InsertButtonRow(0, row); diff --git a/TelegramBotBase/Localizations/English.cs b/TelegramBotBase/Localizations/English.cs index 5a7c362..51881b1 100644 --- a/TelegramBotBase/Localizations/English.cs +++ b/TelegramBotBase/Localizations/English.cs @@ -10,8 +10,7 @@ public class English : Localization Values["ButtonGrid_PreviousPage"] = "◀️"; Values["ButtonGrid_NextPage"] = "▶️"; Values["ButtonGrid_CurrentPage"] = "Page {0} of {1}"; - Values["ButtonGrid_SearchFeature"] = - "💡 Send a message to filter the list. Click the 🔍 to reset the filter."; + Values["ButtonGrid_SearchFeature"] = "💡 Send a message to filter the list. Click the 🔍 to reset the filter."; Values["ButtonGrid_Back"] = "Back"; Values["ButtonGrid_CheckAll"] = "Check all"; Values["ButtonGrid_UncheckAll"] = "Uncheck all"; @@ -31,5 +30,7 @@ public class English : Localization Values["MultiToggleButton_Changed"] = "Chosen"; Values["PromptDialog_Back"] = "Back"; Values["ToggleButton_Changed"] = "Setting changed"; + Values["ButtonGrid_SearchIcon"] = "🔍"; + Values["ButtonGrid_TagIcon"] = "📁"; } } From c463878bb4cbd7aa3d67923efed1cf677ae8eaaa Mon Sep 17 00:00:00 2001 From: FlorianDahn Date: Sun, 4 Jun 2023 17:17:32 +0200 Subject: [PATCH 21/22] Bugfix TaggedButtonGrid max page calculation --- TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs b/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs index 7fac716..c2fec7e 100644 --- a/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs +++ b/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs @@ -277,10 +277,10 @@ public class TaggedButtonGrid : MultiView var max = DataSource.CalculateMax(EnableSearch ? SearchQuery : null); - //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") - //{ - // bf = bf.FilterDuplicate(this.SearchQuery); - //} + if(SelectedTags.Count < Tags.Count) + { + max = DataSource.ButtonForm.TagDuplicate(SelectedTags).Count; + } if (max == 0) { From da8a2f630b6bf62c2f0afc635fe4135cf8d6b3bc Mon Sep 17 00:00:00 2001 From: FlorianDahn Date: Sun, 4 Jun 2023 17:59:55 +0200 Subject: [PATCH 22/22] Switching MessageId property from private to public #42 --- TelegramBotBase/Controls/Inline/CalendarPicker.cs | 2 +- TelegramBotBase/Controls/Inline/TreeView.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/TelegramBotBase/Controls/Inline/CalendarPicker.cs b/TelegramBotBase/Controls/Inline/CalendarPicker.cs index 4420cc1..07d6e96 100644 --- a/TelegramBotBase/Controls/Inline/CalendarPicker.cs +++ b/TelegramBotBase/Controls/Inline/CalendarPicker.cs @@ -36,7 +36,7 @@ public class CalendarPicker : ControlBase public CultureInfo Culture { get; set; } - private int? MessageId { get; set; } + public int? MessageId { get; set; } public string Title { get; set; } = Default.Language["CalendarPicker_Title"]; diff --git a/TelegramBotBase/Controls/Inline/TreeView.cs b/TelegramBotBase/Controls/Inline/TreeView.cs index 1aee568..0299d6d 100644 --- a/TelegramBotBase/Controls/Inline/TreeView.cs +++ b/TelegramBotBase/Controls/Inline/TreeView.cs @@ -23,7 +23,7 @@ public class TreeView : ControlBase public string Title { get; set; } - private int? MessageId { get; set; } + public int? MessageId { get; set; } public string MoveUpIcon { get; set; } = Default.Language["TreeView_LevelUp"];