diff --git a/Examples/AsyncFormUpdates/App.config b/Examples/AsyncFormUpdates/App.config deleted file mode 100644 index 8ffc026..0000000 --- a/Examples/AsyncFormUpdates/App.config +++ /dev/null @@ -1,378 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj b/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj index 579f062..5e6ad70 100644 --- a/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj +++ b/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj @@ -1,74 +1,14 @@ - - - - - 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 + + + + Exe + net6.0 + enable + disable + + + + + + + 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 b12cb83..cc7404d 100644 --- a/Examples/AsyncFormUpdates/Program.cs +++ b/Examples/AsyncFormUpdates/Program.cs @@ -1,51 +1,47 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Timers; +using System.Timers; +using AsyncFormUpdates.Forms; +using TelegramBotBase; using TelegramBotBase.Builder; +using Timer = System.Timers.Timer; -namespace AsyncFormUpdates +namespace AsyncFormUpdates; + +internal class Program { - class Program + private static BotBase __bot; + + private static async Task Main(string[] args) { - static TelegramBotBase.BotBase bot = null; + __bot = BotBaseBuilder.Create() + .QuickStart(Environment.GetEnvironmentVariable("API_KEY") ?? + throw new Exception("API_KEY is not set")) + .Build(); - static void 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) { - String apiKey = "APIKey"; - - bot = BotBaseBuilder.Create() - .QuickStart(apiKey) - .Build(); - - bot.Start(); - - var timer = new Timer(5000); - - timer.Elapsed += Timer_Elapsed; - timer.Start(); - - Console.ReadLine(); - - timer.Stop(); - 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(forms.AsyncFormUpdate) && s.Value.ActiveForm.GetType() != typeof(forms.AsyncFormEdit)) - continue; - - await bot.InvokeMessageLoop(s.Key); + continue; } - + await __bot.InvokeMessageLoop(s.Key); } } } diff --git a/Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs b/Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs deleted file mode 100644 index 216bef4..0000000 --- a/Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -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")] diff --git a/Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs b/Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs deleted file mode 100644 index 1e176d7..0000000 --- a/Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using TelegramBotBase.Attributes; -using TelegramBotBase.Base; -using TelegramBotBase.Form; - -namespace AsyncFormUpdates.forms -{ - public class AsyncFormEdit : FormBase - { - [SaveState] - int counter = 0; - - int MessageId = 0; - - public override async Task Load(MessageResult message) - { - counter++; - } - - 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 deleted file mode 100644 index 4a4b4c7..0000000 --- a/Examples/AsyncFormUpdates/forms/AsyncFormUpdate.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using TelegramBotBase.Attributes; -using TelegramBotBase.Base; -using TelegramBotBase.Form; - -namespace AsyncFormUpdates.forms -{ - public class AsyncFormUpdate : AutoCleanForm - { - [SaveState] - int counter = 0; - - - public override async Task Load(MessageResult message) - { - counter++; - } - - 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 deleted file mode 100644 index c69fa4a..0000000 --- a/Examples/AsyncFormUpdates/forms/Start.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -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); - } - - } -} 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..37f5587 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 bot.Start(); await Task.Delay(-1); diff --git a/Examples/JoinHiderBot/Forms/GroupManageForm.cs b/Examples/JoinHiderBot/Forms/GroupManageForm.cs new file mode 100644 index 0000000..5d3915e --- /dev/null +++ b/Examples/JoinHiderBot/Forms/GroupManageForm.cs @@ -0,0 +1,21 @@ +using Telegram.Bot.Types.Enums; +using TelegramBotBase.Args; +using TelegramBotBase.Form; + +namespace JoinHiderBot.Forms; + +public class GroupManageForm : GroupForm +{ + public override async Task OnMemberChanges(MemberChangeEventArgs e) + { + if (e.Type != MessageType.ChatMembersAdded && e.Type != MessageType.ChatMemberLeft) + { + return; + } + + + var m = e.Result.Message; + + await Device.DeleteMessage(m); + } +} diff --git a/Examples/JoinHiderBot/Forms/Start.cs b/Examples/JoinHiderBot/Forms/Start.cs new file mode 100644 index 0000000..c94b60a --- /dev/null +++ b/Examples/JoinHiderBot/Forms/Start.cs @@ -0,0 +1,23 @@ +using TelegramBotBase.Base; +using TelegramBotBase.Form; + +namespace JoinHiderBot.Forms; + +public class Start : SplitterForm +{ + 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; + } +} \ No newline at end of file diff --git a/Examples/JoinHiderBot/JoinHiderBot.csproj b/Examples/JoinHiderBot/JoinHiderBot.csproj index aa8f8d7..5e6ad70 100644 --- a/Examples/JoinHiderBot/JoinHiderBot.csproj +++ b/Examples/JoinHiderBot/JoinHiderBot.csproj @@ -1,12 +1,14 @@  - - Exe - net6.0 - + + Exe + net6.0 + enable + disable + - - - + + + diff --git a/Examples/JoinHiderBot/Program.cs b/Examples/JoinHiderBot/Program.cs index d2d05fe..054c761 100644 --- a/Examples/JoinHiderBot/Program.cs +++ b/Examples/JoinHiderBot/Program.cs @@ -1,22 +1,19 @@ -using System; +using JoinHiderBot.Forms; using TelegramBotBase.Builder; -namespace JoinHiderBot +namespace JoinHiderBot; + +internal class Program { - class Program + private static async Task Main(string[] args) { - static void Main(string[] args) - { + var bot = BotBaseBuilder.Create() + .QuickStart(Environment.GetEnvironmentVariable("API_KEY") ?? + throw new Exception("API_KEY is not set")) + .Build(); - String apiKey = ""; + await bot.Start(); - var bot = BotBaseBuilder.Create() - .QuickStart(apiKey) - .Build(); - - bot.Start(); - - Console.ReadLine(); - } + Console.ReadLine(); } } diff --git a/Examples/JoinHiderBot/forms/GroupManageForm.cs b/Examples/JoinHiderBot/forms/GroupManageForm.cs deleted file mode 100644 index 3e6cc2a..0000000 --- a/Examples/JoinHiderBot/forms/GroupManageForm.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using TelegramBotBase.Args; -using TelegramBotBase.Form; - -namespace JoinHiderBot.forms -{ - public class GroupManageForm : GroupForm - { - - public override async Task OnMemberChanges(MemberChangeEventArgs e) - { - if (e.Type != Telegram.Bot.Types.Enums.MessageType.ChatMembersAdded && e.Type != Telegram.Bot.Types.Enums.MessageType.ChatMemberLeft) - return; - - - var m = e.Result.Message; - - await this.Device.DeleteMessage(m); - } - - } -} diff --git a/Examples/JoinHiderBot/forms/Start.cs b/Examples/JoinHiderBot/forms/Start.cs deleted file mode 100644 index aef4c7d..0000000 --- a/Examples/JoinHiderBot/forms/Start.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using TelegramBotBase.Base; -using TelegramBotBase.Form; - -namespace JoinHiderBot.forms -{ - public class Start : SplitterForm - { - public override async Task Open(MessageResult e) - { - await this.Device.Send("This bot works only in groups."); - - return true; - } - - public override async Task OpenGroup(MessageResult e) - { - var gmf = new GroupManageForm(); - - await this.NavigateTo(gmf); - - return true; - } - - } -} diff --git a/Examples/SystemCommandsBot/Command.cs b/Examples/SystemCommandsBot/Command.cs new file mode 100644 index 0000000..cd58074 --- /dev/null +++ b/Examples/SystemCommandsBot/Command.cs @@ -0,0 +1,21 @@ +namespace SystemCommandsBot; + +public class Command +{ + public int Id { get; set; } + + public string Title { get; set; } + + public string ShellCmd { get; set; } + + public bool Enabled { get; set; } = true; + + public string Action { get; set; } + + public bool UseShell { get; set; } = true; + + + public int? MaxInstances { get; set; } + + public string ProcName { get; set; } +} diff --git a/Examples/SystemCommandsBot/Config.cs b/Examples/SystemCommandsBot/Config.cs new file mode 100644 index 0000000..3a74502 --- /dev/null +++ b/Examples/SystemCommandsBot/Config.cs @@ -0,0 +1,90 @@ +using Newtonsoft.Json; + +namespace SystemCommandsBot; + +public class Config +{ + public Config() + { + Commands = new List(); + } + + public string Password { get; set; } + + public string ApiKey { get; set; } + + public List Commands { get; set; } + + public void LoadDefaultValues() + { + ApiKey = ""; + Commands.Add(new Command + { + 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); + } + + return null; + } + + + public static Config Load(string path) + { + 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 + { + } + } +} diff --git a/Examples/SystemCommandsBot/Forms/CmdForm.cs b/Examples/SystemCommandsBot/Forms/CmdForm.cs new file mode 100644 index 0000000..58a0674 --- /dev/null +++ b/Examples/SystemCommandsBot/Forms/CmdForm.cs @@ -0,0 +1,156 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using TelegramBotBase.Base; +using TelegramBotBase.Form; + +namespace SystemCommandsBot.Forms; + +public class CmdForm : AutoCleanForm +{ + 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.Commands.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.Commands.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); + } + } +} diff --git a/Examples/SystemCommandsBot/Forms/StartForm.cs b/Examples/SystemCommandsBot/Forms/StartForm.cs new file mode 100644 index 0000000..885f4d2 --- /dev/null +++ b/Examples/SystemCommandsBot/Forms/StartForm.cs @@ -0,0 +1,38 @@ +using System; +using System.Threading.Tasks; +using TelegramBotBase.Base; +using TelegramBotBase.Form; + +namespace SystemCommandsBot.Forms; + +public class StartForm : FormBase +{ + public string Password { get; set; } + + public override Task Load(MessageResult message) + { + 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); + } +} \ No newline at end of file diff --git a/Examples/SystemCommandsBot/Program.cs b/Examples/SystemCommandsBot/Program.cs index 17ff8b7..4d44afe 100644 --- a/Examples/SystemCommandsBot/Program.cs +++ b/Examples/SystemCommandsBot/Program.cs @@ -1,39 +1,35 @@ using System; +using System.Threading.Tasks; +using SystemCommandsBot.Forms; using TelegramBotBase.Builder; -namespace SystemCommandsBot +namespace SystemCommandsBot; + +internal class Program { - class Program + public static Config BotConfig { get; set; } + + private static async Task Main(string[] args) { - public static config.Config BotConfig { get; set; } + BotConfig = Config.Load(); - - static void Main(string[] args) + if (BotConfig.ApiKey == null || BotConfig.ApiKey.Trim() == "") { - - BotConfig = config.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(); + + await bot.Start(); + + Console.WriteLine("Bot started"); + Console.ReadLine(); + + + await bot.Stop(); } } diff --git a/Examples/SystemCommandsBot/SystemCommandsBot.csproj b/Examples/SystemCommandsBot/SystemCommandsBot.csproj index b299409..f14db93 100644 --- a/Examples/SystemCommandsBot/SystemCommandsBot.csproj +++ b/Examples/SystemCommandsBot/SystemCommandsBot.csproj @@ -1,13 +1,14 @@ - - Exe - net6.0 - + + Exe + net6.0 + enable + disable + - - - - + + + \ No newline at end of file diff --git a/Examples/SystemCommandsBot/commands/Commando.cs b/Examples/SystemCommandsBot/commands/Commando.cs deleted file mode 100644 index 97d6554..0000000 --- a/Examples/SystemCommandsBot/commands/Commando.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; - -namespace SystemCommandsBot.commands -{ - public class Commando - { - public int ID { get; set; } - - public String Title { get; set; } - - public String ShellCmd { get; set; } - - public bool Enabled { get; set; } = true; - - public String Action { get; set; } - - public bool UseShell { get; set; } = true; - - - public int? MaxInstances { get; set; } - - public String ProcName - { - get;set; - } - } -} diff --git a/Examples/SystemCommandsBot/config/Config.cs b/Examples/SystemCommandsBot/config/Config.cs deleted file mode 100644 index 8300806..0000000 --- a/Examples/SystemCommandsBot/config/Config.cs +++ /dev/null @@ -1,92 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; - -namespace SystemCommandsBot.config -{ - public class Config - { - public String Password { get; set; } - - public String ApiKey { get; set; } - - public List Commandos { get; set; } - - - public Config() - { - this.Commandos = new List(); - } - - 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 }); - } - - - public static Config load() - { - try - { - return load(AppContext.BaseDirectory + "config\\default.cfg"); - - - } - catch(Exception ex) - { - Console.WriteLine(ex.Message); - } - return null; - } - - - public static Config load(String path) - { - try - { - var cfg = Newtonsoft.Json.JsonConvert.DeserializeObject(File.ReadAllText(path)) as Config; - return cfg; - } - catch (DirectoryNotFoundException ex) - { - DirectoryInfo 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 ex) - { - 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, Newtonsoft.Json.JsonConvert.SerializeObject(this)); - } - catch - { - - } - } - } -} diff --git a/Examples/SystemCommandsBot/forms/CmdForm.cs b/Examples/SystemCommandsBot/forms/CmdForm.cs deleted file mode 100644 index 85a90ce..0000000 --- a/Examples/SystemCommandsBot/forms/CmdForm.cs +++ /dev/null @@ -1,172 +0,0 @@ -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 DateTime ExpiresAt { get; set; } - - public int? MessageId { get; set; } - - public override async Task Load(MessageResult message) - { - - } - - public override async Task Action(MessageResult message) - { - var btn = message.RawData; - - int 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 this.Device.Send("Cmd nicht verfügbar."); - return; - } - - message.Handled = true; - - switch (cmd.Action) - { - case "start": - - FileInfo 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 message.ConfirmAction("Anwendung läuft bereits."); - - return; - } - - } - - ProcessStartInfo psi = new ProcessStartInfo(); - psi.FileName = cmd.ShellCmd; - psi.WorkingDirectory = fi.DirectoryName; - psi.UseShellExecute = cmd.UseShell; - - Process.Start(psi); - - await this.Device.Send(fi.Name + " wurde gestarted."); - - await message.ConfirmAction(fi.Name + " wurde gestarted."); - - break; - - case "kill": - - FileInfo fi2 = new FileInfo(cmd.ShellCmd); - - String pros = fi2.Name.Replace(fi2.Extension, ""); - - var proc = Process.GetProcessesByName(pros).ToList(); - - foreach (var p in proc) - { - try - { - p.Kill(); - } - catch - { - - } - } - - await this.Device.Send(fi2.Name + " wurde beendet."); - - await message.ConfirmAction(fi2.Name + " wurde beendet."); - - break; - - case "restart": - - FileInfo fi3 = new FileInfo(cmd.ShellCmd); - - String pros2 = fi3.Name.Replace(fi3.Extension, ""); - - var proc2 = Process.GetProcessesByName(pros2).ToList(); - - foreach (var p in proc2) - { - try - { - p.Kill(); - } - catch - { - - } - } - - FileInfo fi4 = new FileInfo(cmd.ShellCmd); - - ProcessStartInfo psi2 = new ProcessStartInfo(); - psi2.FileName = cmd.ShellCmd; - psi2.WorkingDirectory = fi4.DirectoryName; - psi2.FileName = cmd.ShellCmd; - psi2.UseShellExecute = cmd.UseShell; - - Process.Start(psi2); - - await this.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 (this.MessageId == null) - { - var buttons = Program.BotConfig.Commandos.Where(a => a.Enabled).Select(a => new ButtonBase(a.Title, a.ID.ToString())); - - ButtonForm bf = new ButtonForm(); - bf.AddSplitted(buttons, 1); - await this.Device.Send("Deine Optionen", bf); - - return; - } - - - } - - - - - } -} diff --git a/Examples/SystemCommandsBot/forms/StartForm.cs b/Examples/SystemCommandsBot/forms/StartForm.cs deleted file mode 100644 index c5e6597..0000000 --- a/Examples/SystemCommandsBot/forms/StartForm.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using TelegramBotBase.Base; - -namespace SystemCommandsBot.forms -{ - public class StartForm : TelegramBotBase.Form.FormBase - { - public String Password { get; set; } - - public override async Task Load(MessageResult message) - { - var inp = message.MessageText; - if (Program.BotConfig.Password == inp) - { - this.Password = inp; - } - - - } - - - public override async Task Render(MessageResult message) - { - if (this.Password == null || this.Password.Trim() == "") - { - await this.Device.Send("Bitte gib dein Passwort an."); - return; - } - - - var cmd = new forms.CmdForm(); - cmd.ExpiresAt = DateTime.Now.AddDays(14); - - await this.NavigateTo(cmd); - - } - - } -} diff --git a/README.md b/README.md index c94ea1c..95ce677 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() @@ -102,16 +101,18 @@ 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. `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 @@ -175,7 +176,7 @@ var bot = BotBaseBuilder .QuickStart("{YOUR API KEY}") .Build(); -bot.Start(); +await bot.Start(); ``` ## Features @@ -183,7 +184,7 @@ 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. @@ -206,9 +207,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,25 +220,25 @@ 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; } }; 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 @@ -358,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. @@ -553,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. @@ -595,7 +596,7 @@ await this.NavigateTo(ad); ### AutoCleanForm -Just try it by youself. +Just try it by yourself. ### Prompt Dialog @@ -680,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 @@ -781,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 @@ -809,13 +810,13 @@ var bot = BotBaseBuilder .UseEnglish() .Build(); -bot.Start(); +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 @@ -832,12 +833,12 @@ var bot = BotBaseBuilder .UseEnglish() .Build(); -bot.Start(); +await bot.Start(); ``` #### XMLStateMachine -The last one, should work like the others. +The last one should work like the others. ```csharp var bot = BotBaseBuilder @@ -854,7 +855,7 @@ var bot = BotBaseBuilder .UseEnglish() .Build(); -bot.Start(); +await bot.Start(); ``` ### Interfaces @@ -899,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 @@ -909,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] @@ -932,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 @@ -956,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. @@ -1027,6 +1027,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) diff --git a/TelegramBotBase.Extensions.Images/ImageExtensions.cs b/TelegramBotBase.Extensions.Images/ImageExtensions.cs index 55ddbb2..7ed5dc0 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,14 +13,14 @@ 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; } /// - /// Sends an image + /// Sends an image /// /// /// @@ -29,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)) { - InputOnlineFile fts = new InputOnlineFile(fileStream, name); + 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 /// /// /// @@ -48,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)) { - InputOnlineFile fts = new InputOnlineFile(fileStream, name); + 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 fbf22db..028cc02 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; @@ -10,18 +6,19 @@ 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); + var serializer = new MssqlSerializer(connectionString, tablePrefix, fallbackForm); builder.UseSerialization(serializer); @@ -30,21 +27,24 @@ 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. /// /// - /// - /// - /// - /// + /// + /// + /// + /// /// /// /// - 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); @@ -52,26 +52,31 @@ 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. /// /// - /// - /// + /// + /// /// /// /// - 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); 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 5aca6e4..ed08d95 100644 --- a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/MSSQLSerializer.cs +++ b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/MSSQLSerializer.cs @@ -1,45 +1,44 @@ -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; } - /// - /// 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) + public MssqlSerializer(string connectionString, string tablePrefix = "tgb_", Type fallbackStateForm = null) { - if (ConnectionString is null) - { - throw new ArgumentNullException(nameof(ConnectionString)); - } + 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"); } } + public string ConnectionString { get; } + public string TablePrefix { get; set; } + public Type FallbackStateForm { get; set; } + public StateContainer LoadFormStates() { var sc = new StateContainer(); @@ -49,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)) @@ -58,7 +58,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,32 +77,30 @@ 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); } } - } - } - connection.Close(); } @@ -118,69 +116,68 @@ 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(); } - } 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 deleted file mode 100644 index fa1ddef..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 6e3eb4c..9276cbd 100644 --- a/TelegramBotBase.Test/Program.cs +++ b/TelegramBotBase.Test/Program.cs @@ -1,118 +1,109 @@ 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 TelegramBotBase.Example.Tests; -namespace TelegramBotBaseTest +namespace TelegramBotBase.Example; + +internal class Program { - class Program + private static async Task Main(string[] args) { - static async void Main(string[] args) + var bot = BotBaseBuilder + .Create() + .WithAPIKey(Environment.GetEnvironmentVariable("API_KEY") ?? + throw new Exception("API_KEY is not set")) + .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(); + + + bot.BotCommand += Bb_BotCommand; + + //Update Bot commands to botfather + bot.UploadBotCommands().Wait(); + + bot.SetSetting(ESettings.LogAllMessages, true); + + bot.Message += (s, en) => { + Console.WriteLine(en.DeviceId + " " + en.Message.MessageText + " " + (en.Message.RawData ?? "")); + }; - String APIKey = ""; + await bot.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."); + Console.ReadLine(); - bb.BotCommand += Bb_BotCommand; + await bot.Stop(); + } - //Update Bot commands to botfather - await bb.UploadBotCommands(); - - bb.SetSetting(TelegramBotBase.Enums.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, TelegramBotBase.Args.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": - 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); + 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 deleted file mode 100644 index e9d23b8..0000000 --- a/TelegramBotBase.Test/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -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")] 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 a1abbf6..0000000 --- a/TelegramBotBase.Test/TelegramBotBaseTest.csproj +++ /dev/null @@ -1,34 +0,0 @@ - - - - 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 - - - - - - - - diff --git a/TelegramBotBase.Test/Tests/ButtonTestForm.cs b/TelegramBotBase.Test/Tests/ButtonTestForm.cs index ca41320..3bfab76 100644 --- a/TelegramBotBase.Test/Tests/ButtonTestForm.cs +++ b/TelegramBotBase.Test/Tests/ButtonTestForm.cs @@ -1,102 +1,94 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading.Tasks; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests +namespace TelegramBotBase.Example.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) { - this.Opened += ButtonTestForm_Opened; + return; } - private async Task ButtonTestForm_Opened(object sender, EventArgs e) + message.Handled = true; + + switch (call.Value) { - await this.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 this.Device.Send("Button 1 pressed"); + break; - break; + case "button4": - case "button2": + await Device.Send("Button 4 pressed"); - await this.Device.Send("Button 2 pressed"); + break; - break; + case "back": - case "button3": + var st = new Menu(); - await this.Device.Send("Button 3 pressed"); + await NavigateTo(st); - break; + break; - case "button4": - - await this.Device.Send("Button 4 pressed"); - - break; - - case "back": - - var st = new Menu(); - - await this.NavigateTo(st); - - break; - - default: - - message.Handled = false; - - break; - } - - - } - - - public override async Task Render(MessageResult message) - { - - ButtonForm 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 this.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 01da851..47e7763 100644 --- a/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs @@ -1,81 +1,69 @@ -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 +namespace TelegramBotBase.Example.Tests.Controls; + +public class ButtonGridForm : AutoCleanForm { - public class ButtonGridForm : AutoCleanForm + private ButtonGrid _mButtons; + + public ButtonGridForm() { + DeleteMode = EDeleteMode.OnLeavingForm; - ButtonGrid m_Buttons = null; + Init += ButtonGridForm_Init; + } - public ButtonGridForm() + private Task ButtonGridForm_Init(object sender, InitEventArgs e) + { + _mButtons = new ButtonGrid { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; + KeyboardType = EKeyboardType.InlineKeyBoard + }; - this.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.DataSource.ButtonForm = 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 async Task ButtonGridForm_Init(object sender, InitEventArgs e) + if (e.Button.Value == "back") { - m_Buttons = new ButtonGrid(); - - m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.InlineKeyBoard; - - ButtonForm 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")); - - m_Buttons.ButtonsForm = bf; - - m_Buttons.ButtonClicked += Bg_ButtonClicked; - - this.AddControl(m_Buttons); - - + var start = new Menu(); + await NavigateTo(start); } - - private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) + else if (e.Button.Value == "switch") { - if (e.Button == null) - return; - - if (e.Button.Value == "back") + _mButtons.KeyboardType = _mButtons.KeyboardType switch { - var start = new Menu(); - await this.NavigateTo(start); - } - else if (e.Button.Value == "switch") - { - switch (m_Buttons.KeyboardType) - { - 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; - } - - - } - else - { - - await this.Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}"); - } - - + 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}"); } } } diff --git a/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs b/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs index 49239cd..f12b6a4 100644 --- a/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs @@ -1,74 +1,66 @@ -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 +namespace TelegramBotBase.Example.Tests.Controls; + +public class ButtonGridPagingForm : AutoCleanForm { - public class ButtonGridPagingForm : AutoCleanForm + private ButtonGrid _mButtons; + + public ButtonGridPagingForm() { + DeleteMode = EDeleteMode.OnLeavingForm; - ButtonGrid m_Buttons = null; + Init += ButtonGridForm_Init; + } - public ButtonGridPagingForm() + private Task ButtonGridForm_Init(object sender, InitEventArgs e) + { + _mButtons = new ButtonGrid { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; + KeyboardType = EKeyboardType.ReplyKeyboard, + EnablePaging = true, + EnableSearch = true, + HeadLayoutButtonRow = new List { new("Back", "back") } + }; - this.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 async Task ButtonGridForm_Init(object sender, InitEventArgs e) + _mButtons.DataSource.ButtonForm = bf; + + _mButtons.ButtonClicked += Bg_ButtonClicked; + + AddControl(_mButtons); + return Task.CompletedTask; + } + + private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) + { + if (e.Button == null) { - 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") }; - - var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures); - - ButtonForm 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); - - + 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 this.NavigateTo(start); - } - else - { - - await this.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}"); } } } diff --git a/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs b/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs index c737d10..78bc356 100644 --- a/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs @@ -1,77 +1,74 @@ -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 +namespace TelegramBotBase.Example.Tests.Controls; + +public class ButtonGridTagForm : AutoCleanForm { - public class ButtonGridTagForm : AutoCleanForm + private TaggedButtonGrid _mButtons; + + public ButtonGridTagForm() { + DeleteMode = EDeleteMode.OnLeavingForm; - TaggedButtonGrid m_Buttons = null; - - public ButtonGridTagForm() - { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; - - this.Init += ButtonGridTagForm_Init; - } - - private async Task ButtonGridTagForm_Init(object sender, InitEventArgs e) - { - m_Buttons = new TaggedButtonGrid(); - - 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(); - - 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(); - - m_Buttons.EnableCheckAllTools = true; - - m_Buttons.DataSource = new TelegramBotBase.Datasources.ButtonFormDataSource(bf); - - m_Buttons.ButtonClicked += Bg_ButtonClicked; - - this.AddControl(m_Buttons); - } - - 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 this.NavigateTo(start); - return; - - } - - - await this.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 261cda8..fedde60 100644 --- a/TelegramBotBase.Test/Tests/Controls/CalendarPickerForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/CalendarPickerForm.cs @@ -1,81 +1,69 @@ -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 +namespace TelegramBotBase.Example.Tests.Controls; + +public class CalendarPickerForm : AutoCleanForm { - public class CalendarPickerForm : AutoCleanForm + public CalendarPickerForm() { - - public CalendarPicker Picker { get; set; } - - int? selectedDateMessage { get; set; } - - public CalendarPickerForm() - { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; - this.Init += CalendarPickerForm_Init; - } - - private async Task CalendarPickerForm_Init(object sender, InitEventArgs e) - { - this.Picker = new CalendarPicker(); - this.Picker.Title = "Datum auswählen / Pick date"; - - this.AddControl(Picker); - } - - - public override async Task Action(MessageResult message) - { - - switch(message.RawData) - { - case "back": - - var s = new Menu(); - - await this.NavigateTo(s); - - break; - } - - } - - public override async Task Render(MessageResult message) - { - String 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(); - - ButtonForm bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase("Back","back")); - - if (selectedDateMessage != null) - { - await this.Device.Edit(this.selectedDateMessage.Value, s, bf); - } - else - { - var m = await this.Device.Send(s, bf); - this.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 eeeae3a..55662e3 100644 --- a/TelegramBotBase.Test/Tests/Controls/CheckedButtonListForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/CheckedButtonListForm.cs @@ -1,92 +1,86 @@ -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 +namespace TelegramBotBase.Example.Tests.Controls; + +public class CheckedButtonListForm : AutoCleanForm { - public class CheckedButtonListForm : AutoCleanForm + private CheckedButtonList _mButtons; + + public CheckedButtonListForm() { + DeleteMode = EDeleteMode.OnLeavingForm; - CheckedButtonList m_Buttons = null; + Init += CheckedButtonListForm_Init; + } - public CheckedButtonListForm() + private Task CheckedButtonListForm_Init(object sender, InitEventArgs e) + { + _mButtons = new CheckedButtonList { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; + KeyboardType = EKeyboardType.InlineKeyBoard, + EnablePaging = true, + HeadLayoutButtonRow = new List { new("Back", "back"), new("Switch Keyboard", "switch") }, + SubHeadLayoutButtonRow = new List { new("No checked items", "$") } + }; - this.Init += CheckedButtonListForm_Init; + var bf = new ButtonForm(); + + for (var i = 0; i < 30; i++) + { + bf.AddButtonRow($"{i + 1}. Item", i.ToString()); } - private async 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) { - m_Buttons = new CheckedButtonList(); - - m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.InlineKeyBoard; - m_Buttons.EnablePaging = true; - - 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++) - { - bf.AddButtonRow($"{i + 1}. Item", i.ToString()); - } - - m_Buttons.DataSource = new TelegramBotBase.Datasources.ButtonFormDataSource(bf); - - m_Buttons.ButtonClicked += Bg_ButtonClicked; - m_Buttons.CheckedChanged += M_Buttons_CheckedChanged; - - this.AddControl(m_Buttons); + return; } - private async Task M_Buttons_CheckedChanged(object sender, CheckedChangedEventArgs e) + switch (e.Button.Value) { - m_Buttons.SubHeadLayoutButtonRow = new List() { new ButtonBase($"{m_Buttons.CheckedItems.Count} checked items", "$") }; - } + 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": - switch (m_Buttons.KeyboardType) - { - 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; - } - - - 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 a5973e0..8c5acda 100644 --- a/TelegramBotBase.Test/Tests/Controls/MonthPickerForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/MonthPickerForm.cs @@ -1,79 +1,67 @@ -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 +namespace TelegramBotBase.Example.Tests.Controls; + +public class MonthPickerForm : AutoCleanForm { - public class MonthPickerForm : AutoCleanForm + public MonthPickerForm() { - - public MonthPicker Picker { get; set; } - - int? selectedDateMessage { get; set; } - - public MonthPickerForm() - { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; - this.Init += MonthPickerForm_Init; - } - - private async Task MonthPickerForm_Init(object sender, InitEventArgs e) - { - this.Picker = new MonthPicker(); - this.Picker.Title = "Monat auswählen / Pick month"; - this.AddControl(Picker); - } - - - public override async Task Action(MessageResult message) - { - - switch(message.RawData) - { - case "back": - - var s = new Menu(); - - await this.NavigateTo(s); - - break; - } - - } - - public override async Task Render(MessageResult message) - { - String 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(); - - ButtonForm bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase("Back","back")); - - if (selectedDateMessage != null) - { - await this.Device.Edit(this.selectedDateMessage.Value, s, bf); - } - else - { - var m = await this.Device.Send(s, bf); - this.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 b38abb4..fb46af5 100644 --- a/TelegramBotBase.Test/Tests/Controls/MultiToggleButtons.cs +++ b/TelegramBotBase.Test/Tests/Controls/MultiToggleButtons.cs @@ -1,53 +1,55 @@ 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 +namespace TelegramBotBase.Example.Tests.Controls; + +public class MultiToggleButtons : AutoCleanForm { - public class MultiToggleButtons : AutoCleanForm + public MultiToggleButtons() { - public MultiToggleButtons() - { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; + DeleteMode = EDeleteMode.OnLeavingForm; - this.Init += ToggleButtons_Init; - } - - private async Task ToggleButtons_Init(object sender, InitEventArgs e) - { - - var mtb = new MultiToggleButton(); - - 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); - - mtb = new MultiToggleButton(); - - 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); - } - - private void Tb_Toggled(object sender, EventArgs e) - { - var tb = sender as MultiToggleButton; - if (tb.SelectedOption != null) - { - Console.WriteLine(tb.ID.ToString() + " was pressed, and toggled to " + tb.SelectedOption.Value); - return; - } - - Console.WriteLine("Selection for " + tb.ID.ToString() + " 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 fccdfcb..fbf8aa8 100644 --- a/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs +++ b/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs @@ -1,53 +1,51 @@ -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.DataSources; +using TelegramBotBase.Enums; +using TelegramBotBase.Example.Tests.Controls.Subclass; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Controls +namespace TelegramBotBase.Example.Tests.Controls; + +public class MultiViewForm : AutoCleanForm { - public class MultiViewForm : AutoCleanForm + private ButtonGrid _bg; + private MultiViewTest _mvt; + + public MultiViewForm() { + DeleteMode = EDeleteMode.OnLeavingForm; + Init += MultiViewForm_Init; + } - Subclass.MultiViewTest mvt = null; + private Task MultiViewForm_Init(object sender, InitEventArgs e) + { + _mvt = new MultiViewTest(); - ButtonGrid bg = null; + AddControl(_mvt); - public MultiViewForm() + _bg = new ButtonGrid { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; - this.Init += MultiViewForm_Init; - } + DataSource = new ButtonFormDataSource() + }; + _bg.DataSource.ButtonForm.AddButtonRow("Back", "$back$"); + _bg.ButtonClicked += Bg_ButtonClicked; + _bg.KeyboardType = EKeyboardType.ReplyKeyboard; + AddControl(_bg); + return Task.CompletedTask; + } - private async Task MultiViewForm_Init(object sender, TelegramBotBase.Args.InitEventArgs e) + private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e) + { + switch (e.Button.Value) { - mvt = new Subclass.MultiViewTest(); + case "$back$": - AddControl(mvt); + var mn = new Menu(); + await NavigateTo(mn); - bg = new ButtonGrid(); - bg.ButtonsForm = new ButtonForm(); - bg.ButtonsForm.AddButtonRow("Back", "$back$"); - bg.ButtonClicked += Bg_ButtonClicked; - bg.KeyboardType = TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard; - AddControl(bg); + break; } - - private async Task Bg_ButtonClicked(object sender, TelegramBotBase.Args.ButtonClickedEventArgs e) - { - switch(e.Button.Value) - { - case "$back$": - - var mn = new Menu(); - await NavigateTo(mn); - - break; - } - } - - } } diff --git a/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs b/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs index f376903..c985d54 100644 --- a/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs +++ b/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs @@ -1,64 +1,52 @@ -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 +namespace TelegramBotBase.Example.Tests.Controls.Subclass; + +public class MultiViewTest : MultiView { - public class MultiViewTest : TelegramBotBase.Controls.Hybrid.MultiView + public override Task Action(MessageResult result, string value = null) { - - - public override async Task Action(MessageResult result, string value = null) + switch (result.RawData) { + case "back": - switch (result.RawData) - { - case "back": + SelectedViewIndex--; - this.SelectedViewIndex--; + break; + case "next": - break; - case "next": - - this.SelectedViewIndex++; - - break; - } + SelectedViewIndex++; + break; } - public override async Task RenderView(RenderViewEventArgs e) - { - - ButtonForm 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 55b88e9..77c2e96 100644 --- a/TelegramBotBase.Test/Tests/Controls/ToggleButtons.cs +++ b/TelegramBotBase.Test/Tests/Controls/ToggleButtons.cs @@ -1,51 +1,52 @@ 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 +namespace TelegramBotBase.Example.Tests.Controls; + +public class ToggleButtons : AutoCleanForm { - public class ToggleButtons : AutoCleanForm + public ToggleButtons() { - public ToggleButtons() - { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; + DeleteMode = EDeleteMode.OnLeavingForm; - this.Init += ToggleButtons_Init; - } - - private async Task ToggleButtons_Init(object sender, InitEventArgs e) - { - - var tb = new ToggleButton(); - tb.Checked = true; - tb.Toggled += Tb_Toggled; - - this.AddControl(tb); - - tb = new ToggleButton(); - tb.Checked = false; - tb.Toggled += Tb_Toggled; - - this.AddControl(tb); - - tb = new ToggleButton(); - tb.Checked = true; - tb.Toggled += Tb_Toggled; - - this.AddControl(tb); - - } - - 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")); - } + 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 6c9dd41..0cf9549 100644 --- a/TelegramBotBase.Test/Tests/Controls/TreeViewForms.cs +++ b/TelegramBotBase.Test/Tests/Controls/TreeViewForms.cs @@ -1,101 +1,98 @@ -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 +namespace TelegramBotBase.Example.Tests.Controls; + +public class TreeViewForms : AutoCleanForm { - public class TreeViewForms : AutoCleanForm + public TreeViewForms() { - public TreeView view { get; set; } - - private int? MessageId { get; set; } - - public TreeViewForms() - { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; - this.Init += TreeViewForms_Init; - } - - private async 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); - - this.AddControl(view); - - } - - 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 this.NavigateTo(start); - - break; - - } - - } - - public override async Task Render(MessageResult message) - { - String s = ""; - - s += "Selected Node: " + (this.view.SelectedNode?.Text ?? "(null)") + "\r\n"; - - s += "Visible Node: " + (this.view.VisibleNode?.Text ?? "(top)") + "\r\n"; - - s += "Visible Path: " + this.view.GetPath() + "\r\n"; - s += "Selected Path: " + (this.view.SelectedNode?.GetPath() ?? "(null)") + "\r\n"; - - ButtonForm bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase("Back", "back")); - - if (MessageId != null) - { - await this.Device.Edit(this.MessageId.Value, s, bf); - } - else - { - var m = await this.Device.Send(s, bf); - this.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 4a6edec..49554d0 100644 --- a/TelegramBotBase.Test/Tests/DataForm.cs +++ b/TelegramBotBase.Test/Tests/DataForm.cs @@ -1,143 +1,132 @@ -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; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests +namespace TelegramBotBase.Example.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) { - String tmp = ""; - InputOnlineFile file; + case MessageType.Contact: - switch (data.Type) - { - case Telegram.Bot.Types.Enums.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 this.Device.Send("Your contact: \r\n" + tmp, replyTo: data.MessageId); + break; - break; + case MessageType.Document: - case Telegram.Bot.Types.Enums.MessageType.Document: + file = new InputOnlineFile(data.Document.FileId); - file = new InputOnlineFile(data.Document.FileId); - - await this.Device.SendDocument(file, "Your uploaded document"); + await Device.SendDocument(file, "Your uploaded document"); - break; + break; - case Telegram.Bot.Types.Enums.MessageType.Video: + case MessageType.Video: - file = new InputOnlineFile(data.Document.FileId); + file = new InputOnlineFile(data.Document.FileId); - await this.Device.SendDocument(file, "Your uploaded video"); + await Device.SendDocument(file, "Your uploaded video"); - break; + break; - case Telegram.Bot.Types.Enums.MessageType.Audio: + case MessageType.Audio: - file = new InputOnlineFile(data.Document.FileId); + file = new InputOnlineFile(data.Document.FileId); - await this.Device.SendDocument(file, "Your uploaded audio"); + await Device.SendDocument(file, "Your uploaded audio"); - break; + 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"; + 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; + 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; + break; - default: + default: - await this.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 this.Device.RequestContact(); + case "location": - break; + await Device.RequestLocation(); - case "location": + break; - await this.Device.RequestLocation(); + case "back": - break; + message.Handled = true; - case "back": - - message.Handled = true; - - var start = new Menu(); - - await this.NavigateTo(start); - - break; - } + var start = new Menu(); + await NavigateTo(start); + break; } + } - public override async Task Render(MessageResult message) - { - ButtonForm 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 this.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..079d448 --- /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 TelegramBotBase.Example.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..cde1a85 --- /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 TelegramBotBase.Example.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 3187968..0000000 --- a/TelegramBotBase.Test/Tests/Datasources/CustomDataSource.cs +++ /dev/null @@ -1,163 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; -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 = Newtonsoft.Json.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 = Newtonsoft.Json.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); - - List lst = new List(); - foreach (var c in items) - { - lst.Add(Render(c)); - } - - return lst; - } - - public override List AllItems() - { - List 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) - { - List rows = ItemRange(start, count); - - ButtonForm lst = new ButtonForm(); - foreach (var c in rows) - { - lst.AddButtonRow(c); - } - return lst; - } - - public override ButtonForm PickAllItems(string filter = null) - { - List rows = AllItems(); - - ButtonForm 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) - { - var s = data as String; - if (s == null) - 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 ColumnCount - { - get - { - return 1; - } - } - - public override int RowCount - { - get - { - return this.Count; - } - } - - } -} diff --git a/TelegramBotBase.Test/Tests/Datasources/List.cs b/TelegramBotBase.Test/Tests/Datasources/List.cs deleted file mode 100644 index c352384..0000000 --- a/TelegramBotBase.Test/Tests/Datasources/List.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using TelegramBotBase.Base; -using TelegramBotBase.Controls.Hybrid; -using TelegramBotBase.Form; - -namespace TelegramBotBaseTest.Tests.Datasources -{ - public class List : FormBase - { - ButtonGrid __buttons = null; - - public List() - { - this.Init += List_Init; - } - - private async Task List_Init(object sender, TelegramBotBase.Args.InitEventArgs e) - { - - __buttons = new ButtonGrid(); - - __buttons.EnablePaging = true; - __buttons.EnableSearch = false; - __buttons.ButtonClicked += __buttons_ButtonClicked; - __buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard; - __buttons.DeleteReplyMessage = true; - - __buttons.HeadLayoutButtonRow = new ButtonRow(new ButtonBase("Back", "back")); - - var cds = new CustomDataSource(); - __buttons.DataSource = cds; - - AddControl(__buttons); - } - - private async Task __buttons_ButtonClicked(object sender, TelegramBotBase.Args.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 2322b9f..9359998 100644 --- a/TelegramBotBase.Test/Tests/Groups/GroupChange.cs +++ b/TelegramBotBase.Test/Tests/Groups/GroupChange.cs @@ -1,76 +1,72 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Threading.Tasks; using TelegramBotBase.Args; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Groups +namespace TelegramBotBase.Example.Tests.Groups; + +public class GroupChange : GroupForm { - public class GroupChange : TelegramBotBase.Form.GroupForm + public GroupChange() { - public GroupChange() - { - this.Opened += GroupChange_Opened; - } - - - private async Task GroupChange_Opened(object sender, EventArgs e) - { - - ButtonForm 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); - - } - - 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 this.NavigateTo(gc); - - break; - case "welcomeuser": - - var wu = new WelcomeUser(); - - await this.NavigateTo(wu); - - break; - case "linkreplace": - - var lr = new LinkReplaceTest(); - - await this.NavigateTo(lr); - - break; - } - - } - - 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); - } - + 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 d132303..69bc1ad 100644 --- a/TelegramBotBase.Test/Tests/Groups/LinkReplaceTest.cs +++ b/TelegramBotBase.Test/Tests/Groups/LinkReplaceTest.cs @@ -1,164 +1,165 @@ 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 +namespace TelegramBotBase.Example.Tests.Groups; + +public class LinkReplaceTest : GroupForm { - public class LinkReplaceTest : TelegramBotBase.Form.GroupForm + private const int Maximum = 3; + + + public LinkReplaceTest() { + Opened += LinkReplaceTest_Opened; + } - Dictionary Counter { get; set; } = new Dictionary(); + private Dictionary Counter { get; } = new(); - private const int Maximum = 3; + 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")); - public LinkReplaceTest() + await Device.Send("LinkReplaceTest started, click to switch", bf); + } + + public override async Task Action(MessageResult message) + { + if (message.Handled) { - this.Opened += LinkReplaceTest_Opened; + return; } - private async Task LinkReplaceTest_Opened(object sender, EventArgs e) + var bn = message.RawData; + + await message.ConfirmAction(); + message.Handled = true; + + switch (bn) { + case "groupchange": - ButtonForm bf = new ButtonForm(); + var gc = new GroupChange(); - 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 NavigateTo(gc); - await this.Device.Send("LinkReplaceTest started, click to switch", bf); + 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; } - public override async Task Action(MessageResult message) + //Are urls inside his message ? + if (!HasLinks(e.MessageText)) { - if (message.Handled) - return; - - var bn = message.RawData; - - await message.ConfirmAction(); - message.Handled = true; - - switch (bn) - { - case "groupchange": - - var gc = new GroupChange(); - - await this.NavigateTo(gc); - - break; - case "welcomeuser": - - var wu = new WelcomeUser(); - - await this.NavigateTo(wu); - - break; - case "linkreplace": - - var lr = new LinkReplaceTest(); - - await this.NavigateTo(lr); - - break; - } - + return; } - public override async Task OnMessage(MessageResult e) + var u = await Device.GetChatUser(from); + + //Don't kick Admins or Creators + if ((u.Status == ChatMemberStatus.Administrator) | (u.Status == ChatMemberStatus.Creator)) { - 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 == Telegram.Bot.Types.Enums.ChatMemberStatus.Administrator | u.Status == Telegram.Bot.Types.Enums.ChatMemberStatus.Creator) - { - await this.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; - - //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"); - } - - - + await Device.Send("You won't get kicked,...not this time."); + return; } - /// - /// 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 e.Device.DeleteMessage(e.MessageId); + + var cp = new ChatPermissions { - await OnMessage(message); + 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]++; } - - /// - /// https://stackoverflow.com/a/20651284 - /// - /// - /// - private bool HasLinks(String str) + else { - 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 matches = r.Matches(tmp); - - return (matches.Count > 0); + Counter[from] = 1; } + if (Counter[from] >= 3) + { + await e.Device.BanUser(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; } } diff --git a/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs b/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs index c90a3b9..6a6d09e 100644 --- a/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs +++ b/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs @@ -1,92 +1,82 @@ 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 +namespace TelegramBotBase.Example.Tests.Groups; + +public class WelcomeUser : GroupForm { - public class WelcomeUser : TelegramBotBase.Form.GroupForm + public WelcomeUser() { - - public WelcomeUser() - { - this.Opened += WelcomeUser_Opened; - } - - - private async Task WelcomeUser_Opened(object sender, EventArgs e) - { - - ButtonForm 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); - - } - - 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 this.NavigateTo(gc); - - break; - case "welcomeuser": - - var wu = new WelcomeUser(); - - await this.NavigateTo(wu); - - break; - case "linkreplace": - - var lr = new LinkReplaceTest(); - - await this.NavigateTo(lr); - - break; - } - - } - - public override async Task OnMemberChanges(MemberChangeEventArgs e) - { - - if (e.Type == Telegram.Bot.Types.Enums.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)); - - } - else if (e.Type == Telegram.Bot.Types.Enums.MessageType.ChatMemberLeft) - { - await this.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 6f14fec..740cfd7 100644 --- a/TelegramBotBase.Test/Tests/Menu.cs +++ b/TelegramBotBase.Test/Tests/Menu.cs @@ -1,264 +1,265 @@ -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.Example.Tests.Controls; +using TelegramBotBase.Example.Tests.DataSources; +using TelegramBotBase.Example.Tests.Groups; using TelegramBotBase.Form; -using TelegramBotBaseTest.Tests.Controls; -namespace TelegramBotBaseTest.Tests +namespace TelegramBotBase.Example.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)) { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; - } + var sf = new WelcomeUser(); - 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) - { - var sf = new TelegramBotBaseTest.Tests.Groups.WelcomeUser(); - - await this.NavigateTo(sf); - } - - - await Device.HideReplyKeyboard(); - } - - public override async Task Action(MessageResult message) - { - var call = message.GetData(); - - await message.ConfirmAction(); - - - if (call == null) - return; - - message.Handled = true; - - switch (call.Value) - { - case "text": - - var sf = new SimpleForm(); - - await this.NavigateTo(sf); - - break; - - case "buttons": - - var bf = new ButtonTestForm(); - - await this.NavigateTo(bf); - - break; - - case "progress": - - var pf = new ProgressTest(); - - await this.NavigateTo(pf); - - break; - - case "registration": - - var reg = new Register.Start(); - - await this.NavigateTo(reg); - - break; - - case "form1": - - var form1 = new TestForm(); - - await this.NavigateTo(form1); - - break; - - case "form2": - - var form2 = new TestForm2(); - - await this.NavigateTo(form2); - - break; - - case "data": - - var data = new DataForm(); - - await this.NavigateTo(data); - - break; - - case "calendar": - - var calendar = new Controls.CalendarPickerForm(); - - await this.NavigateTo(calendar); - - break; - - case "month": - - var month = new Controls.MonthPickerForm(); - - await this.NavigateTo(month); - - break; - - case "treeview": - - var tree = new Controls.TreeViewForms(); - - await this.NavigateTo(tree); - - break; - - case "togglebuttons": - - var tb = new Controls.ToggleButtons(); - - await this.NavigateTo(tb); - - break; - - case "multitogglebuttons": - - var mtb = new Controls.MultiToggleButtons(); - - await this.NavigateTo(mtb); - - break; - - case "buttongrid": - - var bg = new Controls.ButtonGridForm(); - - await this.NavigateTo(bg); - - break; - - case "buttongridfilter": - - var bg2 = new Controls.ButtonGridPagingForm(); - - await this.NavigateTo(bg2); - - break; - - case "buttongridtags": - - var bg3 = new Controls.ButtonGridTagForm(); - - await this.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 Datasources.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) - { - - ButtonForm 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 this.Device.Send("Choose your test:", btn); + await NavigateTo(sf); } + await Device.HideReplyKeyboard(); + } + + public override async Task Action(MessageResult message) + { + var call = message.GetData(); + + await message.ConfirmAction(); + + + if (call == null) + { + return; + } + + message.Handled = true; + + 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); + + + 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); } } diff --git a/TelegramBotBase.Test/Tests/Navigation/CustomController.cs b/TelegramBotBase.Test/Tests/Navigation/CustomController.cs index e5b7205..4f2a9a2 100644 --- a/TelegramBotBase.Test/Tests/Navigation/CustomController.cs +++ b/TelegramBotBase.Test/Tests/Navigation/CustomController.cs @@ -1,44 +1,39 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Threading.Tasks; using TelegramBotBase.Form; using TelegramBotBase.Form.Navigation; -namespace TelegramBotBaseTest.Tests.Navigation +namespace TelegramBotBase.Example.Tests.Navigation; + +internal class CustomController : NavigationController { - 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 {this.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 {this.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 {this.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 29e37fc..db4641f 100644 --- a/TelegramBotBase.Test/Tests/Navigation/Form1.cs +++ b/TelegramBotBase.Test/Tests/Navigation/Form1.cs @@ -1,88 +1,83 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Threading.Tasks; using Telegram.Bot.Types; using TelegramBotBase.Base; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Navigation +namespace TelegramBotBase.Example.Tests.Navigation; + +public class Form1 : FormBase { - public class Form1 : FormBase + private Message _msg; + + public Form1() { - Message msg = null; - - public Form1() - { - this.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 1f70b5c..cc53b47 100644 --- a/TelegramBotBase.Test/Tests/Navigation/Start.cs +++ b/TelegramBotBase.Test/Tests/Navigation/Start.cs @@ -1,91 +1,80 @@ -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 +namespace TelegramBotBase.Example.Tests.Navigation; + +public class Start : FormBase { - public class Start : FormBase + private Message _msg; + + + public override Task Load(MessageResult message) { - - Message msg = null; - - public Start() - { - - } - - - public override async Task Load(MessageResult message) - { - - - - } - - 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 9fb96f1..a95ae74 100644 --- a/TelegramBotBase.Test/Tests/Notifications/Start.cs +++ b/TelegramBotBase.Test/Tests/Notifications/Start.cs @@ -1,63 +1,61 @@ -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 +namespace TelegramBotBase.Example.Tests.Notifications; + +public class Start : AutoCleanForm { - public class Start : AutoCleanForm + private bool _sent; + + public Start() { - bool sent = false; - - public Start() - { - this.DeleteMode = TelegramBotBase.Enums.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 8b0ea16..5fa059d 100644 --- a/TelegramBotBase.Test/Tests/ProgressTest.cs +++ b/TelegramBotBase.Test/Tests/ProgressTest.cs @@ -1,130 +1,136 @@ 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 +namespace TelegramBotBase.Example.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) { - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; - this.Opened += ProgressTest_Opened; - this.Closed += ProgressTest_Closed; + return; } + ProgressBar bar = null; - private async Task ProgressTest_Opened(object sender, EventArgs e) + switch (call.Value) { - await this.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; - - switch (call.Value) - { - case "standard": - - Bar = new ProgressBar(0, 100, ProgressBar.eProgressStyle.standard); - Bar.Device = this.Device; - - break; - - case "squares": - - Bar = new ProgressBar(0, 100, ProgressBar.eProgressStyle.squares); - Bar.Device = this.Device; - - break; - - case "circles": - - Bar = new ProgressBar(0, 100, ProgressBar.eProgressStyle.circles); - Bar.Device = this.Device; - - break; - - case "lines": - - Bar = new ProgressBar(0, 100, ProgressBar.eProgressStyle.lines); - Bar.Device = this.Device; - - break; - - case "squaredlines": - - Bar = new ProgressBar(0, 100, ProgressBar.eProgressStyle.squaredLines); - Bar.Device = this.Device; - - break; - - case "start": - - var sf = new Menu(); - - await this.NavigateTo(sf); - - return; - - default: - - return; - - } - - - //Render Progress bar and show some "example" progress - await Bar.Render(message); - - this.Controls.Add(Bar); - - for (int i = 0; i <= 100; i++) - { - Bar.Value++; - await Bar.Render(message); - - Thread.Sleep(250); - } - + default: + return; } - public override async Task Render(MessageResult message) + //Render Progress bar and show some "example" progress + await bar.Render(message); + + Controls.Add(bar); + + for (var i = 0; i <= 100; i++) { - ButtonForm btn = new ButtonForm(); - btn.AddButtonRow(new ButtonBase("Standard", new CallbackData("a", "standard").Serialize()), new ButtonBase("Squares", new CallbackData("a", "squares").Serialize())); + bar.Value++; + await bar.Render(message); - 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 this.Device.Send("Choose your progress bar:", btn); + Thread.Sleep(250); } - - private async Task ProgressTest_Closed(object sender, EventArgs e) - { - await this.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 b66334c..40ad4bc 100644 --- a/TelegramBotBase.Test/Tests/Register/PerForm.cs +++ b/TelegramBotBase.Test/Tests/Register/PerForm.cs @@ -1,103 +1,98 @@ -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; -namespace TelegramBotBaseTest.Tests.Register +namespace TelegramBotBase.Example.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 async override Task Load(MessageResult message) + if (message.MessageText.Trim() == "") { - if (message.MessageText.Trim() == "") - return; - - if (this.Firstname == null) - { - this.Firstname = message.MessageText; - return; - } - - if (this.Lastname == null) - { - this.Lastname = message.MessageText; - return; - } - - if (this.EMail == null) - { - this.EMail = message.MessageText; - return; - } - + return Task.CompletedTask; } - public async override 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 this.NavigateTo(start); - - break; - - } - - + Firstname = message.MessageText; + return Task.CompletedTask; } - public async override Task Render(MessageResult message) + if (Lastname == null) { - if (this.Firstname == null) - { - await this.Device.Send("Please sent your firstname:"); - return; - } - - if (this.Lastname == null) - { - await this.Device.Send("Please sent your lastname:"); - return; - } - - if (this.EMail == null) - { - await this.Device.Send("Please sent your email address:"); - return; - } - - - String s = ""; - - s += "Firstname: " + this.Firstname + "\r\n"; - s += "Lastname: " + this.Lastname + "\r\n"; - s += "E-Mail: " + this.EMail + "\r\n"; - - ButtonForm bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "back").Serialize())); - - await this.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 afc709a..8249ec4 100644 --- a/TelegramBotBase.Test/Tests/Register/PerStep.cs +++ b/TelegramBotBase.Test/Tests/Register/PerStep.cs @@ -1,47 +1,41 @@ -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.Example.Tests.Register.Steps; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests.Register +namespace TelegramBotBase.Example.Tests.Register; + +public class PerStep : AutoCleanForm { - public class PerStep: AutoCleanForm + public override async Task Action(MessageResult message) { + await message.ConfirmAction(); - public async override Task Action(MessageResult message) + switch (message.RawData) { - await message.ConfirmAction(); + case "start": - switch (message.RawData) - { - case "start": + var step1 = new Step1(); - var step1 = new Steps.Step1(); + await NavigateTo(step1); - await this.NavigateTo(step1); + break; + case "back": - break; - case "back": + var start = new Start(); - var start = new Start(); + await NavigateTo(start); - await this.NavigateTo(start); - - break; - - } - } - - public async override Task Render(MessageResult message) - { - ButtonForm bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase("Goto Step 1", "start")); - bf.AddButtonRow(new ButtonBase("Back", "back")); - - await this.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 73ed856..8f1071c 100644 --- a/TelegramBotBase.Test/Tests/Register/Start.cs +++ b/TelegramBotBase.Test/Tests/Register/Start.cs @@ -1,72 +1,57 @@ -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; -namespace TelegramBotBaseTest.Tests.Register +namespace TelegramBotBase.Example.Tests.Register; + +public class Start : AutoCleanForm { - public class Start : AutoCleanForm + public override async Task Action(MessageResult message) { - public Start() - { + var call = message.GetData(); + await message.ConfirmAction(); + + + if (call == null) + { + return; } - public async override Task Action(MessageResult message) + switch (call.Value) { - var call = message.GetData(); + case "form": - await message.ConfirmAction(); + var form = new PerForm(); + await NavigateTo(form); - if (call == null) - return; + break; + case "step": - switch (call.Value) - { - case "form": + var step = new PerStep(); - var form = new PerForm(); + await NavigateTo(step); - await this.NavigateTo(form); + break; + case "backtodashboard": - break; - case "step": - - var step = new PerStep(); - - await this.NavigateTo(step); - - break; - case "backtodashboard": - - var start = new Tests.Menu(); - - await this.NavigateTo(start); - - break; - } + var start = new Menu(); + await NavigateTo(start); + break; } - - public async override Task Render(MessageResult message) - { - - ButtonForm 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); - - - } - - } -} + + 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 1fe077b..af8c471 100644 --- a/TelegramBotBase.Test/Tests/Register/Steps/Data.cs +++ b/TelegramBotBase.Test/Tests/Register/Steps/Data.cs @@ -1,18 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace TelegramBotBase.Example.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 1952a1b..13e61b6 100644 --- a/TelegramBotBase.Test/Tests/Register/Steps/Step1.cs +++ b/TelegramBotBase.Test/Tests/Register/Steps/Step1.cs @@ -1,60 +1,61 @@ -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; -namespace TelegramBotBaseTest.Tests.Register.Steps +namespace TelegramBotBase.Example.Tests.Register.Steps; + +public class Step1 : AutoCleanForm { - public class Step1 : AutoCleanForm + public Step1() { - public Data UserData { get; set; } - - public Step1() - { - this.Init += Step1_Init; - } - - private async Task Step1_Init(object sender, InitEventArgs e) - { - this.UserData = new Data(); - } - - - public async override Task Load(MessageResult message) - { - if (message.Handled) - return; - - if (message.MessageText.Trim() == "") - return; - - if (this.UserData.Firstname == null) - { - this.UserData.Firstname = message.MessageText; - return; - } - } - - public async override Task Render(MessageResult message) - { - if (this.UserData.Firstname == null) - { - await this.Device.Send("Please sent your firstname:"); - return; - } - - message.Handled = true; - - var step2 = new Step2(); - - step2.UserData = this.UserData; - - await this.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 6ca2362..c5a0752 100644 --- a/TelegramBotBase.Test/Tests/Register/Steps/Step2.cs +++ b/TelegramBotBase.Test/Tests/Register/Steps/Step2.cs @@ -1,50 +1,50 @@ -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; -namespace TelegramBotBaseTest.Tests.Register.Steps +namespace TelegramBotBase.Example.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 async override Task Load(MessageResult message) + if (message.Handled) { - if (message.Handled) - return; - - if (message.MessageText.Trim() == "") - return; - - if (this.UserData.Lastname == null) - { - this.UserData.Lastname = message.MessageText; - return; - } + return Task.CompletedTask; } - - public async override Task Render(MessageResult message) + if (message.MessageText.Trim() == "") { - if (this.UserData.Lastname == null) - { - await this.Device.Send("Please sent your lastname:"); - return; - } - - message.Handled = true; - - var step3 = new Step3(); - - step3.UserData = this.UserData; - - await this.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 038a9a2..afe5989 100644 --- a/TelegramBotBase.Test/Tests/Register/Steps/Step3.cs +++ b/TelegramBotBase.Test/Tests/Register/Steps/Step3.cs @@ -1,71 +1,69 @@ -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; -namespace TelegramBotBaseTest.Tests.Register.Steps +namespace TelegramBotBase.Example.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 async override Task Load(MessageResult message) + if (message.Handled) { - if (message.Handled) - return; - - if (message.MessageText.Trim() == "") - return; - - if (this.UserData.EMail == null) - { - this.UserData.EMail = message.MessageText; - return; - } + return Task.CompletedTask; } - public async override Task Action(MessageResult message) + if (message.MessageText.Trim() == "") { - await message.ConfirmAction(); - - switch (message.RawData) - { - case "back": - - var start = new Start(); - - await this.NavigateTo(start); - - break; - - } - + return Task.CompletedTask; } - public async override Task Render(MessageResult message) + if (UserData.EMail == null) { - if (this.UserData.EMail == null) - { - await this.Device.Send("Please sent your email:"); - return; - } - - message.Handled = true; - - String s = ""; - - s += "Firstname: " + this.UserData.Firstname + "\r\n"; - s += "Lastname: " + this.UserData.Lastname + "\r\n"; - s += "E-Mail: " + this.UserData.EMail + "\r\n"; - - ButtonForm bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase("Back", "back")); - - await this.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 0830cda..71669bf 100644 --- a/TelegramBotBase.Test/Tests/SimpleForm.cs +++ b/TelegramBotBase.Test/Tests/SimpleForm.cs @@ -1,68 +1,62 @@ 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 +namespace TelegramBotBase.Example.Tests; + +public class SimpleForm : AutoCleanForm { - public class SimpleForm : AutoCleanForm + public SimpleForm() { + DeleteSide = EDeleteSide.Both; + DeleteMode = EDeleteMode.OnLeavingForm; - public SimpleForm() - { - this.DeleteSide = TelegramBotBase.Enums.eDeleteSide.Both; - this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm; - - this.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"); - } - - 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 this.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); - - break; - - case "bye": - case "ciao": - - //Send him a simple message - await this.Device.Send("Ok, take care !"); - break; - - case "back": - - var st = new Menu(); - - await this.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 e56642f..08a14d6 100644 --- a/TelegramBotBase.Test/Tests/Start.cs +++ b/TelegramBotBase.Test/Tests/Start.cs @@ -1,40 +1,36 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TelegramBotBase.Base; +using TelegramBotBase.Example.Tests.Groups; using TelegramBotBase.Form; -namespace TelegramBotBaseTest.Tests +namespace TelegramBotBase.Example.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 this.NavigateTo(st); - - return true; - } - - - public override async Task OpenGroup(MessageResult e) - { - var st = new Groups.LinkReplaceTest(); - await this.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 8994465..d7d7873 100644 --- a/TelegramBotBase.Test/Tests/TestForm.cs +++ b/TelegramBotBase.Test/Tests/TestForm.cs @@ -1,78 +1,67 @@ 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; -namespace TelegramBotBaseTest.Tests +namespace TelegramBotBase.Example.Tests; + +public class TestForm : FormBase { - public class TestForm : FormBase + public TestForm() { - - - String LastMessage { get; set; } - - public TestForm() - { - this.Opened += TestForm_Opened; - this.Closed += TestForm_Closed; - } - - private async Task TestForm_Opened(object sender, EventArgs e) - { - await this.Device.Send("Welcome to Form 1"); - } - - private async Task TestForm_Closed(object sender, EventArgs e) - { - await this.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 this.NavigateTo(tf); - - break; - - default: - - if (message.UpdateData == null) - return; - - this.LastMessage = message.Message.Text; - - break; - } - - - } - - - public override async Task Render(MessageResult message) - { - if (message.Command == "reply") - { - - await this.Device.Send("Last message: " + this.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 089430e..302a953 100644 --- a/TelegramBotBase.Test/Tests/TestForm2.cs +++ b/TelegramBotBase.Test/Tests/TestForm2.cs @@ -1,128 +1,108 @@ 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; -namespace TelegramBotBaseTest.Tests +namespace TelegramBotBase.Example.Tests; + +public class TestForm2 : FormBase { - public class TestForm2 : FormBase + public TestForm2() { - - - public TestForm2() - { - this.Opened += TestForm2_Opened; - this.Closed += TestForm2_Closed; - } - - private async Task TestForm2_Opened(object sender, EventArgs e) - { - await this.Device.Send("Welcome to Form 2"); - } - - private async Task TestForm2_Closed(object sender, EventArgs e) - { - await this.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 this.NavigateTo(tf); - } - else if (call.Value == "alert") - { - AlertDialog ad = new AlertDialog("This is a message", "Ok"); - - ad.ButtonClicked += async (s, en) => - { - var fto = new TestForm2(); - await this.NavigateTo(fto); - }; - - await this.NavigateTo(ad); - } - else if (call.Value == "confirm") - { - ConfirmDialog 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 this.NavigateTo(pd); - } - else if (call.Value == "prompt") - { - PromptDialog pd = new PromptDialog("Please tell me your name ?"); - - pd.Completed += async (s, en) => - { - await this.Device.Send("Hello " + pd.Value); - }; - - await this.OpenModal(pd); - } - - - } - - public override async Task Render(MessageResult message) - { - - Bitmap bmp = new Bitmap(800, 600); - using (Graphics 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 this.Device.SetAction(Telegram.Bot.Types.Enums.ChatAction.UploadPhoto); - - ButtonForm 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 this.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 OpenModal(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 OpenModal(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 224d067..5f28270 100644 --- a/TelegramBotBase.Test/packages.config +++ b/TelegramBotBase.Test/packages.config @@ -1,6 +1 @@ - - - - - - \ No newline at end of file + \ No newline at end of file diff --git a/TelegramBotBase/Args/BotCommandEventArgs.cs b/TelegramBotBase/Args/BotCommandEventArgs.cs index ed9e62c..02ec9d8 100644 --- a/TelegramBotBase/Args/BotCommandEventArgs.cs +++ b/TelegramBotBase/Args/BotCommandEventArgs.cs @@ -1,45 +1,38 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; 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; - this.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 ef9ef71..1bb69a4 100644 --- a/TelegramBotBase/Args/ButtonClickedEventArgs.cs +++ b/TelegramBotBase/Args/ButtonClickedEventArgs.cs @@ -1,49 +1,42 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; 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) - { - this.Button = button; - this.Index = -1; - } - - public ButtonClickedEventArgs(ButtonBase button, int Index) - { - this.Button = button; - this.Index = Index; - } - - public ButtonClickedEventArgs(ButtonBase button, int Index, ButtonRow row) - { - this.Button = button; - this.Index = Index; - this.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 4750334..6e5288e 100644 --- a/TelegramBotBase/Args/CheckedChangedEventArgs.cs +++ b/TelegramBotBase/Args/CheckedChangedEventArgs.cs @@ -1,44 +1,36 @@ using System; -using System.Collections.Generic; -using System.Text; using TelegramBotBase.Controls.Hybrid; -using TelegramBotBase.Form; -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) - { - this.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 c1668a0..5d8b9ae 100644 --- a/TelegramBotBase/Args/GroupChangedEventArgs.cs +++ b/TelegramBotBase/Args/GroupChangedEventArgs.cs @@ -1,24 +1,18 @@ using System; -using System.Collections.Generic; -using System.Text; 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) - { - this.Type = type; - this.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 ec30db8..a0af03a 100644 --- a/TelegramBotBase/Args/InitEventArgs.cs +++ b/TelegramBotBase/Args/InitEventArgs.cs @@ -1,18 +1,13 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace TelegramBotBase.Args +namespace TelegramBotBase.Args; + +public class InitEventArgs : EventArgs { - public class InitEventArgs : EventArgs + public InitEventArgs(params object[] args) { - public object[] Args { get; set; } - - public InitEventArgs(params object[] args) - { - this.Args = 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 7e79cb8..42fc51b 100644 --- a/TelegramBotBase/Args/LoadStateEventArgs.cs +++ b/TelegramBotBase/Args/LoadStateEventArgs.cs @@ -1,63 +1,59 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; -using System.Text; -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 - { - get - { - return Values.Keys.ToList(); - } - } - - public String Get(String key) - { - return Values[key].ToString(); - } - - public int GetInt(String key) - { - int 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) - { - bool 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 bc07add..f59f8c0 100644 --- a/TelegramBotBase/Args/MemberChangeEventArgs.cs +++ b/TelegramBotBase/Args/MemberChangeEventArgs.cs @@ -1,37 +1,29 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; 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() - { - this.Members = new List(); - - } - - public MemberChangeEventArgs(MessageType type, MessageResult result, params User[] members) - { - this.Type = type; - this.Result = result; - this.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 69d262b..34f174b 100644 --- a/TelegramBotBase/Args/MessageDeletedEventArgs.cs +++ b/TelegramBotBase/Args/MessageDeletedEventArgs.cs @@ -1,23 +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; -namespace TelegramBotBase.Args +public class MessageDeletedEventArgs { - public class MessageDeletedEventArgs + public MessageDeletedEventArgs(int messageId) { - public int MessageId - { - get;set; - } - - public MessageDeletedEventArgs(int messageId) - { - this.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 38bad2a..ddc0ac8 100644 --- a/TelegramBotBase/Args/MessageIncomeEventArgs.cs +++ b/TelegramBotBase/Args/MessageIncomeEventArgs.cs @@ -1,30 +1,20 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; 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; - this.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 397c6af..85fce86 100644 --- a/TelegramBotBase/Args/MessageReceivedEventArgs.cs +++ b/TelegramBotBase/Args/MessageReceivedEventArgs.cs @@ -1,28 +1,15 @@ -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 +namespace TelegramBotBase.Args; + +public class MessageReceivedEventArgs { - public class MessageReceivedEventArgs + public MessageReceivedEventArgs(Message m) { - public int MessageId - { - get - { - return this.Message.MessageId; - } - } - - public Message Message { get; set; } - - public MessageReceivedEventArgs(Message m) - { - this.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 9cfe651..3086908 100644 --- a/TelegramBotBase/Args/MessageSentEventArgs.cs +++ b/TelegramBotBase/Args/MessageSentEventArgs.cs @@ -1,36 +1,22 @@ 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 MessageSentEventArgs : EventArgs { - public class MessageSentEventArgs : EventArgs + public MessageSentEventArgs(Message message, Type origin) { - public int MessageId - { - get - { - return this.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) - { - this.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 14f9cf8..9de7888 100644 --- a/TelegramBotBase/Args/PromptDialogCompletedEventArgs.cs +++ b/TelegramBotBase/Args/PromptDialogCompletedEventArgs.cs @@ -1,14 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Text; +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 a733291..cc736eb 100644 --- a/TelegramBotBase/Args/RenderViewEventArgs.cs +++ b/TelegramBotBase/Args/RenderViewEventArgs.cs @@ -1,20 +1,13 @@ using System; -using System.Collections.Generic; -using System.Text; -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 4b26dea..39d3e46 100644 --- a/TelegramBotBase/Args/SaveStateEventArgs.cs +++ b/TelegramBotBase/Args/SaveStateEventArgs.cs @@ -1,41 +1,38 @@ -using System; -using System.Collections.Generic; -using System.Text; +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 2d6a3e5..b300d11 100644 --- a/TelegramBotBase/Args/SaveStatesEventArgs.cs +++ b/TelegramBotBase/Args/SaveStatesEventArgs.cs @@ -1,20 +1,13 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using TelegramBotBase.Base; -using TelegramBotBase.Sessions; +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) - { - this.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 778b5df..53a54b9 100644 --- a/TelegramBotBase/Args/SessionBeginEventArgs.cs +++ b/TelegramBotBase/Args/SessionBeginEventArgs.cs @@ -1,22 +1,17 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; 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 229fa91..5fbaf69 100644 --- a/TelegramBotBase/Args/SystemExceptionEventArgs.cs +++ b/TelegramBotBase/Args/SystemExceptionEventArgs.cs @@ -1,36 +1,27 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; 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; - this.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 e839e2d..844bc43 100644 --- a/TelegramBotBase/Args/UnhandledCallEventArgs.cs +++ b/TelegramBotBase/Args/UnhandledCallEventArgs.cs @@ -1,45 +1,38 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; 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() - { - this.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; - this.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 e1c5543..3deb6f4 100644 --- a/TelegramBotBase/Attributes/IgnoreState.cs +++ b/TelegramBotBase/Attributes/IgnoreState.cs @@ -1,17 +1,11 @@ using System; -using System.Collections.Generic; -using System.Text; -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 a07fe6b..71f5edc 100644 --- a/TelegramBotBase/Attributes/SaveState.cs +++ b/TelegramBotBase/Attributes/SaveState.cs @@ -1,15 +1,11 @@ using System; -using System.Collections.Generic; -using System.Text; -namespace TelegramBotBase.Attributes +namespace TelegramBotBase.Attributes; + +/// +/// Declares that the field or property should be save and recovered an restart. +/// +public class SaveState : Attribute { - /// - /// Declares that the field or property should be save and recovered an restart. - /// - public class SaveState : Attribute - { - public String Key { get; set; } - - } -} + public string Key { get; set; } +} \ No newline at end of file diff --git a/TelegramBotBase/Base/Async.cs b/TelegramBotBase/Base/Async.cs index ac190c7..260c7a1 100644 --- a/TelegramBotBase/Base/Async.cs +++ b/TelegramBotBase/Base/Async.cs @@ -1,25 +1,27 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; 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))); } } diff --git a/TelegramBotBase/Base/ControlBase.cs b/TelegramBotBase/Base/ControlBase.cs index 234554f..4c25177 100644 --- a/TelegramBotBase/Base/ControlBase.cs +++ b/TelegramBotBase/Base/ControlBase.cs @@ -1,80 +1,59 @@ -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 +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 Sessions.DeviceSession Device { get; set; } - - public int ID { get; set; } - - public String ControlID - { - get - { - return "#c" + this.ID.ToString(); - } - } - - /// - /// 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 async Task Load(MessageResult result) - { - - - - } - - public virtual async Task Action(MessageResult result, String value = null) - { - - - - } - - - - public virtual async Task Render(MessageResult result) - { - - - - - } - - public virtual async Task Hidden(bool FormClose) - { - - - } - - /// - /// Will be called on a cleanup. - /// - /// - public virtual async Task Cleanup() - { - - } - } -} + + 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 fb87df0..14c7d9b 100644 --- a/TelegramBotBase/Base/DataResult.cs +++ b/TelegramBotBase/Base/DataResult.cs @@ -1,226 +1,170 @@ -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 +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 - { - get - { - return this.Message.Contact; - } - } - - public Location Location - { - get - { - return this.Message.Location; - } - } - - public Document Document - { - get - { - return this.Message.Document; - } - } - - public Audio Audio - { - get - { - return this.Message.Audio; - } - } - - public Video Video - { - get - { - return this.Message.Video; - } - } - - public PhotoSize[] Photos - { - get - { - return this.Message.Photo; - } - } - - - public Telegram.Bot.Types.Enums.MessageType Type - { - get - { - return this.Message?.Type ?? Telegram.Bot.Types.Enums.MessageType.Unknown; - } - } - - public override Message Message - { - get - { - return this.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 DataResult(UpdateResult update) - { - this.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); - - return new InputOnlineFile(encryptedContent, this.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(this.Document.FileId); - FileStream 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() - { - MemoryStream ms = new MemoryStream(); - await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.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) - { - MemoryStream ms = new MemoryStream(); - await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Document.FileId, ms); - - ms.Position = 0; - - var sr = new StreamReader(ms, encoding); - - return sr.ReadToEnd(); - } - - 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); - - return new InputOnlineFile(encryptedContent, ""); - } - - public async Task DownloadVideo(String path) - { - var file = await Device.Client.TelegramClient.GetFileAsync(this.Video.FileId); - FileStream 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 System.IO.MemoryStream(); - encryptedContent.SetLength(this.Audio.FileSize.Value); - var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Audio.FileId, encryptedContent); - - return new InputOnlineFile(encryptedContent, ""); - } - - public async Task DownloadAudio(String path) - { - var file = await Device.Client.TelegramClient.GetFileAsync(this.Audio.FileId); - FileStream 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 = this.Photos[index]; - var encryptedContent = new System.IO.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 = this.Photos[index]; - var file = await Device.Client.TelegramClient.GetFileAsync(photo.FileId); - FileStream 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 291e733..479e5ee 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; @@ -10,436 +9,448 @@ 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 { + private static readonly object EvInit = new(); + + private static readonly object EvOpened = new(); + + private static readonly object EvClosed = new(); + + + public EventHandlerList Events = new(); + + + public NavigationController NavigationController { get; set; } + + public DeviceSession Device { get; set; } + + public MessageClient Client { get; set; } + /// - /// Base class for forms + /// has this formular already been disposed ? /// - public class FormBase : IDisposable + public bool IsDisposed { get; set; } + + public List Controls { get; set; } + + public FormBase() { + Controls = new List(); + } - public NavigationController NavigationController { get; set; } + public FormBase(MessageClient client) : this() + { + Client = client; + } - public DeviceSession Device { get; set; } - - public MessageClient Client { get; set; } - - /// - /// has this formular already been disposed ? - /// - public bool IsDisposed { get; set; } = false; - - public List Controls { get; set; } + /// + /// Cleanup + /// + public void Dispose() + { + Client = null; + Device = null; + IsDisposed = true; + } - public EventHandlerList Events = new EventHandlerList(); - - - private static object __evInit = new object(); - - private static object __evOpened = new object(); - - private static object __evClosed = new object(); - - - public FormBase() + public async Task OnInit(InitEventArgs e) + { + var handler = Events[EvInit]?.GetInvocationList().Cast>(); + if (handler == null) { - this.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 = this.Events[__evInit]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) - { - await Async.InvokeAllAsync(h, this, e); - } - } - - ///// - ///// Will get called at the initialization (once per context) - ///// - public event AsyncEventHandler Init - { - add - { - this.Events.AddHandler(__evInit, value); - } - remove - { - this.Events.RemoveHandler(__evInit, value); - } - } - - - - public async Task OnOpened(EventArgs e) - { - var handler = this.Events[__evOpened]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) - { - await Async.InvokeAllAsync(h, this, e); - } - } - - /// - /// Gets invoked if gets navigated to this form - /// - /// - public event AsyncEventHandler Opened - { - add - { - this.Events.AddHandler(__evOpened, value); - } - remove - { - this.Events.RemoveHandler(__evOpened, value); - } - } - - - - public async Task OnClosed(EventArgs e) - { - var handler = this.Events[__evClosed]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) - { - await Async.InvokeAllAsync(h, this, e); - } - } - - - /// - /// Form has been closed (left) - /// - /// - public event AsyncEventHandler Closed - { - add - { - this.Events.AddHandler(__evClosed, value); - } - remove - { - this.Events.RemoveHandler(__evClosed, value); - } - } - - /// - /// Get invoked when a modal child from has been closed. - /// - /// - /// - public virtual async Task ReturnFromModal(ModalDialog modal) - { - - } - - - /// - /// Pre to form close, cleanup all controls - /// - /// - public async Task CloseControls() - { - foreach (var b in this.Controls) - { - b.Cleanup().Wait(); - } - } - - public virtual async Task PreLoad(MessageResult message) - { - - } - - /// - /// 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 = this.Controls.FirstOrDefault(a => a.ControlID == message.RawData.Split('_')[0]); - if (c != null) - { - await c.Load(message); - return; - } - } - - foreach (var b in this.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 async Task Load(MessageResult message) - { - - } - - /// - /// Gets invoked, when a messages has been edited. - /// - /// - /// - public virtual async Task Edited(MessageResult message) - { - - } - - - /// - /// 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 = this.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 this.Controls) - { - if (!b.Enabled) - continue; - - await b.Action(message); - - if (message.Handled) - return; - } - } - - /// - /// Gets invoked if the user has clicked a button. - /// - /// - /// - public virtual async Task Action(MessageResult message) - { - - } - - /// - /// Gets invoked if the user has sent some media (Photo, Audio, Video, Contact, Location, Document) - /// - /// - /// - public virtual async Task SentData(DataResult message) - { - - } - - /// - /// 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 this.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 async Task Render(MessageResult message) - { - - } - - - - /// - /// Navigates to a new form - /// - /// - /// - public virtual async Task NavigateTo(FormBase newForm, params object[] args) - { - DeviceSession ds = this.Device; - if (ds == null) - return; - - ds.FormSwitched = true; - - ds.PreviousForm = ds.ActiveForm; - - ds.ActiveForm = newForm; - newForm.Client = this.Client; - newForm.Device = ds; - - //Notify prior to close - foreach (var b in this.Controls) - { - if (!b.Enabled) - continue; - - await b.Hidden(true); - } - - this.CloseControls().Wait(); - - await this.OnClosed(new EventArgs()); - - await newForm.OnInit(new InitEventArgs(args)); - - await newForm.OnOpened(new EventArgs()); - } - - /// - /// Opens this form modal, but don't closes the original ones - /// - /// - /// - public virtual async Task OpenModal(ModalDialog newForm, params object[] args) - { - DeviceSession ds = this.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 this.Controls) - { - if (!b.Enabled) - continue; - - await b.Hidden(false); - } - - await newForm.OnInit(new InitEventArgs(args)); - - await newForm.OnOpened(new EventArgs()); - } - - public async Task CloseModal(ModalDialog modalForm, FormBase oldForm) - { - DeviceSession ds = this.Device; - if (ds == null) - return; - - if (modalForm == null) - throw new Exception("No modal form"); - - ds.FormSwitched = true; - - ds.PreviousForm = ds.ActiveForm; - - ds.ActiveForm = oldForm; - } - - /// - /// Adds a control to the formular and sets its ID and Device. - /// - /// - public void AddControl(ControlBase control) - { - //Duplicate check - if (this.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.Init(); - } - - /// - /// Removes control from the formular and runs a cleanup on it. - /// - /// - public void RemoveControl(ControlBase control) - { - if (!this.Controls.Contains(control)) - return; - - control.Cleanup().Wait(); - - this.Controls.Remove(control); - } - - /// - /// Removes all controls. - /// - public void RemoveAllControls() - { - foreach(var c in this.Controls) - { - c.Cleanup().Wait(); - - this.Controls.Remove(c); - } - } - - /// - /// Cleanup - /// - public void Dispose() - { - this.Client = null; - this.Device = null; - this.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); + } + } + + /// + /// 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/Base/MessageClient.cs b/TelegramBotBase/Base/MessageClient.cs index 85195f9..db7e27b 100644 --- a/TelegramBotBase/Base/MessageClient.cs +++ b/TelegramBotBase/Base/MessageClient.cs @@ -1,214 +1,193 @@ 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 +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 object __evOnMessageLoop = new object(); - - private static object __evOnMessage = new object(); - - private static object __evOnMessageEdit = new object(); - - private static object __evCallbackQuery = new object(); - - CancellationTokenSource __cancellationTokenSource; - - - public MessageClient(String APIKey) - { - this.APIKey = APIKey; - this.TelegramClient = new Telegram.Bot.TelegramBotClient(APIKey); - - Prepare(); - } - - public MessageClient(String APIKey, HttpClient proxy) - { - this.APIKey = APIKey; - this.TelegramClient = new Telegram.Bot.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 } - ); - - this.TelegramClient = new Telegram.Bot.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 } - ); - - this.TelegramClient = new Telegram.Bot.TelegramBotClient(APIKey, httpClient); - - Prepare(); - } - - - - public MessageClient(String APIKey, Telegram.Bot.TelegramBotClient Client) - { - this.APIKey = APIKey; - this.TelegramClient = Client; - - Prepare(); - } - - - public void Prepare() - { - this.TelegramClient.Timeout = new TimeSpan(0, 0, 30); - - } - - - - public void StartReceiving() - { - __cancellationTokenSource = new CancellationTokenSource(); - - var receiverOptions = new ReceiverOptions - { - AllowedUpdates = { } // receive all update types - }; - - this.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 this.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 this.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 this.TelegramClient.DeleteMyCommandsAsync(scope, languageCode); - } - - - #region "Events" - - - - public event Async.AsyncEventHandler MessageLoop - { - add - { - this.__Events.AddHandler(__evOnMessageLoop, value); - } - remove - { - this.__Events.RemoveHandler(__evOnMessageLoop, value); - } - } - - public void OnMessageLoop(UpdateResult update) - { - (this.__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; } + + 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 async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken) + { + await OnMessageLoop(new UpdateResult(update, null)); + } + + 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 async Task OnMessageLoop(UpdateResult update) + { + await (Events[EvOnMessageLoop] as Async.AsyncEventHandler)?.Invoke(this, update); + } + + #endregion } diff --git a/TelegramBotBase/Base/MessageResult.cs b/TelegramBotBase/Base/MessageResult.cs index ed5d4d2..11e33d7 100644 --- a/TelegramBotBase/Base/MessageResult.cs +++ b/TelegramBotBase/Base/MessageResult.cs @@ -1,200 +1,145 @@ -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 +namespace TelegramBotBase.Base; + +public class MessageResult : ResultBase { - public class MessageResult : ResultBase + internal MessageResult() { + } - public Telegram.Bot.Types.Update UpdateData { get; set; } + public MessageResult(Update update) + { + UpdateData = update; + } - /// - /// Returns the Device/ChatId - /// - public override long DeviceId + public Update UpdateData { get; set; } + + /// + /// Returns the Device/ChatId + /// + public override long DeviceId => + UpdateData?.Message?.Chat?.Id + ?? UpdateData?.EditedMessage?.Chat.Id + ?? UpdateData?.CallbackQuery.Message?.Chat.Id + ?? Device?.DeviceId + ?? 0; + + /// + /// The message id + /// + public override int MessageId => + UpdateData?.Message?.MessageId + ?? Message?.MessageId + ?? UpdateData?.CallbackQuery?.Message?.MessageId + ?? 0; + + public string Command => UpdateData?.Message?.Text ?? ""; + + public string MessageText => UpdateData?.Message?.Text ?? ""; + + 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) + /// + public bool IsAction => UpdateData.CallbackQuery != null; + + /// + /// 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) { - return this.UpdateData?.Message?.Chat?.Id - ?? this.UpdateData?.EditedMessage?.Chat.Id - ?? this.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 String Command - { - get - { - return this.UpdateData?.Message?.Text ?? ""; - } - } - - public String MessageText - { - get - { - return this.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; - } - } - - /// - /// Is this an action ? (i.e. button click) - /// - public bool IsAction - { - get - { - return (this.UpdateData.CallbackQuery != null); - } - } - - /// - /// Is this a command ? Starts with a slash '/' and a command - /// - public bool IsBotCommand - { - get - { - return (this.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 - { - if (!IsBotCommand) - return new List(); - - //Split by empty space and skip first entry (command itself), return as list - return this.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 this.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 - { - get - { - return this.UpdateData?.CallbackQuery?.Data; - } - } - - public T GetData() - where T : class - { - T cd = null; - try - { - cd = Newtonsoft.Json.JsonConvert.DeserializeObject(this.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 incoming 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 this.Device.ConfirmAction(this.UpdateData.CallbackQuery.Id, message, showAlert, urlToOpen); - } - - public override async Task DeleteMessage() - { - try + if (!IsBotCommand) { - await base.DeleteMessage(this.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(Telegram.Bot.Types.Update update) + catch { - this.UpdateData = update; - } + return null; + } + + /// + /// Confirm incoming 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 adf8ecc..69a4f74 100644 --- a/TelegramBotBase/Base/ResultBase.cs +++ b/TelegramBotBase/Base/ResultBase.cs @@ -1,59 +1,45 @@ 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 +namespace TelegramBotBase.Base; + +public class ResultBase : EventArgs { - public class ResultBase : EventArgs + public DeviceSession Device { get; set; } + + public virtual long DeviceId { get; set; } + + public virtual int MessageId => Message.MessageId; + + public virtual Message Message { get; set; } + + /// + /// Deletes the current message + /// + /// + /// + public virtual async Task DeleteMessage() { - public DeviceSession Device + await DeleteMessage(MessageId); + } + + /// + /// Deletes the current message or the given one. + /// + /// + /// + public virtual async Task DeleteMessage(int messageId = -1) + { + try { - get; - set; + await Device.Client.TelegramClient.DeleteMessageAsync(DeviceId, + messageId == -1 ? MessageId : messageId); } - - public virtual long DeviceId { get; set; } - - public int MessageId + catch { - get - { - return this.Message.MessageId; - } } - - public virtual Telegram.Bot.Types.Message Message { get; set; } - - /// - /// Deletes the current message - /// - /// - /// - public virtual async Task DeleteMessage() - { - await DeleteMessage(this.MessageId); - } - - /// - ///Deletes the current message or the given one. - /// - /// - /// - public virtual async Task DeleteMessage(int messageId = -1) - { - try - { - await Device.Client.TelegramClient.DeleteMessageAsync(this.DeviceId, (messageId == -1 ? this.MessageId : messageId)); - } - catch - { - - } - } - } } diff --git a/TelegramBotBase/Base/StateContainer.cs b/TelegramBotBase/Base/StateContainer.cs index d4a12f0..de6b766 100644 --- a/TelegramBotBase/Base/StateContainer.cs +++ b/TelegramBotBase/Base/StateContainer.cs @@ -1,34 +1,24 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; -using System.Text; -namespace TelegramBotBase.Base +namespace TelegramBotBase.Base; + +public class StateContainer { - public partial 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() - { - this.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 9a7e0c1..8513804 100644 --- a/TelegramBotBase/Base/StateEntry.cs +++ b/TelegramBotBase/Base/StateEntry.cs @@ -1,44 +1,38 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Diagnostics; -using System.Runtime.Serialization; -using System.Text; -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() - { - this.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 f2341dd..82d46b3 100644 --- a/TelegramBotBase/Base/UpdateResult.cs +++ b/TelegramBotBase/Base/UpdateResult.cs @@ -1,59 +1,31 @@ -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 +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 - { - get - { - return this.RawData?.Message?.Chat?.Id - ?? this.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; - } - - + 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 903505c..05f8053 100644 --- a/TelegramBotBase/BotBase.cs +++ b/TelegramBotBase/BotBase.cs @@ -2,132 +2,119 @@ 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 message handling +/// +/// +public sealed class BotBase { - /// - /// Bot base class for full Device/Context and Messagehandling - /// - /// - public sealed class BotBase + internal BotBase(string apiKey, MessageClient client) { - public MessageClient Client { get; set; } + ApiKey = apiKey; + Client = client; - /// - /// Your TelegramBot APIKey - /// - public String APIKey { get; set; } = ""; + SystemSettings = new Dictionary(); - /// - /// List of all running/active sessions - /// - public SessionManager Sessions { get; set; } + SetSetting(ESettings.MaxNumberOfRetries, 5); + SetSetting(ESettings.NavigationMaximum, 10); + SetSetting(ESettings.LogAllMessages, false); + SetSetting(ESettings.SkipAllMessages, false); + SetSetting(ESettings.SaveSessionsOnConsoleExit, false); - /// - /// 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>(); + BotCommandScopes = new Dictionary>(); + + Sessions = new SessionManager(this); + } + + public MessageClient Client { get; } + + /// + /// Your TelegramBot APIKey + /// + public string ApiKey { get; } + + /// + /// List of all running/active sessions + /// + 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; internal set; } - #region "Events" + /// + /// Enable the SessionState (you need to implement on call forms the IStateForm interface) + /// + public IStateMachine StateMachine { get; internal set; } - private EventHandlerList __events = new EventHandlerList(); + /// + /// Offers functionality to manage the creation process of the start form. + /// + public IStartFormFactory StartFormFactory { get; internal set; } - private static object __evSessionBegins = new object(); + /// + /// Contains the message loop factory, which cares about "message-management." + /// + public IMessageLoopFactory MessageLoopFactory { get; internal set; } - private static 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 object __evUnhandledCall = new object(); - - #endregion + /// + /// All internal used settings. + /// + public Dictionary SystemSettings { get; } - /// - /// 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; } - - internal BotBase() + /// + /// Start your Bot + /// + public async Task Start() + { + if (Client == null) { - 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 SessionManager(this); + return; } + Client.MessageLoop += Client_MessageLoop; - - /// - /// Start your Bot - /// - public async Task Start() + if (StateMachine != null) { - Client.MessageLoop += Client_MessageLoop; - - - if (StateMachine != null) await Sessions.LoadSessionStates(StateMachine); - - - //Enable auto session saving - if (GetSetting(eSettings.SaveSessionsOnConsoleExit, false)) - TelegramBotBase.Tools.Console.SetHandler(() => { Task.Run(Sessions.SaveSessionStates); }); - - - DeviceSession.MaxNumberOfRetries = GetSetting(eSettings.MaxNumberOfRetries, 5); - - Client.StartReceiving(); + await Sessions.LoadSessionStates(StateMachine); } - - private async Task Client_MessageLoop(object sender, UpdateResult e) + // Enable auto session saving + if (GetSetting(ESettings.SaveSessionsOnConsoleExit, false)) { - DeviceSession ds = this.Sessions.GetSession(e.DeviceId); + // should be waited until finish + Console.SetHandler(() => { Sessions.SaveSessionStates().GetAwaiter().GetResult(); }); + } + + DeviceSession.MaxNumberOfRetries = GetSetting(ESettings.MaxNumberOfRetries, 5); + + Client.StartReceiving(); + } + + + private async Task Client_MessageLoop(object sender, UpdateResult e) + { + try + { + var ds = Sessions.GetSession(e.DeviceId); if (ds == null) { - ds = Sessions.StartSession(e.DeviceId).GetAwaiter().GetResult(); + ds = await Sessions.StartSession(e.DeviceId); e.Device = ds; ds.LastMessage = e.RawData.Message; @@ -136,7 +123,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 @@ -149,277 +136,278 @@ namespace TelegramBotBase await MessageLoopFactory.MessageLoop(this, ds, e, mr); mr.IsFirstHandler = false; + } while (ds.FormSwitched && i < GetSetting(ESettings.NavigationMaximum, 10)); + } + catch (Exception ex) + { + var ds = Sessions.GetSession(e.DeviceId); + OnException(new SystemExceptionEventArgs(e.Message.Text, e.DeviceId, ds, ex)); + } + } - } while (ds.FormSwitched && i < GetSetting(eSettings.NavigationMaximum, 10)); + + /// + /// Stop your Bot + /// + public async Task Stop() + { + if (Client == null) + { + return; } + Client.MessageLoop -= Client_MessageLoop; + Client.StopReceiving(); - /// - /// Stop your Bot - /// - public async Task Stop() + await Sessions.SaveSessionStates(); + } + + /// + /// Send a message to all active Sessions. + /// + /// + /// + public async Task SentToAll(string message) + { + if (Client == null) { - if (Client == null) - return; - - Client.MessageLoop -= Client_MessageLoop; - - - Client.StopReceiving(); - - await Sessions.SaveSessionStates(); + return; } - /// - /// Send a message to all active Sessions. - /// - /// - /// - public async Task SentToAll(String message) + foreach (var s in Sessions.SessionList) { - if (Client == null) - return; - - foreach (var s in Sessions.SessionList) - { - await Client.TelegramClient.SendTextMessageAsync(s.Key, message); - } + 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) + /// + /// 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 { - var mr = new MessageResult(); - - mr.UpdateData = new Update() + 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 - { - DeviceSession ds = this.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) - { - DeviceSession ds = this.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 + }; + 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); + } + 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; + } + + + #region "Events" + + private readonly EventHandlerList _events = new(); + + private static readonly object EvSessionBegins = new(); + + private static readonly object EvMessage = 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 incoming 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 handled 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 } diff --git a/TelegramBotBase/Builder/BotBaseBuilder.cs b/TelegramBotBase/Builder/BotBaseBuilder.cs index 63b3658..dc22976 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,340 +10,356 @@ using TelegramBotBase.Factories; using TelegramBotBase.Form; using TelegramBotBase.Interfaces; 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() { - - String _apiKey = null; - - IStartFormFactory _factory = null; - - MessageClient _client = null; - - /// - /// Contains different Botcommands for different areas. - /// - Dictionary> _BotCommandScopes { get; set; } = new Dictionary>(); - - //List _botcommands = new List(); - - IStateMachine _statemachine = null; - - IMessageLoopFactory _messageloopfactory = null; - - private BotBaseBuilder() - { - - } - - public static IAPIKeySelectionStage Create() - { - return new BotBaseBuilder(); - } - - #region "Step 1 (Basic Stuff)" - - public IMessageLoopSelectionStage WithAPIKey(string apiKey) - { - this._apiKey = apiKey; - return this; - } - - - public IBuildingStage QuickStart(string apiKey, Type StartForm) - { - this._apiKey = apiKey; - this._factory = new Factories.DefaultStartFormFactory(StartForm); - - DefaultMessageLoop(); - - NoProxy(); - - OnlyStart(); - - NoSerialization(); - - DefaultLanguage(); - - return this; - } - - - public IBuildingStage QuickStart(string apiKey) - where T : FormBase - { - this._apiKey = apiKey; - this._factory = new Factories.DefaultStartFormFactory(typeof(T)); - - DefaultMessageLoop(); - - NoProxy(); - - OnlyStart(); - - NoSerialization(); - - DefaultLanguage(); - - return this; - } - - public IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory) - { - this._apiKey = apiKey; - this._factory = StartFormFactory; - - DefaultMessageLoop(); - - NoProxy(); - - OnlyStart(); - - NoSerialization(); - - DefaultLanguage(); - - return this; - } - - #endregion - - - #region "Step 2 (Message Loop)" - - public IStartFormSelectionStage DefaultMessageLoop() - { - _messageloopfactory = new MessageLoops.FormBaseMessageLoop(); - - return this; - } - - - public IStartFormSelectionStage MinimalMessageLoop() - { - _messageloopfactory = new MessageLoops.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) - { - this._factory = new Factories.DefaultStartFormFactory(startFormClass); - return this; - } - - public INetworkingSelectionStage WithStartForm() - where T : FormBase, new() - { - this._factory = new Factories.DefaultStartFormFactory(typeof(T)); - return this; - } - - public INetworkingSelectionStage WithServiceProvider(Type startFormClass, IServiceProvider serviceProvider) - { - this._factory = new ServiceProviderStartFormFactory(startFormClass, serviceProvider); - return this; - } - - public INetworkingSelectionStage WithServiceProvider(IServiceProvider serviceProvider) - where T : FormBase - { - this._factory = new ServiceProviderStartFormFactory(serviceProvider); - return this; - } - - public INetworkingSelectionStage WithStartFormFactory(IStartFormFactory factory) - { - this._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); - _client.TelegramClient.Timeout = new TimeSpan(0, 1, 0); - return this; - } - - - public IBotCommandsStage NoProxy() - { - _client = new MessageClient(_apiKey); - _client.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); - return this; - } - - - public IBotCommandsStage WithHostAndPort(string proxyHost, int proxyPort) - { - _client = new MessageClient(_apiKey, proxyHost, proxyPort); - _client.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); - 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) - { - this._statemachine = machine; - return this; - } - - - public ILanguageSelectionStage UseJSON(string path) - { - this._statemachine = new JSONStateMachine(path); - return this; - } - - public ILanguageSelectionStage UseSimpleJSON(string path) - { - this._statemachine = new SimpleJSONStateMachine(path); - return this; - } - - public ILanguageSelectionStage UseXML(string path) - { - this._statemachine = new XMLStateMachine(path); - return this; - } - - #endregion - - - #region "Step 7 (Language)" - - public IBuildingStage DefaultLanguage() - { - return this; - } - - public IBuildingStage UseEnglish() - { - Localizations.Default.Language = new Localizations.English(); - return this; - } - - public IBuildingStage UseGerman() - { - Localizations.Default.Language = new Localizations.German(); - return this; - } - - public IBuildingStage Custom(Localization language) - { - Localizations.Default.Language = language; - return this; - } - - #endregion - - - public BotBase Build() - { - var bb = new BotBase(); - - bb.APIKey = _apiKey; - bb.StartFormFactory = _factory; - - bb.Client = _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 bot = new BotBase(_apiKey, _client) + { + StartFormFactory = _factory, + BotCommandScopes = BotCommandScopes, + StateMachine = _stateMachine, + MessageLoopFactory = _messageLoopFactory + }; + + bot.MessageLoopFactory.UnhandledCall += bot.MessageLoopFactory_UnhandledCall; + + return bot; + } + + 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 } diff --git a/TelegramBotBase/Builder/Interfaces/IAPIKeySelectionStage.cs b/TelegramBotBase/Builder/Interfaces/IAPIKeySelectionStage.cs index bd6f05e..bcbe23b 100644 --- a/TelegramBotBase/Builder/Interfaces/IAPIKeySelectionStage.cs +++ b/TelegramBotBase/Builder/Interfaces/IAPIKeySelectionStage.cs @@ -1,45 +1,42 @@ using System; -using System.Collections.Generic; -using System.Text; 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 a275090..510db3b 100644 --- a/TelegramBotBase/Builder/Interfaces/IBotCommandsStage.cs +++ b/TelegramBotBase/Builder/Interfaces/IBotCommandsStage.cs @@ -1,41 +1,36 @@ using System; using System.Collections.Generic; -using System.Text; 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 8313b0b..17e49cc 100644 --- a/TelegramBotBase/Builder/Interfaces/IBuildingStage.cs +++ b/TelegramBotBase/Builder/Interfaces/IBuildingStage.cs @@ -1,11 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Text; +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 2e5e01a..e32f710 100644 --- a/TelegramBotBase/Builder/Interfaces/ILanguageSelectionStage.cs +++ b/TelegramBotBase/Builder/Interfaces/ILanguageSelectionStage.cs @@ -1,36 +1,30 @@ -using System; -using System.Collections.Generic; -using System.Text; -using TelegramBotBase.Localizations; +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 429a81d..21223e7 100644 --- a/TelegramBotBase/Builder/Interfaces/IMessageLoopSelectionStage.cs +++ b/TelegramBotBase/Builder/Interfaces/IMessageLoopSelectionStage.cs @@ -1,44 +1,36 @@ -using System; -using System.Collections.Generic; -using System.Text; -using TelegramBotBase.Form; -using TelegramBotBase.Interfaces; +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 4b5bcce..3e48b21 100644 --- a/TelegramBotBase/Builder/Interfaces/INetworkingSelectionStage.cs +++ b/TelegramBotBase/Builder/Interfaces/INetworkingSelectionStage.cs @@ -1,51 +1,44 @@ -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Text; +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 a729da2..5ed022b 100644 --- a/TelegramBotBase/Builder/Interfaces/ISessionSerializationStage.cs +++ b/TelegramBotBase/Builder/Interfaces/ISessionSerializationStage.cs @@ -1,49 +1,44 @@ -using System; -using System.Collections.Generic; -using System.Text; -using TelegramBotBase.Interfaces; +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 78692ea..1254693 100644 --- a/TelegramBotBase/Builder/Interfaces/IStartFormSelectionStage.cs +++ b/TelegramBotBase/Builder/Interfaces/IStartFormSelectionStage.cs @@ -1,50 +1,45 @@ using System; -using System.Collections.Generic; -using System.Text; 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 8237d4f..6a19ce1 100644 --- a/TelegramBotBase/Commands/Extensions.cs +++ b/TelegramBotBase/Commands/Extensions.cs @@ -1,145 +1,182 @@ -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 +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, null); - - /// - /// Adding the default /help command with a description. - /// - /// - /// - public static void Help(this Dictionary> cmds, String description) => Add(cmds, "help", description, null); - - /// - /// Adding the default /settings command with a description. - /// - /// - /// - public static void Settings(this Dictionary> cmds, String description) => Add(cmds, "settings", description, null); - - /// - /// Clears all default commands. - /// - /// - public static void ClearDefaultCommands(this Dictionary> cmds) => Clear(cmds, null); - - /// - /// 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 d203123..a2837d7 100644 --- a/TelegramBotBase/Constants/Telegram.cs +++ b/TelegramBotBase/Constants/Telegram.cs @@ -1,27 +1,19 @@ -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 { - 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 d62179f..ca0a895 100644 --- a/TelegramBotBase/Controls/Hybrid/ButtonGrid.cs +++ b/TelegramBotBase/Controls/Hybrid/ButtonGrid.cs @@ -1,238 +1,344 @@ 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 +namespace TelegramBotBase.Controls.Hybrid; + +public class ButtonGrid : ControlBase { - public class ButtonGrid : Base.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; } = Localizations.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 + /// + /// 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 + if (_mEKeyboardType != value) { - return DataSource.ButtonForm; - } - set - { - DataSource = new ButtonFormDataSource(value); + _renderNecessary = true; + + Cleanup().Wait(); + + _mEKeyboardType = 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; } = 0; - - public String PreviousPageLabel = Localizations.Default.Language["ButtonGrid_PreviousPage"]; - - public String NextPageLabel = Localizations.Default.Language["ButtonGrid_NextPage"]; - - public String NoItemsLabel = Localizations.Default.Language["ButtonGrid_NoItems"]; - - public String SearchLabel = Localizations.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 + public bool PagingNecessary + { + get { - get + if (KeyboardType == EKeyboardType.InlineKeyBoard && + TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) { - return m_eKeyboardType; - } - set - { - if (m_eKeyboardType != value) - { - this.RenderNecessary = true; - - Cleanup().Wait(); - - m_eKeyboardType = value; - } - - } - } - - private eKeyboardType m_eKeyboardType = eKeyboardType.ReplyKeyboard; - - public ButtonGrid() - { - this.DataSource = new ButtonFormDataSource(); - - } - - public ButtonGrid(eKeyboardType type) : this() - { - m_eKeyboardType = type; - } - - - public ButtonGrid(ButtonForm form) - { - this.DataSource = new ButtonFormDataSource(form); - } - - - public event AsyncEventHandler ButtonClicked - { - add - { - this.Events.AddHandler(__evButtonClicked, value); - } - remove - { - this.Events.RemoveHandler(__evButtonClicked, value); - } - } - - public async Task OnButtonClicked(ButtonClickedEventArgs e) - { - var handler = this.Events[__evButtonClicked]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) - { - await Async.InvokeAllAsync(h, this, e); - } - } - - public override void Init() - { - this.Device.MessageDeleted += Device_MessageDeleted; - } - - private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e) - { - if (this.MessageId == null) - return; - - if (e.MessageId != this.MessageId) - return; - - this.MessageId = null; - } - - public async override Task Load(MessageResult result) - { - if (this.KeyboardType != eKeyboardType.ReplyKeyboard) - return; - - if (!result.IsFirstHandler) - return; - - if (result.MessageText == null || result.MessageText == "") - return; - - var matches = new List(); - ButtonRow match = null; - int 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); @@ -243,98 +349,106 @@ namespace TelegramBotBase.Controls.Hybrid check: - //Remove button click message - if (this.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 (this.CurrentPageIndex > 0) - this.CurrentPageIndex--; - - this.Updated(); - } - else if (result.MessageText == NextPageLabel) - { - if (this.CurrentPageIndex < this.PageCount - 1) - this.CurrentPageIndex++; - - this.Updated(); - } - 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(); - } - - } - - - + //Remove button click message + if (DeleteReplyMessage) + { + await Device.DeleteMessage(result.MessageId); } - public async override 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 (this.KeyboardType != eKeyboardType.InlineKeyBoard) - return; - await result.ConfirmAction(this.ConfirmationText ?? ""); - - ButtonRow match = null; - int 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; @@ -346,393 +460,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 (this.CurrentPageIndex > 0) - this.CurrentPageIndex--; - - this.Updated(); - - break; - case "$next$": - - if (this.CurrentPageIndex < this.PageCount - 1) - this.CurrentPageIndex++; - - this.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 (m_eKeyboardType) - { - case eKeyboardType.InlineKeyBoard: + case "$previous$": - if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !this.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 && !this.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 async override Task Render(MessageResult result) - { - if (!this.RenderNecessary) - return; - - //Check for rows and column limits - CheckGrid(); - - this.RenderNecessary = false; - - ButtonForm form = this.DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (this.EnableSearch ? this.SearchQuery : null)); - - - //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") - //{ - // form = form.FilterDuplicate(this.SearchQuery, true); - //} - //else - //{ - // form = form.Duplicate(); - //} - - if (this.EnablePaging) - { - IntegratePagingView(form); - } - - if (this.HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) - { - form.InsertButtonRow(0, this.HeadLayoutButtonRow); - } - - if (this.SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) - { - if (this.IsNavigationBarVisible) + if (CurrentPageIndex > 0) { - form.InsertButtonRow(2, this.SubHeadLayoutButtonRow); - } - else - { - form.InsertButtonRow(1, this.SubHeadLayoutButtonRow); - } - } - - Message m = null; - - switch (this.KeyboardType) - { - //Reply Keyboard could only be updated with a new keyboard. - case eKeyboardType.ReplyKeyboard: - - - if (form.Count == 0) - { - if (this.MessageId != null) - { - await this.Device.HideReplyKeyboard(); - this.MessageId = null; - } - - return; - } - - //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 = this.ResizeKeyboard; - rkm.OneTimeKeyboard = this.OneTimeKeyboard; - m = await this.Device.Send(this.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); - - 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 (this.MessageId != null) - { - m = await this.Device.Edit(this.MessageId.Value, this.Title, (InlineKeyboardMarkup)form); - if (m != null) - { - this.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); - - break; - } - - if (m != null) - { - this.MessageId = m.MessageId; - } - - - } - - private void IntegratePagingView(ButtonForm dataForm) - { - //No Items - if (dataForm.Rows == 0) - { - dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$")); - } - - if (this.IsNavigationBarVisible) - { - //🔍 - ButtonRow 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(NextPageLabel, "$next$")); - - if (this.EnableSearch) - { - row.Insert(2, new ButtonBase("🔍 " + (this.SearchQuery ?? ""), "$search$")); + CurrentPageIndex--; } - dataForm.InsertButtonRow(0, row); + Updated(); - dataForm.AddButtonRow(row); - } - } + break; + case "$next$": - public bool PagingNecessary - { - get - { - if (this.KeyboardType == eKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) + if (CurrentPageIndex < PageCount - 1) { - return true; + CurrentPageIndex++; } - if (this.KeyboardType == eKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows) + Updated(); + + break; + } + } + + /// + /// This method checks of the amount of buttons + /// + private void CheckGrid() + { + switch (_mEKeyboardType) + { + case EKeyboardType.InlineKeyBoard: + + if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging) { - return true; + throw new MaximumRowsReachedException + { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; } - return false; - } - } - - public bool IsNavigationBarVisible - { - get - { - if (this.NavigationBarVisibility == eNavigationBarVisibility.always | (this.NavigationBarVisibility == eNavigationBarVisibility.auto && PagingNecessary)) + if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols) { - return true; + throw new MaximumColsException + { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; } - return false; - } - } + break; - /// - /// Returns the maximum number of rows - /// - public int MaximumRow - { - get - { - switch (this.KeyboardType) + case EKeyboardType.ReplyKeyboard: + + if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging) { - case eKeyboardType.InlineKeyBoard: - return Constants.Telegram.MaxInlineKeyBoardRows; - - case eKeyboardType.ReplyKeyboard: - return Constants.Telegram.MaxReplyKeyboardRows; - - default: - return 0; + 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; } - /// - /// Returns the number of all rows (layout + navigation + content); - /// - public int TotalRows + //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) { - get - { - return this.LayoutRows + DataSource.RowCount; - } + IntegratePagingView(form); } - - /// - /// Contains the Number of Rows which are used by the layout. - /// - private int LayoutRows + if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) { - get - { - int layoutRows = 0; - - if (this.NavigationBarVisibility == eNavigationBarVisibility.always | this.NavigationBarVisibility == eNavigationBarVisibility.auto) - layoutRows += 2; - - if (this.HeadLayoutButtonRow != null && this.HeadLayoutButtonRow.Count > 0) - layoutRows++; - - if (this.SubHeadLayoutButtonRow != null && this.SubHeadLayoutButtonRow.Count > 0) - layoutRows++; - - return layoutRows; - } + form.InsertButtonRow(0, HeadLayoutButtonRow); } - /// - /// Returns the number of item rows per page. - /// - public int ItemRowsPerPage + if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) { - get + if (IsNavigationBarVisible) { - return this.MaximumRow - this.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 = this.DataSource.CalculateMax(this.EnableSearch ? this.SearchQuery : null); - - //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") - //{ - // bf = bf.FilterDuplicate(this.SearchQuery); - //} - - if (max == 0) - return 1; - - return (int)Math.Ceiling((decimal)((decimal)max / (decimal)ItemRowsPerPage)); - } - } - - public override async Task Hidden(bool FormClose) - { - //Prepare for opening Modal, and comming back - if (!FormClose) - { - this.Updated(); + form.InsertButtonRow(2, SubHeadLayoutButtonRow); } else { - //Remove event handler - this.Device.MessageDeleted -= Device_MessageDeleted; + form.InsertButtonRow(1, SubHeadLayoutButtonRow); } } - /// - /// Tells the control that it has been updated. - /// - public void Updated() + Message m = null; + + switch (KeyboardType) { - this.RenderNecessary = true; - } + //Reply Keyboard could only be updated with a new keyboard. + case EKeyboardType.ReplyKeyboard: - public async override Task Cleanup() - { - if (this.MessageId == null) - return; - switch (this.KeyboardType) - { - case eKeyboardType.InlineKeyBoard: - - await this.Device.DeleteMessage(this.MessageId.Value); - - this.MessageId = null; - - break; - case eKeyboardType.ReplyKeyboard: - - if (this.HideKeyboardOnCleanup) + if (form.Count == 0) + { + if (MessageId != null) { - await this.Device.HideReplyKeyboard(); + await Device.HideReplyKeyboard(); + MessageId = null; } - this.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; + } + } } diff --git a/TelegramBotBase/Controls/Hybrid/ButtonRow.cs b/TelegramBotBase/Controls/Hybrid/ButtonRow.cs index 2d0deab..fbf6dee 100644 --- a/TelegramBotBase/Controls/Hybrid/ButtonRow.cs +++ b/TelegramBotBase/Controls/Hybrid/ButtonRow.cs @@ -1,112 +1,104 @@ 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 +namespace TelegramBotBase.Controls.Hybrid; + +[DebuggerDisplay("{Count} columns")] +public class ButtonRow { - [DebuggerDisplay("{Count} columns")] - public class ButtonRow + private List _buttons = new(); + + public ButtonRow() { - - List __buttons = new List(); - - public ButtonRow() - { - - - } - - public ButtonRow(params ButtonBase[] buttons) - { - __buttons = buttons.ToList(); - } - - - public ButtonBase this[int index] - { - get - { - return __buttons[index]; - } - } - - public int Count - { - get - { - return __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 12026b2..ed44fc0 100644 --- a/TelegramBotBase/Controls/Hybrid/CheckedButtonList.cs +++ b/TelegramBotBase/Controls/Hybrid/CheckedButtonList.cs @@ -1,251 +1,364 @@ 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 +namespace TelegramBotBase.Controls.Hybrid; + +public class CheckedButtonList : ControlBase { - public class CheckedButtonList : Base.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; } = Localizations.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(); + /// + /// Data source of the items. + /// + public ButtonFormDataSource DataSource { get; set; } - [Obsolete("This property is obsolete. Please use the DataSource property instead.")] - public ButtonForm ButtonsForm + 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 + if (_mEKeyboardType != value) { - return DataSource.ButtonForm; - } - set - { - DataSource = new ButtonFormDataSource(value); + _renderNecessary = true; + + Cleanup().Wait(); + + _mEKeyboardType = value; } } + } - /// - /// Data source of the items. - /// - public ButtonFormDataSource DataSource { get; set; } - - 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; } = 0; - - public String PreviousPageLabel = Localizations.Default.Language["ButtonGrid_PreviousPage"]; - - public String NextPageLabel = Localizations.Default.Language["ButtonGrid_NextPage"]; - - public String NoItemsLabel = Localizations.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 + public bool PagingNecessary + { + get { - get + if (KeyboardType == EKeyboardType.InlineKeyBoard && + TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) { - return m_eKeyboardType; + return true; } - set + + if (KeyboardType == EKeyboardType.ReplyKeyboard && + TotalRows > Constants.Telegram.MaxReplyKeyboardRows) { - if (m_eKeyboardType != value) - { - this.RenderNecessary = true; - - Cleanup().Wait(); - - m_eKeyboardType = value; - } - + 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; + + 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(DataSource.ButtonForm[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; } - private eKeyboardType m_eKeyboardType = eKeyboardType.ReplyKeyboard; - - public CheckedButtonList() + foreach (var h in handler) { - this.DataSource = new ButtonFormDataSource(); + 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; } - public CheckedButtonList(eKeyboardType type) : this() + foreach (var h in handler) { - m_eKeyboardType = type; + await h.InvokeAllAsync(this, e); + } + } + + public override async Task Load(MessageResult result) + { + if (KeyboardType != EKeyboardType.ReplyKeyboard) + { + return; } - - public CheckedButtonList(ButtonForm form) + if (!result.IsFirstHandler) { - this.DataSource = new ButtonFormDataSource(form); + return; } - public event AsyncEventHandler ButtonClicked + if (result.MessageText == null || result.MessageText == "") { - add - { - this.Events.AddHandler(__evButtonClicked, value); - } - remove - { - this.Events.RemoveHandler(__evButtonClicked, value); - } + return; } - public async Task OnButtonClicked(ButtonClickedEventArgs e) - { - var handler = this.Events[__evButtonClicked]?.GetInvocationList().Cast>(); - if (handler == null) - return; + var matches = new List(); + ButtonRow match = null; + var index = -1; - foreach (var h in handler) - { - await Async.InvokeAllAsync(h, this, e); - } + if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false) + { + match = HeadLayoutButtonRow; + goto check; } - public event AsyncEventHandler CheckedChanged + if (SubHeadLayoutButtonRow?.Matches(result.MessageText) ?? false) { - add - { - this.Events.AddHandler(__evCheckedChanged, value); - } - remove - { - this.Events.RemoveHandler(__evCheckedChanged, value); - } + match = SubHeadLayoutButtonRow; + goto check; } - public async Task OnCheckedChanged(CheckedChangedEventArgs e) + var br = DataSource.FindRow(result.MessageText); + if (br != null) { - var handler = this.Events[__evCheckedChanged]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) - { - await Async.InvokeAllAsync(h, this, e); - } + match = br.Item1; + index = br.Item2; } - public async override Task Load(MessageResult result) - { - if (this.KeyboardType != eKeyboardType.ReplyKeyboard) - return; - - if (!result.IsFirstHandler) - return; - - if (result.MessageText == null || result.MessageText == "") - return; - - var matches = new List(); - ButtonRow match = null; - int 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); @@ -255,142 +368,152 @@ namespace TelegramBotBase.Controls.Hybrid //var index = bf.FindRowByButton(button); - check: - //Remove button click message - if (this.DeleteReplyMessage) - await Device.DeleteMessage(result.MessageId); - - if (match == null) - { - if (result.MessageText == PreviousPageLabel) - { - if (this.CurrentPageIndex > 0) - this.CurrentPageIndex--; - - this.Updated(); - } - else if (result.MessageText == NextPageLabel) - { - if (this.CurrentPageIndex < this.PageCount - 1) - this.CurrentPageIndex++; - - this.Updated(); - } - else if (result.MessageText.EndsWith(CheckedIconLabel)) - { - var s = result.MessageText.Split(' ', '.'); - index = int.Parse(s[0]) - 1; - - if (!this.CheckedRows.Contains(index)) - return; - - this.CheckedRows.Remove(index); - - this.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 (this.CheckedRows.Contains(index)) - return; - - - this.CheckedRows.Add(index); - - this.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 async override 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 (this.KeyboardType != eKeyboardType.InlineKeyBoard) - return; - - await result.ConfirmAction(this.ConfirmationText ?? ""); - - ButtonRow match = null; - int 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(DataSource.ButtonForm[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(DataSource.ButtonForm[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; @@ -402,473 +525,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 (this.CurrentPageIndex > 0) - this.CurrentPageIndex--; - - this.Updated(); - - break; - case "$next$": - - if (this.CurrentPageIndex < this.PageCount - 1) - this.CurrentPageIndex++; - - this.Updated(); - - break; - - default: - - var s = result.RawData.Split('$'); - - - switch (s[0]) - { - case "check": - - index = int.Parse(s[1]); - - if (!this.CheckedRows.Contains(index)) - { - this.CheckedRows.Add(index); - - this.Updated(); - - await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, true)); - } - - break; - - case "uncheck": - - index = int.Parse(s[1]); - - if (this.CheckedRows.Contains(index)) - { - this.CheckedRows.Remove(index); - - this.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 (m_eKeyboardType) - { - case eKeyboardType.InlineKeyBoard: + case "$previous$": - if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !this.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 && !this.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(DataSource.ButtonForm[index], index, true)); + } + + break; + + case "uncheck": + + index = int.Parse(s[1]); + + if (CheckedRows.Contains(index)) + { + CheckedRows.Remove(index); + + Updated(); + + await OnCheckedChanged(new CheckedChangedEventArgs(DataSource.ButtonForm[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 async override 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 (!this.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()); + } - this.RenderNecessary = false; - - Message m = null; - - ButtonForm form = this.DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, null); - - //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") - //{ - // form = form.FilterDuplicate(this.SearchQuery, true); - //} - //else - //{ - //form = form.Duplicate(); - //} - - if (this.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 (this.HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) - { - form.InsertButtonRow(0, this.HeadLayoutButtonRow.ToArray()); - } + switch (KeyboardType) + { + //Reply Keyboard could only be updated with a new keyboard. + case EKeyboardType.ReplyKeyboard: - if (this.SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) - { - if (this.IsNavigationBarVisible) + if (form.Count == 0) { - form.InsertButtonRow(2, this.SubHeadLayoutButtonRow.ToArray()); + 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 { - form.InsertButtonRow(1, this.SubHeadLayoutButtonRow.ToArray()); - } - } - - switch (this.KeyboardType) - { - //Reply Keyboard could only be updated with a new keyboard. - case eKeyboardType.ReplyKeyboard: - - if (form.Count == 0) - { - if (this.MessageId != null) - { - await this.Device.HideReplyKeyboard(); - this.MessageId = null; - } - - return; - } - - //if (form.Count == 0) - // 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); - - //Prevent flicker of keyboard - if (this.DeletePreviousMessage && this.MessageId != null) - await this.Device.DeleteMessage(this.MessageId.Value); - - break; - - case eKeyboardType.InlineKeyBoard: - - if (this.MessageId != null) - { - m = await this.Device.Edit(this.MessageId.Value, this.Title, (InlineKeyboardMarkup)form); - } - else - { - m = await this.Device.Send(this.Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false); - } - - break; - } - - if (m != null) - { - this.MessageId = m.MessageId; - } - - - } - - private void IntegratePagingView(ButtonForm dataForm) - { - //No Items - if (dataForm.Rows == 0) - { - dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$")); - } - - ButtonForm bf = new ButtonForm(); - - bf = PrepareCheckableLayout(dataForm); - - - if (this.IsNavigationBarVisible) - { - //🔍 - ButtonRow 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(NextPageLabel, "$next$")); - - - dataForm.InsertButtonRow(0, row); - - dataForm.AddButtonRow(row); - } - } - - private ButtonForm PrepareCheckableLayout(ButtonForm dataForm) - { - var bf = new ButtonForm(); - for (int i = 0; i < dataForm.Rows; i++) - { - int it = (this.CurrentPageIndex * (this.MaximumRow - LayoutRows)) + i; - - //if (it > dataForm.Rows - 1) - // break; - - var r = dataForm[i]; - - String s = CheckedRows.Contains(it) ? this.CheckedIconLabel : this.UncheckedIconLabel; - - //On reply keyboards we need a unique text. - if (this.KeyboardType == eKeyboardType.ReplyKeyboard) - { - s = $"{it + 1}. " + s; + m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, + parseMode: MessageParseMode, markdownV2AutoEscape: false); } - if (CheckedRows.Contains(it)) - { - r.Insert(0, new ButtonBase(s, "uncheck$" + it.ToString())); - } - else - { - r.Insert(0, new ButtonBase(s, "check$" + it.ToString())); - } - - 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 (this.KeyboardType == eKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) - { - return true; - } - - if (this.KeyboardType == eKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows) - { - return true; - } - - return false; + s = $"{it + 1}. " + s; } - } - public bool IsNavigationBarVisible - { - get + if (CheckedRows.Contains(it)) { - if (this.NavigationBarVisibility == eNavigationBarVisibility.always | (this.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 { - switch (this.KeyboardType) - { - case eKeyboardType.InlineKeyBoard: - return Constants.Telegram.MaxInlineKeyBoardRows; - - case eKeyboardType.ReplyKeyboard: - return Constants.Telegram.MaxReplyKeyboardRows; - - default: - return 0; - } - } - } - - /// - /// Returns the number of all rows (layout + navigation + content); - /// - public int TotalRows - { - get - { - return this.LayoutRows + DataSource.RowCount; - } - } - - - /// - /// Contains the Number of Rows which are used by the layout. - /// - private int LayoutRows - { - get - { - int layoutRows = 0; - - if (this.NavigationBarVisibility == eNavigationBarVisibility.always | this.NavigationBarVisibility == eNavigationBarVisibility.auto) - layoutRows += 2; - - if (this.HeadLayoutButtonRow != null && this.HeadLayoutButtonRow.Count > 0) - layoutRows++; - - if (this.SubHeadLayoutButtonRow != null && this.SubHeadLayoutButtonRow.Count > 0) - layoutRows++; - - return layoutRows; - } - } - - /// - /// Returns the number of item rows per page. - /// - public int ItemRowsPerPage - { - get - { - return this.MaximumRow - this.LayoutRows; - } - } - - public int PageCount - { - get - { - if (DataSource.RowCount == 0) - return 1; - - //var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null); - - var max = this.DataSource.RowCount; - - //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") - //{ - // bf = bf.FilterDuplicate(this.SearchQuery); - //} - - if (max == 0) - return 1; - - return (int)Math.Ceiling((decimal)((decimal)max / (decimal)ItemRowsPerPage)); - } - } - - public override async Task Hidden(bool FormClose) - { - //Prepare for opening Modal, and comming back - if (!FormClose) - { - this.Updated(); - } - } - - public List CheckedItems - { - get - { - List lst = new List(); - - foreach (var c in CheckedRows) - { - lst.Add(this.ButtonsForm[c][0]); - } - - return lst; - } - } - - - /// - /// Tells the control that it has been updated. - /// - public void Updated() - { - this.RenderNecessary = true; - } - - public async override Task Cleanup() - { - if (this.MessageId == null) - return; - - switch (this.KeyboardType) - { - case eKeyboardType.InlineKeyBoard: - - await this.Device.DeleteMessage(this.MessageId.Value); - - this.MessageId = null; - - break; - case eKeyboardType.ReplyKeyboard: - - if (this.HideKeyboardOnCleanup) - { - await this.Device.HideReplyKeyboard(); - } - - this.MessageId = null; - - break; + r.Insert(0, new ButtonBase(s, "check$" + it)); } - - - + bf.AddButtonRow(r); } + return bf; + } + + public override Task Hidden(bool formClose) + { + //Prepare for opening Modal, and comming back + if (!formClose) + { + 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 83eb0e6..2c8b98d 100644 --- a/TelegramBotBase/Controls/Hybrid/MultiView.cs +++ b/TelegramBotBase/Controls/Hybrid/MultiView.cs @@ -1,132 +1,127 @@ -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; -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 : Base.ControlBase + private bool _rendered; + + + public MultiView() { - /// - /// Index of the current View. - /// - public int SelectedViewIndex - { - get - { - return m_iSelectedViewIndex; - } - set - { - m_iSelectedViewIndex = value; - - //Already rendered? Re-Render - if (_Rendered) - ForceRender().Wait(); - } - } - - private int m_iSelectedViewIndex = 0; - - /// - /// Hold if the View has been rendered already. - /// - private bool _Rendered = false; - - private List Messages { get; set; } - - - public MultiView() - { - Messages = new List(); - } - - - private async Task Device_MessageSent(object sender, MessageSentEventArgs e) - { - if (e.Origin == null || !e.Origin.IsSubclassOf(typeof(MultiView))) - return; - - this.Messages.Add(e.MessageId); - } - - public override void Init() - { - Device.MessageSent += Device_MessageSent; - } - - public override async Task Load(MessageResult result) - { - _Rendered = false; - } - - - public override async Task Render(MessageResult result) - { - //When already rendered, skip rendering - if (_Rendered) - return; - - await CleanUpView(); - - await RenderView(new RenderViewEventArgs(this.SelectedViewIndex)); - - _Rendered = true; - } - - - /// - /// Will get invoked on rendering the current controls view. - /// - /// - public virtual async Task RenderView(RenderViewEventArgs e) - { - - - } - - async Task CleanUpView() - { - - var tasks = new List(); - - foreach (var msg in this.Messages) - { - tasks.Add(this.Device.DeleteMessage(msg)); - } - - await Task.WhenAll(tasks); - - this.Messages.Clear(); - - } - - /// - /// Forces render of control contents. - /// - public async Task ForceRender() - { - await CleanUpView(); - - await RenderView(new RenderViewEventArgs(this.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 cf0bc90..c2fec7e 100644 --- a/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs +++ b/TelegramBotBase/Controls/Hybrid/TaggedButtonGrid.cs @@ -1,267 +1,383 @@ 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 +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 string SearchIcon = Default.Language["ButtonGrid_SearchIcon"]; + + public string TagIcon = Default.Language["ButtonGrid_TagIcon"]; + + public TaggedButtonGrid() { + DataSource = new ButtonFormDataSource(); - public String Title { get; set; } = Localizations.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; } + + /// + /// 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 + if (_mEKeyboardType != value) { - return DataSource.ButtonForm; - } - set - { - DataSource = new ButtonFormDataSource(value); + _renderNecessary = true; + + Cleanup().Wait(); + + _mEKeyboardType = 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; } = 0; - - public String PreviousPageLabel = Localizations.Default.Language["ButtonGrid_PreviousPage"]; - - public String NextPageLabel = Localizations.Default.Language["ButtonGrid_NextPage"]; - - public String NoItemsLabel = Localizations.Default.Language["ButtonGrid_NoItems"]; - - public String SearchLabel = Localizations.Default.Language["ButtonGrid_SearchFeature"]; - - public String BackLabel = Localizations.Default.Language["ButtonGrid_Back"]; - - public String CheckAllLabel = Localizations.Default.Language["ButtonGrid_CheckAll"]; - - public String UncheckAllLabel = Localizations.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 + public bool PagingNecessary + { + get { - get + if (KeyboardType == EKeyboardType.InlineKeyBoard && + TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) { - return m_eKeyboardType; + return true; } - set + + if (KeyboardType == EKeyboardType.ReplyKeyboard && + TotalRows > Constants.Telegram.MaxReplyKeyboardRows) { - if (m_eKeyboardType != value) - { - this.RenderNecessary = true; - - Cleanup().Wait(); - - m_eKeyboardType = value; - } - + 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(SelectedTags.Count < Tags.Count) + { + max = DataSource.ButtonForm.TagDuplicate(SelectedTags).Count; + } + + 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; } - private eKeyboardType m_eKeyboardType = eKeyboardType.ReplyKeyboard; - - public TaggedButtonGrid() + foreach (var h in handler) { - this.DataSource = new ButtonFormDataSource(); + await h.InvokeAllAsync(this, e); + } + } - this.SelectedViewIndex = 0; + public override void Init() + { + Device.MessageDeleted += Device_MessageDeleted; + } + + private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e) + { + if (MessageId == null) + { + return; } - public TaggedButtonGrid(eKeyboardType type) : this() + if (e.MessageId != MessageId) { - m_eKeyboardType = type; + return; } + MessageId = null; + } - public TaggedButtonGrid(ButtonForm form) + public override async Task Load(MessageResult result) + { + if (KeyboardType != EKeyboardType.ReplyKeyboard) { - this.DataSource = new ButtonFormDataSource(form); + return; } - - public event AsyncEventHandler ButtonClicked + if (!result.IsFirstHandler) { - add - { - this.Events.AddHandler(__evButtonClicked, value); - } - remove - { - this.Events.RemoveHandler(__evButtonClicked, value); - } + return; } - public async Task OnButtonClicked(ButtonClickedEventArgs e) + if (result.MessageText == null || result.MessageText == "") { - var handler = this.Events[__evButtonClicked]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) - { - await Async.InvokeAllAsync(h, this, e); - } + return; } - public override void Init() + var matches = new List(); + ButtonRow match = null; + var index = -1; + + if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false) { - this.Device.MessageDeleted += Device_MessageDeleted; + match = HeadLayoutButtonRow; + goto check; } - private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e) + if (SubHeadLayoutButtonRow?.Matches(result.MessageText) ?? false) { - if (this.MessageId == null) - return; - - if (e.MessageId != this.MessageId) - return; - - this.MessageId = null; + match = SubHeadLayoutButtonRow; + goto check; } - public async override Task Load(MessageResult result) + if (TagsSubHeadLayoutButtonRow?.Matches(result.MessageText) ?? false) { - if (this.KeyboardType != eKeyboardType.ReplyKeyboard) - return; + match = TagsSubHeadLayoutButtonRow; + goto check; + } - if (!result.IsFirstHandler) - return; - - if (result.MessageText == null || result.MessageText == "") - return; - - var matches = new List(); - ButtonRow match = null; - int 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 br = DataSource.FindRow(result.MessageText); + if (br != null) + { + match = br.Item1; + index = br.Item2; + } //var button = HeadLayoutButtonRow?. .FirstOrDefault(a => a.Text.Trim() == result.MessageText) @@ -274,173 +390,184 @@ namespace TelegramBotBase.Controls.Hybrid check: + switch (SelectedViewIndex) + { + case 0: - switch (this.SelectedViewIndex) - { - case 0: + //Remove button click message + if (DeleteReplyMessage) + { + await Device.DeleteMessage(result.MessageId); + } - //Remove button click message - if (this.DeleteReplyMessage) - await Device.DeleteMessage(result.MessageId); + if (match != null) + { + await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.MessageText), + index, match)); - if (match != null) - { - await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.MessageText), index, match)); - - result.Handled = true; - return; - } - - if (result.MessageText == PreviousPageLabel) - { - if (this.CurrentPageIndex > 0) - this.CurrentPageIndex--; - - this.Updated(); - result.Handled = true; - } - else if (result.MessageText == NextPageLabel) - { - if (this.CurrentPageIndex < this.PageCount - 1) - this.CurrentPageIndex++; - - this.Updated(); - result.Handled = 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(); - result.Handled = true; - return; - } - - this.SearchQuery = result.MessageText; - - if (this.SearchQuery != null && this.SearchQuery != "") - { - this.CurrentPageIndex = 0; - this.Updated(); - result.Handled = true; - return; - } - - } - else if (this.Tags != null) - { - if (result.MessageText == "📁") - { - //Remove button click message - if (this.DeletePreviousMessage) - await Device.DeleteMessage(result.MessageId); - - this.SelectedViewIndex = 1; - this.Updated(); - result.Handled = true; - return; - } - } - - break; - case 1: - - //Remove button click message - if (this.DeleteReplyMessage) - await Device.DeleteMessage(result.MessageId); - - if (result.MessageText == this.BackLabel) - { - this.SelectedViewIndex = 0; - this.Updated(); - result.Handled = true; - return; - } - else if (result.MessageText == this.CheckAllLabel) - { - this.CheckAllTags(); - } - else if (result.MessageText == this.UncheckAllLabel) - { - this.UncheckAllTags(); - } - - var i = result.MessageText.LastIndexOf(" "); - if (i == -1) - i = result.MessageText.Length; - - var t = result.MessageText.Substring(0, i); - - if (this.SelectedTags.Contains(t)) - { - this.SelectedTags.Remove(t); - } - else - { - this.SelectedTags.Add(t); - } - - this.Updated(); 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(SearchIcon)) + { + //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 == TagIcon) + { + //Remove button click message + if (DeletePreviousMessage && !Device.ActiveForm.IsAutoCleanForm()) + { + 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 async override 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 (this.KeyboardType != eKeyboardType.InlineKeyBoard) - return; + await result.ConfirmAction(ConfirmationText ?? ""); - await result.ConfirmAction(this.ConfirmationText ?? ""); + ButtonRow match = null; + var index = -1; - ButtonRow match = null; - int 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; @@ -452,552 +579,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 (this.CurrentPageIndex > 0) - this.CurrentPageIndex--; - - this.Updated(); - - break; - - case "$next$": - - if (this.CurrentPageIndex < this.PageCount - 1) - this.CurrentPageIndex++; - - this.Updated(); - - break; - - case "$filter$": - - this.SelectedViewIndex = 1; - this.Updated(); - - break; - - case "$back$": - - this.SelectedViewIndex = 0; - this.Updated(); - - break; - - case "$checkall$": - - this.CheckAllTags(); - - break; - - case "$uncheckall$": - - this.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 (m_eKeyboardType) - { - case eKeyboardType.InlineKeyBoard: + case "$previous$": - if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !this.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 && !this.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 async override Task Render(MessageResult result) - { - if (!this.RenderNecessary) - return; - - //Check for rows and column limits - CheckGrid(); - - this.RenderNecessary = false; - - switch (this.SelectedViewIndex) - { - case 0: - - await RenderDataView(); - - break; - - case 1: - - - await RenderTagView(); - - - - break; - - } - - - - } - - - #region "Data View" - - private async Task RenderDataView() - { - Message m = null; - - ButtonForm form = this.DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (this.EnableSearch ? this.SearchQuery : null)); - - //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") - //{ - // form = form.FilterDuplicate(this.SearchQuery, true); - //} - //else - //{ - // form = form.Duplicate(); - //} - - if (this.Tags != null && this.SelectedTags != null) - { - form = form.TagDuplicate(this.SelectedTags); - } - - if (this.EnablePaging) - { - IntegratePagingView(form); - } - - if (this.HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0) - { - form.InsertButtonRow(0, this.HeadLayoutButtonRow.ToArray()); - } - - if (this.SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0) - { - if (this.IsNavigationBarVisible) + if (CurrentPageIndex > 0) { - form.InsertButtonRow(2, this.SubHeadLayoutButtonRow.ToArray()); - } - else - { - form.InsertButtonRow(1, this.SubHeadLayoutButtonRow.ToArray()); - } - } - - switch (this.KeyboardType) - { - //Reply Keyboard could only be updated with a new keyboard. - case eKeyboardType.ReplyKeyboard: - - if (form.Count == 0) - { - if (this.MessageId != null) - { - await this.Device.HideReplyKeyboard(); - this.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); - - //Prevent flicker of keyboard - if (this.DeletePreviousMessage && this.MessageId != null) - await this.Device.DeleteMessage(this.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 (this.MessageId != null) - { - m = await this.Device.Edit(this.MessageId.Value, this.Title, (InlineKeyboardMarkup)form); - if (m != null) - { - this.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); - break; - } - - if (m != null) - { - this.MessageId = m.MessageId; - } - } - - private void IntegratePagingView(ButtonForm dataForm) - { - //No Items - if (dataForm.Rows == 0) - { - dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$")); - } - - if (this.IsNavigationBarVisible) - { - //🔍 - ButtonRow 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$")); - - if (this.Tags != null && this.Tags.Count > 0) - { - row.Add(new ButtonBase("📁", "$filter$")); + CurrentPageIndex--; } - row.Add(new ButtonBase(NextPageLabel, "$next$")); + Updated(); - if (this.EnableSearch) + break; + + case "$next$": + + if (CurrentPageIndex < PageCount - 1) { - row.Insert(2, new ButtonBase("🔍 " + (this.SearchQuery ?? ""), "$search$")); + CurrentPageIndex++; } - dataForm.InsertButtonRow(0, row); + Updated(); - dataForm.AddButtonRow(row); - } + break; + + case "$filter$": + + SelectedViewIndex = 1; + Updated(); + + break; + + case "$back$": + + SelectedViewIndex = 0; + Updated(); + + break; + + case "$checkall$": + + CheckAllTags(); + + break; + + case "$uncheckall$": + + UncheckAllTags(); + + break; } + } - #endregion - - - #region "Tag View" - - - private async Task RenderTagView() + /// + /// This method checks of the amount of buttons + /// + private void CheckGrid() + { + switch (_mEKeyboardType) { - Message m = null; - ButtonForm bf = new ButtonForm(); + case EKeyboardType.InlineKeyBoard: - bf.AddButtonRow(this.BackLabel, "$back$"); - - if (EnableCheckAllTools) - { - this.TagsSubHeadLayoutButtonRow = new ButtonRow(new ButtonBase(CheckAllLabel, "$checkall$"), new ButtonBase(UncheckAllLabel, "$uncheckall$")); - bf.AddButtonRow(TagsSubHeadLayoutButtonRow); - } - - foreach (var t in this.Tags) - { - - String s = t; - - if (this.SelectedTags?.Contains(t) ?? false) + if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging) { - s += " ✅"; + throw new MaximumRowsReachedException + { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows }; } - bf.AddButtonRow(s, t); - - } - - switch (this.KeyboardType) - { - //Reply Keyboard could only be updated with a new keyboard. - case eKeyboardType.ReplyKeyboard: - - if (bf.Count == 0) - { - if (this.MessageId != null) - { - await this.Device.HideReplyKeyboard(); - this.MessageId = null; - } - return; - } - - //if (bf.Count == 0) - // return; - - - 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); - - //Prevent flicker of keyboard - if (this.DeletePreviousMessage && this.MessageId != null) - await this.Device.DeleteMessage(this.MessageId.Value); - - break; - - case eKeyboardType.InlineKeyBoard: - - if (this.MessageId != null) - { - m = await this.Device.Edit(this.MessageId.Value, "Choose category", (InlineKeyboardMarkup)bf); - } - else - { - m = await this.Device.Send("Choose category", (InlineKeyboardMarkup)bf, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false); - } - - break; - } - - - - if (m != null) - this.MessageId = m.MessageId; - - } - - - #endregion - - - public bool PagingNecessary - { - get - { - if (this.KeyboardType == eKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows) + if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols) { - return true; + throw new MaximumColsException + { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols }; } - if (this.KeyboardType == eKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows) + break; + + case EKeyboardType.ReplyKeyboard: + + if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging) { - return true; + throw new MaximumRowsReachedException + { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows }; } - return false; - } - } - - public bool IsNavigationBarVisible - { - get - { - if (this.NavigationBarVisibility == eNavigationBarVisibility.always | (this.NavigationBarVisibility == eNavigationBarVisibility.auto && PagingNecessary)) + if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols) { - return true; + throw new MaximumColsException + { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols }; } - return false; - } + break; } + } - /// - /// Returns the maximum number of rows - /// - public int MaximumRow + public override async Task Render(MessageResult result) + { + if (!_renderNecessary) { - get - { - switch (this.KeyboardType) - { - case eKeyboardType.InlineKeyBoard: - return Constants.Telegram.MaxInlineKeyBoardRows; - - case eKeyboardType.ReplyKeyboard: - return Constants.Telegram.MaxReplyKeyboardRows; - - default: - return 0; - } - } + return; } - /// - /// Returns the number of all rows (layout + navigation + content); - /// - public int TotalRows + //Check for rows and column limits + CheckGrid(); + + _renderNecessary = false; + + switch (SelectedViewIndex) { - get - { - return this.LayoutRows + DataSource.RowCount; - } + case 0: + + await RenderDataView(); + + break; + + case 1: + + + await RenderTagView(); + + + break; } - - - /// - /// Contains the Number of Rows which are used by the layout. - /// - private int LayoutRows - { - get - { - int layoutRows = 0; - - if (this.NavigationBarVisibility == eNavigationBarVisibility.always | this.NavigationBarVisibility == eNavigationBarVisibility.auto) - layoutRows += 2; - - if (this.HeadLayoutButtonRow != null && this.HeadLayoutButtonRow.Count > 0) - layoutRows++; - - if (this.SubHeadLayoutButtonRow != null && this.SubHeadLayoutButtonRow.Count > 0) - layoutRows++; - - if (EnableCheckAllTools && this.SelectedViewIndex == 1) - { - layoutRows++; - } - - return layoutRows; - } - } - - /// - /// Returns the number of item rows per page. - /// - public int ItemRowsPerPage - { - get - { - return this.MaximumRow - this.LayoutRows; - } - } - - public int PageCount - { - get - { - if (DataSource.RowCount == 0) - return 1; - - //var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null); - - var max = this.DataSource.CalculateMax(this.EnableSearch ? this.SearchQuery : null); - - //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "") - //{ - // bf = bf.FilterDuplicate(this.SearchQuery); - //} - - if (max == 0) - return 1; - - return (int)Math.Ceiling((decimal)((decimal)max / (decimal)ItemRowsPerPage)); - } - } - - public override async Task Hidden(bool FormClose) - { - //Prepare for opening Modal, and comming back - if (!FormClose) - { - this.Updated(); - } - else - { - //Remove event handler - this.Device.MessageDeleted -= Device_MessageDeleted; - } - } - - /// - /// Tells the control that it has been updated. - /// - public void Updated() - { - this.RenderNecessary = true; - } - - public async override Task Cleanup() - { - if (this.MessageId == null) - return; - - switch (this.KeyboardType) - { - case eKeyboardType.InlineKeyBoard: - - await this.Device.DeleteMessage(this.MessageId.Value); - - this.MessageId = null; - - break; - case eKeyboardType.ReplyKeyboard: - - if (this.HideKeyboardOnCleanup) - { - await this.Device.HideReplyKeyboard(); - } - - this.MessageId = null; - - break; - } - - } - - - /// - /// Checks all tags for filtering. - /// - public void CheckAllTags() - { - this.SelectedTags.Clear(); - - this.SelectedTags = this.Tags.Select(a => a).ToList(); - - this.Updated(); - - } - - /// - /// Unchecks all tags for filtering. - /// - public void UncheckAllTags() - { - this.SelectedTags.Clear(); - - this.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(TagIcon, "$filter$")); + } + + row.Add(new ButtonBase(NextPageLabel, "$next$")); + + if (EnableSearch) + { + row.Insert(2, new ButtonBase($"{SearchIcon} {(SearchQuery ?? "")}", "$search$")); + } + + dataForm.InsertButtonRow(0, row); + + dataForm.AddButtonRow(row); + } + } + + #endregion } diff --git a/TelegramBotBase/Controls/Inline/CalendarPicker.cs b/TelegramBotBase/Controls/Inline/CalendarPicker.cs index 0fc968d..07d6e96 100644 --- a/TelegramBotBase/Controls/Inline/CalendarPicker.cs +++ b/TelegramBotBase/Controls/Inline/CalendarPicker.cs @@ -2,278 +2,265 @@ 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 +namespace TelegramBotBase.Controls.Inline; + +public class CalendarPicker : ControlBase { - public class CalendarPicker : Base.ControlBase + public CalendarPicker(CultureInfo culture) { - - public DateTime SelectedDate { get; set; } - - public DateTime VisibleMonth { get; set; } - - public DayOfWeek FirstDayOfWeek { get; set; } - - public CultureInfo Culture { get; set; } - - - private int? MessageId { get; set; } - - public String Title { get; set; } = Localizations.Default.Language["CalendarPicker_Title"]; - - 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; - } - - public CalendarPicker() : this(new CultureInfo("en-en")) { } - - - - - public override async Task Action(MessageResult result, String value = null) - { - await result.ConfirmAction(); - - switch (result.RawData) - { - case "$next$": - - switch (this.PickerMode) - { - 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; - } - - - break; - case "$prev$": - - switch (this.PickerMode) - { - 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; - } - - break; - - case "$monthtitle$": - - if (this.EnableMonthView) - { - this.PickerMode = eMonthPickerMode.month; - } - - break; - - case "$yeartitle$": - - if (this.EnableYearView) - { - this.PickerMode = eMonthPickerMode.year; - } - - break; - case "$yearstitle$": - - if (this.EnableMonthView) - { - this.PickerMode = eMonthPickerMode.month; - } - - this.VisibleMonth = this.SelectedDate; - - break; - - default: - - int day = 0; - if (result.RawData.StartsWith("d-") && TryParseDay(result.RawData.Split('-')[1], this.SelectedDate, out day)) - { - this.SelectedDate = new DateTime(this.VisibleMonth.Year, this.VisibleMonth.Month, day); - } - - int 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; - - if (this.EnableDayView) - { - this.PickerMode = eMonthPickerMode.day; - } - } - - int 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; - - if (this.EnableMonthView) - { - this.PickerMode = eMonthPickerMode.month; - } - - } - - break; - } - - - - } - - - - public override async Task Render(MessageResult result) - { - - - - ButtonForm bf = new ButtonForm(); - - switch (this.PickerMode) - { - case eMonthPickerMode.day: - - var month = this.VisibleMonth; - - string[] dayNamesNormal = this.Culture.DateTimeFormat.ShortestDayNames; - string[] dayNamesShifted = Shift(dayNamesNormal, (int)this.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(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(this.FirstDayOfWeek); - - //End of week where last day of month is (right border) - var end = lastDay.EndOfWeek(this.FirstDayOfWeek); - - for (int i = 0; i <= ((end - start).Days / 7); i++) - { - var lst = new List(); - for (int 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())); - continue; - } - - var day = d.Day.ToString(); - - if (d == DateTime.Today) - { - day = "(" + day + ")"; - } - - lst.Add(new ButtonBase((this.SelectedDate == d ? "[" + day + "]" : day), "d-" + d.Day.ToString())); - } - bf.AddButtonRow(lst); - } - - break; - - 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$")); - - var months = this.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())); - - bf.AddSplitted(buttons, 2); - - break; - - 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$")); - - var starti = Math.Floor(this.VisibleMonth.Year / 10f) * 10; - - for (int 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())); - } - - break; - - } - - - if (this.MessageId != null) - { - var m = await this.Device.Edit(this.MessageId.Value, this.Title, bf); - } - else - { - var m = await this.Device.Send(this.Title, bf); - this.MessageId = m.MessageId; - } - } - - - - public override async Task Cleanup() - { - - if (this.MessageId != null) - { - await this.Device.DeleteMessage(this.MessageId.Value); - } - - } - + SelectedDate = DateTime.Today; + VisibleMonth = DateTime.Today; + FirstDayOfWeek = DayOfWeek.Monday; + Culture = culture; + PickerMode = EMonthPickerMode.day; } -} + + public CalendarPicker() : this(new CultureInfo("en-en")) + { + } + + public DateTime SelectedDate { get; set; } + + public DateTime VisibleMonth { get; set; } + + public DayOfWeek FirstDayOfWeek { get; set; } + + public CultureInfo Culture { get; set; } + + + public int? MessageId { get; set; } + + public string Title { get; set; } = Default.Language["CalendarPicker_Title"]; + + public EMonthPickerMode PickerMode { get; set; } + + public bool EnableDayView { get; set; } = true; + + public bool EnableMonthView { get; set; } = true; + + public bool EnableYearView { get; set; } = true; + + + public override async Task Action(MessageResult result, string value = null) + { + await result.ConfirmAction(); + + switch (result.RawData) + { + case "$next$": + + 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; + + case "$monthtitle$": + + if (EnableMonthView) + { + PickerMode = EMonthPickerMode.month; + } + + break; + + case "$yeartitle$": + + if (EnableYearView) + { + PickerMode = EMonthPickerMode.year; + } + + break; + case "$yearstitle$": + + if (EnableMonthView) + { + PickerMode = EMonthPickerMode.month; + } + + VisibleMonth = SelectedDate; + + break; + + default: + + 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; + + if (EnableDayView) + { + PickerMode = EMonthPickerMode.day; + } + } + + 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; + } + } + + + 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 78c6fc2..d6b5fb1 100644 --- a/TelegramBotBase/Controls/Inline/MonthPicker.cs +++ b/TelegramBotBase/Controls/Inline/MonthPicker.cs @@ -1,26 +1,12 @@ -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 +namespace TelegramBotBase.Controls.Inline; + +public class MonthPicker : CalendarPicker { - public class MonthPicker : CalendarPicker + public MonthPicker() { - - - - public MonthPicker() - { - this.PickerMode = eMonthPickerMode.month; - this.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 1828f2b..488a5f1 100644 --- a/TelegramBotBase/Controls/Inline/MultiToggleButton.cs +++ b/TelegramBotBase/Controls/Inline/MultiToggleButton.cs @@ -1,164 +1,152 @@ 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 +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; } = Localizations.Default.Language["MultiToggleButton_SelectedIcon"]; + Options = new List(); + } - /// - /// This will appear on the ConfirmAction message (if not empty) - /// - public String ChangedString { get; set; } = Localizations.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; } = Localizations.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 - { - this.Events.AddHandler(__evToggled, value); - } - remove - { - this.Events.RemoveHandler(__evToggled, value); - } - } + default: - public void OnToggled(EventArgs e) - { - (this.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(this.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)) { - int index = 0; - if (!int.TryParse(s[1], out index)) - { - return; - } - - if(SelectedOption== null || SelectedOption != this.Options[index]) - { - this.SelectedOption = this.Options[index]; - OnToggled(new EventArgs()); - } - else if(this.AllowEmptySelection) - { - this.SelectedOption = null; - OnToggled(new EventArgs()); - } - - 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 this.Options) - { - var index = this.Options.IndexOf(o); - if (o == this.SelectedOption) - { - lst.Add(new ButtonBase(SelectedIcon + " " + o.Text, "check$" + index)); - continue; + return; } - lst.Add(new ButtonBase(o.Text, "check$" + index)); - } - - bf.AddButtonRow(lst); - - if (this.MessageId != null) - { - var m = await this.Device.Edit(this.MessageId.Value, this.Title, bf); - } - else - { - var m = await this.Device.Send(this.Title, bf, disableNotification: true); - if (m != null) - { - this.MessageId = m.MessageId; - } - } - - this.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 14dd585..ab2fc89 100644 --- a/TelegramBotBase/Controls/Inline/ProgressBar.cs +++ b/TelegramBotBase/Controls/Inline/ProgressBar.cs @@ -1,296 +1,256 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; 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 : Base.ControlBase + public enum EProgressStyle { - public enum eProgressStyle - { - standard = 0, - squares = 1, - circles = 2, - lines = 3, - squaredLines = 4, - custom = 10 - } - - public eProgressStyle ProgressStyle - { - get - { - return m_eStyle; - } - set - { - m_eStyle = value; - LoadStyle(); - } - } - - private eProgressStyle m_eStyle = eProgressStyle.standard; - - - public int Value - { - get - { - return this.m_iValue; - } - set - { - if (value > this.Max) - { - return; - } - - if (this.m_iValue != value) - { - this.RenderNecessary = true; - } - this.m_iValue = value; - } - } - - private int m_iValue = 0; - - public int Max - { - get - { - return this.m_iMax; - } - set - { - if (this.m_iMax != value) - { - this.RenderNecessary = true; - } - this.m_iMax = value; - } - } - - private int m_iMax = 100; - - public int? MessageId { get; set; } - - private bool RenderNecessary { get; set; } = false; - - public int Steps - { - get - { - switch (this.ProgressStyle) - { - 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; - } - } - } - - /// - /// 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() - { - this.ProgressStyle = eProgressStyle.standard; - - this.Value = 0; - this.Max = 100; - - this.RenderNecessary = true; - } - - public ProgressBar(int Value, int Max, eProgressStyle Style) - { - this.Value = Value; - this.Max = Max; - this.ProgressStyle = Style; - - this.RenderNecessary = true; - } - - public override async Task Cleanup() - { - if (this.MessageId == null || this.MessageId == -1) - return; - - - await this.Device.DeleteMessage(this.MessageId.Value); - } - - public void LoadStyle() - { - this.StartChar = ""; - this.EndChar = ""; - - switch (this.ProgressStyle) - { - case eProgressStyle.circles: - - this.BlockChar = "⚫️ "; - this.EmptyBlockChar = "⚪️ "; - - break; - case eProgressStyle.squares: - - this.BlockChar = "⬛️ "; - this.EmptyBlockChar = "⬜️ "; - - break; - case eProgressStyle.lines: - - this.BlockChar = "█"; - this.EmptyBlockChar = "▁"; - - break; - case eProgressStyle.squaredLines: - - this.BlockChar = "▇"; - this.EmptyBlockChar = "—"; - - this.StartChar = "["; - this.EndChar = "]"; - - break; - case eProgressStyle.standard: - case eProgressStyle.custom: - - this.BlockChar = ""; - this.EmptyBlockChar = ""; - - break; - } - - } - - public async override Task Render(MessageResult result) - { - if (!this.RenderNecessary) - { - return; - } - - if (this.Device == null) - { - return; - } - - String message = ""; - int blocks = 0; - int maxBlocks = 0; - - switch (this.ProgressStyle) - { - case eProgressStyle.standard: - - message = this.Value.ToString("0") + "%"; - - break; - - case eProgressStyle.squares: - case eProgressStyle.circles: - case eProgressStyle.lines: - case eProgressStyle.squaredLines: - case eProgressStyle.custom: - - blocks = (int)Math.Floor((decimal)this.Value / this.Steps); - - maxBlocks = (this.Max / this.Steps); - - message += this.StartChar; - - for (int i = 0; i < blocks; i++) - { - message += this.BlockChar; - } - - for (int i = 0; i < (maxBlocks - blocks); i++) - { - message += this.EmptyBlockChar; - } - - message += this.EndChar; - - message += " " + this.Value.ToString("0") + "%"; - - break; - - default: - - return; - } - - if (this.MessageId == null) - { - var m = await this.Device.Send(message); - - this.MessageId = m.MessageId; - } - else - { - await this.Device.Edit(this.MessageId.Value, message); - } - - this.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 5343f7b..4c7811e 100644 --- a/TelegramBotBase/Controls/Inline/ToggleButton.cs +++ b/TelegramBotBase/Controls/Inline/ToggleButton.cs @@ -1,147 +1,137 @@ 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 +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; } = Localizations.Default.Language["ToggleButton_OffIcon"]; - - public String CheckedIcon { get; set; } = Localizations.Default.Language["ToggleButton_OnIcon"]; - - public String CheckedString { get; set; } = Localizations.Default.Language["ToggleButton_On"]; - - public String UncheckedString { get; set; } = Localizations.Default.Language["ToggleButton_Off"]; - - public String ChangedString { get; set; } = Localizations.Default.Language["ToggleButton_Changed"]; - - public String Title { get; set; } = Localizations.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 - { - this.Events.AddHandler(__evToggled, value); - } - remove - { - this.Events.RemoveHandler(__evToggled, value); - } - } - - public void OnToggled(EventArgs e) - { - (this.Events[__evToggled] as EventHandler)?.Invoke(this, e); - } - - public override async Task Action(MessageResult result, String value = null) - { - - if (result.Handled) - return; - - await result.ConfirmAction(this.ChangedString); - - switch (value ?? "unknown") - { - case "on": - - if (this.Checked) - return; - - RenderNecessary = true; - - this.Checked = true; - - OnToggled(new EventArgs()); - - break; - - case "off": - - if (!this.Checked) - return; - - RenderNecessary = true; - - this.Checked = false; - - OnToggled(new EventArgs()); - - break; - - default: - - RenderNecessary = false; - - break; - - } - - result.Handled = true; - - } - - public override async Task Render(MessageResult result) - { - if (!RenderNecessary) - return; - - var bf = new ButtonForm(this); - - ButtonBase bOn = new ButtonBase((this.Checked ? CheckedIcon : UncheckedIcon) + " " + CheckedString, "on"); - - ButtonBase bOff = new ButtonBase((!this.Checked ? CheckedIcon : UncheckedIcon) + " " + UncheckedString, "off"); - - bf.AddButtonRow(bOn, bOff); - - if (this.MessageId != null) - { - var m = await this.Device.Edit(this.MessageId.Value, this.Title, bf); - } - else - { - var m = await this.Device.Send(this.Title, bf, disableNotification: true); - if (m != null) - { - this.MessageId = m.MessageId; - } - } - - this.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 65c8f4f..0299d6d 100644 --- a/TelegramBotBase/Controls/Inline/TreeView.cs +++ b/TelegramBotBase/Controls/Inline/TreeView.cs @@ -1,122 +1,121 @@ -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 +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; } = Localizations.Default.Language["TreeView_LevelUp"]; + public 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) { - this.Nodes = new List(); - this.Title = Localizations.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: - this.VisibleNode = (this.VisibleNode?.ParentNode); + var n = VisibleNode != null + ? VisibleNode.FindNodeByValue(val) + : Nodes.FirstOrDefault(a => a.Value == val); - result.Handled = true; - - break; - default: - - var n = (this.VisibleNode != null ? this.VisibleNode.FindNodeByValue(val) : this.Nodes.FirstOrDefault(a => a.Value == val)); - - if (n == null) - return; - - - if (n.ChildNodes.Count > 0) - { - this.VisibleNode = n; - } - else - { - this.SelectedNode = (this.SelectedNode != n ? n : null); - } - - result.Handled = true; - - - break; - - } - - } - - - public override async Task Render(MessageResult result) - { - var startnode = this.VisibleNode; - - var nodes = (startnode?.ChildNodes ?? this.Nodes); - - ButtonForm bf = new ButtonForm(); - - if (startnode != null) - { - bf.AddButtonRow(new ButtonBase(this.MoveUpIcon, "up"), new ButtonBase(startnode.Text, "parent")); - } - - foreach (var n in nodes) - { - var s = n.Text; - if (this.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 (this.MessageId != null) - { - var m = await this.Device.Edit(this.MessageId.Value, this.Title, bf); - } - else - { - var m = await this.Device.Send(this.Title, bf); - this.MessageId = m.MessageId; - } + break; } - - public String GetPath() - { - return (this.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 a871aae..b714bbd 100644 --- a/TelegramBotBase/Controls/Inline/TreeViewNode.cs +++ b/TelegramBotBase/Controls/Inline/TreeViewNode.cs @@ -1,65 +1,61 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; -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 this.ChildNodes.FirstOrDefault(a => a.Value == Value); - } - - public String GetPath() - { - String s = "\\" + this.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 new file mode 100644 index 0000000..c92a55a --- /dev/null +++ b/TelegramBotBase/DataSources/ButtonFormDataSource.cs @@ -0,0 +1,137 @@ +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; + } +} diff --git a/TelegramBotBase/DataSources/StaticDataSource.cs b/TelegramBotBase/DataSources/StaticDataSource.cs new file mode 100644 index 0000000..2cf1d50 --- /dev/null +++ b/TelegramBotBase/DataSources/StaticDataSource.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; +using System.Linq; +using TelegramBotBase.Interfaces; + +namespace TelegramBotBase.DataSources; + +public class StaticDataSource : IDataSource +{ + public StaticDataSource() + { + } + + 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/Datasources/ButtonFormDataSource.cs b/TelegramBotBase/Datasources/ButtonFormDataSource.cs deleted file mode 100644 index 31ef4f6..0000000 --- a/TelegramBotBase/Datasources/ButtonFormDataSource.cs +++ /dev/null @@ -1,142 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using TelegramBotBase.Controls.Hybrid; -using TelegramBotBase.Form; -using TelegramBotBase.Interfaces; - -namespace TelegramBotBase.Datasources -{ - public class ButtonFormDataSource : Interfaces.IDataSource - { - public virtual ButtonForm ButtonForm - { - get - { - return __buttonform; - } - set - { - __buttonform = value; - } - } - - private ButtonForm __buttonform = null; - - public ButtonFormDataSource() - { - __buttonform = new ButtonForm(); - } - - public ButtonFormDataSource(ButtonForm bf) - { - __buttonform = bf; - } - - - /// - /// Returns the amount of rows existing. - /// - /// - 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) - { - ButtonForm bf = new ButtonForm(); - ButtonForm dataForm = null; - - if (filter == null) - { - dataForm = ButtonForm.Duplicate(); - } - else - { - dataForm = ButtonForm.FilterDuplicate(filter, true); - } - - for (int i = 0; i < count; i++) - { - int 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; - } - - } -} diff --git a/TelegramBotBase/Datasources/StaticDataSource.cs b/TelegramBotBase/Datasources/StaticDataSource.cs deleted file mode 100644 index 19ff96c..0000000 --- a/TelegramBotBase/Datasources/StaticDataSource.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace TelegramBotBase.Datasources -{ - public class StaticDataSource : Interfaces.IDataSource - { - List Data { get; set; } - - public StaticDataSource() - { - - } - - public StaticDataSource(List data) - { - this.Data = data; - } - - - public int Count - { - get - { - return 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; - } - } -} diff --git a/TelegramBotBase/Enums/eDeleteMode.cs b/TelegramBotBase/Enums/eDeleteMode.cs index 1596678..4cd1421 100644 --- a/TelegramBotBase/Enums/eDeleteMode.cs +++ b/TelegramBotBase/Enums/eDeleteMode.cs @@ -1,24 +1,19 @@ -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. - /// - 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 6803291..3c75443 100644 --- a/TelegramBotBase/Enums/eDeleteSide.cs +++ b/TelegramBotBase/Enums/eDeleteSide.cs @@ -1,24 +1,19 @@ -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. - /// - 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 3cd255e..c4f2033 100644 --- a/TelegramBotBase/Enums/eKeyboardType.cs +++ b/TelegramBotBase/Enums/eKeyboardType.cs @@ -1,22 +1,14 @@ -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 - /// - 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 be2a1c3..f61cd08 100644 --- a/TelegramBotBase/Enums/eMonthPickerMode.cs +++ b/TelegramBotBase/Enums/eMonthPickerMode.cs @@ -1,24 +1,19 @@ -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 - /// - 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 d10e027..f9834c2 100644 --- a/TelegramBotBase/Enums/eNavigationBarVisibility.cs +++ b/TelegramBotBase/Enums/eNavigationBarVisibility.cs @@ -1,25 +1,19 @@ -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. - /// - 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 7e55710..cebc8f7 100644 --- a/TelegramBotBase/Enums/eSettings.cs +++ b/TelegramBotBase/Enums/eSettings.cs @@ -1,40 +1,34 @@ -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) - /// - 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 deleted file mode 100644 index 4263a65..0000000 --- a/TelegramBotBase/Exceptions/MaxLengthException.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -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.") - { - - } - - } -} diff --git a/TelegramBotBase/Exceptions/MaximumColsException.cs b/TelegramBotBase/Exceptions/MaximumColsException.cs index de7cffc..781ab40 100644 --- a/TelegramBotBase/Exceptions/MaximumColsException.cs +++ b/TelegramBotBase/Exceptions/MaximumColsException.cs @@ -1,22 +1,12 @@ using System; -using System.Collections.Generic; -using System.Text; -namespace TelegramBotBase.Exceptions +namespace TelegramBotBase.Exceptions; + +public sealed 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 - { - 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}/{Maximum}"; } diff --git a/TelegramBotBase/Exceptions/MaximumRowsException.cs b/TelegramBotBase/Exceptions/MaximumRowsException.cs index 1d00f18..9b1beb8 100644 --- a/TelegramBotBase/Exceptions/MaximumRowsException.cs +++ b/TelegramBotBase/Exceptions/MaximumRowsException.cs @@ -1,22 +1,14 @@ using System; -using System.Collections.Generic; -using System.Text; -namespace TelegramBotBase.Exceptions +namespace TelegramBotBase.Exceptions; + +public sealed 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 - { - 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}/{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/Factories/DefaultStartFormFactory.cs b/TelegramBotBase/Factories/DefaultStartFormFactory.cs index e3c7c20..7ce2988 100644 --- a/TelegramBotBase/Factories/DefaultStartFormFactory.cs +++ b/TelegramBotBase/Factories/DefaultStartFormFactory.cs @@ -1,26 +1,26 @@ using System; -using System.Collections.Generic; -using System.Text; using TelegramBotBase.Form; +using TelegramBotBase.Interfaces; -namespace TelegramBotBase.Factories +namespace TelegramBotBase.Factories; + +public class DefaultStartFormFactory : IStartFormFactory { - public class DefaultStartFormFactory : Interfaces.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 c748b20..2ca4c5c 100644 --- a/TelegramBotBase/Factories/LambdaStartFormFactory.cs +++ b/TelegramBotBase/Factories/LambdaStartFormFactory.cs @@ -1,24 +1,21 @@ -using System; -using System.Collections.Generic; -using System.Text; -using TelegramBotBase.Form; +using TelegramBotBase.Form; +using TelegramBotBase.Interfaces; -namespace TelegramBotBase.Factories +namespace TelegramBotBase.Factories; + +public class LambdaStartFormFactory : IStartFormFactory { - public class LambdaStartFormFactory : Interfaces.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 d0a9731..74f4f1c 100644 --- a/TelegramBotBase/Form/AlertDialog.cs +++ b/TelegramBotBase/Form/AlertDialog.cs @@ -1,28 +1,18 @@ -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 +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) - { - this.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 42749fe..7481563 100644 --- a/TelegramBotBase/Form/ArrayPromptDialog.cs +++ b/TelegramBotBase/Form/ArrayPromptDialog.cs @@ -1,122 +1,112 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Linq; -using System.Text; 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 EventHandlerList __Events { get; set; } = new EventHandlerList(); + /// + /// An additional optional value. + /// + public object Tag { get; set; } - private static object __evButtonClicked { get; } = new object(); + public ButtonBase[][] Buttons { get; set; } - public ArrayPromptDialog() + [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 = this.Buttons.Aggregate((a, b) => a.Union(b).ToArray()).ToList(); - - if(call==null) - { - return; - } - - ButtonBase button = buttons.FirstOrDefault(a => a.Value == call.Value); - - if (button == null) - { - return; - } - - OnButtonClicked(new ButtonClickedEventArgs(button) { Tag = this.Tag }); - - FormBase fb = ButtonForms.ContainsKey(call.Value) ? ButtonForms[call.Value] : null; - - if (fb != null) - { - await this.NavigateTo(fb); - } - } - - - public override async Task Render(MessageResult message) - { - ButtonForm btn = new ButtonForm(); - - foreach(var bl in this.Buttons) - { - btn.AddButtonRow(bl.Select(a => new ButtonBase(a.Text, CallbackData.Create("action", a.Value))).ToList()); - } - - await this.Device.Send(this.Message, btn); - } - - - public event EventHandler ButtonClicked - { - add - { - this.__Events.AddHandler(__evButtonClicked, value); - } - remove - { - this.__Events.RemoveHandler(__evButtonClicked, value); - } - } - - public void OnButtonClicked(ButtonClickedEventArgs e) - { - (this.__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 b05938e..e994ef3 100644 --- a/TelegramBotBase/Form/AutoCleanForm.cs +++ b/TelegramBotBase/Form/AutoCleanForm.cs @@ -11,132 +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) { - this.OldMessages = new List(); - this.DeleteMode = eDeleteMode.OnEveryCall; - this.DeleteSide = eDeleteSide.BotOnly; - - this.Init += AutoCleanForm_Init; - - this.Closed += AutoCleanForm_Closed; - + return Task.CompletedTask; } - private async Task AutoCleanForm_Init(object sender, InitEventArgs 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 (this.Device == null) - return; + OldMessages.Remove(e.MessageId); + } + } - this.Device.MessageSent += Device_MessageSent; - - this.Device.MessageReceived += Device_MessageReceived; - - this.Device.MessageDeleted += Device_MessageDeleted; + private void Device_MessageReceived(object sender, MessageReceivedEventArgs e) + { + if (DeleteSide == EDeleteSide.BotOnly) + { + return; } - private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e) + OldMessages.Add(e.Message.MessageId); + } + + private Task Device_MessageSent(object sender, MessageSentEventArgs e) + { + if (DeleteSide == EDeleteSide.UserOnly) { - if (OldMessages.Contains(e.MessageId)) - OldMessages.Remove(e.MessageId); + return Task.CompletedTask; } - private void Device_MessageReceived(object sender, MessageReceivedEventArgs e) - { - if (this.DeleteSide == eDeleteSide.BotOnly) - return; + OldMessages.Add(e.Message.MessageId); + return Task.CompletedTask; + } - this.OldMessages.Add(e.Message.MessageId); + public override async Task PreLoad(MessageResult message) + { + if (DeleteMode != EDeleteMode.OnEveryCall) + { + return; } - private async Task Device_MessageSent(object sender, MessageSentEventArgs e) - { - if (this.DeleteSide == eDeleteSide.UserOnly) - return; + await MessageCleanup(); + } - this.OldMessages.Add(e.Message.MessageId); + /// + /// 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) + { + return; } - public override async Task PreLoad(MessageResult message) - { - if (this.DeleteMode != eDeleteMode.OnEveryCall) - return; + OldMessages.RemoveAt(OldMessages.Count - 1); + } - await MessageCleanup(); + private Task AutoCleanForm_Closed(object sender, EventArgs e) + { + if (DeleteMode != EDeleteMode.OnLeavingForm) + { + return Task.CompletedTask; } - /// - /// Adds a message to this of removable ones - /// - /// - public void AddMessage(Message m) - { - this.OldMessages.Add(m.MessageId); - } + MessageCleanup().Wait(); + return Task.CompletedTask; + } - - /// - /// Adds a message to this of removable ones - /// - /// - public void AddMessage(int messageId) - { - this.OldMessages.Add(messageId); - } - - /// - /// Keeps the message by removing it from the list - /// - /// - public void LeaveMessage(int Id) - { - this.OldMessages.Remove(Id); - } - - /// - /// Keeps the last sent message - /// - public void LeaveLastMessage() - { - if (this.OldMessages.Count == 0) - return; - - this.OldMessages.RemoveAt(this.OldMessages.Count - 1); - } - - private async Task AutoCleanForm_Closed(object sender, EventArgs e) - { - if (this.DeleteMode != eDeleteMode.OnLeavingForm) - return; - - MessageCleanup().Wait(); - } - - /// - /// Cleans up all remembered messages. - /// - /// - public async Task MessageCleanup() - { - var oldMessages = OldMessages.AsEnumerable(); + /// + /// Cleans up all remembered messages. + /// + /// + public async Task MessageCleanup() + { + var oldMessages = OldMessages.AsEnumerable(); #if !NETSTANDARD2_0 while (oldMessages.Any()) @@ -167,7 +178,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); } @@ -178,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 => (int?)((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, cts.Token); + } - //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(); } } diff --git a/TelegramBotBase/Form/ButtonBase.cs b/TelegramBotBase/Form/ButtonBase.cs index efb4466..c962dcb 100644 --- a/TelegramBotBase/Form/ButtonBase.cs +++ b/TelegramBotBase/Form/ButtonBase.cs @@ -1,70 +1,62 @@ -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 +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) - { - String id = (form.DependencyControl != null ? form.DependencyControl.ControlID + "_" : ""); - if (this.Url == null) - { - return InlineKeyboardButton.WithCallbackData(this.Text, id + this.Value); - } - - var ikb = new InlineKeyboardButton(this.Text); - - //ikb.Text = this.Text; - ikb.Url = this.Url; - - return ikb; - - } - - - /// - /// Returns a KeyBoardButton - /// - /// - /// - public virtual KeyboardButton ToKeyboardButton(ButtonForm form) - { - return new KeyboardButton(this.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 c477b37..9591ddf 100644 --- a/TelegramBotBase/Form/ButtonForm.cs +++ b/TelegramBotBase/Form/ButtonForm.cs @@ -1,343 +1,341 @@ 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; -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() { - 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 + /// + /// Contains the number of rows. + /// + public int Rows => _buttons.Count; + + /// + /// 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.Count; - } - } - - /// - /// 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] - { - get - { - return Buttons[row]; - } - } - - public ButtonForm() - { - - } - - public ButtonForm(ControlBase control) - { - this.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) - { - T[][] 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 (this.Buttons.Count == 0) - return 0; - - return this.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 this.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(); - - return ikb; - } - - public KeyboardButton[][] ToReplyButtonArray() - { - var ikb = this.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 = this.Buttons.FirstOrDefault(a => a.ToArray().Count(b => b == button) > 0); - if (row == null) - return -1; - - return this.Buttons.IndexOf(row); - } - - public Tuple FindRow(String text, bool useText = true) - { - var r = this.Buttons.FirstOrDefault(a => a.Matches(text, useText)); - if (r == null) - return null; - - var i = this.Buttons.IndexOf(r); - return new Tuple(r, i); - } - - - /// - /// Returns the first Button with the given value. - /// - /// - /// - public ButtonBase GetButtonByValue(String value) - { - return this.ToList().Where(a => a.Value == value).FirstOrDefault(); - } - - public static implicit operator InlineKeyboardMarkup(ButtonForm form) - { - if (form == null) - return null; - - InlineKeyboardMarkup ikm = new InlineKeyboardMarkup(form.ToInlineButtonArray()); - - return ikm; - } - - public static implicit operator ReplyKeyboardMarkup(ButtonForm form) - { - if (form == null) - return null; - - ReplyKeyboardMarkup ikm = new ReplyKeyboardMarkup(form.ToReplyButtonArray()); - - return ikm; - } - - /// - /// Creates a copy of this form. - /// - /// - public ButtonForm Duplicate() - { - var bf = new ButtonForm() - { - Markup = this.Markup, - DependencyControl = this.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 = this.Markup, - DependencyControl = this.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; - } - else - { - 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 = this.Markup, - DependencyControl = this.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; - } - else - { - 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 3b50e31..8385551 100644 --- a/TelegramBotBase/Form/CallbackData.cs +++ b/TelegramBotBase/Form/CallbackData.cs @@ -1,82 +1,69 @@ -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 +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) - { - this.Method = method; - this.Value = value; - } - - public static String Create(String method, String value) - { - return new CallbackData(method, value).Serialize(); - } - - /// - /// Serializes data to json string - /// - /// - public String Serialize() - { - String s = ""; - try - { - - s = Newtonsoft.Json.JsonConvert.SerializeObject(this); - } - catch - { - - - } - return s; - } - - /// - /// Deserializes data from json string - /// - /// - /// - public static CallbackData Deserialize(String data) - { - CallbackData cd = null; - try - { - cd = Newtonsoft.Json.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; + } + + public static implicit operator string(CallbackData callbackData) => callbackData.Serialize(); } diff --git a/TelegramBotBase/Form/ConfirmDialog.cs b/TelegramBotBase/Form/ConfirmDialog.cs index dc791db..ebb62c3 100644 --- a/TelegramBotBase/Form/ConfirmDialog.cs +++ b/TelegramBotBase/Form/ConfirmDialog.cs @@ -1,124 +1,119 @@ using System; using System.Collections.Generic; -using System.ComponentModel; using System.Linq; -using System.Text; 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 EventHandlerList __Events { get; set; } = new EventHandlerList(); - - private static object __evButtonClicked { get; } = new object(); - - public ConfirmDialog() - { - - } - - public ConfirmDialog(String Message) - { - this.Message = Message; - this.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) - { - this.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(); - - ButtonBase button = this.Buttons.FirstOrDefault(a => a.Value == call.Value); - - if (button == null) - { - return; - } - - OnButtonClicked(new ButtonClickedEventArgs(button) { Tag = this.Tag }); - - if (AutoCloseOnClick) - await CloseForm(); - } - - - public override async Task Render(MessageResult message) - { - ButtonForm btn = new ButtonForm(); - - var buttons = this.Buttons.Select(a => new ButtonBase(a.Text, CallbackData.Create("action", a.Value))).ToList(); - btn.AddButtonRow(buttons); - - await this.Device.Send(this.Message, btn); - } - - - public event EventHandler ButtonClicked - { - add - { - this.__Events.AddHandler(__evButtonClicked, value); - } - remove - { - this.__Events.RemoveHandler(__evButtonClicked, value); - } - } - - public void OnButtonClicked(ButtonClickedEventArgs e) - { - (this.__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 4935514..129339d 100644 --- a/TelegramBotBase/Form/DynamicButton.cs +++ b/TelegramBotBase/Form/DynamicButton.cs @@ -1,41 +1,30 @@ using System; -using System.Collections.Generic; -using System.Text; -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 - { - return GetText?.Invoke() ?? m_text; - } - set - { - m_text = value; - } - } - - private String m_text = ""; - - 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 ecdc01f..14002f9 100644 --- a/TelegramBotBase/Form/GroupForm.cs +++ b/TelegramBotBase/Form/GroupForm.cs @@ -1,86 +1,75 @@ -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; -namespace TelegramBotBase.Form +namespace TelegramBotBase.Form; + +public class GroupForm : FormBase { - public class GroupForm : FormBase + public override async Task Load(MessageResult message) { - - - public GroupForm() + switch (message.MessageType) { + case MessageType.ChatMembersAdded: + await OnMemberChanges(new MemberChangeEventArgs(MessageType.ChatMembersAdded, message, + message.Message.NewChatMembers)); - } + break; + case MessageType.ChatMemberLeft: - public override async Task Load(MessageResult message) - { - switch (message.MessageType) - { - case Telegram.Bot.Types.Enums.MessageType.ChatMembersAdded: + await OnMemberChanges(new MemberChangeEventArgs(MessageType.ChatMemberLeft, message, + message.Message.LeftChatMember)); - await OnMemberChanges(new MemberChangeEventArgs(Telegram.Bot.Types.Enums.MessageType.ChatMembersAdded, message, message.Message.NewChatMembers)); + break; - break; - case Telegram.Bot.Types.Enums.MessageType.ChatMemberLeft: + 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 OnMemberChanges(new MemberChangeEventArgs(Telegram.Bot.Types.Enums.MessageType.ChatMemberLeft, message, message.Message.LeftChatMember)); + await OnGroupChanged(new GroupChangedEventArgs(message.MessageType, message)); - break; + 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: + default: - await OnGroupChanged(new GroupChangedEventArgs(message.MessageType, message)); - - break; - - default: - - await OnMessage(message); - - break; - } - - } - - public override async Task Edited(MessageResult message) - { - await OnMessageEdit(message); - } - - public virtual async Task OnMemberChanges(MemberChangeEventArgs e) - { - - } - - - public virtual async Task OnGroupChanged(GroupChangedEventArgs e) - { - - } - - - public virtual async Task OnMessage(MessageResult e) - { - - } - - public virtual async Task OnMessageEdit(MessageResult e) - { + 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; + } +} \ No newline at end of file diff --git a/TelegramBotBase/Form/ModalDialog.cs b/TelegramBotBase/Form/ModalDialog.cs index a3c8faa..06e2bbd 100644 --- a/TelegramBotBase/Form/ModalDialog.cs +++ b/TelegramBotBase/Form/ModalDialog.cs @@ -1,28 +1,25 @@ using System; -using System.Collections.Generic; -using System.Text; 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 this.CloseControls(); - - await this.OnClosed(new EventArgs()); + await OnClosed(EventArgs.Empty); - await this.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 d1858b9..b29e203 100644 --- a/TelegramBotBase/Form/Navigation/NavigationController.cs +++ b/TelegramBotBase/Form/Navigation/NavigationController.cs @@ -2,357 +2,366 @@ 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 +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; - - this.Init += NavigationController_Init; - this.Opened += NavigationController_Opened; - this.Closed += NavigationController_Closed; + History.AddRange(forms); + Index = History.Count - 1; } + } - public NavigationController(FormBase startForm, params FormBase[] forms) : this() - { - this.Client = startForm.Client; - this.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, Args.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(new EventArgs()); - - //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); - return; + return null; } - if (History.Count > 0) - { - form = History[Index]; - await form.OnOpened(new EventArgs()); - } + return History[Index]; + } + } + + + public async Task 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 = this.Client; - form.Device = this.Device; + 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; - this.History.Add(form); - Index++; + await form.OnInit(new InitEventArgs()); - Device.FormSwitched = true; + History.Add(form); + } + } - if (Index < 2) - return; + public Task SaveState(SaveStateEventArgs e) + { + e.Set("$controller.history.count", History.Count.ToString()); - await form.OnInit(new InitEventArgs(args)); + 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.OnOpened(new EventArgs()); + 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++; } - /// - /// 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) + return Task.CompletedTask; + } + + 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); + } + } + + /// + /// 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 (this.History.Count == 0) - return null; - - return this.History[Index]; - } - } - - public List GetAllForms() - { - return History.ToList(); - } - - - public void LoadState(LoadStateEventArgs e) - { - if (e.Get("$controller.history.count") == null) - return; - - - int historyCount = e.GetInt("$controller.history.count"); - - for (int 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; - - Type t = Type.GetType(qname.ToString()); - 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) - { - 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(); - - 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 ex) - { - - Tools.Conversion.CustomConversionChecks(form, p, f); - - } - catch - { - - } - } - - form.Device = this.Device; - form.Client = this.Client; - form.NavigationController = this; - - form.OnInit(new InitEventArgs()); - - this.History.Add(form); - } - - } - - public void SaveState(SaveStateEventArgs e) - { - e.Set("$controller.history.count", History.Count.ToString()); - - int 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 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 ec9e61c..a2d4c56 100644 --- a/TelegramBotBase/Form/PromptDialog.cs +++ b/TelegramBotBase/Form/PromptDialog.cs @@ -1,125 +1,112 @@ 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 +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 EventHandlerList __Events { get; set; } = new EventHandlerList(); - - private static object __evCompleted { get; } = new object(); - - public bool ShowBackButton { get; set; } = false; - - public String BackLabel { get; set; } = Localizations.Default.Language["PromptDialog_Back"]; - - /// - /// Contains the RAW received message. - /// - public Message ReceivedMessage { get; set; } - - public PromptDialog() - { - - } - - public PromptDialog(String Message) - { - this.Message = Message; - } - - public async override Task Load(MessageResult message) - { - if (message.Handled) - return; - - if (!message.IsFirstHandler) - return; - - if (this.ShowBackButton && message.MessageText == BackLabel) - { - await this.CloseForm(); - - return; - } - - if (this.Value == null) - { - this.Value = message.MessageText; - - ReceivedMessage = message.Message; - } - - - } - - public override async Task Render(MessageResult message) - { - - if (this.Value == null) - { - if (this.ShowBackButton) - { - ButtonForm bf = new ButtonForm(); - bf.AddButtonRow(new ButtonBase(BackLabel, "back")); - await this.Device.Send(this.Message, (ReplyMarkupBase)bf); - return; - } - - await this.Device.Send(this.Message); - return; - } - - - message.Handled = true; - - OnCompleted(new PromptDialogCompletedEventArgs() { Tag = this.Tag, Value = this.Value }); - - await this.CloseForm(); - } - - - public event EventHandler Completed - { - add - { - this.__Events.AddHandler(__evCompleted, value); - } - remove - { - this.__Events.RemoveHandler(__evCompleted, value); - } - } - - public void OnCompleted(PromptDialogCompletedEventArgs e) - { - (this.__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 89b3ce7..99c0d85 100644 --- a/TelegramBotBase/Form/SplitterForm.cs +++ b/TelegramBotBase/Form/SplitterForm.cs @@ -1,100 +1,93 @@ -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; -namespace TelegramBotBase.Form +/// +/// This is used to split incoming 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 == Telegram.Bot.Types.Enums.ChatType.Channel) + if (message.Message.Chat.Type == ChatType.Supergroup) + { + if (await OpenSupergroup(message)) { - if (await OpenChannel(message)) - { - return; - } - } - if (message.Message.Chat.Type == Telegram.Bot.Types.Enums.ChatType.Supergroup) - { - if (await OpenSupergroup(message)) - { - return; - } - if (await OpenGroup(message)) - { - return; - } - } - if (message.Message.Chat.Type == Telegram.Bot.Types.Enums.ChatType.Group) - { - if (await OpenGroup(message)) - { - return; - } + return; } - await Open(message); + if (await OpenGroup(message)) + { + return; + } } - - public virtual async Task OpenSupergroup(MessageResult e) + if (message.Message.Chat.Type == ChatType.Group) { - return false; + if (await OpenGroup(message)) + { + return; + } } - public virtual async Task OpenChannel(MessageResult e) - { - return false; - } - - public virtual async Task Open(MessageResult e) - { - return false; - } - - public virtual async Task OpenGroup(MessageResult e) - { - return false; - } + 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 Action(MessageResult message) + { + return base.Action(message); + } - public override Task PreLoad(MessageResult message) - { - return base.PreLoad(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); - } + public override Task Render(MessageResult message) + { + return base.Render(message); + } + public override Task SentData(DataResult message) + { + return base.SentData(message); } } diff --git a/TelegramBotBase/Form/TagButtonBase.cs b/TelegramBotBase/Form/TagButtonBase.cs index add8b80..8a6cb9e 100644 --- a/TelegramBotBase/Form/TagButtonBase.cs +++ b/TelegramBotBase/Form/TagButtonBase.cs @@ -1,55 +1,46 @@ -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 +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) - { - String id = (form.DependencyControl != null ? form.DependencyControl.ControlID + "_" : ""); - - return InlineKeyboardButton.WithCallbackData(this.Text, id + this.Value); - - } - - - /// - /// Returns a KeyBoardButton - /// - /// - /// - public override KeyboardButton ToKeyboardButton(ButtonForm form) - { - return new KeyboardButton(this.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/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); + } + + } +} diff --git a/TelegramBotBase/Interfaces/IDataSource.cs b/TelegramBotBase/Interfaces/IDataSource.cs index d3662e5..fe759ee 100644 --- a/TelegramBotBase/Interfaces/IDataSource.cs +++ b/TelegramBotBase/Interfaces/IDataSource.cs @@ -1,43 +1,36 @@ -using System; -using System.Collections.Generic; -using System.Text; -using TelegramBotBase.Controls.Hybrid; +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 de487b6..8e0d95a 100644 --- a/TelegramBotBase/Interfaces/IDeviceSession.cs +++ b/TelegramBotBase/Interfaces/IDeviceSession.cs @@ -1,42 +1,38 @@ using System; -using System.Collections.Generic; -using System.Text; using TelegramBotBase.Form; -namespace TelegramBotBase.Interfaces +namespace TelegramBotBase.Interfaces; + +internal interface IDeviceSession { - 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 fec857f..951b7fa 100644 --- a/TelegramBotBase/Interfaces/IMessageLoopFactory.cs +++ b/TelegramBotBase/Interfaces/IMessageLoopFactory.cs @@ -1,21 +1,14 @@ 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; -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 7c1c44d..28a2df2 100644 --- a/TelegramBotBase/Interfaces/IStartFormFactory.cs +++ b/TelegramBotBase/Interfaces/IStartFormFactory.cs @@ -1,12 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Text; -using TelegramBotBase.Form; +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 b7e3e69..0a713cb 100644 --- a/TelegramBotBase/Interfaces/IStateForm.cs +++ b/TelegramBotBase/Interfaces/IStateForm.cs @@ -1,20 +1,14 @@ -using System; -using System.Collections.Generic; -using System.Text; +using System.Threading.Tasks; using TelegramBotBase.Args; -using TelegramBotBase.Base; -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 - { + Task LoadState(LoadStateEventArgs e); - void LoadState(LoadStateEventArgs e); - - void SaveState(SaveStateEventArgs e); - - } + Task SaveState(SaveStateEventArgs e); } diff --git a/TelegramBotBase/Interfaces/IStateMachine.cs b/TelegramBotBase/Interfaces/IStateMachine.cs index 7cd3e65..221fc77 100644 --- a/TelegramBotBase/Interfaces/IStateMachine.cs +++ b/TelegramBotBase/Interfaces/IStateMachine.cs @@ -1,18 +1,14 @@ using System; -using System.Collections.Generic; -using System.Text; using TelegramBotBase.Args; using TelegramBotBase.Base; -using TelegramBotBase.Form; -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 6b0a180..0582b8a 100644 --- a/TelegramBotBase/Localizations/Default.cs +++ b/TelegramBotBase/Localizations/Default.cs @@ -1,14 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Text; +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 35ac031..51881b1 100644 --- a/TelegramBotBase/Localizations/English.cs +++ b/TelegramBotBase/Localizations/English.cs @@ -1,41 +1,36 @@ -using System; -using System.Collections.Generic; -using System.Text; +namespace TelegramBotBase.Localizations; -namespace TelegramBotBase.Localizations +public class English : Localization { - public class English : Localization + public English() { - public English() : base() - { - 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"] = "Chosen"; - Values["MultiToggleButton_SelectedIcon"] = "✅"; - Values["MultiToggleButton_Title"] = "Multi-Toggle"; - Values["MultiToggleButton_Changed"] = "Chosen"; - 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"] = "Chosen"; + Values["MultiToggleButton_SelectedIcon"] = "✅"; + Values["MultiToggleButton_Title"] = "Multi-Toggle"; + Values["MultiToggleButton_Changed"] = "Chosen"; + Values["PromptDialog_Back"] = "Back"; + Values["ToggleButton_Changed"] = "Setting changed"; + Values["ButtonGrid_SearchIcon"] = "🔍"; + Values["ButtonGrid_TagIcon"] = "📁"; } } diff --git a/TelegramBotBase/Localizations/German.cs b/TelegramBotBase/Localizations/German.cs index 5861e72..52afbf7 100644 --- a/TelegramBotBase/Localizations/German.cs +++ b/TelegramBotBase/Localizations/German.cs @@ -1,41 +1,35 @@ -using System; -using System.Collections.Generic; -using System.Text; +namespace TelegramBotBase.Localizations; -namespace TelegramBotBase.Localizations +public class German : Localization { - public class German : Localization + public German() { - public German() : base() - { - 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 ed56cb0..3efddff 100644 --- a/TelegramBotBase/Localizations/Localization.cs +++ b/TelegramBotBase/Localizations/Localization.cs @@ -1,27 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Text; +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] - { - get - { - return Values[key]; - } - } - - public Localization() - { - - - } - - } -} + 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 05dbfa7..333c6cf 100644 --- a/TelegramBotBase/Markdown/Generator.cs +++ b/TelegramBotBase/Markdown/Generator.cs @@ -1,178 +1,159 @@ -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 +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 { - switch (OutputMode) - { - case ParseMode.Markdown: - return "[" + (title ?? url) + "](" + url + " " + (tooltip ?? "") + ")"; - case ParseMode.Html: - return $"{title ?? ""}"; - } - return 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.ToString(), 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) - { - switch (OutputMode) - { - case ParseMode.Markdown: - return "*" + text + "*"; - case ParseMode.Html: - return "" + text + ""; - } - return text; - } - - /// - /// Returns a strike through in Markdown or HTML - /// - /// - /// - public static String Strikesthrough(this String text) - { - switch (OutputMode) - { - case ParseMode.Markdown: - return "~" + text + "~"; - case ParseMode.Html: - return "" + text + ""; - } - return text; - } - - /// - /// Returns a italic text in Markdown or HTML - /// - /// - /// - public static String Italic(this String text) - { - switch (OutputMode) - { - case ParseMode.Markdown: - return "_" + text + "_"; - case ParseMode.Html: - return "" + text + ""; - } - return text; - } - - /// - /// Returns a underline text in Markdown or HTML - /// - /// - /// - public static String Underline(this String text) - { - switch (OutputMode) - { - case ParseMode.Markdown: - return "__" + text + "__"; - case ParseMode.Html: - return "" + text + ""; - } - return text; - } - - /// - /// Returns a monospace text in Markdown or HTML - /// - /// - /// - public static String Monospace(this String text) - { - switch (OutputMode) - { - case ParseMode.Markdown: - return "`" + text + "`"; - case ParseMode.Html: - return "" + text + ""; - } - return text; - } - - /// - /// Returns a multi monospace text in Markdown or HTML - /// - /// - /// - public static String MultiMonospace(this String text) - { - switch (OutputMode) - { - case ParseMode.Markdown: - return "```" + text + "```"; - case ParseMode.Html: - return "
" + text + "
"; - } - return 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) - { - char[] toEscape = new char[] { '_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!' }; - - 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 3a6b00c..f1a2d39 100644 --- a/TelegramBotBase/MessageLoops/FormBaseMessageLoop.cs +++ b/TelegramBotBase/MessageLoops/FormBaseMessageLoop.cs @@ -1,137 +1,122 @@ 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; -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 object __evUnhandledCall = new object(); + var update = ur.RawData; - private EventHandlerList __Events = new EventHandlerList(); - public FormBaseMessageLoop() + if (update.Type != UpdateType.Message + && update.Type != UpdateType.EditedMessage + && update.Type != UpdateType.CallbackQuery) { - + return; } - 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); - - 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 (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 == Telegram.Bot.Types.Enums.UpdateType.Message) + if (!mr.Handled) { - 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) + 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 - { - add - { - this.__Events.AddHandler(__evUnhandledCall, value); - } - remove - { - this.__Events.RemoveHandler(__evUnhandledCall, value); } } - public void OnUnhandledCall(UnhandledCallEventArgs e) + if (!session.FormSwitched) { - (this.__Events[__evUnhandledCall] as EventHandler)?.Invoke(this, e); + //Render Event + await activeForm.RenderControls(mr); + await activeForm.Render(mr); } } + + /// + /// Will be called if no form handled 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); + } } diff --git a/TelegramBotBase/MessageLoops/FullMessageLoop.cs b/TelegramBotBase/MessageLoops/FullMessageLoop.cs index 63e8160..b7855c6 100644 --- a/TelegramBotBase/MessageLoops/FullMessageLoop.cs +++ b/TelegramBotBase/MessageLoops/FullMessageLoop.cs @@ -1,130 +1,115 @@ 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; -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 object __evUnhandledCall = new object(); + var update = ur.RawData; - private EventHandlerList __Events = new EventHandlerList(); - public FullMessageLoop() + //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 (sce.Handled) + { + return; + } } - public async Task MessageLoop(BotBase Bot, DeviceSession session, UpdateResult ur, MessageResult mr) + 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) { - var update = ur.RawData; - - - //Is this a bot command ? - if (mr.IsFirstHandler && mr.IsBotCommand && Bot.IsKnownBotCommand(mr.BotCommand)) + 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 == Telegram.Bot.Types.Enums.UpdateType.Message) + if (!mr.Handled) { - 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) + 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 - { - add - { - this.__Events.AddHandler(__evUnhandledCall, value); - } - remove - { - this.__Events.RemoveHandler(__evUnhandledCall, value); } } - public void OnUnhandledCall(UnhandledCallEventArgs e) + if (!session.FormSwitched) { - (this.__Events[__evUnhandledCall] as EventHandler)?.Invoke(this, e); + //Render Event + await activeForm.RenderControls(mr); + await activeForm.Render(mr); } } + + /// + /// Will be called if no form handled 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); + } } diff --git a/TelegramBotBase/MessageLoops/MinimalMessageLoop.cs b/TelegramBotBase/MessageLoops/MinimalMessageLoop.cs index 0be394b..8f72f15 100644 --- a/TelegramBotBase/MessageLoops/MinimalMessageLoop.cs +++ b/TelegramBotBase/MessageLoops/MinimalMessageLoop.cs @@ -1,65 +1,46 @@ 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; -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 object __evUnhandledCall = new object(); - - private EventHandlerList __Events = new EventHandlerList(); - - public MinimalMessageLoop() - { - - } - - 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); + //Loading Event + await activeForm.Load(mr); + } - } + /// + /// Will be called if no form handled this call + /// + public event EventHandler UnhandledCall + { + add => _events.AddHandler(EvUnhandledCall, value); + remove => _events.RemoveHandler(EvUnhandledCall, value); + } - /// - /// Will be called if no form handeled this call - /// - public event EventHandler UnhandledCall - { - add - { - this.__Events.AddHandler(__evUnhandledCall, value); - } - remove - { - this.__Events.RemoveHandler(__evUnhandledCall, value); - } - } - - public void OnUnhandledCall(UnhandledCallEventArgs e) - { - (this.__Events[__evUnhandledCall] as EventHandler)?.Invoke(this, e); - - } + public void OnUnhandledCall(UnhandledCallEventArgs e) + { + (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e); } } diff --git a/TelegramBotBase/Properties/AssemblyInfo.cs b/TelegramBotBase/Properties/AssemblyInfo.cs index 23bb4de..7f6a35f 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 @@ -33,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/SessionManager.cs b/TelegramBotBase/SessionManager.cs index 0cceeda..7e9d257 100644 --- a/TelegramBotBase/SessionManager.cs +++ b/TelegramBotBase/SessionManager.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,314 +9,330 @@ using TelegramBotBase.Base; using TelegramBotBase.Form; using TelegramBotBase.Interfaces; using TelegramBotBase.Sessions; -namespace TelegramBotBase +using TelegramBotBase.Tools; + +namespace TelegramBotBase; + +/// +/// Base class for managing all active sessions +/// +public class SessionManager { - /// - /// Class for managing all active sessions - /// - public sealed class SessionManager + public SessionManager(BotBase botBase) { - /// - /// The Basic message client. - /// - public MessageClient Client => BotBase.Client; + BotBase = botBase; + SessionList = new Dictionary(); + } - /// - /// A list of all active sessions. - /// - public Dictionary SessionList { get; set; } + /// + /// The Basic message client. + /// + public MessageClient Client => BotBase.Client; + + /// + /// A list of all active sessions. + /// + public Dictionary SessionList { get; set; } - /// - /// Reference to the Main BotBase instance for later use. - /// - public BotBase BotBase { get; } + /// + /// Reference to the Main BotBase instance for later use. + /// + public BotBase BotBase { get; } + /// + /// Get device session from Device/ChatId + /// + /// + /// + public DeviceSession GetSession(long deviceId) + { + var ds = SessionList.FirstOrDefault(a => a.Key == deviceId).Value ?? null; + return ds; + } - public SessionManager(BotBase botBase) + /// + /// 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); + + SessionList[deviceId] = ds; + return ds; + } + + /// + /// End session + /// + /// + public void EndSession(long deviceId) + { + var d = SessionList[deviceId]; + if (d != null) { - BotBase = botBase; - SessionList = new Dictionary(); - } - - /// - /// 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 = this.Client; - - DeviceSession ds = new Sessions.DeviceSession(deviceId, start); - - start.Device = ds; - await start.OnInit(new InitEventArgs()); - - await start.OnOpened(new EventArgs()); - - SessionList[deviceId] = ds; - return ds; - } - - /// - /// End session - /// - /// - public void EndSession(long deviceId) - { - var d = SessionList[deviceId]; - if (d != null) 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 Task LoadSessionStates() - { - if (BotBase.StateMachine == null) - { - return; - } - - await LoadSessionStates(BotBase.StateMachine); - } - - - /// - /// Loads the previously saved states from the machine. - /// - public async Task LoadSessionStates(IStateMachine statemachine) - { - if (statemachine == null) - { - throw new ArgumentNullException("StateMachine", "No StateMachine defined. Please set one to property BotBase.StateMachine"); - } - - var container = statemachine.LoadFormStates(); - - foreach (var s in container.States) - { - Type t = Type.GetType(s.QualifiedName); - if (t == null || !t.IsSubclassOf(typeof(FormBase))) - { - continue; - } - - //Key already existing - 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 (!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) - { - 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(); - - 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 ex) - { - - Tools.Conversion.CustomConversionChecks(form, p, f); - - } - catch - { - - } - } - } - - form.Client = Client; - var device = new DeviceSession(s.DeviceId, form); - - device.ChatTitle = s.ChatTitle; - - SessionList.Add(s.DeviceId, device); - - //Is Subclass of IStateForm - var iform = form as IStateForm; - if (iform != null) - { - var ls = new LoadStateEventArgs(); - ls.Values = s.Values; - iform.LoadState(ls); - } - - try - { - await form.OnInit(new InitEventArgs()); - - await form.OnOpened(new EventArgs()); - } - catch - { - //Skip on exception - SessionList.Remove(s.DeviceId); - } - } - - } - - - - - /// - /// Saves all open states into the machine. - /// - public async Task 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(); - se.DeviceId = s.Key; - se.ChatTitle = s.Value.GetChatTitle(); - se.FormUri = form.GetType().FullName; - se.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 - var iform = form as IStateForm; - if (iform != null) - { - //Loading Session states - SaveStateEventArgs 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(); - - 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) - continue; - } - } - - var sc = new StateContainer(); - sc.States = states; - - statemachine.SaveFormStates(new SaveStatesEventArgs(sc)); - } - - /// - /// Saves all open states into the machine. - /// - public async Task SaveSessionStates() - { - if (BotBase.StateMachine == null) - return; - - - await SaveSessionStates(BotBase.StateMachine); + 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 Task LoadSessionStates() + { + if (BotBase.StateMachine == null) + { + return; + } + + await LoadSessionStates(BotBase.StateMachine); + } + + + /// + /// Loads the previously saved states from the machine. + /// + public async Task LoadSessionStates(IStateMachine statemachine) + { + if (statemachine == null) + { + throw new ArgumentNullException(nameof(statemachine), + "No StateMachine defined. Please set one to property BotBase.StateMachine"); + } + + var container = statemachine.LoadFormStates(); + + foreach (var s in container.States) + { + var t = Type.GetType(s.QualifiedName); + if (t == null || !t.IsSubclassOf(typeof(FormBase))) + { + continue; + } + + //Key already existing + if (SessionList.ContainsKey(s.DeviceId)) + { + 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) + { + 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) + { + 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.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 + { + Values = s.Values + }; + await 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 async Task SaveSessionStates(IStateMachine statemachine) + { + if (statemachine == null) + { + throw new ArgumentNullException(nameof(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 + }; + + //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(); + await 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 async Task SaveSessionStates() + { + if (BotBase.StateMachine == null) + { + return; + } + + + await SaveSessionStates(BotBase.StateMachine); + } } diff --git a/TelegramBotBase/Sessions/DeviceSession.cs b/TelegramBotBase/Sessions/DeviceSession.cs index 17d52e8..f823c59 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; @@ -19,952 +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; } - - /// - /// Returns the ChatTitle depending on groups/channels or users - /// - /// - public String GetChatTitle() - { - return LastMessage?.Chat.Title - ?? LastMessage?.Chat.Username - ?? LastMessage?.Chat.FirstName - ?? ChatTitle; - } - - /// - /// 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 - { - get - { - return this.LastMessage?.MessageId ?? -1; - } - } - - /// - /// Returns the last received message. - /// - public Message LastMessage { get; set; } - - public MessageClient Client - { - get - { - return this.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); - } - } - - /// - /// Returns if the messages is posted within a channel. - /// - public bool IsChannel - { - get - { - return this.LastMessage != null && this.LastMessage.Chat.Type == ChatType.Channel; - } - } - - private EventHandlerList __Events = new EventHandlerList(); - - private static object __evMessageSent = new object(); - private static object __evMessageReceived = new object(); - private static object __evMessageDeleted = new object(); - - public DeviceSession() - { - - } - - public DeviceSession(long DeviceId) - { - this.DeviceId = DeviceId; - } - - public DeviceSession(long DeviceId, FormBase StartForm) - { - this.DeviceId = DeviceId; - this.ActiveForm = StartForm; - this.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 this.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); - } - - try - { - return await API(a => a.EditMessageTextAsync(this.DeviceId, messageId, text, parseMode, replyMarkup: markup)); - } - 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); - } - - try - { - return await API(a => a.EditMessageTextAsync(this.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(this.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(this.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 (this.ActiveForm == null) - return null; - - InlineKeyboardMarkup markup = buttons; - - 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 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(this.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 (this.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(this.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 (this.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(this.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 (this.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 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 (this.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 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 (this.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 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 (this.ActiveForm == null) - return null; - - InlineKeyboardMarkup markup = buttons; - - try - { - MemoryStream ms = new MemoryStream(video); - - InputOnlineFile fts = new InputOnlineFile(ms, filename); - - var t = API(a => a.SendVideoAsync(this.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 (this.ActiveForm == null) - return null; - - InlineKeyboardMarkup markup = buttons; - - try - { - FileStream fs = new FileStream(filepath, FileMode.Open); - - var filename = Path.GetFileName(filepath); - - InputOnlineFile fts = new InputOnlineFile(fs, filename); - - var t = API(a => a.SendVideoAsync(this.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) - { - MemoryStream ms = new MemoryStream(document); - - InputOnlineFile 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(this.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(this.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)); - rck.OneTimeKeyboard = OneTimeOnly; - return await API(a => a.SendTextMessageAsync(this.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)); - rcl.OneTimeKeyboard = OneTimeOnly; - return await API(a => a.SendTextMessageAsync(this.DeviceId, requestMessage, replyMarkup: rcl)); - } - - public async Task HideReplyKeyboard(String closedMsg = "Closed", bool autoDeleteResponse = true) - { - try - { - var m = await this.Send(closedMsg, new ReplyKeyboardRemove()); - - if (autoDeleteResponse && m != null) - { - await this.DeleteMessage(m); - } - - return m; - } - catch - { - - } - return null; - } - - /// - /// Deletes a message - /// - /// - /// - public virtual async Task DeleteMessage(int messageId = -1) - { - - await RAW(a => a.DeleteMessageAsync(this.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(this.DeviceId, permissions)); - } - catch - { - - } - } - - private Type GetOrigin(StackTrace stackTrace) - { - for (int 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(this.DeviceId, userId, permissions, until)); - } - catch - { - - } - } - - public virtual async Task GetChatUser(long userId) - { - try - { - return await API(a => a.GetChatMemberAsync(this.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(this.DeviceId, userId, until)); - } - catch - { - - } - } - - public virtual async Task BanUser(long userId, DateTime until = default(DateTime)) - { - try - { - await API(a => a.BanChatMemberAsync(this.DeviceId, userId, until)); - } - catch - { - - } - } - - public virtual async Task UnbanUser(long userId) - { - try - { - await API(a => a.UnbanChatMemberAsync(this.DeviceId, userId)); - } - catch - { - - } - } - - #endregion - - /// - /// Gives access to the original TelegramClient without any Exception catchings. - /// - /// - /// - /// - public T RAW(Func call) - { - return call(this.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 < DeviceSession.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 < DeviceSession.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 Base.Async.AsyncEventHandler MessageSent - { - add - { - this.__Events.AddHandler(__evMessageSent, value); - } - remove - { - this.__Events.RemoveHandler(__evMessageSent, value); - } - } - - - public async Task OnMessageSent(MessageSentEventArgs e) - { - if (e.Message == null) - return; - - var handler = this.__Events[__evMessageSent]?.GetInvocationList().Cast>(); - if (handler == null) - return; - - foreach (var h in handler) - { - await Base.Async.InvokeAllAsync(h, this, e); - } - - //(this.__Events[__evMessageSent] as EventHandler)?.Invoke(this, e); - } - - /// - /// Eventhandler for received messages - /// - public event EventHandler MessageReceived - { - add - { - this.__Events.AddHandler(__evMessageReceived, value); - } - remove - { - this.__Events.RemoveHandler(__evMessageReceived, value); - } - } - - - public void OnMessageReceived(MessageReceivedEventArgs e) - { - (this.__Events[__evMessageReceived] as EventHandler)?.Invoke(this, e); - } - - /// - /// Eventhandler for deleting messages - /// - public event EventHandler MessageDeleted - { - add - { - this.__Events.AddHandler(__evMessageDeleted, value); - } - remove - { - this.__Events.RemoveHandler(__evMessageDeleted, value); - } - } - - - public void OnMessageDeleted(MessageDeletedEventArgs e) - { - (this.__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" } + + public DeviceSession(long deviceId) + { + DeviceId = deviceId; + } + + 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 incoming 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 + { + } + } + + /// + /// 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 MessageTooLongException(text.Length); + } + + try + { + return await Api(a => + a.EditMessageTextAsync(DeviceId, messageId, text, parseMode, replyMarkup: markup)); + } + 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 MessageTooLongException(text.Length); + } + + try + { + 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 MessageTooLongException(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; + } + + InlineKeyboardMarkup markup = buttons; + + if (text.Length > Constants.Telegram.MaxMessageLength) + { + throw new MessageTooLongException(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 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; + } + + if (text.Length > Constants.Telegram.MaxMessageLength) + { + throw new MessageTooLongException(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 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; + } + + if (text.Length > Constants.Telegram.MaxMessageLength) + { + throw new MessageTooLongException(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, 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 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 } diff --git a/TelegramBotBase/States/JSONStateMachine.cs b/TelegramBotBase/States/JSONStateMachine.cs index 7035692..ada7fe4 100644 --- a/TelegramBotBase/States/JSONStateMachine.cs +++ b/TelegramBotBase/States/JSONStateMachine.cs @@ -1,99 +1,92 @@ -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; 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))) { - if (file is null) - { - throw new ArgumentNullException(nameof(file)); - } - - this.FallbackStateForm = fallbackStateForm; - - if (this.FallbackStateForm != null && !this.FallbackStateForm.IsSubclassOf(typeof(FormBase))) - { - throw new ArgumentException("FallbackStateForm is not a subclass of FormBase"); - } - - this.FilePath = file; - this.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 = System.IO.File.ReadAllText(FilePath); + TypeNameHandling = TypeNameHandling.All, + TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple + }); - var sc = Newtonsoft.Json.JsonConvert.DeserializeObject(content, new JsonSerializerSettings - { - TypeNameHandling = TypeNameHandling.All, - TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple - }) as StateContainer; - - 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 (System.IO.File.Exists(FilePath)) + if (!Overwrite) { - if (!this.Overwrite) - { - throw new Exception("File exists already."); - } - - System.IO.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 = Newtonsoft.Json.JsonConvert.SerializeObject(e.States, Formatting.Indented, new JsonSerializerSettings - { - TypeNameHandling = TypeNameHandling.All, - TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple - }); - - System.IO.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 faba2af..7e8fa58 100644 --- a/TelegramBotBase/States/SimpleJSONStateMachine.cs +++ b/TelegramBotBase/States/SimpleJSONStateMachine.cs @@ -1,91 +1,85 @@ -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; 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))) { - if (file is null) - { - throw new ArgumentNullException(nameof(file)); - } - - this.FallbackStateForm = fallbackStateForm; - - if (this.FallbackStateForm != null && !this.FallbackStateForm.IsSubclassOf(typeof(FormBase))) - { - throw new ArgumentException("FallbackStateForm is not a subclass of FormBase"); - } - - this.FilePath = file; - this.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 = 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; - } - 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 (System.IO.File.Exists(FilePath)) + if (!Overwrite) { - if (!this.Overwrite) - { - throw new Exception("File exists already."); - } - - System.IO.File.Delete(FilePath); + throw new Exception("File exists already."); } - try - { - var content = Newtonsoft.Json.JsonConvert.SerializeObject(e.States, Formatting.Indented); + File.Delete(FilePath); + } - System.IO.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 2542f6a..1a569eb 100644 --- a/TelegramBotBase/States/XMLStateMachine.cs +++ b/TelegramBotBase/States/XMLStateMachine.cs @@ -1,104 +1,95 @@ 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; 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))) { - if (file is null) - { - throw new ArgumentNullException(nameof(file)); - } - - this.FallbackStateForm = fallbackStateForm; - - if (this.FallbackStateForm != null && !this.FallbackStateForm.IsSubclassOf(typeof(FormBase))) - { - throw new ArgumentException("FallbackStateForm is not a subclass of FormBase"); - } - - this.FilePath = file; - this.Overwrite = overwrite; + throw new ArgumentException("FallbackStateForm is not a subclass of FormBase"); } - public StateContainer LoadFormStates() - { - try - { - DataContractSerializer serializer = new DataContractSerializer(typeof(StateContainer)); - - using (var reader = new StreamReader(FilePath)) - { - using (var xml = new XmlTextReader(reader)) - { - StateContainer sc = serializer.ReadObject(xml) as StateContainer; - return sc; - } - } - } - catch - { - - } - - return new StateContainer(); - } - - public void SaveFormStates(SaveStatesEventArgs e) - { - if (System.IO.File.Exists(FilePath)) - { - if (!this.Overwrite) - { - throw new Exception("File exists already."); - } - - System.IO.File.Delete(FilePath); - } - - try - { - DataContractSerializer serializer = new DataContractSerializer(typeof(StateContainer)); - - using (var sw = new StreamWriter(this.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 a5b9666..12c0a79 100644 --- a/TelegramBotBase/TelegramBotBase.csproj +++ b/TelegramBotBase/TelegramBotBase.csproj @@ -1,69 +1,64 @@  - - netstandard2.0;net5;netcoreapp3.1;net6 - 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 3023e97..7e14769 100644 --- a/TelegramBotBase/TelegramBotBase.nuspec +++ b/TelegramBotBase/TelegramBotBase.nuspec @@ -24,4 +24,4 @@ - \ No newline at end of file + diff --git a/TelegramBotBase/Tools/Arrays.cs b/TelegramBotBase/Tools/Arrays.cs index 01efa34..9ad3993 100644 --- a/TelegramBotBase/Tools/Arrays.cs +++ b/TelegramBotBase/Tools/Arrays.cs @@ -1,22 +1,14 @@ 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 +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) - { - T[] 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 a239df5..31af172 100644 --- a/TelegramBotBase/Tools/Console.cs +++ b/TelegramBotBase/Tools/Console.cs @@ -1,65 +1,64 @@ using System; using System.Collections.Generic; using System.Runtime.InteropServices; -using System.Text; -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); - static EventHandler _handler; - - static List Actions = new List(); - - enum CtrlType - { - CTRL_C_EVENT = 0, - CTRL_BREAK_EVENT = 1, - CTRL_CLOSE_EVENT = 2, - CTRL_LOGOFF_EVENT = 5, - CTRL_SHUTDOWN_EVENT = 6 - } - - static Console() - { - - } - - public static void SetHandler(Action action) - { - Actions.Add(action); - - if (_handler != null) - return; - - _handler += new EventHandler(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: - - 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 b9e40da..00ffc47 100644 --- a/TelegramBotBase/Tools/Conversion.cs +++ b/TelegramBotBase/Tools/Conversion.cs @@ -1,38 +1,32 @@ -using System; -using System.Collections.Generic; -using System.Text; +using System.Collections.Generic; +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, System.Reflection.PropertyInfo f) + //Newtonsoft Int64/Int32 converter issue + if (f.PropertyType == typeof(int)) { - //Newtonsoft Int64/Int32 converter issue - if (f.PropertyType == typeof(Int32)) + if (int.TryParse(p.Value.ToString(), out var i)) { - int i = 0; - if (int.TryParse(p.Value.ToString(), out i)) - { - f.SetValue(form, i); - } - return; + f.SetValue(form, i); } - //Newtonsoft Double/Decimal converter issue - if (f.PropertyType == typeof(Decimal) | f.PropertyType == typeof(Nullable)) - { - decimal d = 0; - if (decimal.TryParse(p.Value.ToString(), out d)) - { - f.SetValue(form, d); - } - return; - } - - + 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 b0cd93f..28d73c4 100644 --- a/TelegramBotBase/Tools/Time.cs +++ b/TelegramBotBase/Tools/Time.cs @@ -1,51 +1,48 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -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) - { - int 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 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