diff --git a/Examples/AsyncFormUpdates/App.config b/Examples/AsyncFormUpdates/App.config
index 8ffc026..e784e10 100644
--- a/Examples/AsyncFormUpdates/App.config
+++ b/Examples/AsyncFormUpdates/App.config
@@ -1,378 +1,426 @@
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj b/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj
index 579f062..6c2fe0b 100644
--- a/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj
+++ b/Examples/AsyncFormUpdates/AsyncFormUpdates.csproj
@@ -1,74 +1,74 @@
-
-
- Debug
- AnyCPU
- {673A56F5-6110-4AED-A68D-562FD6ED3EA6}
- Exe
- AsyncFormUpdates
- AsyncFormUpdates
- v4.8
- 512
- true
- true
-
-
-
- AnyCPU
- true
- full
- false
- bin\Debug\
- DEBUG;TRACE
- prompt
- 4
-
-
- AnyCPU
- pdbonly
- true
- bin\Release\
- TRACE
- prompt
- 4
-
-
-
-
-
-
-
-
-
-
-
-
- ..\..\packages\Telegram.Bot.17.0.0\lib\netstandard2.0\Telegram.Bot.dll
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {0bd16fb9-7ed4-4ccb-83eb-5cee538e1b6c}
- TelegramBotBase
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
+
+
+ Debug
+ AnyCPU
+ {673A56F5-6110-4AED-A68D-562FD6ED3EA6}
+ Exe
+ AsyncFormUpdates
+ AsyncFormUpdates
+ v4.8
+ 512
+ true
+ true
+
+
+
+ AnyCPU
+ true
+ full
+ false
+ bin\Debug\
+ DEBUG;TRACE
+ prompt
+ 4
+
+
+ AnyCPU
+ pdbonly
+ true
+ bin\Release\
+ TRACE
+ prompt
+ 4
+
+
+
+
+
+
+
+
+
+
+
+
+ ..\..\packages\Telegram.Bot.17.0.0\lib\netstandard2.0\Telegram.Bot.dll
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {0bd16fb9-7ed4-4ccb-83eb-5cee538e1b6c}
+ TelegramBotBase
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Examples/AsyncFormUpdates/Program.cs b/Examples/AsyncFormUpdates/Program.cs
index 27283f7..facc257 100644
--- a/Examples/AsyncFormUpdates/Program.cs
+++ b/Examples/AsyncFormUpdates/Program.cs
@@ -15,8 +15,8 @@ namespace AsyncFormUpdates
var apiKey = "APIKey";
__bot = BotBaseBuilder.Create()
- .QuickStart(apiKey)
- .Build();
+ .QuickStart(apiKey)
+ .Build();
__bot.Start();
@@ -33,17 +33,17 @@ namespace AsyncFormUpdates
private static async void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
-
- foreach(var s in __bot.Sessions.SessionList)
+ foreach (var s in __bot.Sessions.SessionList)
{
//Only for AsyncUpdateForm
- if (s.Value.ActiveForm.GetType() != typeof(AsyncFormUpdate) && s.Value.ActiveForm.GetType() != typeof(AsyncFormEdit))
+ if (s.Value.ActiveForm.GetType() != typeof(AsyncFormUpdate) &&
+ s.Value.ActiveForm.GetType() != typeof(AsyncFormEdit))
+ {
continue;
+ }
await __bot.InvokeMessageLoop(s.Key);
}
-
-
}
}
-}
+}
\ No newline at end of file
diff --git a/Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs b/Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs
index 7703157..f89e22b 100644
--- a/Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs
+++ b/Examples/AsyncFormUpdates/Properties/AssemblyInfo.cs
@@ -32,4 +32,4 @@ using System.Runtime.InteropServices;
// indem Sie "*" wie unten gezeigt eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
\ No newline at end of file
diff --git a/Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs b/Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs
index c24b8c2..2ad3694 100644
--- a/Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs
+++ b/Examples/AsyncFormUpdates/forms/AsyncFormEdit.cs
@@ -46,8 +46,6 @@ namespace AsyncFormUpdates.forms
var m = await Device.Send($"Your current count is at: {_counter}", bf, disableNotification: true);
_messageId = m.MessageId;
}
-
}
-
}
-}
+}
\ No newline at end of file
diff --git a/Examples/AsyncFormUpdates/forms/AsyncFormUpdate.cs b/Examples/AsyncFormUpdates/forms/AsyncFormUpdate.cs
index 9e888a5..8a3b0b1 100644
--- a/Examples/AsyncFormUpdates/forms/AsyncFormUpdate.cs
+++ b/Examples/AsyncFormUpdates/forms/AsyncFormUpdate.cs
@@ -38,7 +38,5 @@ namespace AsyncFormUpdates.forms
await Device.Send($"Your current count is at: {_counter}", bf, disableNotification: true);
}
-
-
}
-}
+}
\ No newline at end of file
diff --git a/Examples/AsyncFormUpdates/forms/Start.cs b/Examples/AsyncFormUpdates/forms/Start.cs
index a8a726d..8713a04 100644
--- a/Examples/AsyncFormUpdates/forms/Start.cs
+++ b/Examples/AsyncFormUpdates/forms/Start.cs
@@ -6,8 +6,6 @@ namespace AsyncFormUpdates.forms
{
public class Start : AutoCleanForm
{
-
-
public override async Task Action(MessageResult message)
{
await message.ConfirmAction();
@@ -30,7 +28,6 @@ namespace AsyncFormUpdates.forms
break;
}
-
}
public override async Task Render(MessageResult message)
@@ -43,6 +40,5 @@ namespace AsyncFormUpdates.forms
await Device.Send("Choose your option", bf);
}
-
}
-}
+}
\ No newline at end of file
diff --git a/Examples/EFCoreBot/Database/BotDbContext.cs b/Examples/EFCoreBot/Database/BotDbContext.cs
index 18a3c4a..da7e42d 100644
--- a/Examples/EFCoreBot/Database/BotDbContext.cs
+++ b/Examples/EFCoreBot/Database/BotDbContext.cs
@@ -9,4 +9,4 @@ public class BotDbContext : DbContext
}
public DbSet Users { get; set; }
-}
+}
\ No newline at end of file
diff --git a/Examples/EFCoreBot/Database/User.cs b/Examples/EFCoreBot/Database/User.cs
index e106815..fbe1662 100644
--- a/Examples/EFCoreBot/Database/User.cs
+++ b/Examples/EFCoreBot/Database/User.cs
@@ -4,4 +4,4 @@ public class User
{
public long Id { get; set; }
public string LastMessage { get; set; }
-}
+}
\ No newline at end of file
diff --git a/Examples/EFCoreBot/EFCoreBot.csproj b/Examples/EFCoreBot/EFCoreBot.csproj
index 7421594..885fc87 100644
--- a/Examples/EFCoreBot/EFCoreBot.csproj
+++ b/Examples/EFCoreBot/EFCoreBot.csproj
@@ -8,12 +8,12 @@
-
-
+
+
-
+
diff --git a/Examples/EFCoreBot/Program.cs b/Examples/EFCoreBot/Program.cs
index fa427ee..3d983e1 100644
--- a/Examples/EFCoreBot/Program.cs
+++ b/Examples/EFCoreBot/Program.cs
@@ -10,14 +10,15 @@ var serviceCollection = new ServiceCollection()
var serviceProvider = serviceCollection.BuildServiceProvider();
var bot = BotBaseBuilder.Create()
- .WithAPIKey(Environment.GetEnvironmentVariable("API_KEY") ?? throw new Exception("API_KEY is not set"))
- .DefaultMessageLoop()
- .WithServiceProvider(serviceProvider)
- .NoProxy()
- .NoCommands()
- .NoSerialization()
- .DefaultLanguage()
- .Build();
+ .WithAPIKey(Environment.GetEnvironmentVariable("API_KEY") ??
+ throw new Exception("API_KEY is not set"))
+ .DefaultMessageLoop()
+ .WithServiceProvider(serviceProvider)
+ .NoProxy()
+ .NoCommands()
+ .NoSerialization()
+ .DefaultLanguage()
+ .Build();
bot.Start();
-await Task.Delay(-1);
+await Task.Delay(-1);
\ No newline at end of file
diff --git a/Examples/EFCoreBot/StartForm.cs b/Examples/EFCoreBot/StartForm.cs
index 1bfee77..7081c1a 100644
--- a/Examples/EFCoreBot/StartForm.cs
+++ b/Examples/EFCoreBot/StartForm.cs
@@ -33,4 +33,4 @@ public class StartForm : FormBase
user.LastMessage = string.IsNullOrWhiteSpace(message.MessageText) ? "" : message.MessageText;
await _dbContext.SaveChangesAsync();
}
-}
+}
\ No newline at end of file
diff --git a/Examples/JoinHiderBot/JoinHiderBot.csproj b/Examples/JoinHiderBot/JoinHiderBot.csproj
index aa8f8d7..76dddc9 100644
--- a/Examples/JoinHiderBot/JoinHiderBot.csproj
+++ b/Examples/JoinHiderBot/JoinHiderBot.csproj
@@ -1,12 +1,12 @@
-
- Exe
- net6.0
-
+
+ Exe
+ net6.0
+
-
-
-
+
+
+
diff --git a/Examples/JoinHiderBot/Program.cs b/Examples/JoinHiderBot/Program.cs
index 369b758..9c0bfff 100644
--- a/Examples/JoinHiderBot/Program.cs
+++ b/Examples/JoinHiderBot/Program.cs
@@ -2,22 +2,20 @@
using JoinHiderBot.forms;
using TelegramBotBase.Builder;
-namespace JoinHiderBot
+namespace JoinHiderBot;
+
+internal class Program
{
- internal class Program
+ private static void Main(string[] args)
{
- private static void Main(string[] args)
- {
+ var apiKey = "";
- var apiKey = "";
+ var bot = BotBaseBuilder.Create()
+ .QuickStart(apiKey)
+ .Build();
- var bot = BotBaseBuilder.Create()
- .QuickStart(apiKey)
- .Build();
+ bot.Start();
- bot.Start();
-
- Console.ReadLine();
- }
+ Console.ReadLine();
}
-}
+}
\ No newline at end of file
diff --git a/Examples/JoinHiderBot/forms/GroupManageForm.cs b/Examples/JoinHiderBot/forms/GroupManageForm.cs
index 61fdadc..6ccf246 100644
--- a/Examples/JoinHiderBot/forms/GroupManageForm.cs
+++ b/Examples/JoinHiderBot/forms/GroupManageForm.cs
@@ -3,21 +3,20 @@ using Telegram.Bot.Types.Enums;
using TelegramBotBase.Args;
using TelegramBotBase.Form;
-namespace JoinHiderBot.forms
+namespace JoinHiderBot.forms;
+
+public class GroupManageForm : GroupForm
{
- public class GroupManageForm : GroupForm
+ public override async Task OnMemberChanges(MemberChangeEventArgs e)
{
-
- public override async Task OnMemberChanges(MemberChangeEventArgs e)
+ if (e.Type != MessageType.ChatMembersAdded && e.Type != MessageType.ChatMemberLeft)
{
- if (e.Type != MessageType.ChatMembersAdded && e.Type != MessageType.ChatMemberLeft)
- return;
-
-
- var m = e.Result.Message;
-
- await Device.DeleteMessage(m);
+ return;
}
+
+ var m = e.Result.Message;
+
+ await Device.DeleteMessage(m);
}
-}
+}
\ No newline at end of file
diff --git a/Examples/JoinHiderBot/forms/Start.cs b/Examples/JoinHiderBot/forms/Start.cs
index f506451..0b868b6 100644
--- a/Examples/JoinHiderBot/forms/Start.cs
+++ b/Examples/JoinHiderBot/forms/Start.cs
@@ -2,25 +2,23 @@
using TelegramBotBase.Base;
using TelegramBotBase.Form;
-namespace JoinHiderBot.forms
+namespace JoinHiderBot.forms;
+
+public class Start : SplitterForm
{
- public class Start : SplitterForm
+ public override async Task Open(MessageResult e)
{
- public override async Task Open(MessageResult e)
- {
- await Device.Send("This bot works only in groups.");
-
- return true;
- }
-
- public override async Task OpenGroup(MessageResult e)
- {
- var gmf = new GroupManageForm();
-
- await NavigateTo(gmf);
-
- return true;
- }
+ await Device.Send("This bot works only in groups.");
+ return true;
}
-}
+
+ public override async Task OpenGroup(MessageResult e)
+ {
+ var gmf = new GroupManageForm();
+
+ await NavigateTo(gmf);
+
+ return true;
+ }
+}
\ No newline at end of file
diff --git a/Examples/SystemCommandsBot/Program.cs b/Examples/SystemCommandsBot/Program.cs
index d0131f9..b5330ac 100644
--- a/Examples/SystemCommandsBot/Program.cs
+++ b/Examples/SystemCommandsBot/Program.cs
@@ -3,39 +3,35 @@ using SystemCommandsBot.config;
using SystemCommandsBot.forms;
using TelegramBotBase.Builder;
-namespace SystemCommandsBot
+namespace SystemCommandsBot;
+
+internal class Program
{
- internal class Program
+ public static Config BotConfig { get; set; }
+
+
+ private static void Main(string[] args)
{
- public static Config BotConfig { get; set; }
+ BotConfig = Config.Load();
-
- private static void Main(string[] args)
+ if (BotConfig.ApiKey == null || BotConfig.ApiKey.Trim() == "")
{
-
- BotConfig = Config.Load();
-
- if (BotConfig.ApiKey == null || BotConfig.ApiKey.Trim() == "")
- {
- Console.WriteLine("Config created...");
- Console.ReadLine();
- return;
- }
-
- var bot = BotBaseBuilder.Create()
- .QuickStart(BotConfig.ApiKey)
- .Build();
-
- bot.Start();
-
- Console.WriteLine("Bot started");
-
+ Console.WriteLine("Config created...");
Console.ReadLine();
-
-
- bot.Stop();
-
-
+ return;
}
+
+ var bot = BotBaseBuilder.Create()
+ .QuickStart(BotConfig.ApiKey)
+ .Build();
+
+ bot.Start();
+
+ Console.WriteLine("Bot started");
+
+ Console.ReadLine();
+
+
+ bot.Stop();
}
-}
+}
\ No newline at end of file
diff --git a/Examples/SystemCommandsBot/SystemCommandsBot.csproj b/Examples/SystemCommandsBot/SystemCommandsBot.csproj
index 4e20f6a..95990e5 100644
--- a/Examples/SystemCommandsBot/SystemCommandsBot.csproj
+++ b/Examples/SystemCommandsBot/SystemCommandsBot.csproj
@@ -1,13 +1,13 @@
-
- Exe
- net6.0
-
+
+ Exe
+ net6.0
+
-
-
-
-
+
+
+
+
diff --git a/Examples/SystemCommandsBot/commands/Commando.cs b/Examples/SystemCommandsBot/commands/Commando.cs
index d93eb81..8eb56d1 100644
--- a/Examples/SystemCommandsBot/commands/Commando.cs
+++ b/Examples/SystemCommandsBot/commands/Commando.cs
@@ -1,25 +1,21 @@
-namespace SystemCommandsBot.commands
+namespace SystemCommandsBot.commands;
+
+public class Commando
{
- public class Commando
- {
- public int Id { get; set; }
+ public int Id { get; set; }
- public string Title { get; set; }
+ public string Title { get; set; }
- public string ShellCmd { get; set; }
+ public string ShellCmd { get; set; }
- public bool Enabled { get; set; } = true;
+ public bool Enabled { get; set; } = true;
- public string Action { get; set; }
+ public string Action { get; set; }
- public bool UseShell { get; set; } = true;
+ public bool UseShell { get; set; } = true;
- public int? MaxInstances { get; set; }
+ public int? MaxInstances { get; set; }
- public string ProcName
- {
- get;set;
- }
- }
-}
+ public string ProcName { get; set; }
+}
\ No newline at end of file
diff --git a/Examples/SystemCommandsBot/config/Config.cs b/Examples/SystemCommandsBot/config/Config.cs
index f63b8fc..3125790 100644
--- a/Examples/SystemCommandsBot/config/Config.cs
+++ b/Examples/SystemCommandsBot/config/Config.cs
@@ -4,90 +4,90 @@ using System.IO;
using Newtonsoft.Json;
using SystemCommandsBot.commands;
-namespace SystemCommandsBot.config
+namespace SystemCommandsBot.config;
+
+public class Config
{
- public class Config
+ public Config()
{
- public string Password { get; set; }
+ Commandos = new List();
+ }
- public string ApiKey { get; set; }
+ public string Password { get; set; }
- public List Commandos { get; set; }
+ public string ApiKey { get; set; }
+ public List Commandos { get; set; }
- public Config()
+ public void LoadDefaultValues()
+ {
+ ApiKey = "";
+ Commandos.Add(new Commando
{
- Commandos = new List();
+ Id = 0, Enabled = true, Title = "Test Befehl", ShellCmd = "explorer.exe", Action = "start", MaxInstances = 2
+ });
+ }
+
+
+ public static Config Load()
+ {
+ try
+ {
+ return Load(AppContext.BaseDirectory + "config\\default.cfg");
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine(ex.Message);
}
- public void LoadDefaultValues()
+ return null;
+ }
+
+
+ public static Config Load(string path)
+ {
+ try
{
- ApiKey = "";
- Commandos.Add(new Commando { Id = 0, Enabled = true, Title = "Test Befehl", ShellCmd = "explorer.exe", Action = "start", MaxInstances = 2 });
+ var cfg = JsonConvert.DeserializeObject(File.ReadAllText(path));
+ return cfg;
+ }
+ catch (DirectoryNotFoundException)
+ {
+ var di = new DirectoryInfo(path);
+
+ if (!Directory.Exists(di.Parent.FullName))
+ {
+ Directory.CreateDirectory(di.Parent.FullName);
+ }
+
+ var cfg = new Config();
+ cfg.LoadDefaultValues();
+ cfg.Save(path);
+ return cfg;
+ }
+ catch (FileNotFoundException)
+ {
+ var cfg = new Config();
+ cfg.LoadDefaultValues();
+ cfg.Save(path);
+ return cfg;
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine(ex.Message);
}
+ return null;
+ }
- public static Config Load()
+ public void Save(string path)
+ {
+ try
{
- try
- {
- return Load(AppContext.BaseDirectory + "config\\default.cfg");
-
-
- }
- catch(Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- return null;
+ File.WriteAllText(path, JsonConvert.SerializeObject(this));
}
-
-
- public static Config Load(string path)
+ catch
{
- try
- {
- var cfg = JsonConvert.DeserializeObject(File.ReadAllText(path));
- return cfg;
- }
- catch (DirectoryNotFoundException)
- {
- var di = new DirectoryInfo(path);
-
- if (!Directory.Exists(di.Parent.FullName))
- {
- Directory.CreateDirectory(di.Parent.FullName);
- }
-
- var cfg = new Config();
- cfg.LoadDefaultValues();
- cfg.Save(path);
- return cfg;
- }
- catch (FileNotFoundException)
- {
- var cfg = new Config();
- cfg.LoadDefaultValues();
- cfg.Save(path);
- return cfg;
- }
- catch(Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- return null;
- }
-
- public void Save(string path)
- {
- try
- {
- File.WriteAllText(path, JsonConvert.SerializeObject(this));
- }
- catch
- {
-
- }
}
}
-}
+}
\ No newline at end of file
diff --git a/Examples/SystemCommandsBot/forms/CmdForm.cs b/Examples/SystemCommandsBot/forms/CmdForm.cs
index d42e713..a5660fe 100644
--- a/Examples/SystemCommandsBot/forms/CmdForm.cs
+++ b/Examples/SystemCommandsBot/forms/CmdForm.cs
@@ -6,167 +6,151 @@ using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
-namespace SystemCommandsBot.forms
+namespace SystemCommandsBot.forms;
+
+public class CmdForm : AutoCleanForm
{
- public class CmdForm : AutoCleanForm
+ public DateTime ExpiresAt { get; set; }
+
+ public int? MessageId { get; set; }
+
+ public override Task Load(MessageResult message)
{
- public DateTime ExpiresAt { get; set; }
-
- public int? MessageId { get; set; }
-
- public override Task Load(MessageResult message)
- {
- return Task.CompletedTask;
- }
-
- public override async Task Action(MessageResult message)
- {
- var btn = message.RawData;
-
- var id = -1;
-
- if (!int.TryParse(btn, out id))
- {
-
- return;
- }
-
- var cmd = Program.BotConfig.Commandos.Where(a => a.Enabled && a.Id == id).FirstOrDefault();
- if (cmd == null)
- {
- await Device.Send("Cmd nicht verfügbar.");
- return;
- }
-
- message.Handled = true;
-
- switch (cmd.Action)
- {
- case "start":
-
- var fi = new FileInfo(cmd.ShellCmd);
-
- if (cmd.MaxInstances != null && cmd.MaxInstances >= 0)
- {
-
- if (Process.GetProcessesByName(cmd.ProcName).Count() >= cmd.MaxInstances)
- {
- await Device.Send("Anwendung läuft bereits.");
- await message.ConfirmAction("Anwendung läuft bereits.");
-
- return;
- }
-
- }
-
- var psi = new ProcessStartInfo
- {
- FileName = cmd.ShellCmd,
- WorkingDirectory = fi.DirectoryName,
- UseShellExecute = cmd.UseShell
- };
-
- Process.Start(psi);
-
- await Device.Send(fi.Name + " wurde gestarted.");
-
- await message.ConfirmAction(fi.Name + " wurde gestarted.");
-
- break;
-
- case "kill":
-
- var fi2 = new FileInfo(cmd.ShellCmd);
-
- var pros = fi2.Name.Replace(fi2.Extension, "");
-
- var proc = Process.GetProcessesByName(pros).ToList();
-
- foreach (var p in proc)
- {
- try
- {
- p.Kill();
- }
- catch
- {
-
- }
- }
-
- await Device.Send(fi2.Name + " wurde beendet.");
-
- await message.ConfirmAction(fi2.Name + " wurde beendet.");
-
- break;
-
- case "restart":
-
- var fi3 = new FileInfo(cmd.ShellCmd);
-
- var pros2 = fi3.Name.Replace(fi3.Extension, "");
-
- var proc2 = Process.GetProcessesByName(pros2).ToList();
-
- foreach (var p in proc2)
- {
- try
- {
- p.Kill();
- }
- catch
- {
-
- }
- }
-
- var fi4 = new FileInfo(cmd.ShellCmd);
-
- var psi2 = new ProcessStartInfo
- {
- FileName = cmd.ShellCmd,
- WorkingDirectory = fi4.DirectoryName
- };
- psi2.FileName = cmd.ShellCmd;
- psi2.UseShellExecute = cmd.UseShell;
-
- Process.Start(psi2);
-
- await Device.Send(fi3.Name + " wurde neugestarted.");
- await message.ConfirmAction(fi3.Name + " wurde neugestarted.");
-
-
- break;
-
- default:
-
- await message.ConfirmAction();
-
- break;
-
- }
-
-
-
-
- }
-
- public override async Task Render(MessageResult message)
- {
- if (MessageId == null)
- {
- var buttons = Program.BotConfig.Commandos.Where(a => a.Enabled).Select(a => new ButtonBase(a.Title, a.Id.ToString()));
-
- var bf = new ButtonForm();
- bf.AddSplitted(buttons, 1);
- await Device.Send("Deine Optionen", bf);
- }
-
-
- }
-
-
-
-
+ return Task.CompletedTask;
}
-}
+
+ public override async Task Action(MessageResult message)
+ {
+ var btn = message.RawData;
+
+ var id = -1;
+
+ if (!int.TryParse(btn, out id))
+ {
+ return;
+ }
+
+ var cmd = Program.BotConfig.Commandos.Where(a => a.Enabled && a.Id == id).FirstOrDefault();
+ if (cmd == null)
+ {
+ await Device.Send("Cmd nicht verfügbar.");
+ return;
+ }
+
+ message.Handled = true;
+
+ switch (cmd.Action)
+ {
+ case "start":
+
+ var fi = new FileInfo(cmd.ShellCmd);
+
+ if (cmd.MaxInstances != null && cmd.MaxInstances >= 0)
+ {
+ if (Process.GetProcessesByName(cmd.ProcName).Count() >= cmd.MaxInstances)
+ {
+ await Device.Send("Anwendung läuft bereits.");
+ await message.ConfirmAction("Anwendung läuft bereits.");
+
+ return;
+ }
+ }
+
+ var psi = new ProcessStartInfo
+ {
+ FileName = cmd.ShellCmd,
+ WorkingDirectory = fi.DirectoryName,
+ UseShellExecute = cmd.UseShell
+ };
+
+ Process.Start(psi);
+
+ await Device.Send(fi.Name + " wurde gestarted.");
+
+ await message.ConfirmAction(fi.Name + " wurde gestarted.");
+
+ break;
+
+ case "kill":
+
+ var fi2 = new FileInfo(cmd.ShellCmd);
+
+ var pros = fi2.Name.Replace(fi2.Extension, "");
+
+ var proc = Process.GetProcessesByName(pros).ToList();
+
+ foreach (var p in proc)
+ {
+ try
+ {
+ p.Kill();
+ }
+ catch
+ {
+ }
+ }
+
+ await Device.Send(fi2.Name + " wurde beendet.");
+
+ await message.ConfirmAction(fi2.Name + " wurde beendet.");
+
+ break;
+
+ case "restart":
+
+ var fi3 = new FileInfo(cmd.ShellCmd);
+
+ var pros2 = fi3.Name.Replace(fi3.Extension, "");
+
+ var proc2 = Process.GetProcessesByName(pros2).ToList();
+
+ foreach (var p in proc2)
+ {
+ try
+ {
+ p.Kill();
+ }
+ catch
+ {
+ }
+ }
+
+ var fi4 = new FileInfo(cmd.ShellCmd);
+
+ var psi2 = new ProcessStartInfo
+ {
+ FileName = cmd.ShellCmd,
+ WorkingDirectory = fi4.DirectoryName
+ };
+ psi2.FileName = cmd.ShellCmd;
+ psi2.UseShellExecute = cmd.UseShell;
+
+ Process.Start(psi2);
+
+ await Device.Send(fi3.Name + " wurde neugestarted.");
+ await message.ConfirmAction(fi3.Name + " wurde neugestarted.");
+
+
+ break;
+
+ default:
+
+ await message.ConfirmAction();
+
+ break;
+ }
+ }
+
+ public override async Task Render(MessageResult message)
+ {
+ if (MessageId == null)
+ {
+ var buttons = Program.BotConfig.Commandos.Where(a => a.Enabled)
+ .Select(a => new ButtonBase(a.Title, a.Id.ToString()));
+
+ var bf = new ButtonForm();
+ bf.AddSplitted(buttons, 1);
+ await Device.Send("Deine Optionen", bf);
+ }
+ }
+}
\ No newline at end of file
diff --git a/Examples/SystemCommandsBot/forms/StartForm.cs b/Examples/SystemCommandsBot/forms/StartForm.cs
index ede4203..7b34f4d 100644
--- a/Examples/SystemCommandsBot/forms/StartForm.cs
+++ b/Examples/SystemCommandsBot/forms/StartForm.cs
@@ -3,39 +3,36 @@ using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
-namespace SystemCommandsBot.forms
+namespace SystemCommandsBot.forms;
+
+public class StartForm : FormBase
{
- public class StartForm : FormBase
+ public string Password { get; set; }
+
+ public override Task Load(MessageResult message)
{
- public string Password { get; set; }
-
- public override Task Load(MessageResult message)
+ var inp = message.MessageText;
+ if (Program.BotConfig.Password == inp)
{
- var inp = message.MessageText;
- if (Program.BotConfig.Password == inp)
- {
- Password = inp;
- }
-
- return Task.CompletedTask;
- }
-
-
- public override async Task Render(MessageResult message)
- {
- if (Password == null || Password.Trim() == "")
- {
- await Device.Send("Bitte gib dein Passwort an.");
- return;
- }
-
-
- var cmd = new CmdForm();
- cmd.ExpiresAt = DateTime.Now.AddDays(14);
-
- await NavigateTo(cmd);
-
+ Password = inp;
}
+ return Task.CompletedTask;
}
-}
+
+
+ public override async Task Render(MessageResult message)
+ {
+ if (Password == null || Password.Trim() == "")
+ {
+ await Device.Send("Bitte gib dein Passwort an.");
+ return;
+ }
+
+
+ var cmd = new CmdForm();
+ cmd.ExpiresAt = DateTime.Now.AddDays(14);
+
+ await NavigateTo(cmd);
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Extensions.Images/ImageExtensions.cs b/TelegramBotBase.Extensions.Images/ImageExtensions.cs
index 314679c..7ed5dc0 100644
--- a/TelegramBotBase.Extensions.Images/ImageExtensions.cs
+++ b/TelegramBotBase.Extensions.Images/ImageExtensions.cs
@@ -20,7 +20,7 @@ namespace TelegramBotBase.Extensions.Images
}
///
- /// Sends an image
+ /// Sends an image
///
///
///
@@ -28,18 +28,20 @@ namespace TelegramBotBase.Extensions.Images
///
///
///
- public static async Task SendPhoto(this DeviceSession session, Image image, string name, string caption, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false)
+ public static async Task SendPhoto(this DeviceSession session, Image image, string name,
+ string caption, ButtonForm buttons = null, int replyTo = 0,
+ bool disableNotification = false)
{
using (var fileStream = ToStream(image, ImageFormat.Png))
{
var fts = new InputOnlineFile(fileStream, name);
- return await session.SendPhoto(fts, caption: caption, buttons, replyTo, disableNotification);
+ return await session.SendPhoto(fts, caption, buttons, replyTo, disableNotification);
}
}
///
- /// Sends an image
+ /// Sends an image
///
///
///
@@ -47,14 +49,16 @@ namespace TelegramBotBase.Extensions.Images
///
///
///
- public static async Task SendPhoto(this DeviceSession session, Bitmap image, string name, string caption, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false)
+ public static async Task SendPhoto(this DeviceSession session, Bitmap image, string name,
+ string caption, ButtonForm buttons = null, int replyTo = 0,
+ bool disableNotification = false)
{
using (var fileStream = ToStream(image, ImageFormat.Png))
{
var fts = new InputOnlineFile(fileStream, name);
- return await session.SendPhoto(fts, caption: caption, buttons, replyTo, disableNotification);
+ return await session.SendPhoto(fts, caption, buttons, replyTo, disableNotification);
}
}
}
-}
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Extensions.Images/README.md b/TelegramBotBase.Extensions.Images/README.md
index 2611a85..072c797 100644
--- a/TelegramBotBase.Extensions.Images/README.md
+++ b/TelegramBotBase.Extensions.Images/README.md
@@ -3,6 +3,5 @@
[](https://www.nuget.org/packages/TelegramBotBase.Extensions.Images/)
[](https://www.t.me/tgbotbase)
-
[](https://raw.githubusercontent.com/MajMcCloud/TelegramBotFramework/master/LICENCE.md)
[](https://www.nuget.org/packages/TelegramBotBase.Extensions.Images)
diff --git a/TelegramBotBase.Extensions.Images/TelegramBotBase.Extensions.Images.csproj b/TelegramBotBase.Extensions.Images/TelegramBotBase.Extensions.Images.csproj
index 0b84053..942981b 100644
--- a/TelegramBotBase.Extensions.Images/TelegramBotBase.Extensions.Images.csproj
+++ b/TelegramBotBase.Extensions.Images/TelegramBotBase.Extensions.Images.csproj
@@ -1,24 +1,24 @@
-
- netstandard2.0;net5;netcoreapp3.1;net6
- https://github.com/MajMcCloud/TelegramBotFramework
- https://github.com/MajMcCloud/TelegramBotFramework
- MIT
- true
- snupkg
-
+
+ netstandard2.0;net5;netcoreapp3.1;net6
+ https://github.com/MajMcCloud/TelegramBotFramework
+ https://github.com/MajMcCloud/TelegramBotFramework
+ MIT
+ true
+ snupkg
+
-
-
- all
- runtime; build; native; contentfiles; analyzers; buildtransitive
-
-
-
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
+
-
-
-
+
+
+
diff --git a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/BotBaseBuilderExtensions.cs b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/BotBaseBuilderExtensions.cs
index 06e1611..028cc02 100644
--- a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/BotBaseBuilderExtensions.cs
+++ b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/BotBaseBuilderExtensions.cs
@@ -6,16 +6,17 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
{
public static class BotBaseBuilderExtensions
{
-
///
- /// Uses an Microsoft SQL Server Database to save and restore sessions.
+ /// Uses an Microsoft SQL Server Database to save and restore sessions.
///
///
///
///
///
///
- public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string connectionString, Type fallbackForm = null, string tablePrefix = "tgb_")
+ public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder,
+ string connectionString, Type fallbackForm = null,
+ string tablePrefix = "tgb_")
{
var serializer = new MssqlSerializer(connectionString, tablePrefix, fallbackForm);
@@ -26,7 +27,7 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
///
- /// Uses an Microsoft SQL Server Database to save and restore sessions.
+ /// Uses an Microsoft SQL Server Database to save and restore sessions.
///
///
///
@@ -36,9 +37,12 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
///
///
///
- public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string hostOrIP, string databaseName, string userId, string password, Type fallbackForm = null, string tablePrefix = "tgb_")
+ public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string hostOrIP,
+ string databaseName, string userId, string password,
+ Type fallbackForm = null, string tablePrefix = "tgb_")
{
- var connectionString = $"Server={hostOrIP}; Database={databaseName}; User Id={userId}; Password={password}; TrustServerCertificate=true;";
+ var connectionString =
+ $"Server={hostOrIP}; Database={databaseName}; User Id={userId}; Password={password}; TrustServerCertificate=true;";
var serializer = new MssqlSerializer(connectionString, tablePrefix, fallbackForm);
@@ -48,7 +52,7 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
}
///
- /// Uses an Microsoft SQL Server Database with Windows Authentication to save and restore sessions.
+ /// Uses an Microsoft SQL Server Database with Windows Authentication to save and restore sessions.
///
///
///
@@ -56,12 +60,17 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
///
///
///
- public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string hostOrIP, string databaseName, bool integratedSecurity = true, Type fallbackForm = null, string tablePrefix = "tgb_")
+ public static ILanguageSelectionStage UseSqlDatabase(this ISessionSerializationStage builder, string hostOrIP,
+ string databaseName, bool integratedSecurity = true,
+ Type fallbackForm = null, string tablePrefix = "tgb_")
{
if (!integratedSecurity)
+ {
throw new ArgumentOutOfRangeException();
+ }
- var connectionString = $"Server={hostOrIP}; Database={databaseName}; Integrated Security=true; TrustServerCertificate=true;";
+ var connectionString =
+ $"Server={hostOrIP}; Database={databaseName}; Integrated Security=true; TrustServerCertificate=true;";
var serializer = new MssqlSerializer(connectionString, tablePrefix, fallbackForm);
@@ -70,4 +79,4 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
return builder as BotBaseBuilder;
}
}
-}
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/MSSQLSerializer.cs b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/MSSQLSerializer.cs
index fe271e0..ed08d95 100644
--- a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/MSSQLSerializer.cs
+++ b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/MSSQLSerializer.cs
@@ -11,19 +11,19 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
{
public class MssqlSerializer : IStateMachine
{
- public Type FallbackStateForm { get; set; }
- public string ConnectionString { get; }
- public string TablePrefix { get; set; }
-
///
- /// Will initialize the state machine.
+ /// Will initialize the state machine.
///
/// Path of the file and name where to save the session details.
- /// Type of Form which will be saved instead of Form which has attribute declared. Needs to be subclass of .
+ ///
+ /// Type of Form which will be saved instead of Form which has
+ /// attribute declared. Needs to be subclass of
+ /// .
+ ///
/// Declares of the file could be overwritten.
public MssqlSerializer(string connectionString, string tablePrefix = "tgb_", Type fallbackStateForm = null)
{
- this.ConnectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString));
+ ConnectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString));
TablePrefix = tablePrefix;
@@ -35,6 +35,10 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
}
}
+ public string ConnectionString { get; }
+ public string TablePrefix { get; set; }
+ public Type FallbackStateForm { get; set; }
+
public StateContainer LoadFormStates()
{
var sc = new StateContainer();
@@ -44,7 +48,8 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
connection.Open();
var command = connection.CreateCommand();
- command.CommandText = "SELECT deviceId, deviceTitle, FormUri, QualifiedName FROM " + TablePrefix + "devices_sessions";
+ command.CommandText = "SELECT deviceId, deviceTitle, FormUri, QualifiedName FROM " + TablePrefix +
+ "devices_sessions";
var dataTable = new DataTable();
using (var dataAdapter = new SqlDataAdapter(command))
@@ -73,7 +78,8 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
}
var command2 = connection.CreateCommand();
- command2.CommandText = "SELECT [key], value, type FROM " + TablePrefix + "devices_sessions_data WHERE deviceId = @deviceId";
+ command2.CommandText = "SELECT [key], value, type FROM " + TablePrefix +
+ "devices_sessions_data WHERE deviceId = @deviceId";
command2.Parameters.Add(new SqlParameter("@deviceId", r["deviceId"]));
var dataTable2 = new DataTable();
@@ -91,13 +97,10 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
se.Values.Add(key, value);
}
}
-
}
-
}
-
connection.Close();
}
@@ -127,13 +130,15 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
var sessionCommand = connection.CreateCommand();
var dataCommand = connection.CreateCommand();
- sessionCommand.CommandText = "INSERT INTO " + TablePrefix + "devices_sessions (deviceId, deviceTitle, FormUri, QualifiedName) VALUES (@deviceId, @deviceTitle, @FormUri, @QualifiedName)";
+ sessionCommand.CommandText = "INSERT INTO " + TablePrefix +
+ "devices_sessions (deviceId, deviceTitle, FormUri, QualifiedName) VALUES (@deviceId, @deviceTitle, @FormUri, @QualifiedName)";
sessionCommand.Parameters.Add(new SqlParameter("@deviceId", ""));
sessionCommand.Parameters.Add(new SqlParameter("@deviceTitle", ""));
sessionCommand.Parameters.Add(new SqlParameter("@FormUri", ""));
sessionCommand.Parameters.Add(new SqlParameter("@QualifiedName", ""));
- dataCommand.CommandText = "INSERT INTO " + TablePrefix + "devices_sessions_data (deviceId, [key], value, type) VALUES (@deviceId, @key, @value, @type)";
+ dataCommand.CommandText = "INSERT INTO " + TablePrefix +
+ "devices_sessions_data (deviceId, [key], value, type) VALUES (@deviceId, @key, @value, @type)";
dataCommand.Parameters.Add(new SqlParameter("@deviceId", ""));
dataCommand.Parameters.Add(new SqlParameter("@key", ""));
dataCommand.Parameters.Add(new SqlParameter("@value", ""));
@@ -169,13 +174,10 @@ namespace TelegramBotBase.Extensions.Serializer.Database.MSSQL
dataCommand.ExecuteNonQuery();
}
-
}
connection.Close();
}
-
-
}
}
-}
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/README.md b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/README.md
index 1a7f027..1255d6e 100644
--- a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/README.md
+++ b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/README.md
@@ -3,7 +3,6 @@
[](https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Database.MSSQL/)
[](https://www.t.me/tgbotbase)
-
[](https://raw.githubusercontent.com/MajMcCloud/TelegramBotFramework/master/LICENCE.md)
[](https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Database.MSSQL)
diff --git a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/TelegramBotBase.Extensions.Serializer.Database.MSSQL.csproj b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/TelegramBotBase.Extensions.Serializer.Database.MSSQL.csproj
index a0d40f7..4782e67 100644
--- a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/TelegramBotBase.Extensions.Serializer.Database.MSSQL.csproj
+++ b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/TelegramBotBase.Extensions.Serializer.Database.MSSQL.csproj
@@ -1,30 +1,30 @@
-
- netstandard2.0;net5;netcoreapp3.1;net6
- True
- https://github.com/MajMcCloud/TelegramBotFramework
- https://github.com/MajMcCloud/TelegramBotFramework
- MIT
- true
- snupkg
- 1.0.1
- 1.0.1
- 1.0.1
- A session serializer for Microsoft SQL Server.
-
-
+
+ netstandard2.0;net5;netcoreapp3.1;net6
+ True
+ https://github.com/MajMcCloud/TelegramBotFramework
+ https://github.com/MajMcCloud/TelegramBotFramework
+ MIT
+ true
+ snupkg
+ 1.0.1
+ 1.0.1
+ 1.0.1
+ A session serializer for Microsoft SQL Server.
+
+
-
-
-
- all
- runtime; build; native; contentfiles; analyzers; buildtransitive
-
-
+
+
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
+
-
-
-
+
+
+
diff --git a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/create_tables.sql b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/create_tables.sql
index 587eb4f..8d895f8 100644
--- a/TelegramBotBase.Extensions.Serializer.Database.MSSQL/create_tables.sql
+++ b/TelegramBotBase.Extensions.Serializer.Database.MSSQL/create_tables.sql
@@ -1,37 +1,81 @@
-USE [telegram_bot]
+USE
+[telegram_bot]
GO
/****** Object: Table [dbo].[tgb_devices_sessions] Script Date: 30.06.2022 16:22:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-CREATE TABLE [dbo].[tgb_devices_sessions](
- [deviceId] [bigint] NOT NULL,
- [deviceTitle] [nvarchar](512) NOT NULL,
- [FormUri] [nvarchar](512) NOT NULL,
- [QualifiedName] [nvarchar](512) NOT NULL,
- CONSTRAINT [PK_tgb_devices_sessions_1] PRIMARY KEY CLUSTERED
+CREATE TABLE [dbo].[tgb_devices_sessions]
(
- [deviceId] ASC
-)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
-) ON [PRIMARY]
-GO
+ [
+ deviceId] [
+ bigint]
+ NOT
+ NULL, [
+ deviceTitle] [
+ nvarchar]
+(
+ 512
+) NOT NULL,
+ [FormUri] [nvarchar]
+(
+ 512
+) NOT NULL,
+ [QualifiedName] [nvarchar]
+(
+ 512
+) NOT NULL,
+ CONSTRAINT [PK_tgb_devices_sessions_1] PRIMARY KEY CLUSTERED
+(
+[
+ deviceId] ASC
+)
+ WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF)
+ ON [PRIMARY]
+ )
+ ON [PRIMARY]
+ GO
/****** Object: Table [dbo].[tgb_devices_sessions_data] Script Date: 30.06.2022 16:22:09 ******/
-SET ANSI_NULLS ON
-GO
-SET QUOTED_IDENTIFIER ON
-GO
-CREATE TABLE [dbo].[tgb_devices_sessions_data](
- [Id] [uniqueidentifier] NOT NULL,
- [deviceId] [bigint] NOT NULL,
- [key] [nvarchar](512) NOT NULL,
- [value] [nvarchar](max) NOT NULL,
- [type] [nvarchar](512) NOT NULL,
- CONSTRAINT [PK_tgb_devices_session_data] PRIMARY KEY CLUSTERED
+ SET ANSI_NULLS
+ ON
+ GO
+ SET QUOTED_IDENTIFIER
+ ON
+ GO
+CREATE TABLE [dbo].[tgb_devices_sessions_data]
(
- [Id] ASC
-)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
-) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
-GO
-ALTER TABLE [dbo].[tgb_devices_sessions_data] ADD CONSTRAINT [DF_tgb_devices_session_data_Id] DEFAULT (newid()) FOR [Id]
-GO
+ [
+ Id] [
+ uniqueidentifier]
+ NOT
+ NULL, [
+ deviceId] [
+ bigint]
+ NOT
+ NULL, [
+ key] [
+ nvarchar]
+(
+ 512
+) NOT NULL,
+ [value] [nvarchar]
+(
+ max
+) NOT NULL,
+ [type] [nvarchar]
+(
+ 512
+) NOT NULL,
+ CONSTRAINT [PK_tgb_devices_session_data] PRIMARY KEY CLUSTERED
+(
+[
+ Id] ASC
+)
+ WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF)
+ ON [PRIMARY]
+ )
+ ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
+ GO
+ALTER TABLE [dbo].[tgb_devices_sessions_data] ADD CONSTRAINT [DF_tgb_devices_session_data_Id] DEFAULT (newid()) FOR [Id]
+ GO
diff --git a/TelegramBotBase.Test/App.config b/TelegramBotBase.Test/App.config
index fa1ddef..94f3e49 100644
--- a/TelegramBotBase.Test/App.config
+++ b/TelegramBotBase.Test/App.config
@@ -1,14 +1,14 @@
-
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
diff --git a/TelegramBotBase.Test/Program.cs b/TelegramBotBase.Test/Program.cs
index a1d4b31..044dba2 100644
--- a/TelegramBotBase.Test/Program.cs
+++ b/TelegramBotBase.Test/Program.cs
@@ -7,109 +7,106 @@ using TelegramBotBase.Commands;
using TelegramBotBase.Enums;
using TelegramBotBaseTest.Tests;
-namespace TelegramBotBaseTest
+namespace TelegramBotBaseTest;
+
+internal class Program
{
- internal class Program
+ private static void Main(string[] args)
{
- private static void Main(string[] args)
+ var apiKey = "";
+
+ var bb = BotBaseBuilder
+ .Create()
+ .WithAPIKey(apiKey)
+ .DefaultMessageLoop()
+ .WithStartForm()
+ .NoProxy()
+ .CustomCommands(a =>
+ {
+ a.Start("Starts the bot");
+ a.Add("myid", "Returns my Device ID");
+ a.Help("Should show you some help");
+ a.Settings("Should show you some settings");
+ a.Add("form1", "Opens test form 1");
+ a.Add("form2", "Opens test form 2");
+ a.Add("params", "Returns all send parameters as a message.");
+ })
+ .NoSerialization()
+ .UseEnglish()
+ .Build();
+
+
+ bb.BotCommand += Bb_BotCommand;
+
+ //Update Bot commands to botfather
+ bb.UploadBotCommands().Wait();
+
+ bb.SetSetting(ESettings.LogAllMessages, true);
+
+ bb.Message += (s, en) =>
{
+ Console.WriteLine(en.DeviceId + " " + en.Message.MessageText + " " + (en.Message.RawData ?? ""));
+ };
- var apiKey = "";
+ bb.Start();
- var bb = BotBaseBuilder
- .Create()
- .WithAPIKey(apiKey)
- .DefaultMessageLoop()
- .WithStartForm()
- .NoProxy()
- .CustomCommands(a =>
- {
- a.Start("Starts the bot");
- a.Add("myid", "Returns my Device ID");
- a.Help("Should show you some help");
- a.Settings("Should show you some settings");
- a.Add("form1", "Opens test form 1");
- a.Add("form2", "Opens test form 2");
- a.Add("params", "Returns all send parameters as a message.");
- })
- .NoSerialization()
- .UseEnglish()
- .Build();
+ Console.WriteLine("Telegram Bot started...");
+
+ Console.WriteLine("Press q to quit application.");
- bb.BotCommand += Bb_BotCommand;
+ Console.ReadLine();
- //Update Bot commands to botfather
- bb.UploadBotCommands().Wait();
+ bb.Stop();
+ }
- bb.SetSetting(ESettings.LogAllMessages, true);
-
- bb.Message += (s, en) =>
- {
- Console.WriteLine(en.DeviceId + " " + en.Message.MessageText + " " + (en.Message.RawData ?? ""));
- };
-
- bb.Start();
-
- Console.WriteLine("Telegram Bot started...");
-
- Console.WriteLine("Press q to quit application.");
-
-
- Console.ReadLine();
-
- bb.Stop();
-
- }
-
- private static async Task Bb_BotCommand(object sender, BotCommandEventArgs en)
+ private static async Task Bb_BotCommand(object sender, BotCommandEventArgs en)
+ {
+ switch (en.Command)
{
- switch (en.Command)
- {
- case "/start":
+ case "/start":
- var start = new Menu();
+ var start = new Menu();
- await en.Device.ActiveForm.NavigateTo(start);
+ await en.Device.ActiveForm.NavigateTo(start);
- break;
- case "/form1":
+ break;
+ case "/form1":
- var form1 = new TestForm();
+ var form1 = new TestForm();
- await en.Device.ActiveForm.NavigateTo(form1);
+ await en.Device.ActiveForm.NavigateTo(form1);
- break;
+ break;
- case "/form2":
+ case "/form2":
- var form2 = new TestForm2();
+ var form2 = new TestForm2();
- await en.Device.ActiveForm.NavigateTo(form2);
+ await en.Device.ActiveForm.NavigateTo(form2);
- break;
+ break;
- case "/myid":
+ case "/myid":
- await en.Device.Send($"Your Device ID is: {en.DeviceId}");
+ await en.Device.Send($"Your Device ID is: {en.DeviceId}");
- en.Handled = true;
+ en.Handled = true;
- break;
+ break;
- case "/params":
+ case "/params":
- var m = en.Parameters.DefaultIfEmpty("").Aggregate((a, b) => a + " and " + b);
+ var m = en.Parameters.DefaultIfEmpty("").Aggregate((a, b) => a + " and " + b);
- await en.Device.Send("Your parameters are: " + m, replyTo: en.Device.LastMessageId);
+ await en.Device.Send("Your parameters are: " + m, replyTo: en.Device.LastMessageId);
- en.Handled = true;
+ en.Handled = true;
- break;
- }
+ break;
}
}
}
diff --git a/TelegramBotBase.Test/Properties/AssemblyInfo.cs b/TelegramBotBase.Test/Properties/AssemblyInfo.cs
index 53a2683..af85f77 100644
--- a/TelegramBotBase.Test/Properties/AssemblyInfo.cs
+++ b/TelegramBotBase.Test/Properties/AssemblyInfo.cs
@@ -32,4 +32,4 @@ using System.Runtime.InteropServices;
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
\ No newline at end of file
diff --git a/TelegramBotBase.Test/TelegramBotBaseTest.csproj b/TelegramBotBase.Test/TelegramBotBaseTest.csproj
index a1abbf6..c40ee57 100644
--- a/TelegramBotBase.Test/TelegramBotBaseTest.csproj
+++ b/TelegramBotBase.Test/TelegramBotBaseTest.csproj
@@ -1,34 +1,35 @@
-
- Exe
- netcoreapp3.1;net5;net6
- false
- Debug;Release
-
-
- AnyCPU
- true
- full
- false
- bin\Debug\
- DEBUG;TRACE
- prompt
- 4
-
-
- AnyCPU
- pdbonly
- true
- bin\Release\
- TRACE
- prompt
- 4
-
+
+ Exe
+ netcoreapp3.1;net5;net6
+ 10
+ false
+ Debug;Release
+
+
+ AnyCPU
+ true
+ full
+ false
+ bin\Debug\
+ DEBUG;TRACE
+ prompt
+ 4
+
+
+ AnyCPU
+ pdbonly
+ true
+ bin\Release\
+ TRACE
+ prompt
+ 4
+
-
-
-
-
+
+
+
+
diff --git a/TelegramBotBase.Test/Tests/ButtonTestForm.cs b/TelegramBotBase.Test/Tests/ButtonTestForm.cs
index 8f89af6..f19b7d0 100644
--- a/TelegramBotBase.Test/Tests/ButtonTestForm.cs
+++ b/TelegramBotBase.Test/Tests/ButtonTestForm.cs
@@ -3,97 +3,92 @@ using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests
+namespace TelegramBotBaseTest.Tests;
+
+public class ButtonTestForm : AutoCleanForm
{
- public class ButtonTestForm : AutoCleanForm
+ public ButtonTestForm()
{
+ Opened += ButtonTestForm_Opened;
+ }
- public ButtonTestForm()
+ private async Task ButtonTestForm_Opened(object sender, EventArgs e)
+ {
+ await Device.Send("Hello world! (Click 'back' to get back to Start)");
+ }
+
+ public override async Task Action(MessageResult message)
+ {
+ var call = message.GetData();
+
+ await message.ConfirmAction();
+
+
+ if (call == null)
{
- Opened += ButtonTestForm_Opened;
+ return;
}
- private async Task ButtonTestForm_Opened(object sender, EventArgs e)
+ message.Handled = true;
+
+ switch (call.Value)
{
- await Device.Send("Hello world! (Click 'back' to get back to Start)");
- }
+ case "button1":
- public override async Task Action(MessageResult message)
- {
+ await Device.Send("Button 1 pressed");
- var call = message.GetData();
+ break;
- await message.ConfirmAction();
+ case "button2":
+ await Device.Send("Button 2 pressed");
- if (call == null)
- return;
+ break;
- message.Handled = true;
+ case "button3":
- switch (call.Value)
- {
- case "button1":
+ await Device.Send("Button 3 pressed");
- await Device.Send("Button 1 pressed");
+ break;
- break;
+ case "button4":
- case "button2":
+ await Device.Send("Button 4 pressed");
- await Device.Send("Button 2 pressed");
+ break;
- break;
+ case "back":
- case "button3":
+ var st = new Menu();
- await Device.Send("Button 3 pressed");
+ await NavigateTo(st);
- break;
+ break;
- case "button4":
-
- await Device.Send("Button 4 pressed");
-
- break;
-
- case "back":
-
- var st = new Menu();
-
- await NavigateTo(st);
-
- break;
-
- default:
-
- message.Handled = false;
-
- break;
- }
-
-
- }
-
-
- public override async Task Render(MessageResult message)
- {
-
- var btn = new ButtonForm();
-
- btn.AddButtonRow(new ButtonBase("Button 1", new CallbackData("a", "button1").Serialize()), new ButtonBase("Button 2", new CallbackData("a", "button2").Serialize()));
-
- btn.AddButtonRow(new ButtonBase("Button 3", new CallbackData("a", "button3").Serialize()), new ButtonBase("Button 4", new CallbackData("a", "button4").Serialize()));
-
- btn.AddButtonRow(new ButtonBase("Google.com", "google", "https://www.google.com"), new ButtonBase("Telegram", "telegram", "https://telegram.org/"));
-
- btn.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "back").Serialize()));
-
- await Device.Send("Click a button", btn);
+ default:
+ message.Handled = false;
+ break;
}
}
-}
+ public override async Task Render(MessageResult message)
+ {
+ var btn = new ButtonForm();
+
+ btn.AddButtonRow(new ButtonBase("Button 1", new CallbackData("a", "button1").Serialize()),
+ new ButtonBase("Button 2", new CallbackData("a", "button2").Serialize()));
+
+ btn.AddButtonRow(new ButtonBase("Button 3", new CallbackData("a", "button3").Serialize()),
+ new ButtonBase("Button 4", new CallbackData("a", "button4").Serialize()));
+
+ btn.AddButtonRow(new ButtonBase("Google.com", "google", "https://www.google.com"),
+ new ButtonBase("Telegram", "telegram", "https://telegram.org/"));
+
+ btn.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "back").Serialize()));
+
+ await Device.Send("Click a button", btn);
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs b/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs
index 3a7bdd9..0669d2e 100644
--- a/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs
+++ b/TelegramBotBase.Test/Tests/Controls/ButtonGridForm.cs
@@ -4,68 +4,66 @@ using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests.Controls
+namespace TelegramBotBaseTest.Tests.Controls;
+
+public class ButtonGridForm : AutoCleanForm
{
- public class ButtonGridForm : AutoCleanForm
+ private ButtonGrid _mButtons;
+
+ public ButtonGridForm()
{
- private ButtonGrid _mButtons;
+ DeleteMode = EDeleteMode.OnLeavingForm;
- public ButtonGridForm()
+ Init += ButtonGridForm_Init;
+ }
+
+ private Task ButtonGridForm_Init(object sender, InitEventArgs e)
+ {
+ _mButtons = new ButtonGrid
{
- DeleteMode = EDeleteMode.OnLeavingForm;
+ KeyboardType = EKeyboardType.InlineKeyBoard
+ };
- Init += ButtonGridForm_Init;
+ var bf = new ButtonForm();
+
+ bf.AddButtonRow(new ButtonBase("Back", "back"), new ButtonBase("Switch Keyboard", "switch"));
+
+ bf.AddButtonRow(new ButtonBase("Button1", "b1"), new ButtonBase("Button2", "b2"));
+
+ bf.AddButtonRow(new ButtonBase("Button3", "b3"), new ButtonBase("Button4", "b4"));
+
+ _mButtons.ButtonsForm = bf;
+
+ _mButtons.ButtonClicked += Bg_ButtonClicked;
+
+ AddControl(_mButtons);
+ return Task.CompletedTask;
+ }
+
+ private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
+ {
+ if (e.Button == null)
+ {
+ return;
}
- private Task ButtonGridForm_Init(object sender, InitEventArgs e)
+ if (e.Button.Value == "back")
{
- _mButtons = new ButtonGrid
+ var start = new Menu();
+ await NavigateTo(start);
+ }
+ else if (e.Button.Value == "switch")
+ {
+ _mButtons.KeyboardType = _mButtons.KeyboardType switch
{
- KeyboardType = EKeyboardType.InlineKeyBoard
+ EKeyboardType.ReplyKeyboard => EKeyboardType.InlineKeyBoard,
+ EKeyboardType.InlineKeyBoard => EKeyboardType.ReplyKeyboard,
+ _ => _mButtons.KeyboardType
};
-
- var bf = new ButtonForm();
-
- bf.AddButtonRow(new ButtonBase("Back", "back"), new ButtonBase("Switch Keyboard", "switch"));
-
- bf.AddButtonRow(new ButtonBase("Button1", "b1"), new ButtonBase("Button2", "b2"));
-
- bf.AddButtonRow(new ButtonBase("Button3", "b3"), new ButtonBase("Button4", "b4"));
-
- _mButtons.ButtonsForm = bf;
-
- _mButtons.ButtonClicked += Bg_ButtonClicked;
-
- AddControl(_mButtons);
- return Task.CompletedTask;
}
-
- private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
+ else
{
- if (e.Button == null)
- return;
-
- if (e.Button.Value == "back")
- {
- var start = new Menu();
- await NavigateTo(start);
- }
- else if (e.Button.Value == "switch")
- {
- _mButtons.KeyboardType = _mButtons.KeyboardType switch
- {
- EKeyboardType.ReplyKeyboard => EKeyboardType.InlineKeyBoard,
- EKeyboardType.InlineKeyBoard => EKeyboardType.ReplyKeyboard,
- _ => _mButtons.KeyboardType
- };
- }
- else
- {
-
- await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}");
- }
-
-
+ await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}");
}
}
-}
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs b/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs
index cc62321..47d6205 100644
--- a/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs
+++ b/TelegramBotBase.Test/Tests/Controls/ButtonGridPagingForm.cs
@@ -6,63 +6,61 @@ using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests.Controls
+namespace TelegramBotBaseTest.Tests.Controls;
+
+public class ButtonGridPagingForm : AutoCleanForm
{
- public class ButtonGridPagingForm : AutoCleanForm
+ private ButtonGrid _mButtons;
+
+ public ButtonGridPagingForm()
{
- private ButtonGrid _mButtons;
+ DeleteMode = EDeleteMode.OnLeavingForm;
- public ButtonGridPagingForm()
+ Init += ButtonGridForm_Init;
+ }
+
+ private Task ButtonGridForm_Init(object sender, InitEventArgs e)
+ {
+ _mButtons = new ButtonGrid
{
- DeleteMode = EDeleteMode.OnLeavingForm;
+ KeyboardType = EKeyboardType.ReplyKeyboard,
+ EnablePaging = true,
+ EnableSearch = true,
+ HeadLayoutButtonRow = new List { new("Back", "back") }
+ };
- Init += ButtonGridForm_Init;
+ var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
+
+ var bf = new ButtonForm();
+
+ foreach (var c in countries)
+ {
+ bf.AddButtonRow(new ButtonBase(c.EnglishName, c.EnglishName));
}
- private Task ButtonGridForm_Init(object sender, InitEventArgs e)
+ _mButtons.ButtonsForm = bf;
+
+ _mButtons.ButtonClicked += Bg_ButtonClicked;
+
+ AddControl(_mButtons);
+ return Task.CompletedTask;
+ }
+
+ private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
+ {
+ if (e.Button == null)
{
- _mButtons = new ButtonGrid
- {
- KeyboardType = EKeyboardType.ReplyKeyboard,
- EnablePaging = true,
- EnableSearch = true,
- HeadLayoutButtonRow = new List { new ButtonBase("Back", "back") }
- };
-
- var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
-
- var bf = new ButtonForm();
-
- foreach (var c in countries)
- {
- bf.AddButtonRow(new ButtonBase(c.EnglishName, c.EnglishName));
- }
-
- _mButtons.ButtonsForm = bf;
-
- _mButtons.ButtonClicked += Bg_ButtonClicked;
-
- AddControl(_mButtons);
- return Task.CompletedTask;
+ return;
}
- private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
+ if (e.Button.Value == "back")
{
- if (e.Button == null)
- return;
-
- if (e.Button.Value == "back")
- {
- var start = new Menu();
- await NavigateTo(start);
- }
- else
- {
-
- await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}");
- }
-
-
+ var start = new Menu();
+ await NavigateTo(start);
+ }
+ else
+ {
+ await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}");
}
}
-}
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs b/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs
index 510f208..23b4b1d 100644
--- a/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs
+++ b/TelegramBotBase.Test/Tests/Controls/ButtonGridTagForm.cs
@@ -8,68 +8,67 @@ using TelegramBotBase.DataSources;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests.Controls
+namespace TelegramBotBaseTest.Tests.Controls;
+
+public class ButtonGridTagForm : AutoCleanForm
{
- public class ButtonGridTagForm : AutoCleanForm
+ private TaggedButtonGrid _mButtons;
+
+ public ButtonGridTagForm()
{
- private TaggedButtonGrid _mButtons;
+ DeleteMode = EDeleteMode.OnLeavingForm;
- public ButtonGridTagForm()
- {
- DeleteMode = EDeleteMode.OnLeavingForm;
-
- Init += ButtonGridTagForm_Init;
- }
-
- private Task ButtonGridTagForm_Init(object sender, InitEventArgs e)
- {
- _mButtons = new TaggedButtonGrid
- {
- KeyboardType = EKeyboardType.ReplyKeyboard,
- EnablePaging = true,
- HeadLayoutButtonRow = new List { new ButtonBase("Back", "back") }
- };
-
-
- var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
-
- var bf = new ButtonForm();
-
- foreach (var c in countries)
- {
- bf.AddButtonRow(new TagButtonBase(c.EnglishName, c.EnglishName, c.Parent.EnglishName));
- }
-
- _mButtons.Tags = countries.Select(a => a.Parent.EnglishName).Distinct().OrderBy(a => a).ToList();
- _mButtons.SelectedTags = countries.Select(a => a.Parent.EnglishName).Distinct().OrderBy(a => a).ToList();
-
- _mButtons.EnableCheckAllTools = true;
-
- _mButtons.DataSource = new ButtonFormDataSource(bf);
-
- _mButtons.ButtonClicked += Bg_ButtonClicked;
-
- AddControl(_mButtons);
- return Task.CompletedTask;
- }
-
- private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
- {
- if (e.Button == null)
- return;
-
- switch (e.Button.Value)
- {
-
- case "back":
- var start = new Menu();
- await NavigateTo(start);
- return;
-
- }
-
-
- await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}");
- }
+ Init += ButtonGridTagForm_Init;
}
-}
+
+ private Task ButtonGridTagForm_Init(object sender, InitEventArgs e)
+ {
+ _mButtons = new TaggedButtonGrid
+ {
+ KeyboardType = EKeyboardType.ReplyKeyboard,
+ EnablePaging = true,
+ HeadLayoutButtonRow = new List { new("Back", "back") }
+ };
+
+
+ var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
+
+ var bf = new ButtonForm();
+
+ foreach (var c in countries)
+ {
+ bf.AddButtonRow(new TagButtonBase(c.EnglishName, c.EnglishName, c.Parent.EnglishName));
+ }
+
+ _mButtons.Tags = countries.Select(a => a.Parent.EnglishName).Distinct().OrderBy(a => a).ToList();
+ _mButtons.SelectedTags = countries.Select(a => a.Parent.EnglishName).Distinct().OrderBy(a => a).ToList();
+
+ _mButtons.EnableCheckAllTools = true;
+
+ _mButtons.DataSource = new ButtonFormDataSource(bf);
+
+ _mButtons.ButtonClicked += Bg_ButtonClicked;
+
+ AddControl(_mButtons);
+ return Task.CompletedTask;
+ }
+
+ private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
+ {
+ if (e.Button == null)
+ {
+ return;
+ }
+
+ switch (e.Button.Value)
+ {
+ case "back":
+ var start = new Menu();
+ await NavigateTo(start);
+ return;
+ }
+
+
+ await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}");
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Controls/CalendarPickerForm.cs b/TelegramBotBase.Test/Tests/Controls/CalendarPickerForm.cs
index 4d1eaac..69de30f 100644
--- a/TelegramBotBase.Test/Tests/Controls/CalendarPickerForm.cs
+++ b/TelegramBotBase.Test/Tests/Controls/CalendarPickerForm.cs
@@ -5,75 +5,65 @@ using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests.Controls
+namespace TelegramBotBaseTest.Tests.Controls;
+
+public class CalendarPickerForm : AutoCleanForm
{
- public class CalendarPickerForm : AutoCleanForm
+ public CalendarPickerForm()
{
-
- public CalendarPicker Picker { get; set; }
-
- private int? SelectedDateMessage { get; set; }
-
- public CalendarPickerForm()
- {
- DeleteMode = EDeleteMode.OnLeavingForm;
- Init += CalendarPickerForm_Init;
- }
-
- private Task CalendarPickerForm_Init(object sender, InitEventArgs e)
- {
- Picker = new CalendarPicker
- {
- Title = "Datum auswählen / Pick date"
- };
-
- AddControl(Picker);
- return Task.CompletedTask;
- }
-
-
- public override async Task Action(MessageResult message)
- {
-
- switch(message.RawData)
- {
- case "back":
-
- var s = new Menu();
-
- await NavigateTo(s);
-
- break;
- }
-
- }
-
- public override async Task Render(MessageResult message)
- {
- var s = "";
-
- s = "Selected date is " + Picker.SelectedDate.ToShortDateString() + "\r\n";
- s += "Selected month is " + Picker.Culture.DateTimeFormat.MonthNames[Picker.VisibleMonth.Month - 1] + "\r\n";
- s += "Selected year is " + Picker.VisibleMonth.Year;
-
- var bf = new ButtonForm();
- bf.AddButtonRow(new ButtonBase("Back","back"));
-
- if (SelectedDateMessage != null)
- {
- await Device.Edit(SelectedDateMessage.Value, s, bf);
- }
- else
- {
- var m = await Device.Send(s, bf);
- SelectedDateMessage = m.MessageId;
- }
-
-
-
- }
-
-
-
+ DeleteMode = EDeleteMode.OnLeavingForm;
+ Init += CalendarPickerForm_Init;
}
-}
+
+ public CalendarPicker Picker { get; set; }
+
+ private int? SelectedDateMessage { get; set; }
+
+ private Task CalendarPickerForm_Init(object sender, InitEventArgs e)
+ {
+ Picker = new CalendarPicker
+ {
+ Title = "Datum auswählen / Pick date"
+ };
+
+ AddControl(Picker);
+ return Task.CompletedTask;
+ }
+
+
+ public override async Task Action(MessageResult message)
+ {
+ switch (message.RawData)
+ {
+ case "back":
+
+ var s = new Menu();
+
+ await NavigateTo(s);
+
+ break;
+ }
+ }
+
+ public override async Task Render(MessageResult message)
+ {
+ var s = "";
+
+ s = "Selected date is " + Picker.SelectedDate.ToShortDateString() + "\r\n";
+ s += "Selected month is " + Picker.Culture.DateTimeFormat.MonthNames[Picker.VisibleMonth.Month - 1] + "\r\n";
+ s += "Selected year is " + Picker.VisibleMonth.Year;
+
+ var bf = new ButtonForm();
+ bf.AddButtonRow(new ButtonBase("Back", "back"));
+
+ if (SelectedDateMessage != null)
+ {
+ await Device.Edit(SelectedDateMessage.Value, s, bf);
+ }
+ else
+ {
+ var m = await Device.Send(s, bf);
+ SelectedDateMessage = m.MessageId;
+ }
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Controls/CheckedButtonListForm.cs b/TelegramBotBase.Test/Tests/Controls/CheckedButtonListForm.cs
index 6906c4f..33849ae 100644
--- a/TelegramBotBase.Test/Tests/Controls/CheckedButtonListForm.cs
+++ b/TelegramBotBase.Test/Tests/Controls/CheckedButtonListForm.cs
@@ -6,81 +6,81 @@ using TelegramBotBase.DataSources;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests.Controls
+namespace TelegramBotBaseTest.Tests.Controls;
+
+public class CheckedButtonListForm : AutoCleanForm
{
- public class CheckedButtonListForm : AutoCleanForm
+ private CheckedButtonList _mButtons;
+
+ public CheckedButtonListForm()
{
- private CheckedButtonList _mButtons;
+ DeleteMode = EDeleteMode.OnLeavingForm;
- public CheckedButtonListForm()
+ Init += CheckedButtonListForm_Init;
+ }
+
+ private Task CheckedButtonListForm_Init(object sender, InitEventArgs e)
+ {
+ _mButtons = new CheckedButtonList
{
- DeleteMode = EDeleteMode.OnLeavingForm;
+ KeyboardType = EKeyboardType.InlineKeyBoard,
+ EnablePaging = true,
+ HeadLayoutButtonRow = new List { new("Back", "back"), new("Switch Keyboard", "switch") },
+ SubHeadLayoutButtonRow = new List { new("No checked items", "$") }
+ };
- Init += CheckedButtonListForm_Init;
+ var bf = new ButtonForm();
+
+ for (var i = 0; i < 30; i++)
+ {
+ bf.AddButtonRow($"{i + 1}. Item", i.ToString());
}
- private Task CheckedButtonListForm_Init(object sender, InitEventArgs e)
+ _mButtons.DataSource = new ButtonFormDataSource(bf);
+
+ _mButtons.ButtonClicked += Bg_ButtonClicked;
+ _mButtons.CheckedChanged += M_Buttons_CheckedChanged;
+
+ AddControl(_mButtons);
+ return Task.CompletedTask;
+ }
+
+ private Task M_Buttons_CheckedChanged(object sender, CheckedChangedEventArgs e)
+ {
+ _mButtons.SubHeadLayoutButtonRow = new List
+ { new($"{_mButtons.CheckedItems.Count} checked items", "$") };
+ return Task.CompletedTask;
+ }
+
+ private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
+ {
+ if (e.Button == null)
{
- _mButtons = new CheckedButtonList
- {
- KeyboardType = EKeyboardType.InlineKeyBoard,
- EnablePaging = true,
- HeadLayoutButtonRow = new List { new ButtonBase("Back", "back"), new ButtonBase("Switch Keyboard", "switch") },
- SubHeadLayoutButtonRow = new List { new ButtonBase("No checked items", "$") }
- };
-
- var bf = new ButtonForm();
-
- for (var i = 0; i < 30; i++)
- {
- bf.AddButtonRow($"{i + 1}. Item", i.ToString());
- }
-
- _mButtons.DataSource = new ButtonFormDataSource(bf);
-
- _mButtons.ButtonClicked += Bg_ButtonClicked;
- _mButtons.CheckedChanged += M_Buttons_CheckedChanged;
-
- AddControl(_mButtons);
- return Task.CompletedTask;
+ return;
}
- private Task M_Buttons_CheckedChanged(object sender, CheckedChangedEventArgs e)
+ switch (e.Button.Value)
{
- _mButtons.SubHeadLayoutButtonRow = new List { new ButtonBase($"{_mButtons.CheckedItems.Count} checked items", "$") };
- return Task.CompletedTask;
- }
+ case "back":
- private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
- {
- if (e.Button == null)
- return;
-
- switch (e.Button.Value)
- {
- case "back":
-
- var start = new Menu();
- await NavigateTo(start);
- break;
+ var start = new Menu();
+ await NavigateTo(start);
+ break;
- case "switch":
- _mButtons.KeyboardType = _mButtons.KeyboardType switch
- {
- EKeyboardType.ReplyKeyboard => EKeyboardType.InlineKeyBoard,
- EKeyboardType.InlineKeyBoard => EKeyboardType.ReplyKeyboard,
- _ => _mButtons.KeyboardType
- };
-
- break;
-
- default:
- await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}");
- break;
- }
+ case "switch":
+ _mButtons.KeyboardType = _mButtons.KeyboardType switch
+ {
+ EKeyboardType.ReplyKeyboard => EKeyboardType.InlineKeyBoard,
+ EKeyboardType.InlineKeyBoard => EKeyboardType.ReplyKeyboard,
+ _ => _mButtons.KeyboardType
+ };
+ break;
+ default:
+ await Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}");
+ break;
}
}
-}
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Controls/MonthPickerForm.cs b/TelegramBotBase.Test/Tests/Controls/MonthPickerForm.cs
index 3774430..c44021f 100644
--- a/TelegramBotBase.Test/Tests/Controls/MonthPickerForm.cs
+++ b/TelegramBotBase.Test/Tests/Controls/MonthPickerForm.cs
@@ -5,73 +5,63 @@ using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests.Controls
+namespace TelegramBotBaseTest.Tests.Controls;
+
+public class MonthPickerForm : AutoCleanForm
{
- public class MonthPickerForm : AutoCleanForm
+ public MonthPickerForm()
{
-
- public MonthPicker Picker { get; set; }
-
- private int? SelectedDateMessage { get; set; }
-
- public MonthPickerForm()
- {
- DeleteMode = EDeleteMode.OnLeavingForm;
- Init += MonthPickerForm_Init;
- }
-
- private Task MonthPickerForm_Init(object sender, InitEventArgs e)
- {
- Picker = new MonthPicker
- {
- Title = "Monat auswählen / Pick month"
- };
- AddControl(Picker);
- return Task.CompletedTask;
- }
-
-
- public override async Task Action(MessageResult message)
- {
-
- switch(message.RawData)
- {
- case "back":
-
- var s = new Menu();
-
- await NavigateTo(s);
-
- break;
- }
-
- }
-
- public override async Task Render(MessageResult message)
- {
- var s = "";
-
- s += "Selected month is " + Picker.Culture.DateTimeFormat.MonthNames[Picker.SelectedDate.Month - 1] + "\r\n";
- s += "Selected year is " + Picker.VisibleMonth.Year;
-
- var bf = new ButtonForm();
- bf.AddButtonRow(new ButtonBase("Back","back"));
-
- if (SelectedDateMessage != null)
- {
- await Device.Edit(SelectedDateMessage.Value, s, bf);
- }
- else
- {
- var m = await Device.Send(s, bf);
- SelectedDateMessage = m.MessageId;
- }
-
-
-
- }
-
-
-
+ DeleteMode = EDeleteMode.OnLeavingForm;
+ Init += MonthPickerForm_Init;
}
-}
+
+ public MonthPicker Picker { get; set; }
+
+ private int? SelectedDateMessage { get; set; }
+
+ private Task MonthPickerForm_Init(object sender, InitEventArgs e)
+ {
+ Picker = new MonthPicker
+ {
+ Title = "Monat auswählen / Pick month"
+ };
+ AddControl(Picker);
+ return Task.CompletedTask;
+ }
+
+
+ public override async Task Action(MessageResult message)
+ {
+ switch (message.RawData)
+ {
+ case "back":
+
+ var s = new Menu();
+
+ await NavigateTo(s);
+
+ break;
+ }
+ }
+
+ public override async Task Render(MessageResult message)
+ {
+ var s = "";
+
+ s += "Selected month is " + Picker.Culture.DateTimeFormat.MonthNames[Picker.SelectedDate.Month - 1] + "\r\n";
+ s += "Selected year is " + Picker.VisibleMonth.Year;
+
+ var bf = new ButtonForm();
+ bf.AddButtonRow(new ButtonBase("Back", "back"));
+
+ if (SelectedDateMessage != null)
+ {
+ await Device.Edit(SelectedDateMessage.Value, s, bf);
+ }
+ else
+ {
+ var m = await Device.Send(s, bf);
+ SelectedDateMessage = m.MessageId;
+ }
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Controls/MultiToggleButtons.cs b/TelegramBotBase.Test/Tests/Controls/MultiToggleButtons.cs
index dfa774f..c75c065 100644
--- a/TelegramBotBase.Test/Tests/Controls/MultiToggleButtons.cs
+++ b/TelegramBotBase.Test/Tests/Controls/MultiToggleButtons.cs
@@ -7,51 +7,49 @@ using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests.Controls
+namespace TelegramBotBaseTest.Tests.Controls;
+
+public class MultiToggleButtons : AutoCleanForm
{
- public class MultiToggleButtons : AutoCleanForm
+ public MultiToggleButtons()
{
- public MultiToggleButtons()
- {
- DeleteMode = EDeleteMode.OnLeavingForm;
+ DeleteMode = EDeleteMode.OnLeavingForm;
- Init += ToggleButtons_Init;
- }
-
- private Task ToggleButtons_Init(object sender, InitEventArgs e)
- {
-
- var mtb = new MultiToggleButton
- {
- Options = new List { new ButtonBase("Option 1", "1"), new ButtonBase("Option 2", "2"), new ButtonBase("Option 3", "3") }
- };
-
- mtb.SelectedOption = mtb.Options.FirstOrDefault();
- mtb.Toggled += Tb_Toggled;
- AddControl(mtb);
-
- mtb = new MultiToggleButton
- {
- Options = new List { new ButtonBase("Option 4", "4"), new ButtonBase("Option 5", "5"), new ButtonBase("Option 6", "6") }
- };
-
- mtb.SelectedOption = mtb.Options.FirstOrDefault();
- mtb.AllowEmptySelection = false;
- mtb.Toggled += Tb_Toggled;
- AddControl(mtb);
- return Task.CompletedTask;
- }
-
- private void Tb_Toggled(object sender, EventArgs e)
- {
- var tb = sender as MultiToggleButton;
- if (tb.SelectedOption != null)
- {
- Console.WriteLine(tb.Id + " was pressed, and toggled to " + tb.SelectedOption.Value);
- return;
- }
-
- Console.WriteLine("Selection for " + tb.Id + " has been removed.");
- }
+ Init += ToggleButtons_Init;
}
-}
+
+ private Task ToggleButtons_Init(object sender, InitEventArgs e)
+ {
+ var mtb = new MultiToggleButton
+ {
+ Options = new List { new("Option 1", "1"), new("Option 2", "2"), new("Option 3", "3") }
+ };
+
+ mtb.SelectedOption = mtb.Options.FirstOrDefault();
+ mtb.Toggled += Tb_Toggled;
+ AddControl(mtb);
+
+ mtb = new MultiToggleButton
+ {
+ Options = new List { new("Option 4", "4"), new("Option 5", "5"), new("Option 6", "6") }
+ };
+
+ mtb.SelectedOption = mtb.Options.FirstOrDefault();
+ mtb.AllowEmptySelection = false;
+ mtb.Toggled += Tb_Toggled;
+ AddControl(mtb);
+ return Task.CompletedTask;
+ }
+
+ private void Tb_Toggled(object sender, EventArgs e)
+ {
+ var tb = sender as MultiToggleButton;
+ if (tb.SelectedOption != null)
+ {
+ Console.WriteLine(tb.Id + " was pressed, and toggled to " + tb.SelectedOption.Value);
+ return;
+ }
+
+ Console.WriteLine("Selection for " + tb.Id + " has been removed.");
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs b/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs
index e5f6431..0511cb6 100644
--- a/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs
+++ b/TelegramBotBase.Test/Tests/Controls/MultiViewForm.cs
@@ -5,50 +5,46 @@ using TelegramBotBase.Enums;
using TelegramBotBase.Form;
using TelegramBotBaseTest.Tests.Controls.Subclass;
-namespace TelegramBotBaseTest.Tests.Controls
+namespace TelegramBotBaseTest.Tests.Controls;
+
+public class MultiViewForm : AutoCleanForm
{
- public class MultiViewForm : AutoCleanForm
+ private ButtonGrid _bg;
+ private MultiViewTest _mvt;
+
+ public MultiViewForm()
{
- private MultiViewTest _mvt;
-
- private ButtonGrid _bg;
-
- public MultiViewForm()
- {
- DeleteMode = EDeleteMode.OnLeavingForm;
- Init += MultiViewForm_Init;
- }
-
- private Task MultiViewForm_Init(object sender, InitEventArgs e)
- {
- _mvt = new MultiViewTest();
-
- AddControl(_mvt);
-
- _bg = new ButtonGrid
- {
- ButtonsForm = new ButtonForm()
- };
- _bg.ButtonsForm.AddButtonRow("Back", "$back$");
- _bg.ButtonClicked += Bg_ButtonClicked;
- _bg.KeyboardType = EKeyboardType.ReplyKeyboard;
- AddControl(_bg);
- return Task.CompletedTask;
- }
-
- private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
- {
- switch(e.Button.Value)
- {
- case "$back$":
-
- var mn = new Menu();
- await NavigateTo(mn);
-
- break;
- }
- }
-
-
+ DeleteMode = EDeleteMode.OnLeavingForm;
+ Init += MultiViewForm_Init;
}
-}
+
+ private Task MultiViewForm_Init(object sender, InitEventArgs e)
+ {
+ _mvt = new MultiViewTest();
+
+ AddControl(_mvt);
+
+ _bg = new ButtonGrid
+ {
+ ButtonsForm = new ButtonForm()
+ };
+ _bg.ButtonsForm.AddButtonRow("Back", "$back$");
+ _bg.ButtonClicked += Bg_ButtonClicked;
+ _bg.KeyboardType = EKeyboardType.ReplyKeyboard;
+ AddControl(_bg);
+ return Task.CompletedTask;
+ }
+
+ private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
+ {
+ switch (e.Button.Value)
+ {
+ case "$back$":
+
+ var mn = new Menu();
+ await NavigateTo(mn);
+
+ break;
+ }
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs b/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs
index 79dfeab..08c7649 100644
--- a/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs
+++ b/TelegramBotBase.Test/Tests/Controls/Subclass/MultiViewTest.cs
@@ -4,59 +4,49 @@ using TelegramBotBase.Base;
using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests.Controls.Subclass
+namespace TelegramBotBaseTest.Tests.Controls.Subclass;
+
+public class MultiViewTest : MultiView
{
- public class MultiViewTest : MultiView
+ public override Task Action(MessageResult result, string value = null)
{
-
-
- public override Task Action(MessageResult result, string value = null)
+ switch (result.RawData)
{
- switch (result.RawData)
- {
- case "back":
+ case "back":
- SelectedViewIndex--;
+ SelectedViewIndex--;
- break;
- case "next":
+ break;
+ case "next":
- SelectedViewIndex++;
+ SelectedViewIndex++;
- break;
- }
-
- return Task.CompletedTask;
+ break;
}
- public override async Task RenderView(RenderViewEventArgs e)
- {
-
- var bf = new ButtonForm();
- bf.AddButtonRow(new ButtonBase("Back", "back"), new ButtonBase("Next", "next"));
-
- switch (e.CurrentView)
- {
- case 0:
- case 1:
- case 2:
-
- await Device.Send($"Page {e.CurrentView + 1}", bf);
-
- break;
-
- default:
-
- await Device.Send("Unknown Page", bf);
-
- break;
-
-
- }
-
- }
-
-
-
+ return Task.CompletedTask;
}
-}
+
+ public override async Task RenderView(RenderViewEventArgs e)
+ {
+ var bf = new ButtonForm();
+ bf.AddButtonRow(new ButtonBase("Back", "back"), new ButtonBase("Next", "next"));
+
+ switch (e.CurrentView)
+ {
+ case 0:
+ case 1:
+ case 2:
+
+ await Device.Send($"Page {e.CurrentView + 1}", bf);
+
+ break;
+
+ default:
+
+ await Device.Send("Unknown Page", bf);
+
+ break;
+ }
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Controls/ToggleButtons.cs b/TelegramBotBase.Test/Tests/Controls/ToggleButtons.cs
index cb46305..67db7e7 100644
--- a/TelegramBotBase.Test/Tests/Controls/ToggleButtons.cs
+++ b/TelegramBotBase.Test/Tests/Controls/ToggleButtons.cs
@@ -5,50 +5,48 @@ using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests.Controls
+namespace TelegramBotBaseTest.Tests.Controls;
+
+public class ToggleButtons : AutoCleanForm
{
- public class ToggleButtons : AutoCleanForm
+ public ToggleButtons()
{
- public ToggleButtons()
- {
- DeleteMode = EDeleteMode.OnLeavingForm;
+ DeleteMode = EDeleteMode.OnLeavingForm;
- Init += ToggleButtons_Init;
- }
-
- private Task ToggleButtons_Init(object sender, InitEventArgs e)
- {
-
- var tb = new ToggleButton
- {
- Checked = true
- };
- tb.Toggled += Tb_Toggled;
-
- AddControl(tb);
-
- tb = new ToggleButton
- {
- Checked = false
- };
- tb.Toggled += Tb_Toggled;
-
- AddControl(tb);
-
- tb = new ToggleButton
- {
- Checked = true
- };
- tb.Toggled += Tb_Toggled;
-
- AddControl(tb);
- return Task.CompletedTask;
- }
-
- private void Tb_Toggled(object sender, EventArgs e)
- {
- var tb = sender as ToggleButton;
- Console.WriteLine(tb.Id + " was pressed, and toggled to " + (tb.Checked ? "Checked" : "Unchecked"));
- }
+ Init += ToggleButtons_Init;
}
-}
+
+ private Task ToggleButtons_Init(object sender, InitEventArgs e)
+ {
+ var tb = new ToggleButton
+ {
+ Checked = true
+ };
+ tb.Toggled += Tb_Toggled;
+
+ AddControl(tb);
+
+ tb = new ToggleButton
+ {
+ Checked = false
+ };
+ tb.Toggled += Tb_Toggled;
+
+ AddControl(tb);
+
+ tb = new ToggleButton
+ {
+ Checked = true
+ };
+ tb.Toggled += Tb_Toggled;
+
+ AddControl(tb);
+ return Task.CompletedTask;
+ }
+
+ private void Tb_Toggled(object sender, EventArgs e)
+ {
+ var tb = sender as ToggleButton;
+ Console.WriteLine(tb.Id + " was pressed, and toggled to " + (tb.Checked ? "Checked" : "Unchecked"));
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Controls/TreeViewForms.cs b/TelegramBotBase.Test/Tests/Controls/TreeViewForms.cs
index 4a41460..b5d7465 100644
--- a/TelegramBotBase.Test/Tests/Controls/TreeViewForms.cs
+++ b/TelegramBotBase.Test/Tests/Controls/TreeViewForms.cs
@@ -5,93 +5,94 @@ using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests.Controls
+namespace TelegramBotBaseTest.Tests.Controls;
+
+public class TreeViewForms : AutoCleanForm
{
- public class TreeViewForms : AutoCleanForm
+ public TreeViewForms()
{
- public TreeView View { get; set; }
-
- private int? MessageId { get; set; }
-
- public TreeViewForms()
- {
- DeleteMode = EDeleteMode.OnLeavingForm;
- Init += TreeViewForms_Init;
- }
-
- private Task TreeViewForms_Init(object sender, InitEventArgs e)
- {
- View = new TreeView();
-
- var tvn = new TreeViewNode("Cars", "cars");
-
- tvn.AddNode(new TreeViewNode("Porsche", "porsche", new TreeViewNode("Website", "web", "https://www.porsche.com/germany/"), new TreeViewNode("911", "911"), new TreeViewNode("918 Spyder", "918")));
- tvn.AddNode(new TreeViewNode("BMW", "bmw"));
- tvn.AddNode(new TreeViewNode("Audi", "audi"));
- tvn.AddNode(new TreeViewNode("VW", "vw"));
- tvn.AddNode(new TreeViewNode("Lamborghini", "lamborghini"));
-
- View.Nodes.Add(tvn);
-
- tvn = new TreeViewNode("Fruits", "fruits");
-
- tvn.AddNode(new TreeViewNode("Apple", "apple"));
- tvn.AddNode(new TreeViewNode("Orange", "orange"));
- tvn.AddNode(new TreeViewNode("Lemon", "lemon"));
-
- View.Nodes.Add(tvn);
-
- AddControl(View);
- return Task.CompletedTask;
- }
-
- public override async Task Action(MessageResult message)
- {
- await message.ConfirmAction();
-
- if (message.Handled)
- return;
-
- switch (message.RawData)
- {
- case "back":
-
- message.Handled = true;
-
- var start = new Menu();
-
- await NavigateTo(start);
-
- break;
-
- }
-
- }
-
- public override async Task Render(MessageResult message)
- {
- var s = "";
-
- s += "Selected Node: " + (View.SelectedNode?.Text ?? "(null)") + "\r\n";
-
- s += "Visible Node: " + (View.VisibleNode?.Text ?? "(top)") + "\r\n";
-
- s += "Visible Path: " + View.GetPath() + "\r\n";
- s += "Selected Path: " + (View.SelectedNode?.GetPath() ?? "(null)") + "\r\n";
-
- var bf = new ButtonForm();
- bf.AddButtonRow(new ButtonBase("Back", "back"));
-
- if (MessageId != null)
- {
- await Device.Edit(MessageId.Value, s, bf);
- }
- else
- {
- var m = await Device.Send(s, bf);
- MessageId = m.MessageId;
- }
- }
-
+ DeleteMode = EDeleteMode.OnLeavingForm;
+ Init += TreeViewForms_Init;
}
-}
+
+ public TreeView View { get; set; }
+
+ private int? MessageId { get; set; }
+
+ private Task TreeViewForms_Init(object sender, InitEventArgs e)
+ {
+ View = new TreeView();
+
+ var tvn = new TreeViewNode("Cars", "cars");
+
+ tvn.AddNode(new TreeViewNode("Porsche", "porsche",
+ new TreeViewNode("Website", "web", "https://www.porsche.com/germany/"),
+ new TreeViewNode("911", "911"),
+ new TreeViewNode("918 Spyder", "918")));
+ tvn.AddNode(new TreeViewNode("BMW", "bmw"));
+ tvn.AddNode(new TreeViewNode("Audi", "audi"));
+ tvn.AddNode(new TreeViewNode("VW", "vw"));
+ tvn.AddNode(new TreeViewNode("Lamborghini", "lamborghini"));
+
+ View.Nodes.Add(tvn);
+
+ tvn = new TreeViewNode("Fruits", "fruits");
+
+ tvn.AddNode(new TreeViewNode("Apple", "apple"));
+ tvn.AddNode(new TreeViewNode("Orange", "orange"));
+ tvn.AddNode(new TreeViewNode("Lemon", "lemon"));
+
+ View.Nodes.Add(tvn);
+
+ AddControl(View);
+ return Task.CompletedTask;
+ }
+
+ public override async Task Action(MessageResult message)
+ {
+ await message.ConfirmAction();
+
+ if (message.Handled)
+ {
+ return;
+ }
+
+ switch (message.RawData)
+ {
+ case "back":
+
+ message.Handled = true;
+
+ var start = new Menu();
+
+ await NavigateTo(start);
+
+ break;
+ }
+ }
+
+ public override async Task Render(MessageResult message)
+ {
+ var s = "";
+
+ s += "Selected Node: " + (View.SelectedNode?.Text ?? "(null)") + "\r\n";
+
+ s += "Visible Node: " + (View.VisibleNode?.Text ?? "(top)") + "\r\n";
+
+ s += "Visible Path: " + View.GetPath() + "\r\n";
+ s += "Selected Path: " + (View.SelectedNode?.GetPath() ?? "(null)") + "\r\n";
+
+ var bf = new ButtonForm();
+ bf.AddButtonRow(new ButtonBase("Back", "back"));
+
+ if (MessageId != null)
+ {
+ await Device.Edit(MessageId.Value, s, bf);
+ }
+ else
+ {
+ var m = await Device.Send(s, bf);
+ MessageId = m.MessageId;
+ }
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/DataForm.cs b/TelegramBotBase.Test/Tests/DataForm.cs
index 509e58b..7811d33 100644
--- a/TelegramBotBase.Test/Tests/DataForm.cs
+++ b/TelegramBotBase.Test/Tests/DataForm.cs
@@ -7,134 +7,126 @@ using Telegram.Bot.Types.ReplyMarkups;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests
+namespace TelegramBotBaseTest.Tests;
+
+public class DataForm : AutoCleanForm
{
- public class DataForm : AutoCleanForm
+ public override async Task SentData(DataResult data)
{
+ var tmp = "";
+ InputOnlineFile file;
-
- public override async Task SentData(DataResult data)
+ switch (data.Type)
{
- var tmp = "";
- InputOnlineFile file;
+ case MessageType.Contact:
- switch (data.Type)
- {
- case MessageType.Contact:
+ tmp += "Firstname: " + data.Contact.FirstName + "\r\n";
+ tmp += "Lastname: " + data.Contact.LastName + "\r\n";
+ tmp += "Phonenumber: " + data.Contact.PhoneNumber + "\r\n";
+ tmp += "UserId: " + data.Contact.UserId + "\r\n";
- tmp += "Firstname: " + data.Contact.FirstName + "\r\n";
- tmp += "Lastname: " + data.Contact.LastName + "\r\n";
- tmp += "Phonenumber: " + data.Contact.PhoneNumber + "\r\n";
- tmp += "UserId: " + data.Contact.UserId + "\r\n";
+ await Device.Send("Your contact: \r\n" + tmp, replyTo: data.MessageId);
- await Device.Send("Your contact: \r\n" + tmp, replyTo: data.MessageId);
+ break;
- break;
+ case MessageType.Document:
- case MessageType.Document:
+ file = new InputOnlineFile(data.Document.FileId);
- file = new InputOnlineFile(data.Document.FileId);
-
- await Device.SendDocument(file, "Your uploaded document");
+ await Device.SendDocument(file, "Your uploaded document");
- break;
+ break;
- case MessageType.Video:
+ case MessageType.Video:
- file = new InputOnlineFile(data.Document.FileId);
+ file = new InputOnlineFile(data.Document.FileId);
- await Device.SendDocument(file, "Your uploaded video");
+ await Device.SendDocument(file, "Your uploaded video");
- break;
+ break;
- case MessageType.Audio:
+ case MessageType.Audio:
- file = new InputOnlineFile(data.Document.FileId);
+ file = new InputOnlineFile(data.Document.FileId);
- await Device.SendDocument(file, "Your uploaded audio");
+ await Device.SendDocument(file, "Your uploaded audio");
- break;
+ break;
- case MessageType.Location:
+ case MessageType.Location:
- tmp += "Lat: " + data.Location.Latitude + "\r\n";
- tmp += "Lng: " + data.Location.Longitude + "\r\n";
+ tmp += "Lat: " + data.Location.Latitude + "\r\n";
+ tmp += "Lng: " + data.Location.Longitude + "\r\n";
- await Device.Send("Your location: \r\n" + tmp, replyTo: data.MessageId);
+ await Device.Send("Your location: \r\n" + tmp, replyTo: data.MessageId);
- break;
+ break;
- case MessageType.Photo:
+ case MessageType.Photo:
- var photo = new InputOnlineFile(data.Photos.Last().FileId);
+ var photo = new InputOnlineFile(data.Photos.Last().FileId);
- await Device.Send("Your image: ", replyTo: data.MessageId);
- await Client.TelegramClient.SendPhotoAsync(Device.DeviceId, photo);
+ await Device.Send("Your image: ", replyTo: data.MessageId);
+ await Client.TelegramClient.SendPhotoAsync(Device.DeviceId, photo);
- break;
+ break;
- default:
+ default:
- await Device.Send("Unknown response");
+ await Device.Send("Unknown response");
- break;
- }
+ break;
+ }
+ }
+ public override async Task Action(MessageResult message)
+ {
+ await message.ConfirmAction();
+
+ if (message.Handled)
+ {
+ return;
}
- public override async Task Action(MessageResult message)
+ switch (message.RawData)
{
- await message.ConfirmAction();
+ case "contact":
- if (message.Handled)
- return;
+ await Device.RequestContact();
- switch (message.RawData)
- {
- case "contact":
+ break;
- await Device.RequestContact();
+ case "location":
- break;
+ await Device.RequestLocation();
- case "location":
+ break;
- await Device.RequestLocation();
+ case "back":
- break;
+ message.Handled = true;
- case "back":
-
- message.Handled = true;
-
- var start = new Menu();
-
- await NavigateTo(start);
-
- break;
- }
+ var start = new Menu();
+ await NavigateTo(start);
+ break;
}
+ }
- public override async Task Render(MessageResult message)
- {
- var bf = new ButtonForm();
+ public override async Task Render(MessageResult message)
+ {
+ var bf = new ButtonForm();
- bf.AddButtonRow(new ButtonBase("Request User contact", "contact"));
+ bf.AddButtonRow(new ButtonBase("Request User contact", "contact"));
- bf.AddButtonRow(new ButtonBase("Request User location", "location"));
+ bf.AddButtonRow(new ButtonBase("Request User location", "location"));
- bf.AddButtonRow(new ButtonBase("Back", "back"));
+ bf.AddButtonRow(new ButtonBase("Back", "back"));
- InlineKeyboardMarkup ikv = bf;
-
- await Device.Send("Please upload a contact, photo, video, audio, document or location.", bf);
-
-
-
- }
+ InlineKeyboardMarkup ikv = bf;
+ await Device.Send("Please upload a contact, photo, video, audio, document or location.", bf);
}
}
diff --git a/TelegramBotBase.Test/Tests/DataSources/CustomDataSource.cs b/TelegramBotBase.Test/Tests/DataSources/CustomDataSource.cs
new file mode 100644
index 0000000..0246920
--- /dev/null
+++ b/TelegramBotBase.Test/Tests/DataSources/CustomDataSource.cs
@@ -0,0 +1,146 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using Newtonsoft.Json;
+using TelegramBotBase.Controls.Hybrid;
+using TelegramBotBase.DataSources;
+using TelegramBotBase.Form;
+
+namespace TelegramBotBaseTest.Tests.DataSources;
+
+public class CustomDataSource : ButtonFormDataSource
+{
+ public List Countries = new() { "Country 1", "Country 2", "Country 3" };
+
+ public CustomDataSource()
+ {
+ LoadData();
+ }
+
+ public override int Count => Countries.Count;
+
+ public override int ColumnCount => 1;
+
+ public override int RowCount => Count;
+
+ ///
+ /// This method has the example purpose of creating and loading some example data.
+ /// When using a database you do not need this kind of method.
+ ///
+ private void LoadData()
+ {
+ //Exists data source? Read it
+ if (File.Exists(AppContext.BaseDirectory + "countries.json"))
+ {
+ try
+ {
+ var list = JsonConvert.DeserializeObject>(File.ReadAllText("countries.json"));
+
+
+ Countries = list;
+ }
+ catch
+ {
+ }
+
+
+ return;
+ }
+
+ //If not, create it
+ try
+ {
+ var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Select(a => a.DisplayName).ToList();
+
+ Countries = countries;
+
+ var tmp = JsonConvert.SerializeObject(countries);
+
+ File.WriteAllText(AppContext.BaseDirectory + "countries.json", tmp);
+ }
+ catch
+ {
+ }
+ }
+
+ public override ButtonRow ItemAt(int index)
+ {
+ var item = Countries.ElementAt(index);
+ if (item == null)
+ {
+ return new ButtonRow();
+ }
+
+ return Render(item);
+ }
+
+ public override List ItemRange(int start, int count)
+ {
+ var items = Countries.Skip(start).Take(count);
+
+ var lst = new List();
+ foreach (var c in items)
+ {
+ lst.Add(Render(c));
+ }
+
+ return lst;
+ }
+
+ public override List AllItems()
+ {
+ var lst = new List();
+ foreach (var c in Countries)
+ {
+ lst.Add(Render(c));
+ }
+
+ return lst;
+ }
+
+ public override ButtonForm PickItems(int start, int count, string filter = null)
+ {
+ var rows = ItemRange(start, count);
+
+ var lst = new ButtonForm();
+ foreach (var c in rows)
+ {
+ lst.AddButtonRow(c);
+ }
+
+ return lst;
+ }
+
+ public override ButtonForm PickAllItems(string filter = null)
+ {
+ var rows = AllItems();
+
+ var bf = new ButtonForm();
+
+ bf.AddButtonRows(rows);
+
+ return bf;
+ }
+
+ public override int CalculateMax(string filter = null)
+ {
+ if (filter == null)
+ {
+ return Countries.Count;
+ }
+
+ return Countries.Where(a => a.IndexOf(filter, StringComparison.InvariantCultureIgnoreCase) != -1).Count();
+ }
+
+ public override ButtonRow Render(object data)
+ {
+ if (!(data is string s))
+ {
+ return new ButtonRow(new ButtonBase("Empty", "zero"));
+ }
+
+ return new ButtonRow(new ButtonBase(s, s));
+ }
+}
diff --git a/TelegramBotBase.Test/Tests/DataSources/List.cs b/TelegramBotBase.Test/Tests/DataSources/List.cs
new file mode 100644
index 0000000..35c55d7
--- /dev/null
+++ b/TelegramBotBase.Test/Tests/DataSources/List.cs
@@ -0,0 +1,51 @@
+using System.Threading.Tasks;
+using TelegramBotBase.Args;
+using TelegramBotBase.Controls.Hybrid;
+using TelegramBotBase.Enums;
+using TelegramBotBase.Form;
+
+namespace TelegramBotBaseTest.Tests.DataSources;
+
+public class List : FormBase
+{
+ private ButtonGrid _buttons;
+
+ public List()
+ {
+ Init += List_Init;
+ }
+
+ private Task List_Init(object sender, InitEventArgs e)
+ {
+ _buttons = new ButtonGrid
+ {
+ EnablePaging = true,
+ EnableSearch = false
+ };
+
+ _buttons.ButtonClicked += __buttons_ButtonClicked;
+ _buttons.KeyboardType = EKeyboardType.ReplyKeyboard;
+ _buttons.DeleteReplyMessage = true;
+
+ _buttons.HeadLayoutButtonRow = new ButtonRow(new ButtonBase("Back", "back"));
+
+ var cds = new CustomDataSource();
+ _buttons.DataSource = cds;
+
+ AddControl(_buttons);
+ return Task.CompletedTask;
+ }
+
+ private async Task __buttons_ButtonClicked(object sender, ButtonClickedEventArgs e)
+ {
+ switch (e.Button.Value)
+ {
+ case "back":
+
+ var mn = new Menu();
+ await NavigateTo(mn);
+
+ break;
+ }
+ }
+}
diff --git a/TelegramBotBase.Test/Tests/Datasources/CustomDataSource.cs b/TelegramBotBase.Test/Tests/Datasources/CustomDataSource.cs
deleted file mode 100644
index 1e418e8..0000000
--- a/TelegramBotBase.Test/Tests/Datasources/CustomDataSource.cs
+++ /dev/null
@@ -1,143 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using Newtonsoft.Json;
-using TelegramBotBase.Controls.Hybrid;
-using TelegramBotBase.DataSources;
-using TelegramBotBase.Form;
-
-namespace TelegramBotBaseTest.Tests.Datasources
-{
- public class CustomDataSource : ButtonFormDataSource
- {
-
- public List Countries = new List { "Country 1", "Country 2", "Country 3" };
-
- public CustomDataSource()
- {
- LoadData();
- }
-
- ///
- /// This method has the example purpose of creating and loading some example data.
- /// When using a database you do not need this kind of method.
- ///
- private void LoadData()
- {
- //Exists data source? Read it
- if (File.Exists(AppContext.BaseDirectory + "countries.json"))
- {
- try
- {
- var list = JsonConvert.DeserializeObject>(File.ReadAllText("countries.json"));
-
-
- Countries = list;
- }
- catch
- {
-
- }
-
-
- return;
- }
-
- //If not, create it
- try
- {
- var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Select(a => a.DisplayName).ToList();
-
- Countries = countries;
-
- var tmp = JsonConvert.SerializeObject(countries);
-
- File.WriteAllText( AppContext.BaseDirectory + "countries.json", tmp);
- }
- catch
- {
-
- }
-
- }
-
- public override ButtonRow ItemAt(int index)
- {
- var item = Countries.ElementAt(index);
- if (item == null)
- return new ButtonRow();
-
- return Render(item);
- }
-
- public override List ItemRange(int start, int count)
- {
- var items = Countries.Skip(start).Take(count);
-
- var lst = new List();
- foreach (var c in items)
- {
- lst.Add(Render(c));
- }
-
- return lst;
- }
-
- public override List AllItems()
- {
- var lst = new List();
- foreach (var c in Countries)
- {
- lst.Add(Render(c));
- }
- return lst;
- }
-
- public override ButtonForm PickItems(int start, int count, string filter = null)
- {
- var rows = ItemRange(start, count);
-
- var lst = new ButtonForm();
- foreach (var c in rows)
- {
- lst.AddButtonRow(c);
- }
- return lst;
- }
-
- public override ButtonForm PickAllItems(string filter = null)
- {
- var rows = AllItems();
-
- var bf = new ButtonForm();
-
- bf.AddButtonRows(rows);
-
- return bf;
- }
-
- public override int CalculateMax(string filter = null)
- {
- if (filter == null)
- return Countries.Count;
-
- return Countries.Where(a => a.IndexOf(filter, StringComparison.InvariantCultureIgnoreCase) != -1).Count();
- }
-
- public override ButtonRow Render(object data)
- {
- if (!(data is string s))
- return new ButtonRow(new ButtonBase("Empty", "zero"));
-
- return new ButtonRow(new ButtonBase(s, s));
- }
-
- public override int Count => Countries.Count;
-
- public override int ColumnCount => 1;
-
- public override int RowCount => Count;
- }
-}
diff --git a/TelegramBotBase.Test/Tests/Datasources/List.cs b/TelegramBotBase.Test/Tests/Datasources/List.cs
deleted file mode 100644
index d73d92a..0000000
--- a/TelegramBotBase.Test/Tests/Datasources/List.cs
+++ /dev/null
@@ -1,55 +0,0 @@
-using System.Threading.Tasks;
-using TelegramBotBase.Args;
-using TelegramBotBase.Controls.Hybrid;
-using TelegramBotBase.Enums;
-using TelegramBotBase.Form;
-
-namespace TelegramBotBaseTest.Tests.Datasources
-{
- public class List : FormBase
- {
- private ButtonGrid _buttons;
-
- public List()
- {
- Init += List_Init;
- }
-
- private Task List_Init(object sender, InitEventArgs e)
- {
-
- _buttons = new ButtonGrid
- {
- EnablePaging = true,
- EnableSearch = false
- };
-
- _buttons.ButtonClicked += __buttons_ButtonClicked;
- _buttons.KeyboardType = EKeyboardType.ReplyKeyboard;
- _buttons.DeleteReplyMessage = true;
-
- _buttons.HeadLayoutButtonRow = new ButtonRow(new ButtonBase("Back", "back"));
-
- var cds = new CustomDataSource();
- _buttons.DataSource = cds;
-
- AddControl(_buttons);
- return Task.CompletedTask;
- }
-
- private async Task __buttons_ButtonClicked(object sender, ButtonClickedEventArgs e)
- {
- switch(e.Button.Value)
- {
- case "back":
-
- var mn = new Menu();
- await NavigateTo(mn);
-
- break;
- }
- }
-
-
- }
-}
diff --git a/TelegramBotBase.Test/Tests/Groups/GroupChange.cs b/TelegramBotBase.Test/Tests/Groups/GroupChange.cs
index 1d75ccf..fd984b6 100644
--- a/TelegramBotBase.Test/Tests/Groups/GroupChange.cs
+++ b/TelegramBotBase.Test/Tests/Groups/GroupChange.cs
@@ -4,71 +4,69 @@ using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests.Groups
+namespace TelegramBotBaseTest.Tests.Groups;
+
+public class GroupChange : GroupForm
{
- public class GroupChange : GroupForm
+ public GroupChange()
{
- public GroupChange()
- {
- Opened += GroupChange_Opened;
- }
-
-
- private async Task GroupChange_Opened(object sender, EventArgs e)
- {
-
- var bf = new ButtonForm();
-
- bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange"));
- bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser"));
- bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace"));
-
- await Device.Send("GroupChange started, click to switch", bf);
-
- }
-
- public override async Task Action(MessageResult message)
- {
- if (message.Handled)
- return;
-
-
- var bn = message.RawData;
-
- await message.ConfirmAction();
- message.Handled = true;
-
- switch (bn)
- {
- case "groupchange":
-
- var gc = new GroupChange();
-
- await NavigateTo(gc);
-
- break;
- case "welcomeuser":
-
- var wu = new WelcomeUser();
-
- await NavigateTo(wu);
-
- break;
- case "linkreplace":
-
- var lr = new LinkReplaceTest();
-
- await NavigateTo(lr);
-
- break;
- }
-
- }
-
- public override async Task OnGroupChanged(GroupChangedEventArgs e)
- {
- await Device.Send("Group has been changed by " + e.OriginalMessage.Message.From.FirstName + " " + e.OriginalMessage.Message.From.LastName);
- }
-
+ Opened += GroupChange_Opened;
}
-}
+
+
+ private async Task GroupChange_Opened(object sender, EventArgs e)
+ {
+ var bf = new ButtonForm();
+
+ bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange"));
+ bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser"));
+ bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace"));
+
+ await Device.Send("GroupChange started, click to switch", bf);
+ }
+
+ public override async Task Action(MessageResult message)
+ {
+ if (message.Handled)
+ {
+ return;
+ }
+
+
+ var bn = message.RawData;
+
+ await message.ConfirmAction();
+ message.Handled = true;
+
+ switch (bn)
+ {
+ case "groupchange":
+
+ var gc = new GroupChange();
+
+ await NavigateTo(gc);
+
+ break;
+ case "welcomeuser":
+
+ var wu = new WelcomeUser();
+
+ await NavigateTo(wu);
+
+ break;
+ case "linkreplace":
+
+ var lr = new LinkReplaceTest();
+
+ await NavigateTo(lr);
+
+ break;
+ }
+ }
+
+ public override async Task OnGroupChanged(GroupChangedEventArgs e)
+ {
+ await Device.Send("Group has been changed by " + e.OriginalMessage.Message.From.FirstName + " " +
+ e.OriginalMessage.Message.From.LastName);
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Groups/LinkReplaceTest.cs b/TelegramBotBase.Test/Tests/Groups/LinkReplaceTest.cs
index 243d7d4..dd36756 100644
--- a/TelegramBotBase.Test/Tests/Groups/LinkReplaceTest.cs
+++ b/TelegramBotBase.Test/Tests/Groups/LinkReplaceTest.cs
@@ -7,159 +7,159 @@ using Telegram.Bot.Types.Enums;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests.Groups
+namespace TelegramBotBaseTest.Tests.Groups;
+
+public class LinkReplaceTest : GroupForm
{
- public class LinkReplaceTest : GroupForm
+ private const int Maximum = 3;
+
+
+ public LinkReplaceTest()
{
- private Dictionary Counter { get; set; } = new Dictionary();
-
- private const int Maximum = 3;
-
-
- public LinkReplaceTest()
- {
- Opened += LinkReplaceTest_Opened;
- }
-
- private async Task LinkReplaceTest_Opened(object sender, EventArgs e)
- {
-
- var bf = new ButtonForm();
-
- bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange"));
- bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser"));
- bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace"));
-
- await Device.Send("LinkReplaceTest started, click to switch", bf);
-
- }
-
- public override async Task Action(MessageResult message)
- {
- if (message.Handled)
- return;
-
- var bn = message.RawData;
-
- await message.ConfirmAction();
- message.Handled = true;
-
- switch (bn)
- {
- case "groupchange":
-
- var gc = new GroupChange();
-
- await NavigateTo(gc);
-
- break;
- case "welcomeuser":
-
- var wu = new WelcomeUser();
-
- await NavigateTo(wu);
-
- break;
- case "linkreplace":
-
- var lr = new LinkReplaceTest();
-
- await NavigateTo(lr);
-
- break;
- }
-
- }
-
- public override async Task OnMessage(MessageResult e)
- {
- var from = e.Message.From.Id;
-
- if (e.Message.From.IsBot)
- return;
-
- //Are urls inside his message ?
- if (!HasLinks(e.MessageText))
- return;
-
- var u = await Device.GetChatUser(from);
-
- //Don't kick Admins or Creators
- if (u.Status == ChatMemberStatus.Administrator | u.Status == ChatMemberStatus.Creator)
- {
- await Device.Send("You won't get kicked,...not this time.");
- return;
- }
-
- await e.Device.DeleteMessage(e.MessageId);
-
- var cp = new ChatPermissions
- {
- CanAddWebPagePreviews = false,
- CanChangeInfo = false,
- CanInviteUsers = false,
- CanPinMessages = false,
- CanSendMediaMessages = false,
- CanSendMessages = false,
- CanSendOtherMessages = false,
- CanSendPolls = false
- };
-
- //Collect user "mistakes" with sending url, after 3 he gets kicked out.
- if (Counter.ContainsKey(from))
- {
- Counter[from]++;
- }
- else
- {
- Counter[from] = 1;
- }
-
-
- if (Counter[from] >= 3)
- {
- await e.Device.KickUser(from);
-
- await e.Device.Send(e.Message.From.FirstName + " " + e.Message.From.LastName + " has been removed from the group");
- }
- else
- {
- await e.Device.RestrictUser(from, cp, DateTime.UtcNow.AddSeconds(30));
-
- await e.Device.Send(e.Message.From.FirstName + " " + e.Message.From.LastName + " has been blocked for 30 seconds");
- }
-
-
-
- }
-
- ///
- /// Call onmessage also on edited message, if someone want to spoof a failed message and insert a link.
- ///
- ///
- ///
- public override async Task OnMessageEdit(MessageResult message)
- {
- await OnMessage(message);
- }
-
- ///
- /// https://stackoverflow.com/a/20651284
- ///
- ///
- ///
- private bool HasLinks(string str)
- {
- var tmp = str;
-
- var pattern = @"^(http|https|ftp|)\://|[a-zA-Z0-9\-\.]+\.[a-zA-Z](:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*[^\.\,\)\(\s]$";
- var r = new Regex(pattern);
-
- var matches = r.Matches(tmp);
-
- return (matches.Count > 0);
- }
-
-
+ Opened += LinkReplaceTest_Opened;
}
-}
+
+ private Dictionary Counter { get; } = new();
+
+ private async Task LinkReplaceTest_Opened(object sender, EventArgs e)
+ {
+ var bf = new ButtonForm();
+
+ bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange"));
+ bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser"));
+ bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace"));
+
+ await Device.Send("LinkReplaceTest started, click to switch", bf);
+ }
+
+ public override async Task Action(MessageResult message)
+ {
+ if (message.Handled)
+ {
+ return;
+ }
+
+ var bn = message.RawData;
+
+ await message.ConfirmAction();
+ message.Handled = true;
+
+ switch (bn)
+ {
+ case "groupchange":
+
+ var gc = new GroupChange();
+
+ await NavigateTo(gc);
+
+ break;
+ case "welcomeuser":
+
+ var wu = new WelcomeUser();
+
+ await NavigateTo(wu);
+
+ break;
+ case "linkreplace":
+
+ var lr = new LinkReplaceTest();
+
+ await NavigateTo(lr);
+
+ break;
+ }
+ }
+
+ public override async Task OnMessage(MessageResult e)
+ {
+ var from = e.Message.From.Id;
+
+ if (e.Message.From.IsBot)
+ {
+ return;
+ }
+
+ //Are urls inside his message ?
+ if (!HasLinks(e.MessageText))
+ {
+ return;
+ }
+
+ var u = await Device.GetChatUser(from);
+
+ //Don't kick Admins or Creators
+ if ((u.Status == ChatMemberStatus.Administrator) | (u.Status == ChatMemberStatus.Creator))
+ {
+ await Device.Send("You won't get kicked,...not this time.");
+ return;
+ }
+
+ await e.Device.DeleteMessage(e.MessageId);
+
+ var cp = new ChatPermissions
+ {
+ CanAddWebPagePreviews = false,
+ CanChangeInfo = false,
+ CanInviteUsers = false,
+ CanPinMessages = false,
+ CanSendMediaMessages = false,
+ CanSendMessages = false,
+ CanSendOtherMessages = false,
+ CanSendPolls = false
+ };
+
+ //Collect user "mistakes" with sending url, after 3 he gets kicked out.
+ if (Counter.ContainsKey(from))
+ {
+ Counter[from]++;
+ }
+ else
+ {
+ Counter[from] = 1;
+ }
+
+
+ if (Counter[from] >= 3)
+ {
+ await e.Device.KickUser(from);
+
+ await e.Device.Send(e.Message.From.FirstName + " " + e.Message.From.LastName +
+ " has been removed from the group");
+ }
+ else
+ {
+ await e.Device.RestrictUser(from, cp, DateTime.UtcNow.AddSeconds(30));
+
+ await e.Device.Send(e.Message.From.FirstName + " " + e.Message.From.LastName +
+ " has been blocked for 30 seconds");
+ }
+ }
+
+ ///
+ /// Call onmessage also on edited message, if someone want to spoof a failed message and insert a link.
+ ///
+ ///
+ ///
+ public override async Task OnMessageEdit(MessageResult message)
+ {
+ await OnMessage(message);
+ }
+
+ ///
+ /// https://stackoverflow.com/a/20651284
+ ///
+ ///
+ ///
+ private bool HasLinks(string str)
+ {
+ var tmp = str;
+
+ var pattern =
+ @"^(http|https|ftp|)\://|[a-zA-Z0-9\-\.]+\.[a-zA-Z](:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*[^\.\,\)\(\s]$";
+ var r = new Regex(pattern);
+
+ var matches = r.Matches(tmp);
+
+ return matches.Count > 0;
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs b/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs
index c700f85..3dc8048 100644
--- a/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs
+++ b/TelegramBotBase.Test/Tests/Groups/WelcomeUser.cs
@@ -6,86 +6,77 @@ using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests.Groups
+namespace TelegramBotBaseTest.Tests.Groups;
+
+public class WelcomeUser : GroupForm
{
- public class WelcomeUser : GroupForm
+ public WelcomeUser()
{
-
- public WelcomeUser()
- {
- Opened += WelcomeUser_Opened;
- }
-
-
- private async Task WelcomeUser_Opened(object sender, EventArgs e)
- {
-
- var bf = new ButtonForm();
-
- bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange"));
- bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser"));
- bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace"));
-
- await Device.Send("WelcomeUser started, click to switch", bf);
-
- }
-
- public override async Task Action(MessageResult message)
- {
- if (message.Handled)
- return;
-
- var bn = message.RawData;
-
- await message.ConfirmAction();
- message.Handled = true;
-
- switch (bn)
- {
- case "groupchange":
-
- var gc = new GroupChange();
-
- await NavigateTo(gc);
-
- break;
- case "welcomeuser":
-
- var wu = new WelcomeUser();
-
- await NavigateTo(wu);
-
- break;
- case "linkreplace":
-
- var lr = new LinkReplaceTest();
-
- await NavigateTo(lr);
-
- break;
- }
-
- }
-
- public override async Task OnMemberChanges(MemberChangeEventArgs e)
- {
-
- if (e.Type == MessageType.ChatMembersAdded)
- {
-
- await Device.Send("Welcome you new members!\r\n\r\n" + e.Members.Select(a => a.FirstName + " " + a.LastName).Aggregate((a, b) => a + "\r\n" + b));
-
- }
- else if (e.Type == MessageType.ChatMemberLeft)
- {
- await Device.Send(e.Members.Select(a => a.FirstName + " " + a.LastName).Aggregate((a, b) => a + " and " + b) + " has left the group");
-
- }
-
- }
-
-
-
-
+ Opened += WelcomeUser_Opened;
}
-}
+
+
+ private async Task WelcomeUser_Opened(object sender, EventArgs e)
+ {
+ var bf = new ButtonForm();
+
+ bf.AddButtonRow(new ButtonBase("Open GroupChange Test", "groupchange"));
+ bf.AddButtonRow(new ButtonBase("Open WelcomeUser Test", "welcomeuser"));
+ bf.AddButtonRow(new ButtonBase("Open LinkReplace Test", "linkreplace"));
+
+ await Device.Send("WelcomeUser started, click to switch", bf);
+ }
+
+ public override async Task Action(MessageResult message)
+ {
+ if (message.Handled)
+ {
+ return;
+ }
+
+ var bn = message.RawData;
+
+ await message.ConfirmAction();
+ message.Handled = true;
+
+ switch (bn)
+ {
+ case "groupchange":
+
+ var gc = new GroupChange();
+
+ await NavigateTo(gc);
+
+ break;
+ case "welcomeuser":
+
+ var wu = new WelcomeUser();
+
+ await NavigateTo(wu);
+
+ break;
+ case "linkreplace":
+
+ var lr = new LinkReplaceTest();
+
+ await NavigateTo(lr);
+
+ break;
+ }
+ }
+
+ public override async Task OnMemberChanges(MemberChangeEventArgs e)
+ {
+ if (e.Type == MessageType.ChatMembersAdded)
+ {
+ await Device.Send("Welcome you new members!\r\n\r\n" + e.Members.Select(a => a.FirstName + " " + a.LastName)
+ .Aggregate((a, b) => a + "\r\n" + b));
+ }
+ else if (e.Type == MessageType.ChatMemberLeft)
+ {
+ await Device.Send(
+ e.Members.Select(a => a.FirstName + " " + a.LastName).Aggregate((a, b) => a + " and " + b) +
+ " has left the group");
+ }
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Menu.cs b/TelegramBotBase.Test/Tests/Menu.cs
index 3f9d04d..3b161db 100644
--- a/TelegramBotBase.Test/Tests/Menu.cs
+++ b/TelegramBotBase.Test/Tests/Menu.cs
@@ -4,261 +4,262 @@ using TelegramBotBase.Base;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
using TelegramBotBaseTest.Tests.Controls;
-using TelegramBotBaseTest.Tests.Datasources;
+using TelegramBotBaseTest.Tests.DataSources;
using TelegramBotBaseTest.Tests.Groups;
-namespace TelegramBotBaseTest.Tests
+namespace TelegramBotBaseTest.Tests;
+
+public class Menu : AutoCleanForm
{
- public class Menu : AutoCleanForm
+ public Menu()
{
- public Menu()
+ DeleteMode = EDeleteMode.OnLeavingForm;
+ }
+
+ public override async Task Load(MessageResult message)
+ {
+ if ((message.Message.Chat.Type == ChatType.Group) | (message.Message.Chat.Type == ChatType.Supergroup))
{
- DeleteMode = EDeleteMode.OnLeavingForm;
+ var sf = new WelcomeUser();
+
+ await NavigateTo(sf);
}
- public override async Task Load(MessageResult message)
+
+ await Device.HideReplyKeyboard();
+ }
+
+ public override async Task Action(MessageResult message)
+ {
+ var call = message.GetData();
+
+ await message.ConfirmAction();
+
+
+ if (call == null)
{
+ return;
+ }
+ message.Handled = true;
- if (message.Message.Chat.Type == ChatType.Group | message.Message.Chat.Type == ChatType.Supergroup)
- {
- var sf = new WelcomeUser();
+ switch (call.Value)
+ {
+ case "text":
+
+ var sf = new SimpleForm();
await NavigateTo(sf);
- }
+
+ break;
+
+ case "buttons":
+
+ var bf = new ButtonTestForm();
+
+ await NavigateTo(bf);
+
+ break;
+
+ case "progress":
+
+ var pf = new ProgressTest();
+
+ await NavigateTo(pf);
+
+ break;
+
+ case "registration":
+
+ var reg = new Register.Start();
+
+ await NavigateTo(reg);
+
+ break;
+
+ case "form1":
+
+ var form1 = new TestForm();
+
+ await NavigateTo(form1);
+
+ break;
+
+ case "form2":
+
+ var form2 = new TestForm2();
+
+ await NavigateTo(form2);
+
+ break;
+
+ case "data":
+
+ var data = new DataForm();
+
+ await NavigateTo(data);
+
+ break;
+
+ case "calendar":
+
+ var calendar = new CalendarPickerForm();
+
+ await NavigateTo(calendar);
+
+ break;
+
+ case "month":
+
+ var month = new MonthPickerForm();
+
+ await NavigateTo(month);
+
+ break;
+
+ case "treeview":
+
+ var tree = new TreeViewForms();
+
+ await NavigateTo(tree);
+
+ break;
+
+ case "togglebuttons":
+
+ var tb = new ToggleButtons();
+
+ await NavigateTo(tb);
+
+ break;
+
+ case "multitogglebuttons":
+
+ var mtb = new MultiToggleButtons();
+
+ await NavigateTo(mtb);
+
+ break;
+
+ case "buttongrid":
+
+ var bg = new ButtonGridForm();
+
+ await NavigateTo(bg);
+
+ break;
+
+ case "buttongridfilter":
+
+ var bg2 = new ButtonGridPagingForm();
+
+ await NavigateTo(bg2);
+
+ break;
+
+ case "buttongridtags":
+
+ var bg3 = new ButtonGridTagForm();
+
+ await NavigateTo(bg3);
+
+ break;
+
+ case "multiview":
+
+ var mvf = new MultiViewForm();
+
+ await NavigateTo(mvf);
- await Device.HideReplyKeyboard();
+ break;
+
+ case "checkedbuttonlist":
+
+ var cbl = new CheckedButtonListForm();
+
+ await NavigateTo(cbl);
+
+
+ break;
+
+ case "navigationcontroller":
+
+ var nc = new Navigation.Start();
+
+ await NavigateTo(nc);
+
+
+ break;
+
+ case "dynamicbuttongrid":
+
+ var dg = new List();
+
+ await NavigateTo(dg);
+
+ break;
+
+ case "notifications":
+
+ var not = new Notifications.Start();
+ await NavigateTo(not);
+
+ break;
+
+ default:
+
+ message.Handled = false;
+
+ break;
}
+ }
- public override async Task Action(MessageResult message)
- {
- var call = message.GetData();
+ public override async Task Render(MessageResult message)
+ {
+ var btn = new ButtonForm();
- await message.ConfirmAction();
+ btn.AddButtonRow(new ButtonBase("#1 Simple Text", new CallbackData("a", "text").Serialize()),
+ new ButtonBase("#2 Button Test", new CallbackData("a", "buttons").Serialize()));
+ btn.AddButtonRow(new ButtonBase("#3 Progress Bar", new CallbackData("a", "progress").Serialize()));
+ btn.AddButtonRow(new ButtonBase("#4 Registration Example", new CallbackData("a", "registration").Serialize()));
+ btn.AddButtonRow(new ButtonBase("#5 Form1 Command", new CallbackData("a", "form1").Serialize()));
- if (call == null)
- return;
+ btn.AddButtonRow(new ButtonBase("#6 Form2 Command", new CallbackData("a", "form2").Serialize()));
- message.Handled = true;
+ btn.AddButtonRow(new ButtonBase("#7 Data Handling", new CallbackData("a", "data").Serialize()));
+ btn.AddButtonRow(new ButtonBase("#8 Calendar Picker", new CallbackData("a", "calendar").Serialize()));
+ btn.AddButtonRow(new ButtonBase("#9 Month Picker", new CallbackData("a", "month").Serialize()));
- switch (call.Value)
- {
- case "text":
+ btn.AddButtonRow(new ButtonBase("#10 TreeView", new CallbackData("a", "treeview").Serialize()));
- var sf = new SimpleForm();
+ btn.AddButtonRow(new ButtonBase("#11 ToggleButtons", new CallbackData("a", "togglebuttons").Serialize()));
- await NavigateTo(sf);
+ btn.AddButtonRow(new ButtonBase("#11.2 MultiToggleButtons",
+ new CallbackData("a", "multitogglebuttons").Serialize()));
- break;
+ btn.AddButtonRow(new ButtonBase("#12 ButtonGrid", new CallbackData("a", "buttongrid").Serialize()));
- case "buttons":
+ btn.AddButtonRow(new ButtonBase("#13 ButtonGrid Paging & Filter",
+ new CallbackData("a", "buttongridfilter").Serialize()));
- var bf = new ButtonTestForm();
+ btn.AddButtonRow(new ButtonBase("#14 ButtonGrid Tags (Filter)",
+ new CallbackData("a", "buttongridtags").Serialize()));
- await NavigateTo(bf);
+ btn.AddButtonRow(new ButtonBase("#15 MultiView", new CallbackData("a", "multiview").Serialize()));
- break;
+ btn.AddButtonRow(
+ new ButtonBase("#16 CheckedButtonList", new CallbackData("a", "checkedbuttonlist").Serialize()));
- case "progress":
+ btn.AddButtonRow(new ButtonBase("#17 NavigationController (Push/Pop)",
+ new CallbackData("a", "navigationcontroller").Serialize()));
- var pf = new ProgressTest();
-
- await NavigateTo(pf);
-
- break;
-
- case "registration":
-
- var reg = new Register.Start();
-
- await NavigateTo(reg);
-
- break;
-
- case "form1":
-
- var form1 = new TestForm();
-
- await NavigateTo(form1);
-
- break;
-
- case "form2":
-
- var form2 = new TestForm2();
-
- await NavigateTo(form2);
-
- break;
-
- case "data":
-
- var data = new DataForm();
-
- await NavigateTo(data);
-
- break;
-
- case "calendar":
-
- var calendar = new CalendarPickerForm();
-
- await NavigateTo(calendar);
-
- break;
-
- case "month":
-
- var month = new MonthPickerForm();
-
- await NavigateTo(month);
-
- break;
-
- case "treeview":
-
- var tree = new TreeViewForms();
-
- await NavigateTo(tree);
-
- break;
-
- case "togglebuttons":
-
- var tb = new ToggleButtons();
-
- await NavigateTo(tb);
-
- break;
-
- case "multitogglebuttons":
-
- var mtb = new MultiToggleButtons();
-
- await NavigateTo(mtb);
-
- break;
-
- case "buttongrid":
-
- var bg = new ButtonGridForm();
-
- await NavigateTo(bg);
-
- break;
-
- case "buttongridfilter":
-
- var bg2 = new ButtonGridPagingForm();
-
- await NavigateTo(bg2);
-
- break;
-
- case "buttongridtags":
-
- var bg3 = new ButtonGridTagForm();
-
- await NavigateTo(bg3);
-
- break;
-
- case "multiview":
-
- var mvf = new MultiViewForm();
-
- await NavigateTo(mvf);
-
-
- break;
-
- case "checkedbuttonlist":
-
- var cbl = new CheckedButtonListForm();
-
- await NavigateTo(cbl);
-
-
- break;
-
- case "navigationcontroller":
-
- var nc = new Navigation.Start();
-
- await NavigateTo(nc);
-
-
- break;
-
- case "dynamicbuttongrid":
-
- var dg = new List();
-
- await NavigateTo(dg);
-
- break;
-
- case "notifications":
-
- var not = new Notifications.Start();
- await NavigateTo(not);
-
- break;
-
- default:
-
- message.Handled = false;
-
- break;
- }
-
-
- }
-
- public override async Task Render(MessageResult message)
- {
-
- var btn = new ButtonForm();
-
- btn.AddButtonRow(new ButtonBase("#1 Simple Text", new CallbackData("a", "text").Serialize()), new ButtonBase("#2 Button Test", new CallbackData("a", "buttons").Serialize()));
- btn.AddButtonRow(new ButtonBase("#3 Progress Bar", new CallbackData("a", "progress").Serialize()));
- btn.AddButtonRow(new ButtonBase("#4 Registration Example", new CallbackData("a", "registration").Serialize()));
-
- btn.AddButtonRow(new ButtonBase("#5 Form1 Command", new CallbackData("a", "form1").Serialize()));
-
- btn.AddButtonRow(new ButtonBase("#6 Form2 Command", new CallbackData("a", "form2").Serialize()));
-
- btn.AddButtonRow(new ButtonBase("#7 Data Handling", new CallbackData("a", "data").Serialize()));
- btn.AddButtonRow(new ButtonBase("#8 Calendar Picker", new CallbackData("a", "calendar").Serialize()));
- btn.AddButtonRow(new ButtonBase("#9 Month Picker", new CallbackData("a", "month").Serialize()));
-
- btn.AddButtonRow(new ButtonBase("#10 TreeView", new CallbackData("a", "treeview").Serialize()));
-
- btn.AddButtonRow(new ButtonBase("#11 ToggleButtons", new CallbackData("a", "togglebuttons").Serialize()));
-
- btn.AddButtonRow(new ButtonBase("#11.2 MultiToggleButtons", new CallbackData("a", "multitogglebuttons").Serialize()));
-
- btn.AddButtonRow(new ButtonBase("#12 ButtonGrid", new CallbackData("a", "buttongrid").Serialize()));
-
- btn.AddButtonRow(new ButtonBase("#13 ButtonGrid Paging & Filter", new CallbackData("a", "buttongridfilter").Serialize()));
-
- btn.AddButtonRow(new ButtonBase("#14 ButtonGrid Tags (Filter)", new CallbackData("a", "buttongridtags").Serialize()));
-
- btn.AddButtonRow(new ButtonBase("#15 MultiView", new CallbackData("a", "multiview").Serialize()));
-
- btn.AddButtonRow(new ButtonBase("#16 CheckedButtonList", new CallbackData("a", "checkedbuttonlist").Serialize()));
-
- btn.AddButtonRow(new ButtonBase("#17 NavigationController (Push/Pop)", new CallbackData("a", "navigationcontroller").Serialize()));
-
- btn.AddButtonRow(new ButtonBase("#18 Dynamic ButtonGrid (DataSources)", new CallbackData("a", "dynamicbuttongrid").Serialize()));
-
- btn.AddButtonRow(new ButtonBase("#19 Notifications", new CallbackData("a", "notifications").Serialize()));
-
- await Device.Send("Choose your test:", btn);
- }
+ btn.AddButtonRow(new ButtonBase("#18 Dynamic ButtonGrid (DataSources)",
+ new CallbackData("a", "dynamicbuttongrid").Serialize()));
+ btn.AddButtonRow(new ButtonBase("#19 Notifications", new CallbackData("a", "notifications").Serialize()));
+ await Device.Send("Choose your test:", btn);
}
}
diff --git a/TelegramBotBase.Test/Tests/Navigation/CustomController.cs b/TelegramBotBase.Test/Tests/Navigation/CustomController.cs
index 5dff6fd..28d7015 100644
--- a/TelegramBotBase.Test/Tests/Navigation/CustomController.cs
+++ b/TelegramBotBase.Test/Tests/Navigation/CustomController.cs
@@ -3,40 +3,37 @@ using System.Threading.Tasks;
using TelegramBotBase.Form;
using TelegramBotBase.Form.Navigation;
-namespace TelegramBotBaseTest.Tests.Navigation
+namespace TelegramBotBaseTest.Tests.Navigation;
+
+internal class CustomController : NavigationController
{
- internal class CustomController : NavigationController
+ public CustomController(FormBase form) : base(form)
{
- public CustomController(FormBase form) : base(form)
- {
-
- }
-
-
- public override Task PushAsync(FormBase form, params object[] args)
- {
- Console.WriteLine($"Pushes form (Count on stack {Index + 1})");
- //Device.Send($"Pushes form (Count on stack {this.Index + 1})");
-
- return base.PushAsync(form, args);
- }
-
-
- public override Task PopAsync()
- {
- Console.WriteLine($"Pops one form (Count on stack {Index + 1})");
- //Device.Send($"Pops one form (Count on stack {this.Index + 1})");
-
- return base.PopAsync();
- }
-
- public override Task PopToRootAsync()
- {
- Console.WriteLine($"Moved back to root (Count on stack {Index + 1})");
- //Device.Send($"Moved back to root (Count on stack {this.Index + 1})");
-
- return base.PopToRootAsync();
- }
-
}
-}
+
+
+ public override Task PushAsync(FormBase form, params object[] args)
+ {
+ Console.WriteLine($"Pushes form (Count on stack {Index + 1})");
+ //Device.Send($"Pushes form (Count on stack {this.Index + 1})");
+
+ return base.PushAsync(form, args);
+ }
+
+
+ public override Task PopAsync()
+ {
+ Console.WriteLine($"Pops one form (Count on stack {Index + 1})");
+ //Device.Send($"Pops one form (Count on stack {this.Index + 1})");
+
+ return base.PopAsync();
+ }
+
+ public override Task PopToRootAsync()
+ {
+ Console.WriteLine($"Moved back to root (Count on stack {Index + 1})");
+ //Device.Send($"Moved back to root (Count on stack {this.Index + 1})");
+
+ return base.PopToRootAsync();
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Navigation/Form1.cs b/TelegramBotBase.Test/Tests/Navigation/Form1.cs
index b7270a6..c000fe7 100644
--- a/TelegramBotBase.Test/Tests/Navigation/Form1.cs
+++ b/TelegramBotBase.Test/Tests/Navigation/Form1.cs
@@ -4,83 +4,80 @@ using Telegram.Bot.Types;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests.Navigation
+namespace TelegramBotBaseTest.Tests.Navigation;
+
+public class Form1 : FormBase
{
- public class Form1 : FormBase
+ private Message _msg;
+
+ public Form1()
{
- private Message _msg;
-
- public Form1()
- {
- Closed += Form1_Closed;
- }
-
- private async Task Form1_Closed(object sender, EventArgs e)
- {
- if (_msg == null)
- return;
-
- await Device.DeleteMessage(_msg);
- }
-
- public override async Task Action(MessageResult message)
- {
- if (message.Handled)
- return;
-
- await message.ConfirmAction();
-
- switch (message.RawData)
- {
- case "next":
-
- message.Handled = true;
-
- var f1 = new Form1();
-
- await NavigationController.PushAsync(f1);
-
-
- break;
-
- case "previous":
-
- message.Handled = true;
-
- //Pop's the current form and move the previous one. The root form will be the Start class.
- await NavigationController.PopAsync();
-
- break;
-
- case "root":
-
- message.Handled = true;
-
- await NavigationController.PopToRootAsync();
-
- break;
-
-
- }
-
-
-
- }
-
- public override async Task Render(MessageResult message)
- {
- if (_msg != null)
- return;
-
- var bf = new ButtonForm();
- bf.AddButtonRow("Next page", "next");
- bf.AddButtonRow("Previous page", "previous");
- bf.AddButtonRow("Back to root", "root");
-
- _msg = await Device.Send($"Choose your options (Count on stack {NavigationController.Index + 1})", bf);
-
- }
-
-
+ Closed += Form1_Closed;
}
-}
+
+ private async Task Form1_Closed(object sender, EventArgs e)
+ {
+ if (_msg == null)
+ {
+ return;
+ }
+
+ await Device.DeleteMessage(_msg);
+ }
+
+ public override async Task Action(MessageResult message)
+ {
+ if (message.Handled)
+ {
+ return;
+ }
+
+ await message.ConfirmAction();
+
+ switch (message.RawData)
+ {
+ case "next":
+
+ message.Handled = true;
+
+ var f1 = new Form1();
+
+ await NavigationController.PushAsync(f1);
+
+
+ break;
+
+ case "previous":
+
+ message.Handled = true;
+
+ //Pop's the current form and move the previous one. The root form will be the Start class.
+ await NavigationController.PopAsync();
+
+ break;
+
+ case "root":
+
+ message.Handled = true;
+
+ await NavigationController.PopToRootAsync();
+
+ break;
+ }
+ }
+
+ public override async Task Render(MessageResult message)
+ {
+ if (_msg != null)
+ {
+ return;
+ }
+
+ var bf = new ButtonForm();
+ bf.AddButtonRow("Next page", "next");
+ bf.AddButtonRow("Previous page", "previous");
+ bf.AddButtonRow("Back to root", "root");
+
+ _msg = await Device.Send($"Choose your options (Count on stack {NavigationController.Index + 1})", bf);
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Navigation/Start.cs b/TelegramBotBase.Test/Tests/Navigation/Start.cs
index 2599ff3..034a653 100644
--- a/TelegramBotBase.Test/Tests/Navigation/Start.cs
+++ b/TelegramBotBase.Test/Tests/Navigation/Start.cs
@@ -3,77 +3,78 @@ using Telegram.Bot.Types;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests.Navigation
+namespace TelegramBotBaseTest.Tests.Navigation;
+
+public class Start : FormBase
{
- public class Start : FormBase
+ private Message _msg;
+
+
+ public override Task Load(MessageResult message)
{
- private Message _msg;
-
-
- public override Task Load(MessageResult message)
- {
- return Task.CompletedTask;
- }
-
- public override async Task Action(MessageResult message)
- {
- if (message.Handled)
- return;
-
- await message.ConfirmAction();
-
- switch (message.RawData)
- {
- case "yes":
-
- message.Handled = true;
-
- //Create navigation controller and navigate to it, keep the current form as root form so we can get back to here later
- var nc = new CustomController(this);
- nc.ForceCleanupOnLastPop = true;
-
- var f1 = new Form1();
-
- await nc.PushAsync(f1);
-
- await NavigateTo(nc);
-
- if (_msg == null)
- return;
-
- await Device.DeleteMessage(_msg);
-
-
- break;
- case "no":
-
- message.Handled = true;
-
- var mn = new Menu();
-
- await NavigateTo(mn);
-
- if (_msg == null)
- return;
-
- await Device.DeleteMessage(_msg);
-
- break;
- }
-
- }
-
- public override async Task Render(MessageResult message)
- {
- var bf = new ButtonForm();
-
- bf.AddButtonRow("Yes", "yes");
- bf.AddButtonRow("No", "no");
-
- _msg = await Device.Send("Open controller?", bf);
-
-
- }
-
+ return Task.CompletedTask;
}
-}
+
+ public override async Task Action(MessageResult message)
+ {
+ if (message.Handled)
+ {
+ return;
+ }
+
+ await message.ConfirmAction();
+
+ switch (message.RawData)
+ {
+ case "yes":
+
+ message.Handled = true;
+
+ //Create navigation controller and navigate to it, keep the current form as root form so we can get back to here later
+ var nc = new CustomController(this);
+ nc.ForceCleanupOnLastPop = true;
+
+ var f1 = new Form1();
+
+ await nc.PushAsync(f1);
+
+ await NavigateTo(nc);
+
+ if (_msg == null)
+ {
+ return;
+ }
+
+ await Device.DeleteMessage(_msg);
+
+
+ break;
+ case "no":
+
+ message.Handled = true;
+
+ var mn = new Menu();
+
+ await NavigateTo(mn);
+
+ if (_msg == null)
+ {
+ return;
+ }
+
+ await Device.DeleteMessage(_msg);
+
+ break;
+ }
+ }
+
+ public override async Task Render(MessageResult message)
+ {
+ var bf = new ButtonForm();
+
+ bf.AddButtonRow("Yes", "yes");
+ bf.AddButtonRow("No", "no");
+
+ _msg = await Device.Send("Open controller?", bf);
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Notifications/Start.cs b/TelegramBotBase.Test/Tests/Notifications/Start.cs
index 702a9e7..a04b770 100644
--- a/TelegramBotBase.Test/Tests/Notifications/Start.cs
+++ b/TelegramBotBase.Test/Tests/Notifications/Start.cs
@@ -3,59 +3,59 @@ using TelegramBotBase.Base;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests.Notifications
+namespace TelegramBotBaseTest.Tests.Notifications;
+
+public class Start : AutoCleanForm
{
- public class Start : AutoCleanForm
+ private bool _sent;
+
+ public Start()
{
- private bool _sent;
-
- public Start()
- {
- DeleteMode = EDeleteMode.OnLeavingForm;
- }
-
- public override async Task Action(MessageResult message)
- {
- if (message.Handled)
- return;
-
- switch (message.RawData)
- {
- case "alert":
-
- await message.ConfirmAction("This is an alert.", true);
-
- break;
- case "back":
-
- var mn = new Menu();
- await NavigateTo(mn);
-
- break;
- default:
-
- await message.ConfirmAction("This is feedback");
-
- break;
-
- }
-
- }
-
- public override async Task Render(MessageResult message)
- {
- if (_sent)
- return;
-
- var bf = new ButtonForm();
- bf.AddButtonRow("Normal feeback", "normal");
- bf.AddButtonRow("Alert Box", "alert");
- bf.AddButtonRow("Back", "back");
-
- await Device.Send("Choose your test", bf);
-
- _sent = true;
- }
-
+ DeleteMode = EDeleteMode.OnLeavingForm;
}
-}
+
+ public override async Task Action(MessageResult message)
+ {
+ if (message.Handled)
+ {
+ return;
+ }
+
+ switch (message.RawData)
+ {
+ case "alert":
+
+ await message.ConfirmAction("This is an alert.", true);
+
+ break;
+ case "back":
+
+ var mn = new Menu();
+ await NavigateTo(mn);
+
+ break;
+ default:
+
+ await message.ConfirmAction("This is feedback");
+
+ break;
+ }
+ }
+
+ public override async Task Render(MessageResult message)
+ {
+ if (_sent)
+ {
+ return;
+ }
+
+ var bf = new ButtonForm();
+ bf.AddButtonRow("Normal feeback", "normal");
+ bf.AddButtonRow("Alert Box", "alert");
+ bf.AddButtonRow("Back", "back");
+
+ await Device.Send("Choose your test", bf);
+
+ _sent = true;
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/ProgressTest.cs b/TelegramBotBase.Test/Tests/ProgressTest.cs
index 0657c82..a8dcf70 100644
--- a/TelegramBotBase.Test/Tests/ProgressTest.cs
+++ b/TelegramBotBase.Test/Tests/ProgressTest.cs
@@ -6,133 +6,131 @@ using TelegramBotBase.Controls.Inline;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests
+namespace TelegramBotBaseTest.Tests;
+
+public class ProgressTest : AutoCleanForm
{
- public class ProgressTest : AutoCleanForm
+ public ProgressTest()
{
+ DeleteMode = EDeleteMode.OnLeavingForm;
+ Opened += ProgressTest_Opened;
+ Closed += ProgressTest_Closed;
+ }
- public ProgressTest()
+
+ private async Task ProgressTest_Opened(object sender, EventArgs e)
+ {
+ await Device.Send("Welcome to ProgressTest");
+ }
+
+ public override async Task Action(MessageResult message)
+ {
+ var call = message.GetData();
+
+ await message.ConfirmAction();
+
+
+ if (call == null)
{
- DeleteMode = EDeleteMode.OnLeavingForm;
- Opened += ProgressTest_Opened;
- Closed += ProgressTest_Closed;
+ return;
}
+ ProgressBar bar = null;
- private async Task ProgressTest_Opened(object sender, EventArgs e)
+ switch (call.Value)
{
- await Device.Send("Welcome to ProgressTest");
- }
+ case "standard":
- public override async Task Action(MessageResult message)
- {
- var call = message.GetData();
+ bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.standard)
+ {
+ Device = Device
+ };
- await message.ConfirmAction();
+ break;
+ case "squares":
+
+ bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.squares)
+ {
+ Device = Device
+ };
+
+ break;
+
+ case "circles":
+
+ bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.circles)
+ {
+ Device = Device
+ };
+
+ break;
+
+ case "lines":
+
+ bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.lines)
+ {
+ Device = Device
+ };
+
+ break;
+
+ case "squaredlines":
+
+ bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.squaredLines)
+ {
+ Device = Device
+ };
+
+ break;
+
+ case "start":
+
+ var sf = new Menu();
+
+ await NavigateTo(sf);
- if (call == null)
return;
- ProgressBar bar = null;
+ default:
- switch (call.Value)
- {
- case "standard":
-
- bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.standard)
- {
- Device = Device
- };
-
- break;
-
- case "squares":
-
- bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.squares)
- {
- Device = Device
- };
-
- break;
-
- case "circles":
-
- bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.circles)
- {
- Device = Device
- };
-
- break;
-
- case "lines":
-
- bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.lines)
- {
- Device = Device
- };
-
- break;
-
- case "squaredlines":
-
- bar = new ProgressBar(0, 100, ProgressBar.EProgressStyle.squaredLines)
- {
- Device = Device
- };
-
- break;
-
- case "start":
-
- var sf = new Menu();
-
- await NavigateTo(sf);
-
- return;
-
- default:
-
- return;
-
- }
+ return;
+ }
- //Render Progress bar and show some "example" progress
+ //Render Progress bar and show some "example" progress
+ await bar.Render(message);
+
+ Controls.Add(bar);
+
+ for (var i = 0; i <= 100; i++)
+ {
+ bar.Value++;
await bar.Render(message);
- Controls.Add(bar);
-
- for (var i = 0; i <= 100; i++)
- {
- bar.Value++;
- await bar.Render(message);
-
- Thread.Sleep(250);
- }
-
-
+ Thread.Sleep(250);
}
-
-
- public override async Task Render(MessageResult message)
- {
- var btn = new ButtonForm();
- btn.AddButtonRow(new ButtonBase("Standard", new CallbackData("a", "standard").Serialize()), new ButtonBase("Squares", new CallbackData("a", "squares").Serialize()));
-
- btn.AddButtonRow(new ButtonBase("Circles", new CallbackData("a", "circles").Serialize()), new ButtonBase("Lines", new CallbackData("a", "lines").Serialize()));
-
- btn.AddButtonRow(new ButtonBase("Squared Line", new CallbackData("a", "squaredlines").Serialize()));
-
- btn.AddButtonRow(new ButtonBase("Back to start", new CallbackData("a", "start").Serialize()));
-
- await Device.Send("Choose your progress bar:", btn);
- }
-
- private async Task ProgressTest_Closed(object sender, EventArgs e)
- {
- await Device.Send("Ciao from ProgressTest");
- }
-
}
-}
+
+
+ public override async Task Render(MessageResult message)
+ {
+ var btn = new ButtonForm();
+ btn.AddButtonRow(new ButtonBase("Standard", new CallbackData("a", "standard").Serialize()),
+ new ButtonBase("Squares", new CallbackData("a", "squares").Serialize()));
+
+ btn.AddButtonRow(new ButtonBase("Circles", new CallbackData("a", "circles").Serialize()),
+ new ButtonBase("Lines", new CallbackData("a", "lines").Serialize()));
+
+ btn.AddButtonRow(new ButtonBase("Squared Line", new CallbackData("a", "squaredlines").Serialize()));
+
+ btn.AddButtonRow(new ButtonBase("Back to start", new CallbackData("a", "start").Serialize()));
+
+ await Device.Send("Choose your progress bar:", btn);
+ }
+
+ private async Task ProgressTest_Closed(object sender, EventArgs e)
+ {
+ await Device.Send("Ciao from ProgressTest");
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Register/PerForm.cs b/TelegramBotBase.Test/Tests/Register/PerForm.cs
index ab703f7..fde7e05 100644
--- a/TelegramBotBase.Test/Tests/Register/PerForm.cs
+++ b/TelegramBotBase.Test/Tests/Register/PerForm.cs
@@ -2,99 +2,97 @@
using TelegramBotBase.Base;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests.Register
+namespace TelegramBotBaseTest.Tests.Register;
+
+public class PerForm : AutoCleanForm
{
- public class PerForm : AutoCleanForm
+ public string EMail { get; set; }
+
+ public string Firstname { get; set; }
+
+ public string Lastname { get; set; }
+
+ public override Task Load(MessageResult message)
{
- public string EMail { get; set; }
-
- public string Firstname { get; set; }
-
- public string Lastname { get; set; }
-
- public override Task Load(MessageResult message)
+ if (message.MessageText.Trim() == "")
{
- if (message.MessageText.Trim() == "")
- return Task.CompletedTask;
-
- if (Firstname == null)
- {
- Firstname = message.MessageText;
- return Task.CompletedTask;
- }
-
- if (Lastname == null)
- {
- Lastname = message.MessageText;
- return Task.CompletedTask;
- }
-
- if (EMail == null)
- {
- EMail = message.MessageText;
- return Task.CompletedTask;
- }
-
return Task.CompletedTask;
}
- public override async Task Action(MessageResult message)
+ if (Firstname == null)
{
- var call = message.GetData();
-
- await message.ConfirmAction();
-
- if (call == null)
- return;
-
- switch (call.Value)
- {
- case "back":
-
- var start = new Start();
-
- await NavigateTo(start);
-
- break;
-
- }
-
-
+ Firstname = message.MessageText;
+ return Task.CompletedTask;
}
- public override async Task Render(MessageResult message)
+ if (Lastname == null)
{
- if (Firstname == null)
- {
- await Device.Send("Please sent your firstname:");
- return;
- }
-
- if (Lastname == null)
- {
- await Device.Send("Please sent your lastname:");
- return;
- }
-
- if (EMail == null)
- {
- await Device.Send("Please sent your email address:");
- return;
- }
-
-
- var s = "";
-
- s += "Firstname: " + Firstname + "\r\n";
- s += "Lastname: " + Lastname + "\r\n";
- s += "E-Mail: " + EMail + "\r\n";
-
- var bf = new ButtonForm();
- bf.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "back").Serialize()));
-
- await Device.Send("Your details:\r\n" + s, bf);
+ Lastname = message.MessageText;
+ return Task.CompletedTask;
}
+ if (EMail == null)
+ {
+ EMail = message.MessageText;
+ return Task.CompletedTask;
+ }
+ return Task.CompletedTask;
}
-}
+
+ public override async Task Action(MessageResult message)
+ {
+ var call = message.GetData();
+
+ await message.ConfirmAction();
+
+ if (call == null)
+ {
+ return;
+ }
+
+ switch (call.Value)
+ {
+ case "back":
+
+ var start = new Start();
+
+ await NavigateTo(start);
+
+ break;
+ }
+ }
+
+ public override async Task Render(MessageResult message)
+ {
+ if (Firstname == null)
+ {
+ await Device.Send("Please sent your firstname:");
+ return;
+ }
+
+ if (Lastname == null)
+ {
+ await Device.Send("Please sent your lastname:");
+ return;
+ }
+
+ if (EMail == null)
+ {
+ await Device.Send("Please sent your email address:");
+ return;
+ }
+
+
+ var s = "";
+
+ s += "Firstname: " + Firstname + "\r\n";
+ s += "Lastname: " + Lastname + "\r\n";
+ s += "E-Mail: " + EMail + "\r\n";
+
+ var bf = new ButtonForm();
+ bf.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "back").Serialize()));
+
+ await Device.Send("Your details:\r\n" + s, bf);
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Register/PerStep.cs b/TelegramBotBase.Test/Tests/Register/PerStep.cs
index b31779a..437dbce 100644
--- a/TelegramBotBase.Test/Tests/Register/PerStep.cs
+++ b/TelegramBotBase.Test/Tests/Register/PerStep.cs
@@ -3,42 +3,39 @@ using TelegramBotBase.Base;
using TelegramBotBase.Form;
using TelegramBotBaseTest.Tests.Register.Steps;
-namespace TelegramBotBaseTest.Tests.Register
+namespace TelegramBotBaseTest.Tests.Register;
+
+public class PerStep : AutoCleanForm
{
- public class PerStep: AutoCleanForm
+ public override async Task Action(MessageResult message)
{
+ await message.ConfirmAction();
- public override async Task Action(MessageResult message)
+ switch (message.RawData)
{
- await message.ConfirmAction();
+ case "start":
- switch (message.RawData)
- {
- case "start":
+ var step1 = new Step1();
- var step1 = new Step1();
+ await NavigateTo(step1);
- await NavigateTo(step1);
+ break;
+ case "back":
- break;
- case "back":
+ var start = new Start();
- var start = new Start();
+ await NavigateTo(start);
- await NavigateTo(start);
-
- break;
-
- }
- }
-
- public override async Task Render(MessageResult message)
- {
- var bf = new ButtonForm();
- bf.AddButtonRow(new ButtonBase("Goto Step 1", "start"));
- bf.AddButtonRow(new ButtonBase("Back", "back"));
-
- await Device.Send("Register Steps", bf);
+ break;
}
}
-}
+
+ public override async Task Render(MessageResult message)
+ {
+ var bf = new ButtonForm();
+ bf.AddButtonRow(new ButtonBase("Goto Step 1", "start"));
+ bf.AddButtonRow(new ButtonBase("Back", "back"));
+
+ await Device.Send("Register Steps", bf);
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Register/Start.cs b/TelegramBotBase.Test/Tests/Register/Start.cs
index a37c5c7..09b3516 100644
--- a/TelegramBotBase.Test/Tests/Register/Start.cs
+++ b/TelegramBotBase.Test/Tests/Register/Start.cs
@@ -2,62 +2,56 @@
using TelegramBotBase.Base;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests.Register
+namespace TelegramBotBaseTest.Tests.Register;
+
+public class Start : AutoCleanForm
{
- public class Start : AutoCleanForm
+ public override async Task Action(MessageResult message)
{
- public override async Task Action(MessageResult message)
+ var call = message.GetData();
+
+ await message.ConfirmAction();
+
+
+ if (call == null)
{
- var call = message.GetData();
-
- await message.ConfirmAction();
-
-
- if (call == null)
- return;
-
- switch (call.Value)
- {
- case "form":
-
- var form = new PerForm();
-
- await NavigateTo(form);
-
- break;
- case "step":
-
- var step = new PerStep();
-
- await NavigateTo(step);
-
- break;
- case "backtodashboard":
-
- var start = new Menu();
-
- await NavigateTo(start);
-
- break;
- }
-
-
+ return;
}
- public override async Task Render(MessageResult message)
+ switch (call.Value)
{
+ case "form":
- var btn = new ButtonForm();
+ var form = new PerForm();
- btn.AddButtonRow(new ButtonBase("#4.1 Per Form", new CallbackData("a", "form").Serialize()));
- btn.AddButtonRow(new ButtonBase("#4.2 Per Step", new CallbackData("a", "step").Serialize()));
- btn.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "backtodashboard").Serialize()));
+ await NavigateTo(form);
- await Device.Send("Choose your test:", btn);
+ break;
+ case "step":
+ var step = new PerStep();
+ await NavigateTo(step);
+
+ break;
+ case "backtodashboard":
+
+ var start = new Menu();
+
+ await NavigateTo(start);
+
+ break;
}
-
-
}
-}
+
+ public override async Task Render(MessageResult message)
+ {
+ var btn = new ButtonForm();
+
+ btn.AddButtonRow(new ButtonBase("#4.1 Per Form", new CallbackData("a", "form").Serialize()));
+ btn.AddButtonRow(new ButtonBase("#4.2 Per Step", new CallbackData("a", "step").Serialize()));
+ btn.AddButtonRow(new ButtonBase("Back", new CallbackData("a", "backtodashboard").Serialize()));
+
+ await Device.Send("Choose your test:", btn);
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Register/Steps/Data.cs b/TelegramBotBase.Test/Tests/Register/Steps/Data.cs
index fab243b..63a56ff 100644
--- a/TelegramBotBase.Test/Tests/Register/Steps/Data.cs
+++ b/TelegramBotBase.Test/Tests/Register/Steps/Data.cs
@@ -1,12 +1,10 @@
-namespace TelegramBotBaseTest.Tests.Register.Steps
+namespace TelegramBotBaseTest.Tests.Register.Steps;
+
+public class Data
{
- public class Data
- {
- public string EMail { get; set; }
+ public string EMail { get; set; }
- public string Firstname { get; set; }
+ public string Firstname { get; set; }
- public string Lastname { get; set; }
-
- }
-}
+ public string Lastname { get; set; }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Register/Steps/Step1.cs b/TelegramBotBase.Test/Tests/Register/Steps/Step1.cs
index 0b0616d..3cf1570 100644
--- a/TelegramBotBase.Test/Tests/Register/Steps/Step1.cs
+++ b/TelegramBotBase.Test/Tests/Register/Steps/Step1.cs
@@ -3,57 +3,59 @@ using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests.Register.Steps
+namespace TelegramBotBaseTest.Tests.Register.Steps;
+
+public class Step1 : AutoCleanForm
{
- public class Step1 : AutoCleanForm
+ public Step1()
{
- public Data UserData { get; set; }
-
- public Step1()
- {
- Init += Step1_Init;
- }
-
- private Task Step1_Init(object sender, InitEventArgs e)
- {
- UserData = new Data();
- return Task.CompletedTask;
- }
-
-
- public override Task Load(MessageResult message)
- {
- if (message.Handled)
- return Task.CompletedTask;
-
- if (message.MessageText.Trim() == "")
- return Task.CompletedTask;
-
- if (UserData.Firstname == null)
- {
- UserData.Firstname = message.MessageText;
- return Task.CompletedTask;
- }
-
- return Task.CompletedTask;
- }
-
- public override async Task Render(MessageResult message)
- {
- if (UserData.Firstname == null)
- {
- await Device.Send("Please sent your firstname:");
- return;
- }
-
- message.Handled = true;
-
- var step2 = new Step2();
-
- step2.UserData = UserData;
-
- await NavigateTo(step2);
- }
-
+ Init += Step1_Init;
}
-}
+
+ public Data UserData { get; set; }
+
+ private Task Step1_Init(object sender, InitEventArgs e)
+ {
+ UserData = new Data();
+ return Task.CompletedTask;
+ }
+
+
+ public override Task Load(MessageResult message)
+ {
+ if (message.Handled)
+ {
+ return Task.CompletedTask;
+ }
+
+ if (message.MessageText.Trim() == "")
+ {
+ return Task.CompletedTask;
+ }
+
+ if (UserData.Firstname == null)
+ {
+ UserData.Firstname = message.MessageText;
+ return Task.CompletedTask;
+ }
+
+ return Task.CompletedTask;
+ }
+
+ public override async Task Render(MessageResult message)
+ {
+ if (UserData.Firstname == null)
+ {
+ await Device.Send("Please sent your firstname:");
+ return;
+ }
+
+ message.Handled = true;
+
+ var step2 = new Step2();
+
+ step2.UserData = UserData;
+
+ await NavigateTo(step2);
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Register/Steps/Step2.cs b/TelegramBotBase.Test/Tests/Register/Steps/Step2.cs
index 5a954f4..fffd190 100644
--- a/TelegramBotBase.Test/Tests/Register/Steps/Step2.cs
+++ b/TelegramBotBase.Test/Tests/Register/Steps/Step2.cs
@@ -2,47 +2,49 @@
using TelegramBotBase.Base;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests.Register.Steps
+namespace TelegramBotBaseTest.Tests.Register.Steps;
+
+public class Step2 : AutoCleanForm
{
- public class Step2 : AutoCleanForm
+ public Data UserData { get; set; }
+
+
+ public override Task Load(MessageResult message)
{
- public Data UserData { get; set; }
-
-
- public override Task Load(MessageResult message)
+ if (message.Handled)
{
- if (message.Handled)
- return Task.CompletedTask;
-
- if (message.MessageText.Trim() == "")
- return Task.CompletedTask;
-
- if (UserData.Lastname == null)
- {
- UserData.Lastname = message.MessageText;
- return Task.CompletedTask;
- }
-
return Task.CompletedTask;
}
-
- public override async Task Render(MessageResult message)
+ if (message.MessageText.Trim() == "")
{
- if (UserData.Lastname == null)
- {
- await Device.Send("Please sent your lastname:");
- return;
- }
-
- message.Handled = true;
-
- var step3 = new Step3();
-
- step3.UserData = UserData;
-
- await NavigateTo(step3);
+ return Task.CompletedTask;
}
+ if (UserData.Lastname == null)
+ {
+ UserData.Lastname = message.MessageText;
+ return Task.CompletedTask;
+ }
+
+ return Task.CompletedTask;
}
-}
+
+
+ public override async Task Render(MessageResult message)
+ {
+ if (UserData.Lastname == null)
+ {
+ await Device.Send("Please sent your lastname:");
+ return;
+ }
+
+ message.Handled = true;
+
+ var step3 = new Step3();
+
+ step3.UserData = UserData;
+
+ await NavigateTo(step3);
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Register/Steps/Step3.cs b/TelegramBotBase.Test/Tests/Register/Steps/Step3.cs
index 1f22924..45eaea8 100644
--- a/TelegramBotBase.Test/Tests/Register/Steps/Step3.cs
+++ b/TelegramBotBase.Test/Tests/Register/Steps/Step3.cs
@@ -2,68 +2,68 @@
using TelegramBotBase.Base;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests.Register.Steps
+namespace TelegramBotBaseTest.Tests.Register.Steps;
+
+public class Step3 : AutoCleanForm
{
- public class Step3 : AutoCleanForm
+ public Data UserData { get; set; }
+
+ public override Task Load(MessageResult message)
{
- public Data UserData { get; set; }
-
- public override Task Load(MessageResult message)
+ if (message.Handled)
{
- if (message.Handled)
- return Task.CompletedTask;
-
- if (message.MessageText.Trim() == "")
- return Task.CompletedTask;
-
- if (UserData.EMail == null)
- {
- UserData.EMail = message.MessageText;
- return Task.CompletedTask;
- }
-
return Task.CompletedTask;
}
- public override async Task Action(MessageResult message)
+ if (message.MessageText.Trim() == "")
{
- await message.ConfirmAction();
-
- switch (message.RawData)
- {
- case "back":
-
- var start = new Start();
-
- await NavigateTo(start);
-
- break;
-
- }
-
+ return Task.CompletedTask;
}
- public override async Task Render(MessageResult message)
+ if (UserData.EMail == null)
{
- if (UserData.EMail == null)
- {
- await Device.Send("Please sent your email:");
- return;
- }
-
- message.Handled = true;
-
- var s = "";
-
- s += "Firstname: " + UserData.Firstname + "\r\n";
- s += "Lastname: " + UserData.Lastname + "\r\n";
- s += "E-Mail: " + UserData.EMail + "\r\n";
-
- var bf = new ButtonForm();
- bf.AddButtonRow(new ButtonBase("Back", "back"));
-
- await Device.Send("Your details:\r\n" + s, bf);
+ UserData.EMail = message.MessageText;
+ return Task.CompletedTask;
}
+ return Task.CompletedTask;
}
-}
+
+ public override async Task Action(MessageResult message)
+ {
+ await message.ConfirmAction();
+
+ switch (message.RawData)
+ {
+ case "back":
+
+ var start = new Start();
+
+ await NavigateTo(start);
+
+ break;
+ }
+ }
+
+ public override async Task Render(MessageResult message)
+ {
+ if (UserData.EMail == null)
+ {
+ await Device.Send("Please sent your email:");
+ return;
+ }
+
+ message.Handled = true;
+
+ var s = "";
+
+ s += "Firstname: " + UserData.Firstname + "\r\n";
+ s += "Lastname: " + UserData.Lastname + "\r\n";
+ s += "E-Mail: " + UserData.EMail + "\r\n";
+
+ var bf = new ButtonForm();
+ bf.AddButtonRow(new ButtonBase("Back", "back"));
+
+ await Device.Send("Your details:\r\n" + s, bf);
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/SimpleForm.cs b/TelegramBotBase.Test/Tests/SimpleForm.cs
index 4f5c5fa..d776936 100644
--- a/TelegramBotBase.Test/Tests/SimpleForm.cs
+++ b/TelegramBotBase.Test/Tests/SimpleForm.cs
@@ -4,63 +4,59 @@ using TelegramBotBase.Base;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests
+namespace TelegramBotBaseTest.Tests;
+
+public class SimpleForm : AutoCleanForm
{
- public class SimpleForm : AutoCleanForm
+ public SimpleForm()
{
+ DeleteSide = EDeleteSide.Both;
+ DeleteMode = EDeleteMode.OnLeavingForm;
- public SimpleForm()
- {
- DeleteSide = EDeleteSide.Both;
- DeleteMode = EDeleteMode.OnLeavingForm;
-
- Opened += SimpleForm_Opened;
- }
-
- private async Task SimpleForm_Opened(object sender, EventArgs e)
- {
- await Device.Send("Hello world! (send 'back' to get back to Start)\r\nOr\r\nhi, hello, maybe, bye and ciao");
- }
-
- public override async Task Load(MessageResult message)
- {
- //message.MessageText will work also, cause it is a string you could manage a lot different scenerios here
-
- var messageId = message.MessageId;
-
- switch (message.Command)
- {
- case "hello":
- case "hi":
-
- //Send him a simple message
- await Device.Send("Hello you there !");
- break;
-
- case "maybe":
-
- //Send him a simple message and reply to the one of himself
- await Device.Send("Maybe what?", replyTo: messageId);
-
- break;
-
- case "bye":
- case "ciao":
-
- //Send him a simple message
- await Device.Send("Ok, take care !");
- break;
-
- case "back":
-
- var st = new Menu();
-
- await NavigateTo(st);
-
- break;
- }
- }
-
-
+ Opened += SimpleForm_Opened;
}
-}
+
+ private async Task SimpleForm_Opened(object sender, EventArgs e)
+ {
+ await Device.Send("Hello world! (send 'back' to get back to Start)\r\nOr\r\nhi, hello, maybe, bye and ciao");
+ }
+
+ public override async Task Load(MessageResult message)
+ {
+ //message.MessageText will work also, cause it is a string you could manage a lot different scenerios here
+
+ var messageId = message.MessageId;
+
+ switch (message.Command)
+ {
+ case "hello":
+ case "hi":
+
+ //Send him a simple message
+ await Device.Send("Hello you there !");
+ break;
+
+ case "maybe":
+
+ //Send him a simple message and reply to the one of himself
+ await Device.Send("Maybe what?", replyTo: messageId);
+
+ break;
+
+ case "bye":
+ case "ciao":
+
+ //Send him a simple message
+ await Device.Send("Ok, take care !");
+ break;
+
+ case "back":
+
+ var st = new Menu();
+
+ await NavigateTo(st);
+
+ break;
+ }
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/Start.cs b/TelegramBotBase.Test/Tests/Start.cs
index 5933011..bbe1783 100644
--- a/TelegramBotBase.Test/Tests/Start.cs
+++ b/TelegramBotBase.Test/Tests/Start.cs
@@ -3,36 +3,34 @@ using TelegramBotBase.Base;
using TelegramBotBase.Form;
using TelegramBotBaseTest.Tests.Groups;
-namespace TelegramBotBaseTest.Tests
+namespace TelegramBotBaseTest.Tests;
+
+public class Start : SplitterForm
{
- public class Start : SplitterForm
+ public override async Task Open(MessageResult e)
{
- public override async Task Open(MessageResult e)
- {
- var st = new Menu();
- await NavigateTo(st);
-
- return true;
- }
-
-
- public override async Task OpenGroup(MessageResult e)
- {
- var st = new LinkReplaceTest();
- await NavigateTo(st);
-
- return true;
- }
-
- public override Task OpenChannel(MessageResult e)
- {
- return base.OpenChannel(e);
- }
-
- public override Task OpenSupergroup(MessageResult e)
- {
- return base.OpenSupergroup(e);
- }
+ var st = new Menu();
+ await NavigateTo(st);
+ return true;
}
-}
+
+
+ public override async Task OpenGroup(MessageResult e)
+ {
+ var st = new LinkReplaceTest();
+ await NavigateTo(st);
+
+ return true;
+ }
+
+ public override Task OpenChannel(MessageResult e)
+ {
+ return base.OpenChannel(e);
+ }
+
+ public override Task OpenSupergroup(MessageResult e)
+ {
+ return base.OpenSupergroup(e);
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/TestForm.cs b/TelegramBotBase.Test/Tests/TestForm.cs
index e248414..30cb824 100644
--- a/TelegramBotBase.Test/Tests/TestForm.cs
+++ b/TelegramBotBase.Test/Tests/TestForm.cs
@@ -3,70 +3,65 @@ using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests
+namespace TelegramBotBaseTest.Tests;
+
+public class TestForm : FormBase
{
- public class TestForm : FormBase
+ public TestForm()
{
- private string LastMessage { get; set; }
-
- public TestForm()
- {
- Opened += TestForm_Opened;
- Closed += TestForm_Closed;
- }
-
- private async Task TestForm_Opened(object sender, EventArgs e)
- {
- await Device.Send("Welcome to Form 1");
- }
-
- private async Task TestForm_Closed(object sender, EventArgs e)
- {
- await Device.Send("Ciao from Form 1");
- }
-
-
- public override async Task Action(MessageResult message)
- {
- switch (message.Command)
- {
- case "reply":
-
-
- break;
-
- case "navigate":
-
- var tf = new TestForm2();
-
- await NavigateTo(tf);
-
- break;
-
- default:
-
- if (message.UpdateData == null)
- return;
-
- LastMessage = message.Message.Text;
-
- break;
- }
-
-
- }
-
-
- public override async Task Render(MessageResult message)
- {
- if (message.Command == "reply")
- {
-
- await Device.Send("Last message: " + LastMessage);
-
- }
-
- }
-
+ Opened += TestForm_Opened;
+ Closed += TestForm_Closed;
}
-}
+
+ private string LastMessage { get; set; }
+
+ private async Task TestForm_Opened(object sender, EventArgs e)
+ {
+ await Device.Send("Welcome to Form 1");
+ }
+
+ private async Task TestForm_Closed(object sender, EventArgs e)
+ {
+ await Device.Send("Ciao from Form 1");
+ }
+
+
+ public override async Task Action(MessageResult message)
+ {
+ switch (message.Command)
+ {
+ case "reply":
+
+
+ break;
+
+ case "navigate":
+
+ var tf = new TestForm2();
+
+ await NavigateTo(tf);
+
+ break;
+
+ default:
+
+ if (message.UpdateData == null)
+ {
+ return;
+ }
+
+ LastMessage = message.Message.Text;
+
+ break;
+ }
+ }
+
+
+ public override async Task Render(MessageResult message)
+ {
+ if (message.Command == "reply")
+ {
+ await Device.Send("Last message: " + LastMessage);
+ }
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/Tests/TestForm2.cs b/TelegramBotBase.Test/Tests/TestForm2.cs
index 93cced0..2cff462 100644
--- a/TelegramBotBase.Test/Tests/TestForm2.cs
+++ b/TelegramBotBase.Test/Tests/TestForm2.cs
@@ -6,118 +6,103 @@ using TelegramBotBase.Base;
using TelegramBotBase.Extensions.Images;
using TelegramBotBase.Form;
-namespace TelegramBotBaseTest.Tests
+namespace TelegramBotBaseTest.Tests;
+
+public class TestForm2 : FormBase
{
- public class TestForm2 : FormBase
+ public TestForm2()
{
-
-
- public TestForm2()
- {
- Opened += TestForm2_Opened;
- Closed += TestForm2_Closed;
- }
-
- private async Task TestForm2_Opened(object sender, EventArgs e)
- {
- await Device.Send("Welcome to Form 2");
- }
-
- private async Task TestForm2_Closed(object sender, EventArgs e)
- {
- await Device.Send("Ciao from Form 2");
- }
-
-
-
-
- public override async Task Action(MessageResult message)
- {
- var call = message.GetData();
-
- await message.ConfirmAction();
-
- await message.DeleteMessage();
-
- message.Handled = true;
-
- if (call.Value == "testform1")
- {
-
- var tf = new TestForm();
-
- await NavigateTo(tf);
- }
- else if (call.Value == "alert")
- {
- var ad = new AlertDialog("This is a message", "Ok");
-
- ad.ButtonClicked += async (s, en) =>
- {
- var fto = new TestForm2();
- await NavigateTo(fto);
- };
-
- await NavigateTo(ad);
- }
- else if (call.Value == "confirm")
- {
- var pd = new ConfirmDialog("Please confirm", new ButtonBase("Ok", "ok"), new ButtonBase("Cancel", "cancel"));
-
- pd.ButtonClicked += async (s, en) =>
- {
- var tf = new TestForm2();
-
- await pd.NavigateTo(tf);
- };
-
- await NavigateTo(pd);
- }
- else if (call.Value == "prompt")
- {
- var pd = new PromptDialog("Please tell me your name ?");
-
- pd.Completed += async (s, en) =>
- {
- await Device.Send("Hello " + pd.Value);
- };
-
- await OpenModal(pd);
- }
-
-
- }
-
- public override async Task Render(MessageResult message)
- {
-
- var bmp = new Bitmap(800, 600);
- using (var g = Graphics.FromImage(bmp))
- {
-
- g.FillRectangle(Brushes.White, 0, 0, bmp.Width, bmp.Height);
-
- g.DrawString("Test Image", new Font("Arial", 24, FontStyle.Bold, GraphicsUnit.Pixel), Brushes.Black, new PointF(50, 50));
-
- }
-
- await Device.SetAction(ChatAction.UploadPhoto);
-
- var btn = new ButtonForm();
-
- //btn.AddButtonRow(new ButtonBase("Zum Testformular 1", CallbackData.Create("navigate", "testform1")), new ButtonBase("Zum Testformular 1", CallbackData.Create("navigate", "testform1")));
-
- btn.AddButtonRow(new ButtonBase("Information Prompt", CallbackData.Create("navigate", "alert")));
-
- btn.AddButtonRow(new ButtonBase("Confirmation Prompt with event", CallbackData.Create("navigate", "confirm")));
-
- btn.AddButtonRow(new ButtonBase("Request Prompt", CallbackData.Create("navigate", "prompt")));
-
-
- await Device.SendPhoto(bmp, "Test", "", btn);
-
- }
-
-
+ Opened += TestForm2_Opened;
+ Closed += TestForm2_Closed;
}
-}
+
+ private async Task TestForm2_Opened(object sender, EventArgs e)
+ {
+ await Device.Send("Welcome to Form 2");
+ }
+
+ private async Task TestForm2_Closed(object sender, EventArgs e)
+ {
+ await Device.Send("Ciao from Form 2");
+ }
+
+
+ public override async Task Action(MessageResult message)
+ {
+ var call = message.GetData();
+
+ await message.ConfirmAction();
+
+ await message.DeleteMessage();
+
+ message.Handled = true;
+
+ if (call.Value == "testform1")
+ {
+ var tf = new TestForm();
+
+ await NavigateTo(tf);
+ }
+ else if (call.Value == "alert")
+ {
+ var ad = new AlertDialog("This is a message", "Ok");
+
+ ad.ButtonClicked += async (s, en) =>
+ {
+ var fto = new TestForm2();
+ await NavigateTo(fto);
+ };
+
+ await NavigateTo(ad);
+ }
+ else if (call.Value == "confirm")
+ {
+ var pd = new ConfirmDialog("Please confirm", new ButtonBase("Ok", "ok"),
+ new ButtonBase("Cancel", "cancel"));
+
+ pd.ButtonClicked += async (s, en) =>
+ {
+ var tf = new TestForm2();
+
+ await pd.NavigateTo(tf);
+ };
+
+ await NavigateTo(pd);
+ }
+ else if (call.Value == "prompt")
+ {
+ var pd = new PromptDialog("Please tell me your name ?");
+
+ pd.Completed += async (s, en) => { await Device.Send("Hello " + pd.Value); };
+
+ await OpenModal(pd);
+ }
+ }
+
+ public override async Task Render(MessageResult message)
+ {
+ var bmp = new Bitmap(800, 600);
+ using (var g = Graphics.FromImage(bmp))
+ {
+ g.FillRectangle(Brushes.White, 0, 0, bmp.Width, bmp.Height);
+
+ g.DrawString("Test Image", new Font("Arial", 24, FontStyle.Bold, GraphicsUnit.Pixel), Brushes.Black,
+ new PointF(50, 50));
+ }
+
+ await Device.SetAction(ChatAction.UploadPhoto);
+
+ var btn = new ButtonForm();
+
+ //btn.AddButtonRow(new ButtonBase("Zum Testformular 1", CallbackData.Create("navigate", "testform1")), new ButtonBase("Zum Testformular 1", CallbackData.Create("navigate", "testform1")));
+
+ btn.AddButtonRow(new ButtonBase("Information Prompt", CallbackData.Create("navigate", "alert")));
+
+ btn.AddButtonRow(new ButtonBase("Confirmation Prompt with event", CallbackData.Create("navigate", "confirm")));
+
+ btn.AddButtonRow(new ButtonBase("Request Prompt", CallbackData.Create("navigate", "prompt")));
+
+
+ await Device.SendPhoto(bmp, "Test", "", btn);
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase.Test/packages.config b/TelegramBotBase.Test/packages.config
index d654912..f74d058 100644
--- a/TelegramBotBase.Test/packages.config
+++ b/TelegramBotBase.Test/packages.config
@@ -1,6 +1,6 @@
-
-
-
-
\ No newline at end of file
+
+
+
+
diff --git a/TelegramBotBase/Args/BotCommandEventArgs.cs b/TelegramBotBase/Args/BotCommandEventArgs.cs
index 3f3d545..02ec9d8 100644
--- a/TelegramBotBase/Args/BotCommandEventArgs.cs
+++ b/TelegramBotBase/Args/BotCommandEventArgs.cs
@@ -3,40 +3,36 @@ using System.Collections.Generic;
using Telegram.Bot.Types;
using TelegramBotBase.Sessions;
-namespace TelegramBotBase.Args
+namespace TelegramBotBase.Args;
+
+///
+/// Base class for given bot command results
+///
+public class BotCommandEventArgs : EventArgs
{
- ///
- /// Base class for given bot command results
- ///
- public class BotCommandEventArgs : EventArgs
+ public BotCommandEventArgs()
{
- public string Command { get; set; }
-
- public List Parameters { get; set; }
-
- public long DeviceId { get; set; }
-
- public DeviceSession Device { get; set; }
-
- public bool Handled { get; set; } = false;
-
- public Message OriginalMessage { get; set; }
-
-
- public BotCommandEventArgs()
- {
-
-
- }
-
- public BotCommandEventArgs(string command, List parameters, Message message, long deviceId, DeviceSession device)
- {
- this.Command = command;
- this.Parameters = parameters;
- OriginalMessage = message;
- this.DeviceId = deviceId;
- this.Device = device;
- }
-
}
-}
+
+ public BotCommandEventArgs(string command, List parameters, Message message, long deviceId,
+ DeviceSession device)
+ {
+ Command = command;
+ Parameters = parameters;
+ OriginalMessage = message;
+ DeviceId = deviceId;
+ Device = device;
+ }
+
+ public string Command { get; set; }
+
+ public List Parameters { get; set; }
+
+ public long DeviceId { get; set; }
+
+ public DeviceSession Device { get; set; }
+
+ public bool Handled { get; set; } = false;
+
+ public Message OriginalMessage { get; set; }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Args/ButtonClickedEventArgs.cs b/TelegramBotBase/Args/ButtonClickedEventArgs.cs
index 2227abd..1bb69a4 100644
--- a/TelegramBotBase/Args/ButtonClickedEventArgs.cs
+++ b/TelegramBotBase/Args/ButtonClickedEventArgs.cs
@@ -2,44 +2,41 @@
using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Form;
-namespace TelegramBotBase.Args
+namespace TelegramBotBase.Args;
+
+///
+/// Button get clicked event
+///
+public class ButtonClickedEventArgs : EventArgs
{
- ///
- /// Button get clicked event
- ///
- public class ButtonClickedEventArgs : EventArgs
+ public ButtonClickedEventArgs()
{
- public ButtonBase Button { get; set; }
-
- public int Index { get; set; }
-
- public object Tag { get; set; }
-
- public ButtonRow Row { get; set; }
-
-
- public ButtonClickedEventArgs()
- {
-
- }
-
- public ButtonClickedEventArgs(ButtonBase button)
- {
- Button = button;
- Index = -1;
- }
-
- public ButtonClickedEventArgs(ButtonBase button, int index)
- {
- Button = button;
- this.Index = index;
- }
-
- public ButtonClickedEventArgs(ButtonBase button, int index, ButtonRow row)
- {
- Button = button;
- this.Index = index;
- Row = row;
- }
}
-}
+
+ public ButtonClickedEventArgs(ButtonBase button)
+ {
+ Button = button;
+ Index = -1;
+ }
+
+ public ButtonClickedEventArgs(ButtonBase button, int index)
+ {
+ Button = button;
+ Index = index;
+ }
+
+ public ButtonClickedEventArgs(ButtonBase button, int index, ButtonRow row)
+ {
+ Button = button;
+ Index = index;
+ Row = row;
+ }
+
+ public ButtonBase Button { get; set; }
+
+ public int Index { get; set; }
+
+ public object Tag { get; set; }
+
+ public ButtonRow Row { get; set; }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Args/CheckedChangedEventArgs.cs b/TelegramBotBase/Args/CheckedChangedEventArgs.cs
index 5ec61d3..6e5288e 100644
--- a/TelegramBotBase/Args/CheckedChangedEventArgs.cs
+++ b/TelegramBotBase/Args/CheckedChangedEventArgs.cs
@@ -1,41 +1,36 @@
using System;
using TelegramBotBase.Controls.Hybrid;
-namespace TelegramBotBase.Args
+namespace TelegramBotBase.Args;
+
+public class CheckedChangedEventArgs : EventArgs
{
- public class CheckedChangedEventArgs : EventArgs
+ public CheckedChangedEventArgs()
{
- ///
- /// Contains the index of the row where the button is inside.
- /// Contains -1 when it is a layout button or not found.
- ///
- public int Index { get; set; }
-
-
- ///
- /// Contains all buttons within this row, excluding the checkbox.
- ///
- public ButtonRow Row { get; set; }
-
-
- ///
- /// Contains the new checked status of the row.
- ///
- public bool Checked { get; set; }
-
-
- public CheckedChangedEventArgs()
- {
-
- }
-
- public CheckedChangedEventArgs(ButtonRow row, int index, bool @checked)
- {
- Row = row;
- this.Index = index;
- this.Checked = @checked;
- }
-
-
}
-}
+
+ public CheckedChangedEventArgs(ButtonRow row, int index, bool @checked)
+ {
+ Row = row;
+ Index = index;
+ Checked = @checked;
+ }
+
+ ///
+ /// Contains the index of the row where the button is inside.
+ /// Contains -1 when it is a layout button or not found.
+ ///
+ public int Index { get; set; }
+
+
+ ///
+ /// Contains all buttons within this row, excluding the checkbox.
+ ///
+ public ButtonRow Row { get; set; }
+
+
+ ///
+ /// Contains the new checked status of the row.
+ ///
+ public bool Checked { get; set; }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Args/GroupChangedEventArgs.cs b/TelegramBotBase/Args/GroupChangedEventArgs.cs
index 5493f9d..5d8b9ae 100644
--- a/TelegramBotBase/Args/GroupChangedEventArgs.cs
+++ b/TelegramBotBase/Args/GroupChangedEventArgs.cs
@@ -2,21 +2,17 @@
using Telegram.Bot.Types.Enums;
using TelegramBotBase.Base;
-namespace TelegramBotBase.Args
+namespace TelegramBotBase.Args;
+
+public class GroupChangedEventArgs : EventArgs
{
- public class GroupChangedEventArgs : EventArgs
+ public GroupChangedEventArgs(MessageType type, MessageResult message)
{
- public MessageType Type { get; set; }
-
- public MessageResult OriginalMessage { get; set; }
-
- public GroupChangedEventArgs(MessageType type, MessageResult message)
- {
- Type = type;
- OriginalMessage = message;
- }
-
-
-
+ Type = type;
+ OriginalMessage = message;
}
-}
+
+ public MessageType Type { get; set; }
+
+ public MessageResult OriginalMessage { get; set; }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Args/InitEventArgs.cs b/TelegramBotBase/Args/InitEventArgs.cs
index 360aaa1..a0af03a 100644
--- a/TelegramBotBase/Args/InitEventArgs.cs
+++ b/TelegramBotBase/Args/InitEventArgs.cs
@@ -1,14 +1,13 @@
using System;
-namespace TelegramBotBase.Args
-{
- public class InitEventArgs : EventArgs
- {
- public object[] Args { get; set; }
+namespace TelegramBotBase.Args;
- public InitEventArgs(params object[] args)
- {
- Args = args;
- }
+public class InitEventArgs : EventArgs
+{
+ public InitEventArgs(params object[] args)
+ {
+ Args = args;
}
-}
+
+ public object[] Args { get; set; }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Args/LoadStateEventArgs.cs b/TelegramBotBase/Args/LoadStateEventArgs.cs
index 06834c7..42fc51b 100644
--- a/TelegramBotBase/Args/LoadStateEventArgs.cs
+++ b/TelegramBotBase/Args/LoadStateEventArgs.cs
@@ -1,55 +1,59 @@
using System.Collections.Generic;
using System.Linq;
-namespace TelegramBotBase.Args
+namespace TelegramBotBase.Args;
+
+public class LoadStateEventArgs
{
- public class LoadStateEventArgs
+ public LoadStateEventArgs()
{
- public Dictionary Values { get; set; }
-
- public LoadStateEventArgs()
- {
- Values = new Dictionary();
- }
-
- public List Keys => Values.Keys.ToList();
-
- public string Get(string key)
- {
- return Values[key].ToString();
- }
-
- public int GetInt(string key)
- {
- var i = 0;
- if (int.TryParse(Values[key].ToString(), out i))
- return i;
-
- return 0;
- }
-
- public double GetDouble(string key)
- {
- double d = 0;
- if (double.TryParse(Values[key].ToString(), out d))
- return d;
-
- return 0;
- }
-
- public bool GetBool(string key)
- {
- var b = false;
- if (bool.TryParse(Values[key].ToString(), out b))
- return b;
-
- return false;
- }
-
- public object GetObject(string key)
- {
- return Values[key];
- }
-
+ Values = new Dictionary();
}
-}
+
+ public Dictionary Values { get; set; }
+
+ public List Keys => Values.Keys.ToList();
+
+ public string Get(string key)
+ {
+ return Values[key].ToString();
+ }
+
+ public int GetInt(string key)
+ {
+ var i = 0;
+ if (int.TryParse(Values[key].ToString(), out i))
+ {
+ return i;
+ }
+
+ return 0;
+ }
+
+ public double GetDouble(string key)
+ {
+ double d = 0;
+ if (double.TryParse(Values[key].ToString(), out d))
+ {
+ return d;
+ }
+
+ return 0;
+ }
+
+ public bool GetBool(string key)
+ {
+ var b = false;
+ if (bool.TryParse(Values[key].ToString(), out b))
+ {
+ return b;
+ }
+
+ return false;
+ }
+
+ public object GetObject(string key)
+ {
+ return Values[key];
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Args/MemberChangeEventArgs.cs b/TelegramBotBase/Args/MemberChangeEventArgs.cs
index 34519a9..f59f8c0 100644
--- a/TelegramBotBase/Args/MemberChangeEventArgs.cs
+++ b/TelegramBotBase/Args/MemberChangeEventArgs.cs
@@ -5,32 +5,25 @@ using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using TelegramBotBase.Base;
-namespace TelegramBotBase.Args
+namespace TelegramBotBase.Args;
+
+public class MemberChangeEventArgs : EventArgs
{
- public class MemberChangeEventArgs : EventArgs
+ public MemberChangeEventArgs()
{
- public List Members { get; set; }
-
- public MessageType Type { get; set; }
-
- public MessageResult Result { get; set; }
-
- public MemberChangeEventArgs()
- {
- Members = new List();
-
- }
-
- public MemberChangeEventArgs(MessageType type, MessageResult result, params User[] members)
- {
- Type = type;
- Result = result;
- Members = members.ToList();
- }
-
-
-
-
-
+ Members = new List();
}
-}
+
+ public MemberChangeEventArgs(MessageType type, MessageResult result, params User[] members)
+ {
+ Type = type;
+ Result = result;
+ Members = members.ToList();
+ }
+
+ public List Members { get; set; }
+
+ public MessageType Type { get; set; }
+
+ public MessageResult Result { get; set; }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Args/MessageDeletedEventArgs.cs b/TelegramBotBase/Args/MessageDeletedEventArgs.cs
index bab0af6..34f174b 100644
--- a/TelegramBotBase/Args/MessageDeletedEventArgs.cs
+++ b/TelegramBotBase/Args/MessageDeletedEventArgs.cs
@@ -1,16 +1,11 @@
-namespace TelegramBotBase.Args
+namespace TelegramBotBase.Args;
+
+public class MessageDeletedEventArgs
{
- public class MessageDeletedEventArgs
+ public MessageDeletedEventArgs(int messageId)
{
- public int MessageId
- {
- get;set;
- }
-
- public MessageDeletedEventArgs(int messageId)
- {
- MessageId = messageId;
- }
-
+ MessageId = messageId;
}
-}
+
+ public int MessageId { get; set; }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Args/MessageIncomeEventArgs.cs b/TelegramBotBase/Args/MessageIncomeEventArgs.cs
index 5e6de76..ddc0ac8 100644
--- a/TelegramBotBase/Args/MessageIncomeEventArgs.cs
+++ b/TelegramBotBase/Args/MessageIncomeEventArgs.cs
@@ -1,26 +1,20 @@
using System;
using TelegramBotBase.Sessions;
-namespace TelegramBotBase.Base
+namespace TelegramBotBase.Base;
+
+public class MessageIncomeEventArgs : EventArgs
{
- public class MessageIncomeEventArgs : EventArgs
+ public MessageIncomeEventArgs(long deviceId, DeviceSession device, MessageResult message)
{
-
- public long DeviceId { get; set; }
-
- public DeviceSession Device { get; set; }
-
- public MessageResult Message { get; set; }
-
- public MessageIncomeEventArgs(long deviceId, DeviceSession device, MessageResult message)
- {
- this.DeviceId = deviceId;
- this.Device = device;
- Message = message;
- }
-
-
-
-
+ DeviceId = deviceId;
+ Device = device;
+ Message = message;
}
-}
+
+ public long DeviceId { get; set; }
+
+ public DeviceSession Device { get; set; }
+
+ public MessageResult Message { get; set; }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Args/MessageReceivedEventArgs.cs b/TelegramBotBase/Args/MessageReceivedEventArgs.cs
index 497782f..85fce86 100644
--- a/TelegramBotBase/Args/MessageReceivedEventArgs.cs
+++ b/TelegramBotBase/Args/MessageReceivedEventArgs.cs
@@ -1,17 +1,15 @@
using Telegram.Bot.Types;
-namespace TelegramBotBase.Args
+namespace TelegramBotBase.Args;
+
+public class MessageReceivedEventArgs
{
- public class MessageReceivedEventArgs
+ public MessageReceivedEventArgs(Message m)
{
- public int MessageId => Message.MessageId;
-
- public Message Message { get; set; }
-
- public MessageReceivedEventArgs(Message m)
- {
- Message = m;
- }
-
+ Message = m;
}
-}
+
+ public int MessageId => Message.MessageId;
+
+ public Message Message { get; set; }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Args/MessageSentEventArgs.cs b/TelegramBotBase/Args/MessageSentEventArgs.cs
index a776207..3086908 100644
--- a/TelegramBotBase/Args/MessageSentEventArgs.cs
+++ b/TelegramBotBase/Args/MessageSentEventArgs.cs
@@ -1,26 +1,22 @@
using System;
using Telegram.Bot.Types;
-namespace TelegramBotBase.Args
+namespace TelegramBotBase.Args;
+
+public class MessageSentEventArgs : EventArgs
{
- public class MessageSentEventArgs : EventArgs
+ public MessageSentEventArgs(Message message, Type origin)
{
- public int MessageId => Message.MessageId;
-
- public Message Message { get; set; }
-
- ///
- /// Contains the element, which has called the method.
- ///
- public Type Origin { get; set; }
-
-
- public MessageSentEventArgs(Message message, Type origin)
- {
- Message = message;
- this.Origin = origin;
- }
-
-
+ Message = message;
+ Origin = origin;
}
-}
+
+ public int MessageId => Message.MessageId;
+
+ public Message Message { get; set; }
+
+ ///
+ /// Contains the element, which has called the method.
+ ///
+ public Type Origin { get; set; }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Args/PromptDialogCompletedEventArgs.cs b/TelegramBotBase/Args/PromptDialogCompletedEventArgs.cs
index b0b7e04..9de7888 100644
--- a/TelegramBotBase/Args/PromptDialogCompletedEventArgs.cs
+++ b/TelegramBotBase/Args/PromptDialogCompletedEventArgs.cs
@@ -1,10 +1,8 @@
-namespace TelegramBotBase.Args
+namespace TelegramBotBase.Args;
+
+public class PromptDialogCompletedEventArgs
{
- public class PromptDialogCompletedEventArgs
- {
- public object Tag { get; set; }
+ public object Tag { get; set; }
- public string Value { get; set; }
-
- }
-}
+ public string Value { get; set; }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Args/RenderViewEventArgs.cs b/TelegramBotBase/Args/RenderViewEventArgs.cs
index 82df8e5..cc736eb 100644
--- a/TelegramBotBase/Args/RenderViewEventArgs.cs
+++ b/TelegramBotBase/Args/RenderViewEventArgs.cs
@@ -1,18 +1,13 @@
using System;
-namespace TelegramBotBase.Args
+namespace TelegramBotBase.Args;
+
+public class RenderViewEventArgs : EventArgs
{
- public class RenderViewEventArgs : EventArgs
+ public RenderViewEventArgs(int viewIndex)
{
- public int CurrentView { get; set; }
-
-
- public RenderViewEventArgs(int viewIndex)
- {
-
- CurrentView = viewIndex;
- }
-
-
+ CurrentView = viewIndex;
}
-}
+
+ public int CurrentView { get; set; }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Args/SaveStateEventArgs.cs b/TelegramBotBase/Args/SaveStateEventArgs.cs
index bfc3984..39d3e46 100644
--- a/TelegramBotBase/Args/SaveStateEventArgs.cs
+++ b/TelegramBotBase/Args/SaveStateEventArgs.cs
@@ -1,39 +1,38 @@
using System.Collections.Generic;
-namespace TelegramBotBase.Args
+namespace TelegramBotBase.Args;
+
+public class SaveStateEventArgs
{
- public class SaveStateEventArgs
+ public SaveStateEventArgs()
{
- public Dictionary Values { get; set; }
-
- public SaveStateEventArgs()
- {
- Values = new Dictionary();
- }
-
- public void Set(string key, string value)
- {
- Values[key] = value;
- }
-
- public void SetInt(string key, int value)
- {
- Values[key] = value;
- }
-
- public void SetBool(string key, bool value)
- {
- Values[key] = value;
- }
-
- public void SetDouble(string key, double value)
- {
- Values[key] = value;
- }
- public void SetObject(string key, object value)
- {
- Values[key] = value;
- }
-
+ Values = new Dictionary();
}
-}
+
+ public Dictionary Values { get; set; }
+
+ public void Set(string key, string value)
+ {
+ Values[key] = value;
+ }
+
+ public void SetInt(string key, int value)
+ {
+ Values[key] = value;
+ }
+
+ public void SetBool(string key, bool value)
+ {
+ Values[key] = value;
+ }
+
+ public void SetDouble(string key, double value)
+ {
+ Values[key] = value;
+ }
+
+ public void SetObject(string key, object value)
+ {
+ Values[key] = value;
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Args/SaveStatesEventArgs.cs b/TelegramBotBase/Args/SaveStatesEventArgs.cs
index e2d44f6..b300d11 100644
--- a/TelegramBotBase/Args/SaveStatesEventArgs.cs
+++ b/TelegramBotBase/Args/SaveStatesEventArgs.cs
@@ -1,15 +1,13 @@
using TelegramBotBase.Base;
-namespace TelegramBotBase.Args
+namespace TelegramBotBase.Args;
+
+public class SaveStatesEventArgs
{
- public class SaveStatesEventArgs
+ public SaveStatesEventArgs(StateContainer states)
{
- public StateContainer States { get; set; }
-
-
- public SaveStatesEventArgs(StateContainer states)
- {
- States = states;
- }
+ States = states;
}
-}
+
+ public StateContainer States { get; set; }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Args/SessionBeginEventArgs.cs b/TelegramBotBase/Args/SessionBeginEventArgs.cs
index 9187f0b..53a54b9 100644
--- a/TelegramBotBase/Args/SessionBeginEventArgs.cs
+++ b/TelegramBotBase/Args/SessionBeginEventArgs.cs
@@ -1,18 +1,17 @@
using System;
using TelegramBotBase.Sessions;
-namespace TelegramBotBase.Base
+namespace TelegramBotBase.Base;
+
+public class SessionBeginEventArgs : EventArgs
{
- public class SessionBeginEventArgs : EventArgs
+ public SessionBeginEventArgs(long deviceId, DeviceSession device)
{
- public long DeviceId { get; set; }
-
- public DeviceSession Device { get; set; }
-
- public SessionBeginEventArgs(long deviceId, DeviceSession device)
- {
- this.DeviceId = deviceId;
- this.Device = device;
- }
+ DeviceId = deviceId;
+ Device = device;
}
-}
+
+ public long DeviceId { get; set; }
+
+ public DeviceSession Device { get; set; }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Args/SystemExceptionEventArgs.cs b/TelegramBotBase/Args/SystemExceptionEventArgs.cs
index cc19a62..5fbaf69 100644
--- a/TelegramBotBase/Args/SystemExceptionEventArgs.cs
+++ b/TelegramBotBase/Args/SystemExceptionEventArgs.cs
@@ -1,32 +1,27 @@
using System;
using TelegramBotBase.Sessions;
-namespace TelegramBotBase.Args
+namespace TelegramBotBase.Args;
+
+public class SystemExceptionEventArgs : EventArgs
{
- public class SystemExceptionEventArgs : EventArgs
+ public SystemExceptionEventArgs()
{
-
- public string Command { get; set; }
-
- public long DeviceId { get; set; }
-
- public DeviceSession Device { get; set; }
-
- public Exception Error { get; set; }
-
- public SystemExceptionEventArgs()
- {
-
-
- }
-
- public SystemExceptionEventArgs(string command, long deviceId, DeviceSession device, Exception error)
- {
- this.Command = command;
- this.DeviceId = deviceId;
- this.Device = device;
- Error = error;
- }
}
-}
+ public SystemExceptionEventArgs(string command, long deviceId, DeviceSession device, Exception error)
+ {
+ Command = command;
+ DeviceId = deviceId;
+ Device = device;
+ Error = error;
+ }
+
+ public string Command { get; set; }
+
+ public long DeviceId { get; set; }
+
+ public DeviceSession Device { get; set; }
+
+ public Exception Error { get; set; }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Args/UnhandledCallEventArgs.cs b/TelegramBotBase/Args/UnhandledCallEventArgs.cs
index 279170f..844bc43 100644
--- a/TelegramBotBase/Args/UnhandledCallEventArgs.cs
+++ b/TelegramBotBase/Args/UnhandledCallEventArgs.cs
@@ -2,40 +2,37 @@
using Telegram.Bot.Types;
using TelegramBotBase.Sessions;
-namespace TelegramBotBase.Args
+namespace TelegramBotBase.Args;
+
+public class UnhandledCallEventArgs : EventArgs
{
- public class UnhandledCallEventArgs : EventArgs
+ public UnhandledCallEventArgs()
{
- public string Command { get; set; }
-
- public long DeviceId { get; set; }
-
- public DeviceSession Device {get;set;}
-
- public string RawData { get; set; }
-
- public int MessageId { get; set; }
-
- public Message Message { get; set; }
-
- public bool Handled { get; set; }
-
-
- public UnhandledCallEventArgs()
- {
- Handled = false;
-
- }
-
- public UnhandledCallEventArgs(string command,string rawData, long deviceId, int messageId, Message message, DeviceSession device) : this()
- {
- this.Command = command;
- this.RawData = rawData;
- this.DeviceId = deviceId;
- this.MessageId = messageId;
- Message = message;
- this.Device = device;
- }
-
+ Handled = false;
}
-}
+
+ public UnhandledCallEventArgs(string command, string rawData, long deviceId, int messageId, Message message,
+ DeviceSession device) : this()
+ {
+ Command = command;
+ RawData = rawData;
+ DeviceId = deviceId;
+ MessageId = messageId;
+ Message = message;
+ Device = device;
+ }
+
+ public string Command { get; set; }
+
+ public long DeviceId { get; set; }
+
+ public DeviceSession Device { get; set; }
+
+ public string RawData { get; set; }
+
+ public int MessageId { get; set; }
+
+ public Message Message { get; set; }
+
+ public bool Handled { get; set; }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Attributes/IgnoreState.cs b/TelegramBotBase/Attributes/IgnoreState.cs
index 72c4381..3deb6f4 100644
--- a/TelegramBotBase/Attributes/IgnoreState.cs
+++ b/TelegramBotBase/Attributes/IgnoreState.cs
@@ -1,15 +1,11 @@
using System;
-namespace TelegramBotBase.Attributes
+namespace TelegramBotBase.Attributes;
+
+///
+/// Declares that this class should not be getting serialized
+///
+[AttributeUsage(AttributeTargets.Class)]
+public class IgnoreState : Attribute
{
-
- ///
- /// Declares that this class should not be getting serialized
- ///
- [AttributeUsage(AttributeTargets.Class)]
- public class IgnoreState : Attribute
- {
-
-
- }
-}
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Attributes/SaveState.cs b/TelegramBotBase/Attributes/SaveState.cs
index 9b9190b..71f5edc 100644
--- a/TelegramBotBase/Attributes/SaveState.cs
+++ b/TelegramBotBase/Attributes/SaveState.cs
@@ -1,13 +1,11 @@
using System;
-namespace TelegramBotBase.Attributes
-{
- ///
- /// Declares that the field or property should be save and recovered an restart.
- ///
- public class SaveState : Attribute
- {
- public string Key { get; set; }
+namespace TelegramBotBase.Attributes;
- }
-}
+///
+/// Declares that the field or property should be save and recovered an restart.
+///
+public class SaveState : Attribute
+{
+ public string Key { get; set; }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Base/Async.cs b/TelegramBotBase/Base/Async.cs
index 9eff287..9efe5be 100644
--- a/TelegramBotBase/Base/Async.cs
+++ b/TelegramBotBase/Base/Async.cs
@@ -3,22 +3,25 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
-namespace TelegramBotBase.Base
-{
- public static class Async
- {
- public delegate Task AsyncEventHandler(object sender, TEventArgs e) where TEventArgs : EventArgs;
+namespace TelegramBotBase.Base;
- public static IEnumerable> GetHandlers(
+public static class Async
+{
+ public delegate Task AsyncEventHandler(object sender, TEventArgs e) where TEventArgs : EventArgs;
+
+ public static IEnumerable> GetHandlers(
this AsyncEventHandler handler)
where TEventArgs : EventArgs
- => handler.GetInvocationList().Cast>();
-
- public static Task InvokeAllAsync(this AsyncEventHandler handler, object sender, TEventArgs e)
- where TEventArgs : EventArgs
- => Task.WhenAll(
- handler.GetHandlers()
- .Select(handleAsync => handleAsync(sender, e)));
-
+ {
+ return handler.GetInvocationList().Cast>();
}
-}
+
+ public static Task InvokeAllAsync(this AsyncEventHandler handler, object sender,
+ TEventArgs e)
+ where TEventArgs : EventArgs
+ {
+ return Task.WhenAll(
+ handler.GetHandlers()
+ .Select(handleAsync => handleAsync(sender, e)));
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Base/ControlBase.cs b/TelegramBotBase/Base/ControlBase.cs
index b06b2d3..4c25177 100644
--- a/TelegramBotBase/Base/ControlBase.cs
+++ b/TelegramBotBase/Base/ControlBase.cs
@@ -1,63 +1,59 @@
using System.Threading.Tasks;
using TelegramBotBase.Sessions;
-namespace TelegramBotBase.Base
+namespace TelegramBotBase.Base;
+
+///
+/// Base class for controls
+///
+public class ControlBase
{
+ public DeviceSession Device { get; set; }
+
+ public int Id { get; set; }
+
+ public string ControlId => "#c" + Id;
+
///
- /// Base class for controls
+ /// Defines if the control should be rendered and invoked with actions
///
- public class ControlBase
+ public bool Enabled { get; set; } = true;
+
+ ///
+ /// Get invoked when control will be added to a form and invoked.
+ ///
+ ///
+ public virtual void Init()
{
- public DeviceSession Device { get; set; }
-
- public int Id { get; set; }
-
- public string ControlId => "#c" + Id;
-
- ///
- /// Defines if the control should be rendered and invoked with actions
- ///
- public bool Enabled { get; set; } = true;
-
- ///
- /// Get invoked when control will be added to a form and invoked.
- ///
- ///
- public virtual void Init()
- {
-
- }
-
- public virtual Task Load(MessageResult result)
- {
- return Task.CompletedTask;
- }
-
- public virtual Task Action(MessageResult result, string value = null)
- {
- return Task.CompletedTask;
- }
-
-
-
- public virtual Task Render(MessageResult result)
- {
- return Task.CompletedTask;
- }
-
- public virtual Task Hidden(bool formClose)
- {
- return Task.CompletedTask;
- }
-
- ///
- /// Will be called on a cleanup.
- ///
- ///
- public virtual Task Cleanup()
- {
- return Task.CompletedTask;
- }
-
}
-}
+
+ public virtual Task Load(MessageResult result)
+ {
+ return Task.CompletedTask;
+ }
+
+ public virtual Task Action(MessageResult result, string value = null)
+ {
+ return Task.CompletedTask;
+ }
+
+
+ public virtual Task Render(MessageResult result)
+ {
+ return Task.CompletedTask;
+ }
+
+ public virtual Task Hidden(bool formClose)
+ {
+ return Task.CompletedTask;
+ }
+
+ ///
+ /// Will be called on a cleanup.
+ ///
+ ///
+ public virtual Task Cleanup()
+ {
+ return Task.CompletedTask;
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Base/DataResult.cs b/TelegramBotBase/Base/DataResult.cs
index bebef80..14c7d9b 100644
--- a/TelegramBotBase/Base/DataResult.cs
+++ b/TelegramBotBase/Base/DataResult.cs
@@ -7,166 +7,164 @@ using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.InputFiles;
-namespace TelegramBotBase.Base
+namespace TelegramBotBase.Base;
+
+///
+/// Returns a class to manage attachments within messages.
+///
+public class DataResult : ResultBase
{
- ///
- /// Returns a class to manage attachments within messages.
- ///
- public class DataResult : ResultBase
+ public DataResult(UpdateResult update)
{
-
- //public Telegram.Bot.Args.MessageEventArgs RawMessageData { get; set; }
-
- public UpdateResult UpdateData { get; set; }
-
-
- public Contact Contact => Message.Contact;
-
- public Location Location => Message.Location;
-
- public Document Document => Message.Document;
-
- public Audio Audio => Message.Audio;
-
- public Video Video => Message.Video;
-
- public PhotoSize[] Photos => Message.Photo;
-
-
- public MessageType Type => Message?.Type ?? MessageType.Unknown;
-
- public override Message Message => UpdateData?.Message;
-
- ///
- /// Returns the FileId of the first reachable element.
- ///
- public string FileId =>
- (Document?.FileId ??
- Audio?.FileId ??
- Video?.FileId ??
- Photos.FirstOrDefault()?.FileId);
-
- public DataResult(UpdateResult update)
- {
- UpdateData = update;
- }
-
-
- public async Task DownloadDocument()
- {
- var encryptedContent = new MemoryStream();
- encryptedContent.SetLength(Document.FileSize.Value);
- var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, encryptedContent);
-
- return new InputOnlineFile(encryptedContent, Document.FileName);
- }
-
-
- ///
- /// Downloads a file and saves it to the given path.
- ///
- ///
- ///
- public async Task DownloadDocument(string path)
- {
- var file = await Device.Client.TelegramClient.GetFileAsync(Document.FileId);
- var fs = new FileStream(path, FileMode.Create);
- await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
- fs.Close();
- fs.Dispose();
- }
-
- ///
- /// Downloads the document and returns an byte array.
- ///
- ///
- public async Task DownloadRawDocument()
- {
- var ms = new MemoryStream();
- await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, ms);
- return ms.ToArray();
- }
-
- ///
- /// Downloads a document and returns it as string. (txt,csv,etc) Default encoding ist UTF8.
- ///
- ///
- public async Task DownloadRawTextDocument()
- {
- return await DownloadRawTextDocument(Encoding.UTF8);
- }
-
- ///
- /// Downloads a document and returns it as string. (txt,csv,etc)
- ///
- ///
- public async Task DownloadRawTextDocument(Encoding encoding)
- {
- var ms = new MemoryStream();
- await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, ms);
-
- ms.Position = 0;
-
- var sr = new StreamReader(ms, encoding);
-
- return sr.ReadToEnd();
- }
-
- public async Task DownloadVideo()
- {
- var encryptedContent = new MemoryStream();
- encryptedContent.SetLength(Video.FileSize.Value);
- var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Video.FileId, encryptedContent);
-
- return new InputOnlineFile(encryptedContent, "");
- }
-
- public async Task DownloadVideo(string path)
- {
- var file = await Device.Client.TelegramClient.GetFileAsync(Video.FileId);
- var fs = new FileStream(path, FileMode.Create);
- await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
- fs.Close();
- fs.Dispose();
- }
-
- public async Task DownloadAudio()
- {
- var encryptedContent = new MemoryStream();
- encryptedContent.SetLength(Audio.FileSize.Value);
- var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Audio.FileId, encryptedContent);
-
- return new InputOnlineFile(encryptedContent, "");
- }
-
- public async Task DownloadAudio(string path)
- {
- var file = await Device.Client.TelegramClient.GetFileAsync(Audio.FileId);
- var fs = new FileStream(path, FileMode.Create);
- await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
- fs.Close();
- fs.Dispose();
- }
-
- public async Task DownloadPhoto(int index)
- {
- var photo = Photos[index];
- var encryptedContent = new MemoryStream();
- encryptedContent.SetLength(photo.FileSize.Value);
- var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(photo.FileId, encryptedContent);
-
- return new InputOnlineFile(encryptedContent, "");
- }
-
- public async Task DownloadPhoto(int index, string path)
- {
- var photo = Photos[index];
- var file = await Device.Client.TelegramClient.GetFileAsync(photo.FileId);
- var fs = new FileStream(path, FileMode.Create);
- await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
- fs.Close();
- fs.Dispose();
- }
-
+ UpdateData = update;
}
-}
+
+ //public Telegram.Bot.Args.MessageEventArgs RawMessageData { get; set; }
+
+ public UpdateResult UpdateData { get; set; }
+
+
+ public Contact Contact => Message.Contact;
+
+ public Location Location => Message.Location;
+
+ public Document Document => Message.Document;
+
+ public Audio Audio => Message.Audio;
+
+ public Video Video => Message.Video;
+
+ public PhotoSize[] Photos => Message.Photo;
+
+
+ public MessageType Type => Message?.Type ?? MessageType.Unknown;
+
+ public override Message Message => UpdateData?.Message;
+
+ ///
+ /// Returns the FileId of the first reachable element.
+ ///
+ public string FileId =>
+ Document?.FileId ??
+ Audio?.FileId ??
+ Video?.FileId ??
+ Photos.FirstOrDefault()?.FileId;
+
+
+ public async Task DownloadDocument()
+ {
+ var encryptedContent = new MemoryStream();
+ encryptedContent.SetLength(Document.FileSize.Value);
+ var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId,
+ encryptedContent);
+
+ return new InputOnlineFile(encryptedContent, Document.FileName);
+ }
+
+
+ ///
+ /// Downloads a file and saves it to the given path.
+ ///
+ ///
+ ///
+ public async Task DownloadDocument(string path)
+ {
+ var file = await Device.Client.TelegramClient.GetFileAsync(Document.FileId);
+ var fs = new FileStream(path, FileMode.Create);
+ await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
+ fs.Close();
+ fs.Dispose();
+ }
+
+ ///
+ /// Downloads the document and returns an byte array.
+ ///
+ ///
+ public async Task DownloadRawDocument()
+ {
+ var ms = new MemoryStream();
+ await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, ms);
+ return ms.ToArray();
+ }
+
+ ///
+ /// Downloads a document and returns it as string. (txt,csv,etc) Default encoding ist UTF8.
+ ///
+ ///
+ public async Task DownloadRawTextDocument()
+ {
+ return await DownloadRawTextDocument(Encoding.UTF8);
+ }
+
+ ///
+ /// Downloads a document and returns it as string. (txt,csv,etc)
+ ///
+ ///
+ public async Task DownloadRawTextDocument(Encoding encoding)
+ {
+ var ms = new MemoryStream();
+ await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, ms);
+
+ ms.Position = 0;
+
+ var sr = new StreamReader(ms, encoding);
+
+ return sr.ReadToEnd();
+ }
+
+ public async Task DownloadVideo()
+ {
+ var encryptedContent = new MemoryStream();
+ encryptedContent.SetLength(Video.FileSize.Value);
+ var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Video.FileId, encryptedContent);
+
+ return new InputOnlineFile(encryptedContent, "");
+ }
+
+ public async Task DownloadVideo(string path)
+ {
+ var file = await Device.Client.TelegramClient.GetFileAsync(Video.FileId);
+ var fs = new FileStream(path, FileMode.Create);
+ await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
+ fs.Close();
+ fs.Dispose();
+ }
+
+ public async Task DownloadAudio()
+ {
+ var encryptedContent = new MemoryStream();
+ encryptedContent.SetLength(Audio.FileSize.Value);
+ var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Audio.FileId, encryptedContent);
+
+ return new InputOnlineFile(encryptedContent, "");
+ }
+
+ public async Task DownloadAudio(string path)
+ {
+ var file = await Device.Client.TelegramClient.GetFileAsync(Audio.FileId);
+ var fs = new FileStream(path, FileMode.Create);
+ await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
+ fs.Close();
+ fs.Dispose();
+ }
+
+ public async Task DownloadPhoto(int index)
+ {
+ var photo = Photos[index];
+ var encryptedContent = new MemoryStream();
+ encryptedContent.SetLength(photo.FileSize.Value);
+ var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(photo.FileId, encryptedContent);
+
+ return new InputOnlineFile(encryptedContent, "");
+ }
+
+ public async Task DownloadPhoto(int index, string path)
+ {
+ var photo = Photos[index];
+ var file = await Device.Client.TelegramClient.GetFileAsync(photo.FileId);
+ var fs = new FileStream(path, FileMode.Create);
+ await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
+ fs.Close();
+ fs.Dispose();
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Base/FormBase.cs b/TelegramBotBase/Base/FormBase.cs
index 583eabe..7557348 100644
--- a/TelegramBotBase/Base/FormBase.cs
+++ b/TelegramBotBase/Base/FormBase.cs
@@ -9,421 +9,442 @@ using TelegramBotBase.Form.Navigation;
using TelegramBotBase.Sessions;
using static TelegramBotBase.Base.Async;
-namespace TelegramBotBase.Form
+namespace TelegramBotBase.Form;
+
+///
+/// Base class for forms
+///
+public class FormBase : IDisposable
{
- ///
- /// Base class for forms
- ///
- public class FormBase : IDisposable
+ private static readonly object EvInit = new();
+
+ private static readonly object EvOpened = new();
+
+ private static readonly object EvClosed = new();
+
+
+ public EventHandlerList Events = new();
+
+
+ public FormBase()
{
+ Controls = new List();
+ }
- public NavigationController NavigationController { get; set; }
+ public FormBase(MessageClient client) : this()
+ {
+ Client = client;
+ }
- public DeviceSession Device { get; set; }
+ public NavigationController NavigationController { get; set; }
- public MessageClient Client { get; set; }
+ public DeviceSession Device { get; set; }
- ///
- /// has this formular already been disposed ?
- ///
- public bool IsDisposed { get; set; }
+ public MessageClient Client { get; set; }
- public List Controls { get; set; }
+ ///
+ /// has this formular already been disposed ?
+ ///
+ public bool IsDisposed { get; set; }
+
+ public List Controls { get; set; }
+
+ ///
+ /// Cleanup
+ ///
+ public void Dispose()
+ {
+ Client = null;
+ Device = null;
+ IsDisposed = true;
+ }
- public EventHandlerList Events = new EventHandlerList();
-
-
- private static readonly object EvInit = new object();
-
- private static readonly object EvOpened = new object();
-
- private static readonly object EvClosed = new object();
-
-
- public FormBase()
+ public async Task OnInit(InitEventArgs e)
+ {
+ var handler = Events[EvInit]?.GetInvocationList().Cast>();
+ if (handler == null)
{
- Controls = new List();
+ return;
}
- public FormBase(MessageClient client) : this()
+ foreach (var h in handler)
{
- this.Client = client;
- }
-
-
- public async Task OnInit(InitEventArgs e)
- {
- var handler = Events[EvInit]?.GetInvocationList().Cast>();
- if (handler == null)
- return;
-
- foreach (var h in handler)
- {
- await h.InvokeAllAsync(this, e);
- }
- }
-
- /////
- ///// Will get called at the initialization (once per context)
- /////
- public event AsyncEventHandler Init
- {
- add => Events.AddHandler(EvInit, value);
- remove => Events.RemoveHandler(EvInit, value);
- }
-
-
-
- public async Task OnOpened(EventArgs e)
- {
- var handler = Events[EvOpened]?.GetInvocationList().Cast>();
- if (handler == null)
- return;
-
- foreach (var h in handler)
- {
- await h.InvokeAllAsync(this, e);
- }
- }
-
- ///
- /// Gets invoked if gets navigated to this form
- ///
- ///
- public event AsyncEventHandler Opened
- {
- add => Events.AddHandler(EvOpened, value);
- remove => Events.RemoveHandler(EvOpened, value);
- }
-
-
-
- public async Task OnClosed(EventArgs e)
- {
- var handler = Events[EvClosed]?.GetInvocationList().Cast>();
- if (handler == null)
- return;
-
- foreach (var h in handler)
- {
- await h.InvokeAllAsync(this, e);
- }
- }
-
-
- ///
- /// Form has been closed (left)
- ///
- ///
- public event AsyncEventHandler Closed
- {
- add => Events.AddHandler(EvClosed, value);
- remove => Events.RemoveHandler(EvClosed, value);
- }
-
- ///
- /// Get invoked when a modal child from has been closed.
- ///
- ///
- ///
- public virtual Task ReturnFromModal(ModalDialog modal)
- {
- return Task.CompletedTask;
- }
-
-
- ///
- /// Pre to form close, cleanup all controls
- ///
- ///
- public Task CloseControls()
- {
- foreach (var b in Controls)
- {
- b.Cleanup().Wait();
- }
-
- return Task.CompletedTask;
- }
-
- public virtual Task PreLoad(MessageResult message)
- {
- return Task.CompletedTask;
- }
-
- ///
- /// Gets invoked if a message was sent or an action triggered
- ///
- ///
- ///
- public virtual async Task LoadControls(MessageResult message)
- {
- //Looking for the control by id, if not listened, raise event for all
- if (message.RawData?.StartsWith("#c") ?? false)
- {
- var c = Controls.FirstOrDefault(a => a.ControlId == message.RawData.Split('_')[0]);
- if (c != null)
- {
- await c.Load(message);
- return;
- }
- }
-
- foreach (var b in Controls)
- {
- if (!b.Enabled)
- continue;
-
- await b.Load(message);
- }
- }
-
- ///
- /// Gets invoked if the form gets loaded and on every message belongs to this context
- ///
- ///
- ///
- public virtual Task Load(MessageResult message)
- {
- return Task.CompletedTask;
- }
-
- ///
- /// Gets invoked, when a messages has been edited.
- ///
- ///
- ///
- public virtual Task Edited(MessageResult message)
- {
- return Task.CompletedTask;
- }
-
-
- ///
- /// Gets invoked if the user clicked a button.
- ///
- ///
- ///
- public virtual async Task ActionControls(MessageResult message)
- {
- //Looking for the control by id, if not listened, raise event for all
- if (message.RawData.StartsWith("#c"))
- {
- var c = Controls.FirstOrDefault(a => a.ControlId == message.RawData.Split('_')[0]);
- if (c != null)
- {
- await c.Action(message, message.RawData.Split('_')[1]);
- return;
- }
- }
-
- foreach (var b in Controls)
- {
- if (!b.Enabled)
- continue;
-
- await b.Action(message);
-
- if (message.Handled)
- return;
- }
- }
-
- ///
- /// Gets invoked if the user has clicked a button.
- ///
- ///
- ///
- public virtual Task Action(MessageResult message)
- {
- return Task.CompletedTask;
- }
-
- ///
- /// Gets invoked if the user has sent some media (Photo, Audio, Video, Contact, Location, Document)
- ///
- ///
- ///
- public virtual Task SentData(DataResult message)
- {
- return Task.CompletedTask;
- }
-
- ///
- /// Gets invoked at the end of the cycle to "Render" text, images, buttons, etc...
- ///
- ///
- ///
- public virtual async Task RenderControls(MessageResult message)
- {
- foreach (var b in Controls)
- {
- if (!b.Enabled)
- continue;
-
- await b.Render(message);
- }
- }
-
- ///
- /// Gets invoked at the end of the cycle to "Render" text, images, buttons, etc...
- ///
- ///
- ///
- public virtual Task Render(MessageResult message)
- {
- return Task.CompletedTask;
- }
-
-
-
- ///
- /// Navigates to a new form
- ///
- ///
- ///
- public virtual async Task NavigateTo(FormBase newForm, params object[] args)
- {
- var ds = Device;
- if (ds == null)
- return;
-
- ds.FormSwitched = true;
-
- ds.PreviousForm = ds.ActiveForm;
-
- ds.ActiveForm = newForm;
- newForm.Client = Client;
- newForm.Device = ds;
-
- //Notify prior to close
- foreach (var b in Controls)
- {
- if (!b.Enabled)
- continue;
-
- await b.Hidden(true);
- }
-
- CloseControls().Wait();
-
- await OnClosed(EventArgs.Empty);
-
- await newForm.OnInit(new InitEventArgs(args));
-
- await newForm.OnOpened(EventArgs.Empty);
- }
-
- ///
- /// Opens this form modal, but don't closes the original ones
- ///
- ///
- ///
- public virtual async Task OpenModal(ModalDialog newForm, params object[] args)
- {
- var ds = Device;
- if (ds == null)
- return;
-
- var parentForm = this;
-
- ds.FormSwitched = true;
-
- ds.PreviousForm = ds.ActiveForm;
-
- ds.ActiveForm = newForm;
- newForm.Client = parentForm.Client;
- newForm.Device = ds;
- newForm.ParentForm = parentForm;
-
- newForm.Closed += async (s, en) =>
- {
- await CloseModal(newForm, parentForm);
- };
-
- foreach (var b in Controls)
- {
- if (!b.Enabled)
- continue;
-
- await b.Hidden(false);
- }
-
- await newForm.OnInit(new InitEventArgs(args));
-
- await newForm.OnOpened(EventArgs.Empty);
- }
-
- public Task CloseModal(ModalDialog modalForm, FormBase oldForm)
- {
- var ds = Device;
- if (ds == null)
- return Task.CompletedTask;
-
- if (modalForm == null)
- throw new Exception("No modal form");
-
- ds.FormSwitched = true;
-
- ds.PreviousForm = ds.ActiveForm;
-
- ds.ActiveForm = oldForm;
- return Task.CompletedTask;
- }
-
- ///
- /// Adds a control to the formular and sets its ID and Device.
- ///
- ///
- public void AddControl(ControlBase control)
- {
- //Duplicate check
- if (Controls.Contains(control))
- throw new ArgumentException("Control has been already added.");
-
- control.Id = Controls.Count + 1;
- control.Device = Device;
- Controls.Add(control);
-
- control.Init();
- }
-
- ///
- /// Removes control from the formular and runs a cleanup on it.
- ///
- ///
- public void RemoveControl(ControlBase control)
- {
- if (!Controls.Contains(control))
- return;
-
- control.Cleanup().Wait();
-
- Controls.Remove(control);
- }
-
- ///
- /// Removes all controls.
- ///
- public void RemoveAllControls()
- {
- foreach(var c in Controls)
- {
- c.Cleanup().Wait();
-
- Controls.Remove(c);
- }
- }
-
- ///
- /// Cleanup
- ///
- public void Dispose()
- {
- Client = null;
- Device = null;
- IsDisposed = true;
+ await h.InvokeAllAsync(this, e);
}
}
-}
+
+ /////
+ ///// Will get called at the initialization (once per context)
+ /////
+ public event AsyncEventHandler Init
+ {
+ add => Events.AddHandler(EvInit, value);
+ remove => Events.RemoveHandler(EvInit, value);
+ }
+
+
+ public async Task OnOpened(EventArgs e)
+ {
+ var handler = Events[EvOpened]?.GetInvocationList().Cast>();
+ if (handler == null)
+ {
+ return;
+ }
+
+ foreach (var h in handler)
+ {
+ await h.InvokeAllAsync(this, e);
+ }
+ }
+
+ ///
+ /// Gets invoked if gets navigated to this form
+ ///
+ ///
+ public event AsyncEventHandler Opened
+ {
+ add => Events.AddHandler(EvOpened, value);
+ remove => Events.RemoveHandler(EvOpened, value);
+ }
+
+
+ public async Task OnClosed(EventArgs e)
+ {
+ var handler = Events[EvClosed]?.GetInvocationList().Cast>();
+ if (handler == null)
+ {
+ return;
+ }
+
+ foreach (var h in handler)
+ {
+ await h.InvokeAllAsync(this, e);
+ }
+ }
+
+
+ ///
+ /// Form has been closed (left)
+ ///
+ ///
+ public event AsyncEventHandler Closed
+ {
+ add => Events.AddHandler(EvClosed, value);
+ remove => Events.RemoveHandler(EvClosed, value);
+ }
+
+ ///
+ /// Get invoked when a modal child from has been closed.
+ ///
+ ///
+ ///
+ public virtual Task ReturnFromModal(ModalDialog modal)
+ {
+ return Task.CompletedTask;
+ }
+
+
+ ///
+ /// Pre to form close, cleanup all controls
+ ///
+ ///
+ public Task CloseControls()
+ {
+ foreach (var b in Controls)
+ {
+ b.Cleanup().Wait();
+ }
+
+ return Task.CompletedTask;
+ }
+
+ public virtual Task PreLoad(MessageResult message)
+ {
+ return Task.CompletedTask;
+ }
+
+ ///
+ /// Gets invoked if a message was sent or an action triggered
+ ///
+ ///
+ ///
+ public virtual async Task LoadControls(MessageResult message)
+ {
+ //Looking for the control by id, if not listened, raise event for all
+ if (message.RawData?.StartsWith("#c") ?? false)
+ {
+ var c = Controls.FirstOrDefault(a => a.ControlId == message.RawData.Split('_')[0]);
+ if (c != null)
+ {
+ await c.Load(message);
+ return;
+ }
+ }
+
+ foreach (var b in Controls)
+ {
+ if (!b.Enabled)
+ {
+ continue;
+ }
+
+ await b.Load(message);
+ }
+ }
+
+ ///
+ /// Gets invoked if the form gets loaded and on every message belongs to this context
+ ///
+ ///
+ ///
+ public virtual Task Load(MessageResult message)
+ {
+ return Task.CompletedTask;
+ }
+
+ ///
+ /// Gets invoked, when a messages has been edited.
+ ///
+ ///
+ ///
+ public virtual Task Edited(MessageResult message)
+ {
+ return Task.CompletedTask;
+ }
+
+
+ ///
+ /// Gets invoked if the user clicked a button.
+ ///
+ ///
+ ///
+ public virtual async Task ActionControls(MessageResult message)
+ {
+ //Looking for the control by id, if not listened, raise event for all
+ if (message.RawData.StartsWith("#c"))
+ {
+ var c = Controls.FirstOrDefault(a => a.ControlId == message.RawData.Split('_')[0]);
+ if (c != null)
+ {
+ await c.Action(message, message.RawData.Split('_')[1]);
+ return;
+ }
+ }
+
+ foreach (var b in Controls)
+ {
+ if (!b.Enabled)
+ {
+ continue;
+ }
+
+ await b.Action(message);
+
+ if (message.Handled)
+ {
+ return;
+ }
+ }
+ }
+
+ ///
+ /// Gets invoked if the user has clicked a button.
+ ///
+ ///
+ ///
+ public virtual Task Action(MessageResult message)
+ {
+ return Task.CompletedTask;
+ }
+
+ ///
+ /// Gets invoked if the user has sent some media (Photo, Audio, Video, Contact, Location, Document)
+ ///
+ ///
+ ///
+ public virtual Task SentData(DataResult message)
+ {
+ return Task.CompletedTask;
+ }
+
+ ///
+ /// Gets invoked at the end of the cycle to "Render" text, images, buttons, etc...
+ ///
+ ///
+ ///
+ public virtual async Task RenderControls(MessageResult message)
+ {
+ foreach (var b in Controls)
+ {
+ if (!b.Enabled)
+ {
+ continue;
+ }
+
+ await b.Render(message);
+ }
+ }
+
+ ///
+ /// Gets invoked at the end of the cycle to "Render" text, images, buttons, etc...
+ ///
+ ///
+ ///
+ public virtual Task Render(MessageResult message)
+ {
+ return Task.CompletedTask;
+ }
+
+
+ ///
+ /// Navigates to a new form
+ ///
+ ///
+ ///
+ public virtual async Task NavigateTo(FormBase newForm, params object[] args)
+ {
+ var ds = Device;
+ if (ds == null)
+ {
+ return;
+ }
+
+ ds.FormSwitched = true;
+
+ ds.PreviousForm = ds.ActiveForm;
+
+ ds.ActiveForm = newForm;
+ newForm.Client = Client;
+ newForm.Device = ds;
+
+ //Notify prior to close
+ foreach (var b in Controls)
+ {
+ if (!b.Enabled)
+ {
+ continue;
+ }
+
+ await b.Hidden(true);
+ }
+
+ CloseControls().Wait();
+
+ await OnClosed(EventArgs.Empty);
+
+ await newForm.OnInit(new InitEventArgs(args));
+
+ await newForm.OnOpened(EventArgs.Empty);
+ }
+
+ ///
+ /// Opens this form modal, but don't closes the original ones
+ ///
+ ///
+ ///
+ public virtual async Task OpenModal(ModalDialog newForm, params object[] args)
+ {
+ var ds = Device;
+ if (ds == null)
+ {
+ return;
+ }
+
+ var parentForm = this;
+
+ ds.FormSwitched = true;
+
+ ds.PreviousForm = ds.ActiveForm;
+
+ ds.ActiveForm = newForm;
+ newForm.Client = parentForm.Client;
+ newForm.Device = ds;
+ newForm.ParentForm = parentForm;
+
+ newForm.Closed += async (s, en) => { await CloseModal(newForm, parentForm); };
+
+ foreach (var b in Controls)
+ {
+ if (!b.Enabled)
+ {
+ continue;
+ }
+
+ await b.Hidden(false);
+ }
+
+ await newForm.OnInit(new InitEventArgs(args));
+
+ await newForm.OnOpened(EventArgs.Empty);
+ }
+
+ public Task CloseModal(ModalDialog modalForm, FormBase oldForm)
+ {
+ var ds = Device;
+ if (ds == null)
+ {
+ return Task.CompletedTask;
+ }
+
+ if (modalForm == null)
+ {
+ throw new Exception("No modal form");
+ }
+
+ ds.FormSwitched = true;
+
+ ds.PreviousForm = ds.ActiveForm;
+
+ ds.ActiveForm = oldForm;
+ return Task.CompletedTask;
+ }
+
+ ///
+ /// Adds a control to the formular and sets its ID and Device.
+ ///
+ ///
+ public void AddControl(ControlBase control)
+ {
+ //Duplicate check
+ if (Controls.Contains(control))
+ {
+ throw new ArgumentException("Control has been already added.");
+ }
+
+ control.Id = Controls.Count + 1;
+ control.Device = Device;
+ Controls.Add(control);
+
+ control.Init();
+ }
+
+ ///
+ /// Removes control from the formular and runs a cleanup on it.
+ ///
+ ///
+ public void RemoveControl(ControlBase control)
+ {
+ if (!Controls.Contains(control))
+ {
+ return;
+ }
+
+ control.Cleanup().Wait();
+
+ Controls.Remove(control);
+ }
+
+ ///
+ /// Removes all controls.
+ ///
+ public void RemoveAllControls()
+ {
+ foreach (var c in Controls)
+ {
+ c.Cleanup().Wait();
+
+ Controls.Remove(c);
+ }
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Base/MessageClient.cs b/TelegramBotBase/Base/MessageClient.cs
index 4813d86..a47ea16 100644
--- a/TelegramBotBase/Base/MessageClient.cs
+++ b/TelegramBotBase/Base/MessageClient.cs
@@ -10,193 +10,186 @@ using Telegram.Bot.Exceptions;
using Telegram.Bot.Extensions.Polling;
using Telegram.Bot.Types;
-namespace TelegramBotBase.Base
+namespace TelegramBotBase.Base;
+
+///
+/// Base class for message handling
+///
+public class MessageClient
{
- ///
- /// Base class for message handling
- ///
- public class MessageClient
+ private static readonly object EvOnMessageLoop = new();
+
+ private static object __evOnMessage = new();
+
+ private static object __evOnMessageEdit = new();
+
+ private static object __evCallbackQuery = new();
+
+ private CancellationTokenSource _cancellationTokenSource;
+
+
+ public MessageClient(string apiKey)
{
+ ApiKey = apiKey;
+ TelegramClient = new TelegramBotClient(apiKey);
-
- public string ApiKey { get; set; }
-
- public ITelegramBotClient TelegramClient { get; set; }
-
- private EventHandlerList Events { get; set; } = new EventHandlerList();
-
- private static readonly object EvOnMessageLoop = new object();
-
- private static object __evOnMessage = new object();
-
- private static object __evOnMessageEdit = new object();
-
- private static object __evCallbackQuery = new object();
-
- private CancellationTokenSource _cancellationTokenSource;
-
-
- public MessageClient(string apiKey)
- {
- this.ApiKey = apiKey;
- TelegramClient = new TelegramBotClient(apiKey);
-
- Prepare();
- }
-
- public MessageClient(string apiKey, HttpClient proxy)
- {
- this.ApiKey = apiKey;
- TelegramClient = new TelegramBotClient(apiKey, proxy);
-
-
- Prepare();
- }
-
-
-
- public MessageClient(string apiKey, Uri proxyUrl, NetworkCredential credential = null)
- {
- this.ApiKey = apiKey;
-
- var proxy = new WebProxy(proxyUrl)
- {
- Credentials = credential
- };
-
- var httpClient = new HttpClient(
- new HttpClientHandler { Proxy = proxy, UseProxy = true }
- );
-
- TelegramClient = new TelegramBotClient(apiKey, httpClient);
-
- Prepare();
- }
-
- ///
- /// Initializes the client with a proxy
- ///
- ///
- /// i.e. 127.0.0.1
- /// i.e. 10000
- public MessageClient(string apiKey, string proxyHost, int proxyPort)
- {
- this.ApiKey = apiKey;
-
- var proxy = new WebProxy(proxyHost, proxyPort);
-
- var httpClient = new HttpClient(
- new HttpClientHandler { Proxy = proxy, UseProxy = true }
- );
-
- TelegramClient = new TelegramBotClient(apiKey, httpClient);
-
- Prepare();
- }
-
-
-
- public MessageClient(string apiKey, TelegramBotClient client)
- {
- this.ApiKey = apiKey;
- TelegramClient = client;
-
- Prepare();
- }
-
-
- public void Prepare()
- {
- TelegramClient.Timeout = new TimeSpan(0, 0, 30);
-
- }
-
-
-
- public void StartReceiving()
- {
- _cancellationTokenSource = new CancellationTokenSource();
-
- var receiverOptions = new ReceiverOptions();
-
- TelegramClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, receiverOptions, _cancellationTokenSource.Token);
- }
-
- public void StopReceiving()
- {
- _cancellationTokenSource.Cancel();
- }
-
-
- public Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
- {
- OnMessageLoop(new UpdateResult(update, null));
-
- return Task.CompletedTask;
- }
-
- public Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
- {
- if (exception is ApiRequestException exApi)
- {
- Console.WriteLine($"Telegram API Error:\n[{exApi.ErrorCode}]\n{exApi.Message}");
- }
- else
- {
- Console.WriteLine(exception.ToString());
- }
- return Task.CompletedTask;
- }
-
-
- ///
- /// This will return the current list of bot commands.
- ///
- ///
- public async Task GetBotCommands(BotCommandScope scope = null, string languageCode = null)
- {
- return await TelegramClient.GetMyCommandsAsync(scope, languageCode);
- }
-
-
- ///
- /// This will set your bot commands to the given list.
- ///
- ///
- ///
- public async Task SetBotCommands(List botcommands, BotCommandScope scope = null, string languageCode = null)
- {
- await TelegramClient.SetMyCommandsAsync(botcommands, scope, languageCode);
- }
-
- ///
- /// This will delete the current list of bot commands.
- ///
- ///
- public async Task DeleteBotCommands(BotCommandScope scope = null, string languageCode = null)
- {
- await TelegramClient.DeleteMyCommandsAsync(scope, languageCode);
- }
-
-
- #region "Events"
-
-
-
- public event Async.AsyncEventHandler MessageLoop
- {
- add => Events.AddHandler(EvOnMessageLoop, value);
- remove => Events.RemoveHandler(EvOnMessageLoop, value);
- }
-
- public void OnMessageLoop(UpdateResult update)
- {
- (Events[EvOnMessageLoop] as Async.AsyncEventHandler)?.Invoke(this, update);
- }
-
-
- #endregion
-
-
+ Prepare();
}
-}
+
+ public MessageClient(string apiKey, HttpClient proxy)
+ {
+ ApiKey = apiKey;
+ TelegramClient = new TelegramBotClient(apiKey, proxy);
+
+
+ Prepare();
+ }
+
+
+ public MessageClient(string apiKey, Uri proxyUrl, NetworkCredential credential = null)
+ {
+ ApiKey = apiKey;
+
+ var proxy = new WebProxy(proxyUrl)
+ {
+ Credentials = credential
+ };
+
+ var httpClient = new HttpClient(
+ new HttpClientHandler { Proxy = proxy, UseProxy = true }
+ );
+
+ TelegramClient = new TelegramBotClient(apiKey, httpClient);
+
+ Prepare();
+ }
+
+ ///
+ /// Initializes the client with a proxy
+ ///
+ ///
+ /// i.e. 127.0.0.1
+ /// i.e. 10000
+ public MessageClient(string apiKey, string proxyHost, int proxyPort)
+ {
+ ApiKey = apiKey;
+
+ var proxy = new WebProxy(proxyHost, proxyPort);
+
+ var httpClient = new HttpClient(
+ new HttpClientHandler { Proxy = proxy, UseProxy = true }
+ );
+
+ TelegramClient = new TelegramBotClient(apiKey, httpClient);
+
+ Prepare();
+ }
+
+
+ public MessageClient(string apiKey, TelegramBotClient client)
+ {
+ ApiKey = apiKey;
+ TelegramClient = client;
+
+ Prepare();
+ }
+
+
+ public string ApiKey { get; set; }
+
+ public ITelegramBotClient TelegramClient { get; set; }
+
+ private EventHandlerList Events { get; } = new();
+
+
+ public void Prepare()
+ {
+ TelegramClient.Timeout = new TimeSpan(0, 0, 30);
+ }
+
+
+ public void StartReceiving()
+ {
+ _cancellationTokenSource = new CancellationTokenSource();
+
+ var receiverOptions = new ReceiverOptions();
+
+ TelegramClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, receiverOptions,
+ _cancellationTokenSource.Token);
+ }
+
+ public void StopReceiving()
+ {
+ _cancellationTokenSource.Cancel();
+ }
+
+
+ public Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
+ {
+ OnMessageLoop(new UpdateResult(update, null));
+
+ return Task.CompletedTask;
+ }
+
+ public Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception,
+ CancellationToken cancellationToken)
+ {
+ if (exception is ApiRequestException exApi)
+ {
+ Console.WriteLine($"Telegram API Error:\n[{exApi.ErrorCode}]\n{exApi.Message}");
+ }
+ else
+ {
+ Console.WriteLine(exception.ToString());
+ }
+
+ return Task.CompletedTask;
+ }
+
+
+ ///
+ /// This will return the current list of bot commands.
+ ///
+ ///
+ public async Task GetBotCommands(BotCommandScope scope = null, string languageCode = null)
+ {
+ return await TelegramClient.GetMyCommandsAsync(scope, languageCode);
+ }
+
+
+ ///
+ /// This will set your bot commands to the given list.
+ ///
+ ///
+ ///
+ public async Task SetBotCommands(List botcommands, BotCommandScope scope = null,
+ string languageCode = null)
+ {
+ await TelegramClient.SetMyCommandsAsync(botcommands, scope, languageCode);
+ }
+
+ ///
+ /// This will delete the current list of bot commands.
+ ///
+ ///
+ public async Task DeleteBotCommands(BotCommandScope scope = null, string languageCode = null)
+ {
+ await TelegramClient.DeleteMyCommandsAsync(scope, languageCode);
+ }
+
+
+ #region "Events"
+
+ public event Async.AsyncEventHandler MessageLoop
+ {
+ add => Events.AddHandler(EvOnMessageLoop, value);
+ remove => Events.RemoveHandler(EvOnMessageLoop, value);
+ }
+
+ public void OnMessageLoop(UpdateResult update)
+ {
+ (Events[EvOnMessageLoop] as Async.AsyncEventHandler)?.Invoke(this, update);
+ }
+
+ #endregion
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Base/MessageResult.cs b/TelegramBotBase/Base/MessageResult.cs
index 7d39fe7..531edf4 100644
--- a/TelegramBotBase/Base/MessageResult.cs
+++ b/TelegramBotBase/Base/MessageResult.cs
@@ -5,136 +5,134 @@ using Newtonsoft.Json;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
-namespace TelegramBotBase.Base
+namespace TelegramBotBase.Base;
+
+public class MessageResult : ResultBase
{
- public class MessageResult : ResultBase
+ internal MessageResult()
{
+ }
- public Update UpdateData { get; set; }
+ public MessageResult(Update update)
+ {
+ UpdateData = update;
+ }
- ///
- /// Returns the Device/ChatId
- ///
- public override long DeviceId =>
- UpdateData?.Message?.Chat?.Id
- ?? UpdateData?.EditedMessage?.Chat.Id
- ?? UpdateData?.CallbackQuery.Message?.Chat.Id
- ?? Device?.DeviceId
- ?? 0;
+ public Update UpdateData { get; set; }
- ///
- /// The message id
- ///
- public new int MessageId =>
- UpdateData?.Message?.MessageId
- ?? Message?.MessageId
- ?? UpdateData?.CallbackQuery?.Message?.MessageId
- ?? 0;
+ ///
+ /// Returns the Device/ChatId
+ ///
+ public override long DeviceId =>
+ UpdateData?.Message?.Chat?.Id
+ ?? UpdateData?.EditedMessage?.Chat.Id
+ ?? UpdateData?.CallbackQuery.Message?.Chat.Id
+ ?? Device?.DeviceId
+ ?? 0;
- public string Command => UpdateData?.Message?.Text ?? "";
+ ///
+ /// The message id
+ ///
+ public new int MessageId =>
+ UpdateData?.Message?.MessageId
+ ?? Message?.MessageId
+ ?? UpdateData?.CallbackQuery?.Message?.MessageId
+ ?? 0;
- public string MessageText => UpdateData?.Message?.Text ?? "";
+ public string Command => UpdateData?.Message?.Text ?? "";
- public MessageType MessageType => Message?.Type ?? MessageType.Unknown;
+ public string MessageText => UpdateData?.Message?.Text ?? "";
- ///
- /// Is this an action ? (i.e. button click)
- ///
- public bool IsAction => (UpdateData.CallbackQuery != null);
+ public MessageType MessageType => Message?.Type ?? MessageType.Unknown;
- ///
- /// Is this a command ? Starts with a slash '/' and a command
- ///
- public bool IsBotCommand => (MessageText.StartsWith("/"));
+ ///
+ /// Is this an action ? (i.e. button click)
+ ///
+ public bool IsAction => UpdateData.CallbackQuery != null;
- ///
- /// Returns a List of all parameters which has been sent with the command itself (i.e. /start 123 456 789 => 123,456,789)
- ///
- public List BotCommandParameters
+ ///
+ /// Is this a command ? Starts with a slash '/' and a command
+ ///
+ public bool IsBotCommand => MessageText.StartsWith("/");
+
+ ///
+ /// Returns a List of all parameters which has been sent with the command itself (i.e. /start 123 456 789 =>
+ /// 123,456,789)
+ ///
+ public List BotCommandParameters
+ {
+ get
{
- get
+ if (!IsBotCommand)
{
- if (!IsBotCommand)
- return new List();
-
- //Split by empty space and skip first entry (command itself), return as list
- return MessageText.Split(' ').Skip(1).ToList();
- }
- }
-
- ///
- /// Returns just the command (i.e. /start 1 2 3 => /start)
- ///
- public string BotCommand
- {
- get
- {
- if (!IsBotCommand)
- return null;
-
- return MessageText.Split(' ')[0];
- }
- }
-
- ///
- /// Returns if this message will be used on the first form or not.
- ///
- public bool IsFirstHandler { get; set; } = true;
-
- public bool Handled { get; set; } = false;
-
- public string RawData => UpdateData?.CallbackQuery?.Data;
-
- public T GetData()
- where T : class
- {
- T cd = null;
- try
- {
- cd = JsonConvert.DeserializeObject(RawData);
-
- return cd;
- }
- catch
- {
-
+ return new List();
}
- return null;
+ //Split by empty space and skip first entry (command itself), return as list
+ return MessageText.Split(' ').Skip(1).ToList();
}
+ }
- ///
- /// Confirm incomming action (i.e. Button click)
- ///
- ///
- ///
- public async Task ConfirmAction(string message = "", bool showAlert = false, string urlToOpen = null)
+ ///
+ /// Returns just the command (i.e. /start 1 2 3 => /start)
+ ///
+ public string BotCommand
+ {
+ get
{
- await Device.ConfirmAction(UpdateData.CallbackQuery.Id, message, showAlert, urlToOpen);
- }
-
- public override async Task DeleteMessage()
- {
- try
+ if (!IsBotCommand)
{
- await base.DeleteMessage(MessageId);
+ return null;
}
- catch
- {
- }
+ return MessageText.Split(' ')[0];
}
+ }
- internal MessageResult()
+ ///
+ /// Returns if this message will be used on the first form or not.
+ ///
+ public bool IsFirstHandler { get; set; } = true;
+
+ public bool Handled { get; set; } = false;
+
+ public string RawData => UpdateData?.CallbackQuery?.Data;
+
+ public T GetData()
+ where T : class
+ {
+ T cd = null;
+ try
{
+ cd = JsonConvert.DeserializeObject(RawData);
+ return cd;
}
-
- public MessageResult(Update update)
+ catch
{
- UpdateData = update;
-
}
+ return null;
+ }
+
+ ///
+ /// Confirm incomming action (i.e. Button click)
+ ///
+ ///
+ ///
+ public async Task ConfirmAction(string message = "", bool showAlert = false, string urlToOpen = null)
+ {
+ await Device.ConfirmAction(UpdateData.CallbackQuery.Id, message, showAlert, urlToOpen);
+ }
+
+ public override async Task DeleteMessage()
+ {
+ try
+ {
+ await base.DeleteMessage(MessageId);
+ }
+ catch
+ {
+ }
}
}
diff --git a/TelegramBotBase/Base/ResultBase.cs b/TelegramBotBase/Base/ResultBase.cs
index 59a130f..2845237 100644
--- a/TelegramBotBase/Base/ResultBase.cs
+++ b/TelegramBotBase/Base/ResultBase.cs
@@ -4,48 +4,42 @@ using Telegram.Bot;
using Telegram.Bot.Types;
using TelegramBotBase.Sessions;
-namespace TelegramBotBase.Base
+namespace TelegramBotBase.Base;
+
+public class ResultBase : EventArgs
{
- public class ResultBase : EventArgs
+ public DeviceSession Device { get; set; }
+
+ public virtual long DeviceId { get; set; }
+
+ public int MessageId => Message.MessageId;
+
+ public virtual Message Message { get; set; }
+
+ ///
+ /// Deletes the current message
+ ///
+ ///
+ ///
+ public virtual async Task DeleteMessage()
{
- public DeviceSession Device
- {
- get;
- set;
- }
-
- public virtual long DeviceId { get; set; }
-
- public int MessageId => Message.MessageId;
-
- public virtual Message Message { get; set; }
-
- ///
- /// Deletes the current message
- ///
- ///
- ///
- public virtual async Task DeleteMessage()
- {
- await DeleteMessage(MessageId);
- }
-
- ///
- ///Deletes the current message or the given one.
- ///
- ///
- ///
- public virtual async Task DeleteMessage(int messageId = -1)
- {
- try
- {
- await Device.Client.TelegramClient.DeleteMessageAsync(DeviceId, (messageId == -1 ? MessageId : messageId));
- }
- catch
- {
-
- }
- }
-
+ await DeleteMessage(MessageId);
}
-}
+
+ ///
+ /// Deletes the current message or the given one.
+ ///
+ ///
+ ///
+ public virtual async Task DeleteMessage(int messageId = -1)
+ {
+ try
+ {
+ await Device.Client.TelegramClient.DeleteMessageAsync(DeviceId,
+ messageId == -1 ? MessageId : messageId);
+ }
+ catch
+ {
+ }
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Base/StateContainer.cs b/TelegramBotBase/Base/StateContainer.cs
index 7e74cc6..de6b766 100644
--- a/TelegramBotBase/Base/StateContainer.cs
+++ b/TelegramBotBase/Base/StateContainer.cs
@@ -1,32 +1,24 @@
using System.Collections.Generic;
using System.Linq;
-namespace TelegramBotBase.Base
+namespace TelegramBotBase.Base;
+
+public class StateContainer
{
- public class StateContainer
+ public StateContainer()
{
- public List States { get; set; }
-
- public List ChatIds
- {
- get
- {
- return States.Where(a => a.DeviceId > 0).Select(a => a.DeviceId).ToList();
- }
- }
-
- public List GroupIds
- {
- get
- {
- return States.Where(a => a.DeviceId < 0).Select(a => a.DeviceId).ToList();
- }
- }
-
- public StateContainer()
- {
- States = new List();
- }
-
+ States = new List();
}
-}
+
+ public List States { get; set; }
+
+ public List ChatIds
+ {
+ get { return States.Where(a => a.DeviceId > 0).Select(a => a.DeviceId).ToList(); }
+ }
+
+ public List GroupIds
+ {
+ get { return States.Where(a => a.DeviceId < 0).Select(a => a.DeviceId).ToList(); }
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Base/StateEntry.cs b/TelegramBotBase/Base/StateEntry.cs
index 13e272f..8513804 100644
--- a/TelegramBotBase/Base/StateEntry.cs
+++ b/TelegramBotBase/Base/StateEntry.cs
@@ -1,41 +1,38 @@
using System.Collections.Generic;
using System.Diagnostics;
-namespace TelegramBotBase.Base
+namespace TelegramBotBase.Base;
+
+[DebuggerDisplay("Device: {DeviceId}, {FormUri}")]
+public class StateEntry
{
-
- [DebuggerDisplay("Device: {DeviceId}, {FormUri}")]
- public class StateEntry
+ public StateEntry()
{
- ///
- /// Contains the DeviceId of the entry.
- ///
- public long DeviceId { get; set; }
-
- ///
- /// Contains the Username (on privat chats) or Group title on groups/channels.
- ///
- public string ChatTitle { get; set; }
-
- ///
- /// Contains additional values to save.
- ///
- public Dictionary Values { get; set; }
-
- ///
- /// Contains the full qualified namespace of the form to used for reload it via reflection.
- ///
- public string FormUri {get;set;}
-
- ///
- /// Contains the assembly, where to find that form.
- ///
- public string QualifiedName { get; set; }
-
- public StateEntry()
- {
- Values = new Dictionary();
- }
-
+ Values = new Dictionary();
}
-}
+
+ ///
+ /// Contains the DeviceId of the entry.
+ ///
+ public long DeviceId { get; set; }
+
+ ///
+ /// Contains the Username (on privat chats) or Group title on groups/channels.
+ ///
+ public string ChatTitle { get; set; }
+
+ ///
+ /// Contains additional values to save.
+ ///
+ public Dictionary Values { get; set; }
+
+ ///
+ /// Contains the full qualified namespace of the form to used for reload it via reflection.
+ ///
+ public string FormUri { get; set; }
+
+ ///
+ /// Contains the assembly, where to find that form.
+ ///
+ public string QualifiedName { get; set; }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Base/UpdateResult.cs b/TelegramBotBase/Base/UpdateResult.cs
index 4d8e430..82d46b3 100644
--- a/TelegramBotBase/Base/UpdateResult.cs
+++ b/TelegramBotBase/Base/UpdateResult.cs
@@ -1,35 +1,31 @@
using Telegram.Bot.Types;
using TelegramBotBase.Sessions;
-namespace TelegramBotBase.Base
+namespace TelegramBotBase.Base;
+
+public class UpdateResult : ResultBase
{
- public class UpdateResult : ResultBase
+ public UpdateResult(Update rawData, DeviceSession device)
{
- public UpdateResult(Update rawData, DeviceSession device)
- {
- RawData = rawData;
- Device = device;
-
-
- }
-
- ///
- /// Returns the Device/ChatId
- ///
- public override long DeviceId =>
- RawData?.Message?.Chat?.Id
- ?? RawData?.CallbackQuery?.Message?.Chat?.Id
- ?? Device?.DeviceId
- ?? 0;
-
- public Update RawData { get; set; }
-
- public override Message Message =>
- RawData?.Message
- ?? RawData?.EditedMessage
- ?? RawData?.ChannelPost
- ?? RawData?.EditedChannelPost
- ?? RawData?.CallbackQuery?.Message;
+ RawData = rawData;
+ Device = device;
}
-}
+ ///
+ /// Returns the Device/ChatId
+ ///
+ public override long DeviceId =>
+ RawData?.Message?.Chat?.Id
+ ?? RawData?.CallbackQuery?.Message?.Chat?.Id
+ ?? Device?.DeviceId
+ ?? 0;
+
+ public Update RawData { get; set; }
+
+ public override Message Message =>
+ RawData?.Message
+ ?? RawData?.EditedMessage
+ ?? RawData?.ChannelPost
+ ?? RawData?.EditedChannelPost
+ ?? RawData?.CallbackQuery?.Message;
+}
\ No newline at end of file
diff --git a/TelegramBotBase/BotBase.cs b/TelegramBotBase/BotBase.cs
index 45b8a92..bac92e3 100644
--- a/TelegramBotBase/BotBase.cs
+++ b/TelegramBotBase/BotBase.cs
@@ -2,413 +2,409 @@
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
-using System.Text;
-using System.Threading;
using System.Threading.Tasks;
using Telegram.Bot;
-using Telegram.Bot.Exceptions;
using Telegram.Bot.Types;
-using Telegram.Bot.Types.Enums;
using TelegramBotBase.Args;
-using TelegramBotBase.Attributes;
using TelegramBotBase.Base;
using TelegramBotBase.Enums;
-using TelegramBotBase.MessageLoops;
-using TelegramBotBase.Form;
using TelegramBotBase.Interfaces;
using TelegramBotBase.Sessions;
+using Console = TelegramBotBase.Tools.Console;
-namespace TelegramBotBase
+namespace TelegramBotBase;
+
+///
+/// Bot base class for full Device/Context and Messagehandling
+///
+///
+public class BotBase
{
- ///
- /// Bot base class for full Device/Context and Messagehandling
- ///
- ///
- public class BotBase
+ public BotBase()
{
- public MessageClient Client { get; set; }
+ SystemSettings = new Dictionary();
- ///
- /// Your TelegramBot APIKey
- ///
- public string ApiKey { get; set; } = "";
+ SetSetting(ESettings.MaxNumberOfRetries, 5);
+ SetSetting(ESettings.NavigationMaximum, 10);
+ SetSetting(ESettings.LogAllMessages, false);
+ SetSetting(ESettings.SkipAllMessages, false);
+ SetSetting(ESettings.SaveSessionsOnConsoleExit, false);
- ///
- /// List of all running/active sessions
- ///
- public SessionBase Sessions { get; set; }
+ BotCommandScopes = new Dictionary>();
- ///
- /// Contains System commands which will be available at everytime and didnt get passed to forms, i.e. /start
- ///
- public Dictionary> BotCommandScopes { get; set; } = new Dictionary>();
-
-
- #region "Events"
-
- private readonly EventHandlerList _events = new EventHandlerList();
-
- private static readonly object EvSessionBegins = new object();
-
- private static readonly object EvMessage = new object();
-
- private static object __evSystemCall = new object();
-
- public delegate Task BotCommandEventHandler(object sender, BotCommandEventArgs e);
-
- private static readonly object EvException = new object();
-
- private static readonly object EvUnhandledCall = new object();
-
- #endregion
-
-
- ///
- /// Enable the SessionState (you need to implement on call forms the IStateForm interface)
- ///
- public IStateMachine StateMachine { get; set; }
-
- ///
- /// Offers functionality to manage the creation process of the start form.
- ///
- public IStartFormFactory StartFormFactory { get; set; }
-
- ///
- /// Contains the message loop factory, which cares about "message-management."
- ///
- public IMessageLoopFactory MessageLoopFactory { get; set; }
-
- ///
- /// All internal used settings.
- ///
- public Dictionary SystemSettings { get; private set; }
-
- public BotBase()
+ Sessions = new SessionBase
{
- SystemSettings = new Dictionary();
-
- SetSetting(ESettings.MaxNumberOfRetries, 5);
- SetSetting(ESettings.NavigationMaximum, 10);
- SetSetting(ESettings.LogAllMessages, false);
- SetSetting(ESettings.SkipAllMessages, false);
- SetSetting(ESettings.SaveSessionsOnConsoleExit, false);
-
- BotCommandScopes = new Dictionary>();
-
- Sessions = new SessionBase
- {
- BotBase = this
- };
- }
-
-
-
- ///
- /// Start your Bot
- ///
- public void Start()
- {
- if (Client == null)
- return;
-
- Client.MessageLoop += Client_MessageLoop;
-
-
- if (StateMachine != null)
- {
- Sessions.LoadSessionStates(StateMachine);
- }
-
- //Enable auto session saving
- if (GetSetting(ESettings.SaveSessionsOnConsoleExit, false))
- {
- Tools.Console.SetHandler(() =>
- {
- Sessions.SaveSessionStates();
- });
- }
-
- DeviceSession.MaxNumberOfRetries = GetSetting(ESettings.MaxNumberOfRetries, 5);
-
- Client.StartReceiving();
- }
-
-
- private async Task Client_MessageLoop(object sender, UpdateResult e)
- {
- var ds = Sessions.GetSession(e.DeviceId);
- if (ds == null)
- {
- ds = Sessions.StartSession(e.DeviceId).GetAwaiter().GetResult();
- e.Device = ds;
- ds.LastMessage = e.RawData.Message;
-
- OnSessionBegins(new SessionBeginEventArgs(e.DeviceId, ds));
- }
-
- var mr = new MessageResult(e.RawData);
-
- var i = 0;
-
- //Should formulars get navigated (allow maximum of 10, to dont get loops)
- do
- {
- i++;
-
- //Reset navigation
- ds.FormSwitched = false;
-
- await MessageLoopFactory.MessageLoop(this, ds, e, mr);
-
- mr.IsFirstHandler = false;
-
- } while (ds.FormSwitched && i < GetSetting(ESettings.NavigationMaximum, 10));
- }
-
-
- ///
- /// Stop your Bot
- ///
- public void Stop()
- {
- if (Client == null)
- return;
-
- Client.MessageLoop -= Client_MessageLoop;
-
-
- Client.StopReceiving();
-
- Sessions.SaveSessionStates();
- }
-
- ///
- /// Send a message to all active Sessions.
- ///
- ///
- ///
- public async Task SentToAll(string message)
- {
- if (Client == null)
- return;
-
- foreach (var s in Sessions.SessionList)
- {
- await Client.TelegramClient.SendTextMessageAsync(s.Key, message);
- }
- }
-
-
-
- ///
- /// This will invoke the full message loop for the device even when no "userevent" like message or action has been raised.
- ///
- /// Contains the device/chat id of the device to update.
- public async Task InvokeMessageLoop(long deviceId)
- {
- var mr = new MessageResult
- {
- UpdateData = new Update()
- {
- Message = new Message()
- }
- };
-
- await InvokeMessageLoop(deviceId, mr);
- }
-
- ///
- /// This will invoke the full message loop for the device even when no "userevent" like message or action has been raised.
- ///
- /// Contains the device/chat id of the device to update.
- ///
- public async Task InvokeMessageLoop(long deviceId, MessageResult e)
- {
- try
- {
- var ds = Sessions.GetSession(deviceId);
- e.Device = ds;
-
- await MessageLoopFactory.MessageLoop(this, ds, new UpdateResult(e.UpdateData, ds), e);
- //await Client_Loop(this, e);
- }
- catch (Exception ex)
- {
- var ds = Sessions.GetSession(deviceId);
- OnException(new SystemExceptionEventArgs(e.Message.Text, deviceId, ds, ex));
- }
- }
-
-
- ///
- /// Will get invoke on an unhandled call.
- ///
- ///
- ///
- public void MessageLoopFactory_UnhandledCall(object sender, UnhandledCallEventArgs e)
- {
- OnUnhandledCall(e);
- }
-
- ///
- /// This method will update all local created bot commands to the botfather.
- ///
- public async Task UploadBotCommands()
- {
- foreach (var bs in BotCommandScopes)
- {
- if(bs.Value !=null)
- {
- await Client.SetBotCommands(bs.Value, bs.Key);
- }
- else
- {
- await Client.DeleteBotCommands(bs.Key);
- }
-
- }
- }
-
- ///
- /// Searching if parameter is a known command in all configured BotCommandScopes.
- ///
- ///
- ///
- public bool IsKnownBotCommand(string command)
- {
- foreach (var scope in BotCommandScopes)
- {
- if (scope.Value.Any(a => "/" + a.Command == command))
- return true;
- }
-
- return false;
- }
-
- ///
- /// Could set a variety of settings to improve the bot handling.
- ///
- ///
- ///
- public void SetSetting(ESettings set, uint value)
- {
- SystemSettings[set] = value;
- }
-
- ///
- /// Could set a variety of settings to improve the bot handling.
- ///
- ///
- ///
- public void SetSetting(ESettings set, bool value)
- {
- SystemSettings[set] = (value ? 1u : 0u);
- }
-
- ///
- /// Could get the current value of a setting
- ///
- ///
- ///
- ///
- public uint GetSetting(ESettings set, uint defaultValue)
- {
- if (!SystemSettings.ContainsKey(set))
- return defaultValue;
-
- return SystemSettings[set];
- }
-
- ///
- /// Could get the current value of a setting
- ///
- ///
- ///
- ///
- public bool GetSetting(ESettings set, bool defaultValue)
- {
- if (!SystemSettings.ContainsKey(set))
- return defaultValue;
-
- return SystemSettings[set] == 0u ? false : true;
- }
-
- #region "Events"
-
- ///
- /// Will be called if a session/context gets started
- ///
-
- public event EventHandler SessionBegins
- {
- add => _events.AddHandler(EvSessionBegins, value);
- remove => _events.RemoveHandler(EvSessionBegins, value);
- }
-
- public void OnSessionBegins(SessionBeginEventArgs e)
- {
- (_events[EvSessionBegins] as EventHandler)?.Invoke(this, e);
-
- }
-
- ///
- /// Will be called on incomming message
- ///
- public event EventHandler Message
- {
- add => _events.AddHandler(EvMessage, value);
- remove => _events.RemoveHandler(EvMessage, value);
- }
-
- public void OnMessage(MessageIncomeEventArgs e)
- {
- (_events[EvMessage] as EventHandler)?.Invoke(this, e);
-
- }
-
- ///
- /// Will be called if a bot command gets raised
- ///
- public event BotCommandEventHandler BotCommand;
-
-
- public async Task OnBotCommand(BotCommandEventArgs e)
- {
- if (BotCommand != null)
- await BotCommand(this, e);
- }
-
- ///
- /// Will be called on an inner exception
- ///
- public event EventHandler Exception
- {
- add => _events.AddHandler(EvException, value);
- remove => _events.RemoveHandler(EvException, value);
- }
-
- public void OnException(SystemExceptionEventArgs e)
- {
- (_events[EvException] as EventHandler)?.Invoke(this, e);
-
- }
-
- ///
- /// Will be called if no form handeled this call
- ///
- public event EventHandler UnhandledCall
- {
- add => _events.AddHandler(EvUnhandledCall, value);
- remove => _events.RemoveHandler(EvUnhandledCall, value);
- }
-
- public void OnUnhandledCall(UnhandledCallEventArgs e)
- {
- (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e);
-
- }
-
- #endregion
-
+ BotBase = this
+ };
}
-}
+
+ public MessageClient Client { get; set; }
+
+ ///
+ /// Your TelegramBot APIKey
+ ///
+ public string ApiKey { get; set; } = "";
+
+ ///
+ /// List of all running/active sessions
+ ///
+ public SessionBase Sessions { get; set; }
+
+ ///
+ /// Contains System commands which will be available at everytime and didnt get passed to forms, i.e. /start
+ ///
+ public Dictionary> BotCommandScopes { get; set; } = new();
+
+
+ ///
+ /// Enable the SessionState (you need to implement on call forms the IStateForm interface)
+ ///
+ public IStateMachine StateMachine { get; set; }
+
+ ///
+ /// Offers functionality to manage the creation process of the start form.
+ ///
+ public IStartFormFactory StartFormFactory { get; set; }
+
+ ///
+ /// Contains the message loop factory, which cares about "message-management."
+ ///
+ public IMessageLoopFactory MessageLoopFactory { get; set; }
+
+ ///
+ /// All internal used settings.
+ ///
+ public Dictionary SystemSettings { get; }
+
+
+ ///
+ /// Start your Bot
+ ///
+ public void Start()
+ {
+ if (Client == null)
+ {
+ return;
+ }
+
+ Client.MessageLoop += Client_MessageLoop;
+
+
+ if (StateMachine != null)
+ {
+ Sessions.LoadSessionStates(StateMachine);
+ }
+
+ //Enable auto session saving
+ if (GetSetting(ESettings.SaveSessionsOnConsoleExit, false))
+ {
+ Console.SetHandler(() => { Sessions.SaveSessionStates(); });
+ }
+
+ DeviceSession.MaxNumberOfRetries = GetSetting(ESettings.MaxNumberOfRetries, 5);
+
+ Client.StartReceiving();
+ }
+
+
+ private async Task Client_MessageLoop(object sender, UpdateResult e)
+ {
+ var ds = Sessions.GetSession(e.DeviceId);
+ if (ds == null)
+ {
+ ds = Sessions.StartSession(e.DeviceId).GetAwaiter().GetResult();
+ e.Device = ds;
+ ds.LastMessage = e.RawData.Message;
+
+ OnSessionBegins(new SessionBeginEventArgs(e.DeviceId, ds));
+ }
+
+ var mr = new MessageResult(e.RawData);
+
+ var i = 0;
+
+ //Should formulars get navigated (allow maximum of 10, to dont get loops)
+ do
+ {
+ i++;
+
+ //Reset navigation
+ ds.FormSwitched = false;
+
+ await MessageLoopFactory.MessageLoop(this, ds, e, mr);
+
+ mr.IsFirstHandler = false;
+ } while (ds.FormSwitched && i < GetSetting(ESettings.NavigationMaximum, 10));
+ }
+
+
+ ///
+ /// Stop your Bot
+ ///
+ public void Stop()
+ {
+ if (Client == null)
+ {
+ return;
+ }
+
+ Client.MessageLoop -= Client_MessageLoop;
+
+
+ Client.StopReceiving();
+
+ Sessions.SaveSessionStates();
+ }
+
+ ///
+ /// Send a message to all active Sessions.
+ ///
+ ///
+ ///
+ public async Task SentToAll(string message)
+ {
+ if (Client == null)
+ {
+ return;
+ }
+
+ foreach (var s in Sessions.SessionList)
+ {
+ await Client.TelegramClient.SendTextMessageAsync(s.Key, message);
+ }
+ }
+
+
+ ///
+ /// This will invoke the full message loop for the device even when no "userevent" like message or action has been
+ /// raised.
+ ///
+ /// Contains the device/chat id of the device to update.
+ public async Task InvokeMessageLoop(long deviceId)
+ {
+ var mr = new MessageResult
+ {
+ UpdateData = new Update
+ {
+ Message = new Message()
+ }
+ };
+
+ await InvokeMessageLoop(deviceId, mr);
+ }
+
+ ///
+ /// This will invoke the full message loop for the device even when no "userevent" like message or action has been
+ /// raised.
+ ///
+ /// Contains the device/chat id of the device to update.
+ ///
+ public async Task InvokeMessageLoop(long deviceId, MessageResult e)
+ {
+ try
+ {
+ var ds = Sessions.GetSession(deviceId);
+ e.Device = ds;
+
+ await MessageLoopFactory.MessageLoop(this, ds, new UpdateResult(e.UpdateData, ds), e);
+ //await Client_Loop(this, e);
+ }
+ catch (Exception ex)
+ {
+ var ds = Sessions.GetSession(deviceId);
+ OnException(new SystemExceptionEventArgs(e.Message.Text, deviceId, ds, ex));
+ }
+ }
+
+
+ ///
+ /// Will get invoke on an unhandled call.
+ ///
+ ///
+ ///
+ public void MessageLoopFactory_UnhandledCall(object sender, UnhandledCallEventArgs e)
+ {
+ OnUnhandledCall(e);
+ }
+
+ ///
+ /// This method will update all local created bot commands to the botfather.
+ ///
+ public async Task UploadBotCommands()
+ {
+ foreach (var bs in BotCommandScopes)
+ {
+ if (bs.Value != null)
+ {
+ await Client.SetBotCommands(bs.Value, bs.Key);
+ }
+ else
+ {
+ await Client.DeleteBotCommands(bs.Key);
+ }
+ }
+ }
+
+ ///
+ /// Searching if parameter is a known command in all configured BotCommandScopes.
+ ///
+ ///
+ ///
+ public bool IsKnownBotCommand(string command)
+ {
+ foreach (var scope in BotCommandScopes)
+ {
+ if (scope.Value.Any(a => "/" + a.Command == command))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ ///
+ /// Could set a variety of settings to improve the bot handling.
+ ///
+ ///
+ ///
+ public void SetSetting(ESettings set, uint value)
+ {
+ SystemSettings[set] = value;
+ }
+
+ ///
+ /// Could set a variety of settings to improve the bot handling.
+ ///
+ ///
+ ///
+ public void SetSetting(ESettings set, bool value)
+ {
+ SystemSettings[set] = value ? 1u : 0u;
+ }
+
+ ///
+ /// Could get the current value of a setting
+ ///
+ ///
+ ///
+ ///
+ public uint GetSetting(ESettings set, uint defaultValue)
+ {
+ if (!SystemSettings.ContainsKey(set))
+ {
+ return defaultValue;
+ }
+
+ return SystemSettings[set];
+ }
+
+ ///
+ /// Could get the current value of a setting
+ ///
+ ///
+ ///
+ ///
+ public bool GetSetting(ESettings set, bool defaultValue)
+ {
+ if (!SystemSettings.ContainsKey(set))
+ {
+ return defaultValue;
+ }
+
+ return SystemSettings[set] == 0u ? false : true;
+ }
+
+
+ #region "Events"
+
+ private readonly EventHandlerList _events = new();
+
+ private static readonly object EvSessionBegins = new();
+
+ private static readonly object EvMessage = new();
+
+ private static object __evSystemCall = new();
+
+ public delegate Task BotCommandEventHandler(object sender, BotCommandEventArgs e);
+
+ private static readonly object EvException = new();
+
+ private static readonly object EvUnhandledCall = new();
+
+ #endregion
+
+ #region "Events"
+
+ ///
+ /// Will be called if a session/context gets started
+ ///
+ public event EventHandler SessionBegins
+ {
+ add => _events.AddHandler(EvSessionBegins, value);
+ remove => _events.RemoveHandler(EvSessionBegins, value);
+ }
+
+ public void OnSessionBegins(SessionBeginEventArgs e)
+ {
+ (_events[EvSessionBegins] as EventHandler)?.Invoke(this, e);
+ }
+
+ ///
+ /// Will be called on incomming message
+ ///
+ public event EventHandler Message
+ {
+ add => _events.AddHandler(EvMessage, value);
+ remove => _events.RemoveHandler(EvMessage, value);
+ }
+
+ public void OnMessage(MessageIncomeEventArgs e)
+ {
+ (_events[EvMessage] as EventHandler)?.Invoke(this, e);
+ }
+
+ ///
+ /// Will be called if a bot command gets raised
+ ///
+ public event BotCommandEventHandler BotCommand;
+
+
+ public async Task OnBotCommand(BotCommandEventArgs e)
+ {
+ if (BotCommand != null)
+ {
+ await BotCommand(this, e);
+ }
+ }
+
+ ///
+ /// Will be called on an inner exception
+ ///
+ public event EventHandler Exception
+ {
+ add => _events.AddHandler(EvException, value);
+ remove => _events.RemoveHandler(EvException, value);
+ }
+
+ public void OnException(SystemExceptionEventArgs e)
+ {
+ (_events[EvException] as EventHandler)?.Invoke(this, e);
+ }
+
+ ///
+ /// Will be called if no form handeled this call
+ ///
+ public event EventHandler UnhandledCall
+ {
+ add => _events.AddHandler(EvUnhandledCall, value);
+ remove => _events.RemoveHandler(EvUnhandledCall, value);
+ }
+
+ public void OnUnhandledCall(UnhandledCallEventArgs e)
+ {
+ (_events[EvUnhandledCall] as EventHandler)?.Invoke(this, e);
+ }
+
+ #endregion
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Builder/BotBaseBuilder.cs b/TelegramBotBase/Builder/BotBaseBuilder.cs
index 216d09f..ffd2d58 100644
--- a/TelegramBotBase/Builder/BotBaseBuilder.cs
+++ b/TelegramBotBase/Builder/BotBaseBuilder.cs
@@ -13,362 +13,360 @@ using TelegramBotBase.Localizations;
using TelegramBotBase.MessageLoops;
using TelegramBotBase.States;
-namespace TelegramBotBase.Builder
+namespace TelegramBotBase.Builder;
+
+public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, IStartFormSelectionStage,
+ IBuildingStage, INetworkingSelectionStage, IBotCommandsStage, ISessionSerializationStage,
+ ILanguageSelectionStage
{
- public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, IStartFormSelectionStage, IBuildingStage, INetworkingSelectionStage, IBotCommandsStage, ISessionSerializationStage, ILanguageSelectionStage
+ private string _apiKey;
+
+ private MessageClient _client;
+
+ private IStartFormFactory _factory;
+
+ private IMessageLoopFactory _messageLoopFactory;
+
+ private IStateMachine _statemachine;
+
+ private BotBaseBuilder()
{
- private string _apiKey;
-
- private IStartFormFactory _factory;
-
- private MessageClient _client;
-
- ///
- /// Contains different Botcommands for different areas.
- ///
- private Dictionary> BotCommandScopes { get; set; } = new Dictionary>();
-
- private IStateMachine _statemachine;
-
- private IMessageLoopFactory _messageLoopFactory;
-
- private BotBaseBuilder()
- {
-
- }
-
- public static IAPIKeySelectionStage Create()
- {
- return new BotBaseBuilder();
- }
-
- #region "Step 1 (Basic Stuff)"
-
- public IMessageLoopSelectionStage WithAPIKey(string apiKey)
- {
- _apiKey = apiKey;
- return this;
- }
-
-
- public IBuildingStage QuickStart(string apiKey, Type StartForm)
- {
- _apiKey = apiKey;
- _factory = new DefaultStartFormFactory(StartForm);
-
- DefaultMessageLoop();
-
- NoProxy();
-
- OnlyStart();
-
- NoSerialization();
-
- DefaultLanguage();
-
- return this;
- }
-
-
- public IBuildingStage QuickStart(string apiKey)
- where T : FormBase
- {
- _apiKey = apiKey;
- _factory = new DefaultStartFormFactory(typeof(T));
-
- DefaultMessageLoop();
-
- NoProxy();
-
- OnlyStart();
-
- NoSerialization();
-
- DefaultLanguage();
-
- return this;
- }
-
- public IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory)
- {
- _apiKey = apiKey;
- _factory = StartFormFactory;
-
- DefaultMessageLoop();
-
- NoProxy();
-
- OnlyStart();
-
- NoSerialization();
-
- DefaultLanguage();
-
- return this;
- }
-
- #endregion
-
-
- #region "Step 2 (Message Loop)"
-
- public IStartFormSelectionStage DefaultMessageLoop()
- {
- _messageLoopFactory = new FormBaseMessageLoop();
-
- return this;
- }
-
-
- public IStartFormSelectionStage MinimalMessageLoop()
- {
- _messageLoopFactory = new MinimalMessageLoop();
-
- return this;
- }
-
-
- public IStartFormSelectionStage CustomMessageLoop(IMessageLoopFactory messageLoopClass)
- {
- _messageLoopFactory = messageLoopClass;
-
- return this;
- }
-
- public IStartFormSelectionStage CustomMessageLoop()
- where T : class, new()
- {
- _messageLoopFactory = typeof(T).GetConstructor(new Type[] { })?.Invoke(new object[] { }) as IMessageLoopFactory;
-
- return this;
- }
-
- #endregion
-
-
- #region "Step 3 (Start Form/Factory)"
-
- public INetworkingSelectionStage WithStartForm(Type startFormClass)
- {
- _factory = new DefaultStartFormFactory(startFormClass);
- return this;
- }
-
- public INetworkingSelectionStage WithStartForm()
- where T : FormBase, new()
- {
- _factory = new DefaultStartFormFactory(typeof(T));
- return this;
- }
-
- public INetworkingSelectionStage WithServiceProvider(Type startFormClass, IServiceProvider serviceProvider)
- {
- _factory = new ServiceProviderStartFormFactory(startFormClass, serviceProvider);
- return this;
- }
-
- public INetworkingSelectionStage WithServiceProvider(IServiceProvider serviceProvider)
- where T : FormBase
- {
- _factory = new ServiceProviderStartFormFactory(serviceProvider);
- return this;
- }
-
- public INetworkingSelectionStage WithStartFormFactory(IStartFormFactory factory)
- {
- _factory = factory;
- return this;
- }
-
- #endregion
-
-
- #region "Step 4 (Network Settings)"
-
- public IBotCommandsStage WithProxy(string proxyAddress)
- {
- var url = new Uri(proxyAddress);
- _client = new MessageClient(_apiKey, url)
- {
- TelegramClient =
- {
- Timeout = new TimeSpan(0, 1, 0)
- }
- };
- return this;
- }
-
-
- public IBotCommandsStage NoProxy()
- {
- _client = new MessageClient(_apiKey)
- {
- TelegramClient =
- {
- Timeout = new TimeSpan(0, 1, 0)
- }
- };
- return this;
- }
-
-
- public IBotCommandsStage WithBotClient(TelegramBotClient tgclient)
- {
- _client = new MessageClient(_apiKey, tgclient)
- {
- TelegramClient =
- {
- Timeout = new TimeSpan(0, 1, 0)
- }
- };
- return this;
- }
-
-
- public IBotCommandsStage WithHostAndPort(string proxyHost, int proxyPort)
- {
- _client = new MessageClient(_apiKey, proxyHost, proxyPort)
- {
- TelegramClient =
- {
- Timeout = new TimeSpan(0, 1, 0)
- }
- };
- return this;
- }
-
- public IBotCommandsStage WithHttpClient(HttpClient tgclient)
- {
- _client = new MessageClient(_apiKey, tgclient)
- {
- TelegramClient =
- {
- Timeout = new TimeSpan(0, 1, 0)
- }
- };
- return this;
- }
-
-
- #endregion
-
-
- #region "Step 5 (Bot Commands)"
-
- public ISessionSerializationStage NoCommands()
- {
- return this;
- }
-
- public ISessionSerializationStage OnlyStart()
- {
- BotCommandScopes.Start("Starts the bot");
-
- return this;
-
- }
-
- public ISessionSerializationStage DefaultCommands()
- {
- BotCommandScopes.Start("Starts the bot");
- BotCommandScopes.Help("Should show you some help");
- BotCommandScopes.Settings("Should show you some settings");
- return this;
- }
-
- public ISessionSerializationStage CustomCommands(Action>> action)
- {
- action?.Invoke(BotCommandScopes);
- return this;
- }
-
- #endregion
-
-
- #region "Step 6 (Serialization)"
-
- public ILanguageSelectionStage NoSerialization()
- {
- return this;
- }
-
- public ILanguageSelectionStage UseSerialization(IStateMachine machine)
- {
- _statemachine = machine;
- return this;
- }
-
-
- public ILanguageSelectionStage UseJSON(string path)
- {
- _statemachine = new JsonStateMachine(path);
- return this;
- }
-
- public ILanguageSelectionStage UseSimpleJSON(string path)
- {
- _statemachine = new SimpleJsonStateMachine(path);
- return this;
- }
-
- public ILanguageSelectionStage UseXML(string path)
- {
- _statemachine = new XmlStateMachine(path);
- return this;
- }
-
- #endregion
-
-
- #region "Step 7 (Language)"
-
- public IBuildingStage DefaultLanguage()
- {
- return this;
- }
-
- public IBuildingStage UseEnglish()
- {
- Default.Language = new English();
- return this;
- }
-
- public IBuildingStage UseGerman()
- {
- Default.Language = new German();
- return this;
- }
-
- public IBuildingStage Custom(Localization language)
- {
- Default.Language = language;
- return this;
- }
-
- #endregion
-
-
- public BotBase Build()
- {
- var bb = new BotBase
- {
- ApiKey = _apiKey,
- StartFormFactory = _factory,
- Client = _client
- };
-
- bb.Sessions.Client = bb.Client;
-
- bb.BotCommandScopes = BotCommandScopes;
-
- bb.StateMachine = _statemachine;
-
- bb.MessageLoopFactory = _messageLoopFactory;
-
- bb.MessageLoopFactory.UnhandledCall += bb.MessageLoopFactory_UnhandledCall;
-
- return bb;
- }
-
}
-}
+
+ ///
+ /// Contains different Botcommands for different areas.
+ ///
+ private Dictionary> BotCommandScopes { get; } = new();
+
+
+ public BotBase Build()
+ {
+ var bb = new BotBase
+ {
+ ApiKey = _apiKey,
+ StartFormFactory = _factory,
+ Client = _client
+ };
+
+ bb.Sessions.Client = bb.Client;
+
+ bb.BotCommandScopes = BotCommandScopes;
+
+ bb.StateMachine = _statemachine;
+
+ bb.MessageLoopFactory = _messageLoopFactory;
+
+ bb.MessageLoopFactory.UnhandledCall += bb.MessageLoopFactory_UnhandledCall;
+
+ return bb;
+ }
+
+ public static IAPIKeySelectionStage Create()
+ {
+ return new BotBaseBuilder();
+ }
+
+ #region "Step 1 (Basic Stuff)"
+
+ public IMessageLoopSelectionStage WithAPIKey(string apiKey)
+ {
+ _apiKey = apiKey;
+ return this;
+ }
+
+
+ public IBuildingStage QuickStart(string apiKey, Type StartForm)
+ {
+ _apiKey = apiKey;
+ _factory = new DefaultStartFormFactory(StartForm);
+
+ DefaultMessageLoop();
+
+ NoProxy();
+
+ OnlyStart();
+
+ NoSerialization();
+
+ DefaultLanguage();
+
+ return this;
+ }
+
+
+ public IBuildingStage QuickStart(string apiKey)
+ where T : FormBase
+ {
+ _apiKey = apiKey;
+ _factory = new DefaultStartFormFactory(typeof(T));
+
+ DefaultMessageLoop();
+
+ NoProxy();
+
+ OnlyStart();
+
+ NoSerialization();
+
+ DefaultLanguage();
+
+ return this;
+ }
+
+ public IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory)
+ {
+ _apiKey = apiKey;
+ _factory = StartFormFactory;
+
+ DefaultMessageLoop();
+
+ NoProxy();
+
+ OnlyStart();
+
+ NoSerialization();
+
+ DefaultLanguage();
+
+ return this;
+ }
+
+ #endregion
+
+
+ #region "Step 2 (Message Loop)"
+
+ public IStartFormSelectionStage DefaultMessageLoop()
+ {
+ _messageLoopFactory = new FormBaseMessageLoop();
+
+ return this;
+ }
+
+
+ public IStartFormSelectionStage MinimalMessageLoop()
+ {
+ _messageLoopFactory = new MinimalMessageLoop();
+
+ return this;
+ }
+
+
+ public IStartFormSelectionStage CustomMessageLoop(IMessageLoopFactory messageLoopClass)
+ {
+ _messageLoopFactory = messageLoopClass;
+
+ return this;
+ }
+
+ public IStartFormSelectionStage CustomMessageLoop()
+ where T : class, new()
+ {
+ _messageLoopFactory =
+ typeof(T).GetConstructor(new Type[] { })?.Invoke(new object[] { }) as IMessageLoopFactory;
+
+ return this;
+ }
+
+ #endregion
+
+
+ #region "Step 3 (Start Form/Factory)"
+
+ public INetworkingSelectionStage WithStartForm(Type startFormClass)
+ {
+ _factory = new DefaultStartFormFactory(startFormClass);
+ return this;
+ }
+
+ public INetworkingSelectionStage WithStartForm()
+ where T : FormBase, new()
+ {
+ _factory = new DefaultStartFormFactory(typeof(T));
+ return this;
+ }
+
+ public INetworkingSelectionStage WithServiceProvider(Type startFormClass, IServiceProvider serviceProvider)
+ {
+ _factory = new ServiceProviderStartFormFactory(startFormClass, serviceProvider);
+ return this;
+ }
+
+ public INetworkingSelectionStage WithServiceProvider(IServiceProvider serviceProvider)
+ where T : FormBase
+ {
+ _factory = new ServiceProviderStartFormFactory(serviceProvider);
+ return this;
+ }
+
+ public INetworkingSelectionStage WithStartFormFactory(IStartFormFactory factory)
+ {
+ _factory = factory;
+ return this;
+ }
+
+ #endregion
+
+
+ #region "Step 4 (Network Settings)"
+
+ public IBotCommandsStage WithProxy(string proxyAddress)
+ {
+ var url = new Uri(proxyAddress);
+ _client = new MessageClient(_apiKey, url)
+ {
+ TelegramClient =
+ {
+ Timeout = new TimeSpan(0, 1, 0)
+ }
+ };
+ return this;
+ }
+
+
+ public IBotCommandsStage NoProxy()
+ {
+ _client = new MessageClient(_apiKey)
+ {
+ TelegramClient =
+ {
+ Timeout = new TimeSpan(0, 1, 0)
+ }
+ };
+ return this;
+ }
+
+
+ public IBotCommandsStage WithBotClient(TelegramBotClient tgclient)
+ {
+ _client = new MessageClient(_apiKey, tgclient)
+ {
+ TelegramClient =
+ {
+ Timeout = new TimeSpan(0, 1, 0)
+ }
+ };
+ return this;
+ }
+
+
+ public IBotCommandsStage WithHostAndPort(string proxyHost, int proxyPort)
+ {
+ _client = new MessageClient(_apiKey, proxyHost, proxyPort)
+ {
+ TelegramClient =
+ {
+ Timeout = new TimeSpan(0, 1, 0)
+ }
+ };
+ return this;
+ }
+
+ public IBotCommandsStage WithHttpClient(HttpClient tgclient)
+ {
+ _client = new MessageClient(_apiKey, tgclient)
+ {
+ TelegramClient =
+ {
+ Timeout = new TimeSpan(0, 1, 0)
+ }
+ };
+ return this;
+ }
+
+ #endregion
+
+
+ #region "Step 5 (Bot Commands)"
+
+ public ISessionSerializationStage NoCommands()
+ {
+ return this;
+ }
+
+ public ISessionSerializationStage OnlyStart()
+ {
+ BotCommandScopes.Start("Starts the bot");
+
+ return this;
+ }
+
+ public ISessionSerializationStage DefaultCommands()
+ {
+ BotCommandScopes.Start("Starts the bot");
+ BotCommandScopes.Help("Should show you some help");
+ BotCommandScopes.Settings("Should show you some settings");
+ return this;
+ }
+
+ public ISessionSerializationStage CustomCommands(Action>> action)
+ {
+ action?.Invoke(BotCommandScopes);
+ return this;
+ }
+
+ #endregion
+
+
+ #region "Step 6 (Serialization)"
+
+ public ILanguageSelectionStage NoSerialization()
+ {
+ return this;
+ }
+
+ public ILanguageSelectionStage UseSerialization(IStateMachine machine)
+ {
+ _statemachine = machine;
+ return this;
+ }
+
+
+ public ILanguageSelectionStage UseJSON(string path)
+ {
+ _statemachine = new JsonStateMachine(path);
+ return this;
+ }
+
+ public ILanguageSelectionStage UseSimpleJSON(string path)
+ {
+ _statemachine = new SimpleJsonStateMachine(path);
+ return this;
+ }
+
+ public ILanguageSelectionStage UseXML(string path)
+ {
+ _statemachine = new XmlStateMachine(path);
+ return this;
+ }
+
+ #endregion
+
+
+ #region "Step 7 (Language)"
+
+ public IBuildingStage DefaultLanguage()
+ {
+ return this;
+ }
+
+ public IBuildingStage UseEnglish()
+ {
+ Default.Language = new English();
+ return this;
+ }
+
+ public IBuildingStage UseGerman()
+ {
+ Default.Language = new German();
+ return this;
+ }
+
+ public IBuildingStage Custom(Localization language)
+ {
+ Default.Language = language;
+ return this;
+ }
+
+ #endregion
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Builder/Interfaces/IAPIKeySelectionStage.cs b/TelegramBotBase/Builder/Interfaces/IAPIKeySelectionStage.cs
index 44a1bb8..bcbe23b 100644
--- a/TelegramBotBase/Builder/Interfaces/IAPIKeySelectionStage.cs
+++ b/TelegramBotBase/Builder/Interfaces/IAPIKeySelectionStage.cs
@@ -2,42 +2,41 @@
using TelegramBotBase.Form;
using TelegramBotBase.Interfaces;
-namespace TelegramBotBase.Builder.Interfaces
+namespace TelegramBotBase.Builder.Interfaces;
+
+public interface IAPIKeySelectionStage
{
- public interface IAPIKeySelectionStage
- {
- ///
- /// Sets the API Key which will be used by the telegram bot client.
- ///
- ///
- ///
- IMessageLoopSelectionStage WithAPIKey(string apiKey);
+ ///
+ /// Sets the API Key which will be used by the telegram bot client.
+ ///
+ ///
+ ///
+ IMessageLoopSelectionStage WithAPIKey(string apiKey);
- ///
- /// Quick and easy way to create a BotBase instance.
- /// Uses: DefaultMessageLoop, NoProxy, OnlyStart, NoSerialization, DefaultLanguage
- ///
- ///
- ///
- ///
- IBuildingStage QuickStart(string apiKey, Type StartForm);
+ ///
+ /// Quick and easy way to create a BotBase instance.
+ /// Uses: DefaultMessageLoop, NoProxy, OnlyStart, NoSerialization, DefaultLanguage
+ ///
+ ///
+ ///
+ ///
+ IBuildingStage QuickStart(string apiKey, Type StartForm);
- ///
- /// Quick and easy way to create a BotBase instance.
- /// Uses: DefaultMessageLoop, NoProxy, OnlyStart, NoSerialization, DefaultLanguage
- ///
- ///
- ///
- IBuildingStage QuickStart(string apiKey) where T : FormBase;
+ ///
+ /// Quick and easy way to create a BotBase instance.
+ /// Uses: DefaultMessageLoop, NoProxy, OnlyStart, NoSerialization, DefaultLanguage
+ ///
+ ///
+ ///
+ IBuildingStage QuickStart(string apiKey) where T : FormBase;
- ///
- /// Quick and easy way to create a BotBase instance.
- /// Uses: DefaultMessageLoop, NoProxy, OnlyStart, NoSerialization, DefaultLanguage
- ///
- ///
- ///
- ///
- IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory);
- }
-}
+ ///
+ /// Quick and easy way to create a BotBase instance.
+ /// Uses: DefaultMessageLoop, NoProxy, OnlyStart, NoSerialization, DefaultLanguage
+ ///
+ ///
+ ///
+ ///
+ IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory);
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Builder/Interfaces/IBotCommandsStage.cs b/TelegramBotBase/Builder/Interfaces/IBotCommandsStage.cs
index 2b83453..510db3b 100644
--- a/TelegramBotBase/Builder/Interfaces/IBotCommandsStage.cs
+++ b/TelegramBotBase/Builder/Interfaces/IBotCommandsStage.cs
@@ -2,39 +2,35 @@
using System.Collections.Generic;
using Telegram.Bot.Types;
-namespace TelegramBotBase.Builder.Interfaces
+namespace TelegramBotBase.Builder.Interfaces;
+
+public interface IBotCommandsStage
{
- public interface IBotCommandsStage
- {
- ///
- /// Does not create any commands.
- ///
- ///
- ISessionSerializationStage NoCommands();
+ ///
+ /// Does not create any commands.
+ ///
+ ///
+ ISessionSerializationStage NoCommands();
- ///
- /// Creates default commands for start, help and settings.
- ///
- ///
- ISessionSerializationStage DefaultCommands();
+ ///
+ /// Creates default commands for start, help and settings.
+ ///
+ ///
+ ISessionSerializationStage DefaultCommands();
- ///
- /// Only adds the start command.
- ///
- ///
- ISessionSerializationStage OnlyStart();
+ ///
+ /// Only adds the start command.
+ ///
+ ///
+ ISessionSerializationStage OnlyStart();
- ///
- /// Gives you the ability to add custom commands.
- ///
- ///
- ///
-
- ISessionSerializationStage CustomCommands(Action>> action);
-
-
- }
-}
+ ///
+ /// Gives you the ability to add custom commands.
+ ///
+ ///
+ ///
+ ISessionSerializationStage CustomCommands(Action>> action);
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Builder/Interfaces/IBuildingStage.cs b/TelegramBotBase/Builder/Interfaces/IBuildingStage.cs
index d5b70df..17e49cc 100644
--- a/TelegramBotBase/Builder/Interfaces/IBuildingStage.cs
+++ b/TelegramBotBase/Builder/Interfaces/IBuildingStage.cs
@@ -1,7 +1,6 @@
-namespace TelegramBotBase.Builder.Interfaces
+namespace TelegramBotBase.Builder.Interfaces;
+
+public interface IBuildingStage
{
- public interface IBuildingStage
- {
- BotBase Build();
- }
-}
+ BotBase Build();
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Builder/Interfaces/ILanguageSelectionStage.cs b/TelegramBotBase/Builder/Interfaces/ILanguageSelectionStage.cs
index b7bbd28..e32f710 100644
--- a/TelegramBotBase/Builder/Interfaces/ILanguageSelectionStage.cs
+++ b/TelegramBotBase/Builder/Interfaces/ILanguageSelectionStage.cs
@@ -1,33 +1,30 @@
using TelegramBotBase.Localizations;
-namespace TelegramBotBase.Builder.Interfaces
+namespace TelegramBotBase.Builder.Interfaces;
+
+public interface ILanguageSelectionStage
{
- public interface ILanguageSelectionStage
- {
+ ///
+ /// Selects the default language for control usage. (English)
+ ///
+ ///
+ IBuildingStage DefaultLanguage();
- ///
- /// Selects the default language for control usage. (English)
- ///
- ///
- IBuildingStage DefaultLanguage();
+ ///
+ /// Selects english as the default language for control labels.
+ ///
+ ///
+ IBuildingStage UseEnglish();
- ///
- /// Selects english as the default language for control labels.
- ///
- ///
- IBuildingStage UseEnglish();
+ ///
+ /// Selects german as the default language for control labels.
+ ///
+ ///
+ IBuildingStage UseGerman();
- ///
- /// Selects german as the default language for control labels.
- ///
- ///
- IBuildingStage UseGerman();
-
- ///
- /// Selects a custom language as the default language for control labels.
- ///
- ///
- IBuildingStage Custom(Localization language);
-
- }
-}
+ ///
+ /// Selects a custom language as the default language for control labels.
+ ///
+ ///
+ IBuildingStage Custom(Localization language);
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Builder/Interfaces/IMessageLoopSelectionStage.cs b/TelegramBotBase/Builder/Interfaces/IMessageLoopSelectionStage.cs
index b9a8df0..21223e7 100644
--- a/TelegramBotBase/Builder/Interfaces/IMessageLoopSelectionStage.cs
+++ b/TelegramBotBase/Builder/Interfaces/IMessageLoopSelectionStage.cs
@@ -1,40 +1,36 @@
using TelegramBotBase.Interfaces;
-namespace TelegramBotBase.Builder.Interfaces
+namespace TelegramBotBase.Builder.Interfaces;
+
+public interface IMessageLoopSelectionStage
{
- public interface IMessageLoopSelectionStage
- {
-
- ///
- /// Chooses a default message loop.
- ///
- ///
- ///
- IStartFormSelectionStage DefaultMessageLoop();
+ ///
+ /// Chooses a default message loop.
+ ///
+ ///
+ ///
+ IStartFormSelectionStage DefaultMessageLoop();
- ///
- /// Chooses a minimalistic message loop, which catches all update types and only calls the Load function.
- ///
- ///
- IStartFormSelectionStage MinimalMessageLoop();
+ ///
+ /// Chooses a minimalistic message loop, which catches all update types and only calls the Load function.
+ ///
+ ///
+ IStartFormSelectionStage MinimalMessageLoop();
- ///
- /// Chooses a custom message loop.
- ///
- ///
- ///
- IStartFormSelectionStage CustomMessageLoop(IMessageLoopFactory startFormClass);
+ ///
+ /// Chooses a custom message loop.
+ ///
+ ///
+ ///
+ IStartFormSelectionStage CustomMessageLoop(IMessageLoopFactory startFormClass);
- ///
- /// Chooses a custom message loop.
- ///
- ///
- ///
- IStartFormSelectionStage CustomMessageLoop() where T : class, new();
-
-
- }
-}
+ ///
+ /// Chooses a custom message loop.
+ ///
+ ///
+ ///
+ IStartFormSelectionStage CustomMessageLoop() where T : class, new();
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Builder/Interfaces/INetworkingSelectionStage.cs b/TelegramBotBase/Builder/Interfaces/INetworkingSelectionStage.cs
index a7b0d8e..3e48b21 100644
--- a/TelegramBotBase/Builder/Interfaces/INetworkingSelectionStage.cs
+++ b/TelegramBotBase/Builder/Interfaces/INetworkingSelectionStage.cs
@@ -1,48 +1,44 @@
using System.Net.Http;
using Telegram.Bot;
-namespace TelegramBotBase.Builder.Interfaces
+namespace TelegramBotBase.Builder.Interfaces;
+
+public interface INetworkingSelectionStage
{
- public interface INetworkingSelectionStage
- {
+ ///
+ /// Chooses a proxy as network configuration.
+ ///
+ ///
+ ///
+ IBotCommandsStage WithProxy(string proxyAddress);
- ///
- /// Chooses a proxy as network configuration.
- ///
- ///
- ///
- IBotCommandsStage WithProxy(string proxyAddress);
-
- ///
- /// Do not choose a proxy as network configuration.
- ///
- ///
- IBotCommandsStage NoProxy();
+ ///
+ /// Do not choose a proxy as network configuration.
+ ///
+ ///
+ IBotCommandsStage NoProxy();
- ///
- /// Chooses a custom instance of TelegramBotClient.
- ///
- ///
- ///
- IBotCommandsStage WithBotClient(TelegramBotClient client);
+ ///
+ /// Chooses a custom instance of TelegramBotClient.
+ ///
+ ///
+ ///
+ IBotCommandsStage WithBotClient(TelegramBotClient client);
- ///
- /// Sets the custom proxy host and port.
- ///
- ///
- ///
- ///
- IBotCommandsStage WithHostAndPort(string proxyHost, int Port);
+ ///
+ /// Sets the custom proxy host and port.
+ ///
+ ///
+ ///
+ ///
+ IBotCommandsStage WithHostAndPort(string proxyHost, int Port);
- ///
- /// Uses a custom http client.
- ///
- ///
- ///
- IBotCommandsStage WithHttpClient(HttpClient client);
-
-
- }
-}
+ ///
+ /// Uses a custom http client.
+ ///
+ ///
+ ///
+ IBotCommandsStage WithHttpClient(HttpClient client);
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Builder/Interfaces/ISessionSerializationStage.cs b/TelegramBotBase/Builder/Interfaces/ISessionSerializationStage.cs
index 9adc70f..5ed022b 100644
--- a/TelegramBotBase/Builder/Interfaces/ISessionSerializationStage.cs
+++ b/TelegramBotBase/Builder/Interfaces/ISessionSerializationStage.cs
@@ -1,46 +1,44 @@
using TelegramBotBase.Interfaces;
-namespace TelegramBotBase.Builder.Interfaces
+namespace TelegramBotBase.Builder.Interfaces;
+
+public interface ISessionSerializationStage
{
- public interface ISessionSerializationStage
- {
- ///
- /// Do not uses serialization.
- ///
- ///
- ILanguageSelectionStage NoSerialization();
+ ///
+ /// Do not uses serialization.
+ ///
+ ///
+ ILanguageSelectionStage NoSerialization();
- ///
- /// Sets the state machine for serialization.
- ///
- ///
- ///
- ILanguageSelectionStage UseSerialization(IStateMachine machine);
+ ///
+ /// Sets the state machine for serialization.
+ ///
+ ///
+ ///
+ ILanguageSelectionStage UseSerialization(IStateMachine machine);
- ///
- /// Using the complex version of .Net JSON, which can serialize all objects.
- ///
- ///
- ///
- ILanguageSelectionStage UseJSON(string path);
+ ///
+ /// Using the complex version of .Net JSON, which can serialize all objects.
+ ///
+ ///
+ ///
+ ILanguageSelectionStage UseJSON(string path);
- ///
- /// Use the easy version of .Net JSON, which can serialize basic types, but not generics and others.
- ///
- ///
- ///
- ILanguageSelectionStage UseSimpleJSON(string path);
+ ///
+ /// Use the easy version of .Net JSON, which can serialize basic types, but not generics and others.
+ ///
+ ///
+ ///
+ ILanguageSelectionStage UseSimpleJSON(string path);
- ///
- /// Uses the XML serializer for session serialization.
- ///
- ///
- ///
- ILanguageSelectionStage UseXML(string path);
-
- }
-}
+ ///
+ /// Uses the XML serializer for session serialization.
+ ///
+ ///
+ ///
+ ILanguageSelectionStage UseXML(string path);
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Builder/Interfaces/IStartFormSelectionStage.cs b/TelegramBotBase/Builder/Interfaces/IStartFormSelectionStage.cs
index 52c1890..1254693 100644
--- a/TelegramBotBase/Builder/Interfaces/IStartFormSelectionStage.cs
+++ b/TelegramBotBase/Builder/Interfaces/IStartFormSelectionStage.cs
@@ -2,47 +2,44 @@
using TelegramBotBase.Form;
using TelegramBotBase.Interfaces;
-namespace TelegramBotBase.Builder.Interfaces
+namespace TelegramBotBase.Builder.Interfaces;
+
+public interface IStartFormSelectionStage
{
- public interface IStartFormSelectionStage
- {
+ ///
+ /// Chooses a start form type which will be used for new sessions.
+ ///
+ ///
+ ///
+ INetworkingSelectionStage WithStartForm(Type startFormClass);
- ///
- /// Chooses a start form type which will be used for new sessions.
- ///
- ///
- ///
- INetworkingSelectionStage WithStartForm(Type startFormClass);
+ ///
+ /// Chooses a generic start form which will be used for new sessions.
+ ///
+ ///
+ ///
+ INetworkingSelectionStage WithStartForm() where T : FormBase, new();
- ///
- /// Chooses a generic start form which will be used for new sessions.
- ///
- ///
- ///
- INetworkingSelectionStage WithStartForm() where T : FormBase, new();
+ ///
+ /// Chooses a StartFormFactory which will be use for new sessions.
+ ///
+ ///
+ ///
+ ///
+ INetworkingSelectionStage WithServiceProvider(Type startFormClass, IServiceProvider serviceProvider);
- ///
- /// Chooses a StartFormFactory which will be use for new sessions.
- ///
- ///
- ///
- ///
- INetworkingSelectionStage WithServiceProvider(Type startFormClass, IServiceProvider serviceProvider);
+ ///
+ /// Chooses a StartFormFactory which will be use for new sessions.
+ ///
+ ///
+ ///
+ ///
+ INetworkingSelectionStage WithServiceProvider(IServiceProvider serviceProvider) where T : FormBase;
- ///
- /// Chooses a StartFormFactory which will be use for new sessions.
- ///
- ///
- ///
- ///
- INetworkingSelectionStage WithServiceProvider(IServiceProvider serviceProvider) where T : FormBase;
-
- ///
- /// Chooses a StartFormFactory which will be use for new sessions.
- ///
- ///
- ///
- INetworkingSelectionStage WithStartFormFactory(IStartFormFactory factory);
-
- }
-}
+ ///
+ /// Chooses a StartFormFactory which will be use for new sessions.
+ ///
+ ///
+ ///
+ INetworkingSelectionStage WithStartFormFactory(IStartFormFactory factory);
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Commands/Extensions.cs b/TelegramBotBase/Commands/Extensions.cs
index 55721b8..6a19ce1 100644
--- a/TelegramBotBase/Commands/Extensions.cs
+++ b/TelegramBotBase/Commands/Extensions.cs
@@ -2,141 +2,181 @@
using System.Linq;
using Telegram.Bot.Types;
-namespace TelegramBotBase.Commands
+namespace TelegramBotBase.Commands;
+
+public static class Extensions
{
- public static class Extensions
+ ///
+ /// Adding the command with a description.
+ ///
+ ///
+ ///
+ ///
+ public static void Add(this Dictionary> cmds, string command,
+ string description, BotCommandScope scope = null)
{
- ///
- /// Adding the command with a description.
- ///
- ///
- ///
- ///
- public static void Add(this Dictionary> cmds, string command, string description, BotCommandScope scope = null)
+ if (scope == null)
{
- if (scope == null)
- {
- scope = BotCommandScope.Default();
- }
-
- var item = cmds.FirstOrDefault(a => a.Key.Type == scope.Type);
-
- if (item.Value != null)
- {
- item.Value.Add(new BotCommand { Command = command, Description = description });
- }
- else
- {
- cmds.Add(scope, new List { new BotCommand { Command = command, Description = description } });
- }
+ scope = BotCommandScope.Default();
}
- ///
- /// Adding the command with a description.
- ///
- ///
- ///
- ///
- public static void Clear(this Dictionary> cmds, BotCommandScope scope = null)
+ var item = cmds.FirstOrDefault(a => a.Key.Type == scope.Type);
+
+ if (item.Value != null)
{
- if (scope == null)
- {
- scope = BotCommandScope.Default();
- }
-
- var item = cmds.FirstOrDefault(a => a.Key.Type == scope.Type);
-
- if (item.Key != null)
- {
- cmds[item.Key] = null;
- }
- else
- {
- cmds[scope] = null;
- }
+ item.Value.Add(new BotCommand { Command = command, Description = description });
+ }
+ else
+ {
+ cmds.Add(scope, new List { new() { Command = command, Description = description } });
}
-
- ///
- /// Adding the default /start command with a description.
- ///
- ///
- ///
- public static void Start(this Dictionary> cmds, string description) => Add(cmds, "start", description);
-
- ///
- /// Adding the default /help command with a description.
- ///
- ///
- ///
- public static void Help(this Dictionary> cmds, string description) => Add(cmds, "help", description);
-
- ///
- /// Adding the default /settings command with a description.
- ///
- ///
- ///
- public static void Settings(this Dictionary> cmds, string description) => Add(cmds, "settings", description);
-
- ///
- /// Clears all default commands.
- ///
- ///
- public static void ClearDefaultCommands(this Dictionary> cmds) => Clear(cmds);
-
- ///
- /// Clears all commands of a specific device.
- ///
- ///
- public static void ClearChatCommands(this Dictionary> cmds, long deviceId) => Clear(cmds, new BotCommandScopeChat { ChatId = deviceId });
-
- ///
- /// Adding a chat command with a description.
- ///
- ///
- ///
- ///
- public static void AddChatCommand(this Dictionary> cmds, long deviceId, string command, string description) => Add(cmds, command, description, new BotCommandScopeChat { ChatId = deviceId });
-
- ///
- /// Adding a group command with a description.
- ///
- ///
- ///
- ///
- public static void AddGroupCommand(this Dictionary> cmds, string command, string description) => Add(cmds, command, description, new BotCommandScopeAllGroupChats());
-
- ///
- /// Clears all group commands.
- ///
- ///
- public static void ClearGroupCommands(this Dictionary> cmds) => Clear(cmds, new BotCommandScopeAllGroupChats());
-
- ///
- /// Adding group admin command with a description.
- ///
- ///
- ///
- ///
- public static void AddGroupAdminCommand(this Dictionary> cmds, string command, string description) => Add(cmds, command, description, new BotCommandScopeAllChatAdministrators());
-
- ///
- /// Clears all group admin commands.
- ///
- ///
- public static void ClearGroupAdminCommand(this Dictionary> cmds) => Clear(cmds, new BotCommandScopeAllChatAdministrators());
-
- ///
- /// Adding a privat command with a description.
- ///
- ///
- ///
- ///
- public static void AddPrivateChatCommand(this Dictionary> cmds, string command, string description) => Add(cmds, command, description, new BotCommandScopeAllPrivateChats());
-
- ///
- /// Clears all private commands.
- ///
- ///
- public static void ClearPrivateChatCommand(this Dictionary> cmds) => Clear(cmds, new BotCommandScopeAllPrivateChats());
}
-}
+
+ ///
+ /// Adding the command with a description.
+ ///
+ ///
+ ///
+ ///
+ public static void Clear(this Dictionary> cmds, BotCommandScope scope = null)
+ {
+ if (scope == null)
+ {
+ scope = BotCommandScope.Default();
+ }
+
+ var item = cmds.FirstOrDefault(a => a.Key.Type == scope.Type);
+
+ if (item.Key != null)
+ {
+ cmds[item.Key] = null;
+ }
+ else
+ {
+ cmds[scope] = null;
+ }
+ }
+
+ ///
+ /// Adding the default /start command with a description.
+ ///
+ ///
+ ///
+ public static void Start(this Dictionary> cmds, string description)
+ {
+ Add(cmds, "start", description);
+ }
+
+ ///
+ /// Adding the default /help command with a description.
+ ///
+ ///
+ ///
+ public static void Help(this Dictionary> cmds, string description)
+ {
+ Add(cmds, "help", description);
+ }
+
+ ///
+ /// Adding the default /settings command with a description.
+ ///
+ ///
+ ///
+ public static void Settings(this Dictionary> cmds, string description)
+ {
+ Add(cmds, "settings", description);
+ }
+
+ ///
+ /// Clears all default commands.
+ ///
+ ///
+ public static void ClearDefaultCommands(this Dictionary> cmds)
+ {
+ Clear(cmds);
+ }
+
+ ///
+ /// Clears all commands of a specific device.
+ ///
+ ///
+ public static void ClearChatCommands(this Dictionary> cmds, long deviceId)
+ {
+ Clear(cmds, new BotCommandScopeChat { ChatId = deviceId });
+ }
+
+ ///
+ /// Adding a chat command with a description.
+ ///
+ ///
+ ///
+ ///
+ public static void AddChatCommand(this Dictionary> cmds, long deviceId,
+ string command, string description)
+ {
+ Add(cmds, command, description, new BotCommandScopeChat { ChatId = deviceId });
+ }
+
+ ///
+ /// Adding a group command with a description.
+ ///
+ ///
+ ///
+ ///
+ public static void AddGroupCommand(this Dictionary> cmds, string command,
+ string description)
+ {
+ Add(cmds, command, description, new BotCommandScopeAllGroupChats());
+ }
+
+ ///
+ /// Clears all group commands.
+ ///
+ ///
+ public static void ClearGroupCommands(this Dictionary> cmds)
+ {
+ Clear(cmds, new BotCommandScopeAllGroupChats());
+ }
+
+ ///
+ /// Adding group admin command with a description.
+ ///
+ ///
+ ///
+ ///
+ public static void AddGroupAdminCommand(this Dictionary> cmds, string command,
+ string description)
+ {
+ Add(cmds, command, description, new BotCommandScopeAllChatAdministrators());
+ }
+
+ ///
+ /// Clears all group admin commands.
+ ///
+ ///
+ public static void ClearGroupAdminCommand(this Dictionary> cmds)
+ {
+ Clear(cmds, new BotCommandScopeAllChatAdministrators());
+ }
+
+ ///
+ /// Adding a privat command with a description.
+ ///
+ ///
+ ///
+ ///
+ public static void AddPrivateChatCommand(this Dictionary> cmds,
+ string command, string description)
+ {
+ Add(cmds, command, description, new BotCommandScopeAllPrivateChats());
+ }
+
+ ///
+ /// Clears all private commands.
+ ///
+ ///
+ public static void ClearPrivateChatCommand(this Dictionary> cmds)
+ {
+ Clear(cmds, new BotCommandScopeAllPrivateChats());
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Constants/Telegram.cs b/TelegramBotBase/Constants/Telegram.cs
index a669022..a2837d7 100644
--- a/TelegramBotBase/Constants/Telegram.cs
+++ b/TelegramBotBase/Constants/Telegram.cs
@@ -1,21 +1,19 @@
-namespace TelegramBotBase.Constants
+namespace TelegramBotBase.Constants;
+
+public static class Telegram
{
- public static class Telegram
- {
- ///
- /// The maximum length of message text before the API throws an exception. (We will catch it before)
- ///
- public const int MaxMessageLength = 4096;
+ ///
+ /// The maximum length of message text before the API throws an exception. (We will catch it before)
+ ///
+ public const int MaxMessageLength = 4096;
- public const int MaxInlineKeyBoardRows = 13;
+ public const int MaxInlineKeyBoardRows = 13;
- public const int MaxInlineKeyBoardCols = 8;
+ public const int MaxInlineKeyBoardCols = 8;
- public const int MaxReplyKeyboardRows = 25;
+ public const int MaxReplyKeyboardRows = 25;
- public const int MaxReplyKeyboardCols = 12;
+ public const int MaxReplyKeyboardCols = 12;
- public const int MessageDeletionsPerSecond = 30;
-
- }
-}
+ public const int MessageDeletionsPerSecond = 30;
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Controls/Hybrid/ButtonGrid.cs b/TelegramBotBase/Controls/Hybrid/ButtonGrid.cs
index f8662b2..e2871d9 100644
--- a/TelegramBotBase/Controls/Hybrid/ButtonGrid.cs
+++ b/TelegramBotBase/Controls/Hybrid/ButtonGrid.cs
@@ -15,208 +15,339 @@ using TelegramBotBase.Form;
using TelegramBotBase.Localizations;
using static TelegramBotBase.Base.Async;
-namespace TelegramBotBase.Controls.Hybrid
+namespace TelegramBotBase.Controls.Hybrid;
+
+public class ButtonGrid : ControlBase
{
- public class ButtonGrid : ControlBase
+ private static readonly object EvButtonClicked = new();
+
+ private readonly EventHandlerList _events = new();
+
+ private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard;
+
+ private bool _renderNecessary = true;
+
+ public string NextPageLabel = Default.Language["ButtonGrid_NextPage"];
+
+ public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"];
+
+ public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"];
+
+ public string SearchLabel = Default.Language["ButtonGrid_SearchFeature"];
+
+ public ButtonGrid()
{
+ DataSource = new ButtonFormDataSource();
+ }
- public string Title { get; set; } = Default.Language["ButtonGrid_Title"];
+ public ButtonGrid(EKeyboardType type) : this()
+ {
+ _mEKeyboardType = type;
+ }
- public string ConfirmationText { get; set; } = "";
- private bool _renderNecessary = true;
+ public ButtonGrid(ButtonForm form)
+ {
+ DataSource = new ButtonFormDataSource(form);
+ }
- private static readonly object EvButtonClicked = new object();
+ public string Title { get; set; } = Default.Language["ButtonGrid_Title"];
- private readonly EventHandlerList _events = new EventHandlerList();
+ public string ConfirmationText { get; set; } = "";
- ///
- ///
- ///
- [Obsolete("This property is obsolete. Please use the DataSource property instead.")]
- public ButtonForm ButtonsForm
+ ///
+ ///
+ [Obsolete("This property is obsolete. Please use the DataSource property instead.")]
+ public ButtonForm ButtonsForm
+ {
+ get => DataSource.ButtonForm;
+ set => DataSource = new ButtonFormDataSource(value);
+ }
+
+ ///
+ /// Data source of the items.
+ ///
+ public ButtonFormDataSource DataSource { get; set; }
+
+ public int? MessageId { get; set; }
+
+
+ ///
+ /// Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if
+ /// there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same
+ /// height as the app's standard keyboard.
+ /// Source: https://core.telegram.org/bots/api#replykeyboardmarkup
+ ///
+ public bool ResizeKeyboard { get; set; } = false;
+
+ public bool OneTimeKeyboard { get; set; } = false;
+
+ public bool HideKeyboardOnCleanup { get; set; } = true;
+
+ public bool DeletePreviousMessage { get; set; } = true;
+
+ ///
+ /// Removes the reply message from a user.
+ ///
+ public bool DeleteReplyMessage { get; set; } = true;
+
+ ///
+ /// Parsemode of the message.
+ ///
+ public ParseMode MessageParseMode { get; set; } = ParseMode.Markdown;
+
+ ///
+ /// Enables automatic paging of buttons when the amount of rows is exceeding the limits.
+ ///
+ public bool EnablePaging { get; set; } = false;
+
+
+ ///
+ /// Enabled a search function.
+ ///
+ public bool EnableSearch { get; set; } = false;
+
+ public string SearchQuery { get; set; }
+
+ public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always;
+
+
+ ///
+ /// Index of the current page
+ ///
+ public int CurrentPageIndex { get; set; }
+
+ ///
+ /// Layout of the buttons which should be displayed always on top.
+ ///
+ public ButtonRow HeadLayoutButtonRow { get; set; }
+
+ ///
+ /// Layout of columns which should be displayed below the header
+ ///
+ public ButtonRow SubHeadLayoutButtonRow { get; set; }
+
+ ///
+ /// Defines which type of Button Keyboard should be rendered.
+ ///
+ public EKeyboardType KeyboardType
+ {
+ get => _mEKeyboardType;
+ set
{
- get => DataSource.ButtonForm;
- set => DataSource = new ButtonFormDataSource(value);
- }
-
- ///
- /// Data source of the items.
- ///
- public ButtonFormDataSource DataSource { get; set; }
-
- public int? MessageId { get; set; }
-
-
- ///
- /// Optional. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard.
- /// Source: https://core.telegram.org/bots/api#replykeyboardmarkup
- ///
- public bool ResizeKeyboard { get; set; } = false;
-
- public bool OneTimeKeyboard { get; set; } = false;
-
- public bool HideKeyboardOnCleanup { get; set; } = true;
-
- public bool DeletePreviousMessage { get; set; } = true;
-
- ///
- /// Removes the reply message from a user.
- ///
- public bool DeleteReplyMessage { get; set; } = true;
-
- ///
- /// Parsemode of the message.
- ///
- public ParseMode MessageParseMode { get; set; } = ParseMode.Markdown;
-
- ///
- /// Enables automatic paging of buttons when the amount of rows is exceeding the limits.
- ///
- public bool EnablePaging { get; set; } = false;
-
-
- ///
- /// Enabled a search function.
- ///
- public bool EnableSearch { get; set; } = false;
-
- public string SearchQuery { get; set; }
-
- public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always;
-
-
- ///
- /// Index of the current page
- ///
- public int CurrentPageIndex { get; set; }
-
- public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"];
-
- public string NextPageLabel = Default.Language["ButtonGrid_NextPage"];
-
- public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"];
-
- public string SearchLabel = Default.Language["ButtonGrid_SearchFeature"];
-
- ///
- /// Layout of the buttons which should be displayed always on top.
- ///
- public ButtonRow HeadLayoutButtonRow { get; set; }
-
- ///
- /// Layout of columns which should be displayed below the header
- ///
- public ButtonRow SubHeadLayoutButtonRow { get; set; }
-
- ///
- /// Defines which type of Button Keyboard should be rendered.
- ///
- public EKeyboardType KeyboardType
- {
- get => _mEKeyboardType;
- set
+ if (_mEKeyboardType != value)
{
- if (_mEKeyboardType != value)
- {
- _renderNecessary = true;
+ _renderNecessary = true;
- Cleanup().Wait();
-
- _mEKeyboardType = value;
- }
+ Cleanup().Wait();
+ _mEKeyboardType = value;
}
}
+ }
- private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard;
-
- public ButtonGrid()
+ public bool PagingNecessary
+ {
+ get
{
- DataSource = new ButtonFormDataSource();
-
- }
-
- public ButtonGrid(EKeyboardType type) : this()
- {
- _mEKeyboardType = type;
- }
-
-
- public ButtonGrid(ButtonForm form)
- {
- DataSource = new ButtonFormDataSource(form);
- }
-
-
- public event AsyncEventHandler ButtonClicked
- {
- add => _events.AddHandler(EvButtonClicked, value);
- remove => _events.RemoveHandler(EvButtonClicked, value);
- }
-
- public async Task OnButtonClicked(ButtonClickedEventArgs e)
- {
- var handler = _events[EvButtonClicked]?.GetInvocationList().Cast>();
- if (handler == null)
- return;
-
- foreach (var h in handler)
+ if (KeyboardType == EKeyboardType.InlineKeyBoard &&
+ TotalRows > Constants.Telegram.MaxInlineKeyBoardRows)
{
- await h.InvokeAllAsync(this, e);
- }
- }
-
- public override void Init()
- {
- Device.MessageDeleted += Device_MessageDeleted;
- }
-
- private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e)
- {
- if (MessageId == null)
- return;
-
- if (e.MessageId != MessageId)
- return;
-
- MessageId = null;
- }
-
- public override async Task Load(MessageResult result)
- {
- if (KeyboardType != EKeyboardType.ReplyKeyboard)
- return;
-
- if (!result.IsFirstHandler)
- return;
-
- if (result.MessageText == null || result.MessageText == "")
- return;
-
- var matches = new List();
- ButtonRow match = null;
- var index = -1;
-
- if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false)
- {
- match = HeadLayoutButtonRow;
- goto check;
+ return true;
}
- if (SubHeadLayoutButtonRow?.Matches(result.MessageText) ?? false)
+ if (KeyboardType == EKeyboardType.ReplyKeyboard &&
+ TotalRows > Constants.Telegram.MaxReplyKeyboardRows)
{
- match = SubHeadLayoutButtonRow;
- goto check;
+ return true;
}
- var br = DataSource.FindRow(result.MessageText);
- if (br != null)
+ return false;
+ }
+ }
+
+ public bool IsNavigationBarVisible
+ {
+ get
+ {
+ if ((NavigationBarVisibility == ENavigationBarVisibility.always) |
+ (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary))
{
- match = br.Item1;
- index = br.Item2;
+ return true;
}
+ return false;
+ }
+ }
+
+ ///
+ /// Returns the maximum number of rows
+ ///
+ public int MaximumRow
+ {
+ get
+ {
+ return KeyboardType switch
+ {
+ EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows,
+ EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows,
+ _ => 0
+ };
+ }
+ }
+
+ ///
+ /// Returns the number of all rows (layout + navigation + content);
+ ///
+ public int TotalRows => LayoutRows + DataSource.RowCount;
+
+
+ ///
+ /// Contains the Number of Rows which are used by the layout.
+ ///
+ private int LayoutRows
+ {
+ get
+ {
+ var layoutRows = 0;
+
+ if ((NavigationBarVisibility == ENavigationBarVisibility.always) |
+ (NavigationBarVisibility == ENavigationBarVisibility.auto))
+ {
+ layoutRows += 2;
+ }
+
+ if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
+ {
+ layoutRows++;
+ }
+
+ if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
+ {
+ layoutRows++;
+ }
+
+ return layoutRows;
+ }
+ }
+
+ ///
+ /// Returns the number of item rows per page.
+ ///
+ public int ItemRowsPerPage => MaximumRow - LayoutRows;
+
+ ///
+ /// Return the number of pages.
+ ///
+ public int PageCount
+ {
+ get
+ {
+ if (DataSource.RowCount == 0)
+ {
+ return 1;
+ }
+
+ //var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null);
+
+ var max = DataSource.CalculateMax(EnableSearch ? SearchQuery : null);
+
+ //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
+ //{
+ // bf = bf.FilterDuplicate(this.SearchQuery);
+ //}
+
+ if (max == 0)
+ {
+ return 1;
+ }
+
+ return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage);
+ }
+ }
+
+
+ public event AsyncEventHandler ButtonClicked
+ {
+ add => _events.AddHandler(EvButtonClicked, value);
+ remove => _events.RemoveHandler(EvButtonClicked, value);
+ }
+
+ public async Task OnButtonClicked(ButtonClickedEventArgs e)
+ {
+ var handler = _events[EvButtonClicked]?.GetInvocationList()
+ .Cast>();
+ if (handler == null)
+ {
+ return;
+ }
+
+ foreach (var h in handler)
+ {
+ await h.InvokeAllAsync(this, e);
+ }
+ }
+
+ public override void Init()
+ {
+ Device.MessageDeleted += Device_MessageDeleted;
+ }
+
+ private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e)
+ {
+ if (MessageId == null)
+ {
+ return;
+ }
+
+ if (e.MessageId != MessageId)
+ {
+ return;
+ }
+
+ MessageId = null;
+ }
+
+ public override async Task Load(MessageResult result)
+ {
+ if (KeyboardType != EKeyboardType.ReplyKeyboard)
+ {
+ return;
+ }
+
+ if (!result.IsFirstHandler)
+ {
+ return;
+ }
+
+ if (result.MessageText == null || result.MessageText == "")
+ {
+ return;
+ }
+
+ var matches = new List();
+ ButtonRow match = null;
+ var index = -1;
+
+ if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false)
+ {
+ match = HeadLayoutButtonRow;
+ goto check;
+ }
+
+ if (SubHeadLayoutButtonRow?.Matches(result.MessageText) ?? false)
+ {
+ match = SubHeadLayoutButtonRow;
+ goto check;
+ }
+
+ var br = DataSource.FindRow(result.MessageText);
+ if (br != null)
+ {
+ match = br.Item1;
+ index = br.Item2;
+ }
+
//var button = HeadLayoutButtonRow?. .FirstOrDefault(a => a.Text.Trim() == result.MessageText)
// ?? SubHeadLayoutButtonRow?.FirstOrDefault(a => a.Text.Trim() == result.MessageText);
@@ -227,98 +358,106 @@ namespace TelegramBotBase.Controls.Hybrid
check:
- //Remove button click message
- if (DeleteReplyMessage)
- await Device.DeleteMessage(result.MessageId);
-
- if (match != null)
- {
- await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.MessageText), index, match));
-
- result.Handled = true;
- return;
- }
-
-
- if (result.MessageText == PreviousPageLabel)
- {
- if (CurrentPageIndex > 0)
- CurrentPageIndex--;
-
- Updated();
- }
- else if (result.MessageText == NextPageLabel)
- {
- if (CurrentPageIndex < PageCount - 1)
- CurrentPageIndex++;
-
- Updated();
- }
- else if (EnableSearch)
- {
- if (result.MessageText.StartsWith("🔍"))
- {
- //Sent note about searching
- if (SearchQuery == null)
- {
- await Device.Send(SearchLabel);
- }
-
- SearchQuery = null;
- Updated();
- return;
- }
-
- SearchQuery = result.MessageText;
-
- if (SearchQuery != null && SearchQuery != "")
- {
- CurrentPageIndex = 0;
- Updated();
- }
-
- }
-
-
-
+ //Remove button click message
+ if (DeleteReplyMessage)
+ {
+ await Device.DeleteMessage(result.MessageId);
}
- public override async Task Action(MessageResult result, string value = null)
+ if (match != null)
{
- if (result.Handled)
- return;
+ await OnButtonClicked(
+ new ButtonClickedEventArgs(match.GetButtonMatch(result.MessageText), index, match));
- if (!result.IsFirstHandler)
- return;
+ result.Handled = true;
+ return;
+ }
- //Find clicked button depending on Text or Value (depending on markup type)
- if (KeyboardType != EKeyboardType.InlineKeyBoard)
- return;
- await result.ConfirmAction(ConfirmationText ?? "");
-
- ButtonRow match = null;
- var index = -1;
-
- if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false)
+ if (result.MessageText == PreviousPageLabel)
+ {
+ if (CurrentPageIndex > 0)
{
- match = HeadLayoutButtonRow;
- goto check;
+ CurrentPageIndex--;
}
- if (SubHeadLayoutButtonRow?.Matches(result.RawData, false) ?? false)
+ Updated();
+ }
+ else if (result.MessageText == NextPageLabel)
+ {
+ if (CurrentPageIndex < PageCount - 1)
{
- match = SubHeadLayoutButtonRow;
- goto check;
+ CurrentPageIndex++;
}
- var br = DataSource.FindRow(result.RawData, false);
- if (br != null)
+ Updated();
+ }
+ else if (EnableSearch)
+ {
+ if (result.MessageText.StartsWith("🔍"))
{
- match = br.Item1;
- index = br.Item2;
+ //Sent note about searching
+ if (SearchQuery == null)
+ {
+ await Device.Send(SearchLabel);
+ }
+
+ SearchQuery = null;
+ Updated();
+ return;
}
+ SearchQuery = result.MessageText;
+
+ if (SearchQuery != null && SearchQuery != "")
+ {
+ CurrentPageIndex = 0;
+ Updated();
+ }
+ }
+ }
+
+ public override async Task Action(MessageResult result, string value = null)
+ {
+ if (result.Handled)
+ {
+ return;
+ }
+
+ if (!result.IsFirstHandler)
+ {
+ return;
+ }
+
+ //Find clicked button depending on Text or Value (depending on markup type)
+ if (KeyboardType != EKeyboardType.InlineKeyBoard)
+ {
+ return;
+ }
+
+ await result.ConfirmAction(ConfirmationText ?? "");
+
+ ButtonRow match = null;
+ var index = -1;
+
+ if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false)
+ {
+ match = HeadLayoutButtonRow;
+ goto check;
+ }
+
+ if (SubHeadLayoutButtonRow?.Matches(result.RawData, false) ?? false)
+ {
+ match = SubHeadLayoutButtonRow;
+ goto check;
+ }
+
+ var br = DataSource.FindRow(result.RawData, false);
+ if (br != null)
+ {
+ match = br.Item1;
+ index = br.Item2;
+ }
//var bf = DataSource.ButtonForm;
@@ -330,378 +469,281 @@ namespace TelegramBotBase.Controls.Hybrid
//var index = bf.FindRowByButton(button);
check:
- if (match != null)
- {
- await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.RawData, false), index, match));
-
- result.Handled = true;
- return;
- }
-
- switch (result.RawData)
- {
- case "$previous$":
-
- if (CurrentPageIndex > 0)
- CurrentPageIndex--;
-
- Updated();
-
- break;
- case "$next$":
-
- if (CurrentPageIndex < PageCount - 1)
- CurrentPageIndex++;
-
- Updated();
-
- break;
- }
+ if (match != null)
+ {
+ await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.RawData, false), index,
+ match));
+ result.Handled = true;
+ return;
}
- ///
- /// This method checks of the amount of buttons
- ///
- private void CheckGrid()
+ switch (result.RawData)
{
- switch (_mEKeyboardType)
- {
- case EKeyboardType.InlineKeyBoard:
+ case "$previous$":
- if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging)
- {
- throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows };
- }
-
- if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols)
- {
- throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols };
- }
-
- break;
-
- case EKeyboardType.ReplyKeyboard:
-
- if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging)
- {
- throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows };
- }
-
- if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols)
- {
- throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols };
- }
-
- break;
- }
- }
-
- public override async Task Render(MessageResult result)
- {
- if (!_renderNecessary)
- return;
-
- //Check for rows and column limits
- CheckGrid();
-
- _renderNecessary = false;
-
- var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (EnableSearch ? SearchQuery : null));
-
-
- //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
- //{
- // form = form.FilterDuplicate(this.SearchQuery, true);
- //}
- //else
- //{
- // form = form.Duplicate();
- //}
-
- if (EnablePaging)
- {
- IntegratePagingView(form);
- }
-
- if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
- {
- form.InsertButtonRow(0, HeadLayoutButtonRow);
- }
-
- if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
- {
- if (IsNavigationBarVisible)
+ if (CurrentPageIndex > 0)
{
- form.InsertButtonRow(2, SubHeadLayoutButtonRow);
+ CurrentPageIndex--;
}
- else
+
+ Updated();
+
+ break;
+ case "$next$":
+
+ if (CurrentPageIndex < PageCount - 1)
{
- form.InsertButtonRow(1, SubHeadLayoutButtonRow);
+ CurrentPageIndex++;
}
- }
- Message m = null;
+ Updated();
- switch (KeyboardType)
- {
- //Reply Keyboard could only be updated with a new keyboard.
- case EKeyboardType.ReplyKeyboard:
+ break;
+ }
+ }
+ ///
+ /// This method checks of the amount of buttons
+ ///
+ private void CheckGrid()
+ {
+ switch (_mEKeyboardType)
+ {
+ case EKeyboardType.InlineKeyBoard:
- if (form.Count == 0)
- {
- if (MessageId != null)
- {
- await Device.HideReplyKeyboard();
- MessageId = null;
- }
+ if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging)
+ {
+ throw new MaximumRowsReachedException
+ { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows };
+ }
- return;
- }
+ if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols)
+ {
+ throw new MaximumColsException
+ { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols };
+ }
- //if (this.MessageId != null)
- //{
- // if (form.Count == 0)
- // {
- // await this.Device.HideReplyKeyboard();
- // this.MessageId = null;
- // return;
- // }
- //}
+ break;
- //if (form.Count == 0)
- // return;
+ case EKeyboardType.ReplyKeyboard:
+ if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging)
+ {
+ throw new MaximumRowsReachedException
+ { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows };
+ }
- var rkm = (ReplyKeyboardMarkup)form;
- rkm.ResizeKeyboard = ResizeKeyboard;
- rkm.OneTimeKeyboard = OneTimeKeyboard;
- m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
-
- //Prevent flicker of keyboard
- if (DeletePreviousMessage && MessageId != null)
- await Device.DeleteMessage(MessageId.Value);
-
- break;
-
- case EKeyboardType.InlineKeyBoard:
-
- //Try to edit message if message id is available
- //When the returned message is null then the message has been already deleted, resend it
- if (MessageId != null)
- {
- m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form);
- if (m != null)
- {
- MessageId = m.MessageId;
- return;
- }
- }
-
- //When no message id is available or it has been deleted due the use of AutoCleanForm re-render automatically
- m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
-
- break;
- }
-
- if (m != null)
- {
- MessageId = m.MessageId;
- }
+ if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols)
+ {
+ throw new MaximumColsException
+ { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols };
+ }
+ break;
+ }
+ }
+ public override async Task Render(MessageResult result)
+ {
+ if (!_renderNecessary)
+ {
+ return;
}
- private void IntegratePagingView(ButtonForm dataForm)
- {
- //No Items
- if (dataForm.Rows == 0)
- {
- dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$"));
- }
+ //Check for rows and column limits
+ CheckGrid();
+ _renderNecessary = false;
+
+ var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage,
+ EnableSearch ? SearchQuery : null);
+
+
+ //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
+ //{
+ // form = form.FilterDuplicate(this.SearchQuery, true);
+ //}
+ //else
+ //{
+ // form = form.Duplicate();
+ //}
+
+ if (EnablePaging)
+ {
+ IntegratePagingView(form);
+ }
+
+ if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
+ {
+ form.InsertButtonRow(0, HeadLayoutButtonRow);
+ }
+
+ if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
+ {
if (IsNavigationBarVisible)
{
- //🔍
- var row = new ButtonRow();
- row.Add(new ButtonBase(PreviousPageLabel, "$previous$"));
- row.Add(new ButtonBase(string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), "$site$"));
- row.Add(new ButtonBase(NextPageLabel, "$next$"));
-
- if (EnableSearch)
- {
- row.Insert(2, new ButtonBase("🔍 " + (SearchQuery ?? ""), "$search$"));
- }
-
- dataForm.InsertButtonRow(0, row);
-
- dataForm.AddButtonRow(row);
- }
- }
-
- public bool PagingNecessary
- {
- get
- {
- if (KeyboardType == EKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows)
- {
- return true;
- }
-
- if (KeyboardType == EKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows)
- {
- return true;
- }
-
- return false;
- }
- }
-
- public bool IsNavigationBarVisible
- {
- get
- {
- if (NavigationBarVisibility == ENavigationBarVisibility.always | (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary))
- {
- return true;
- }
-
- return false;
- }
- }
-
- ///
- /// Returns the maximum number of rows
- ///
- public int MaximumRow
- {
- get
- {
- return KeyboardType switch
- {
- EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows,
- EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows,
- _ => 0
- };
- }
- }
-
- ///
- /// Returns the number of all rows (layout + navigation + content);
- ///
- public int TotalRows => LayoutRows + DataSource.RowCount;
-
-
- ///
- /// Contains the Number of Rows which are used by the layout.
- ///
- private int LayoutRows
- {
- get
- {
- var layoutRows = 0;
-
- if (NavigationBarVisibility == ENavigationBarVisibility.always | NavigationBarVisibility == ENavigationBarVisibility.auto)
- layoutRows += 2;
-
- if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
- layoutRows++;
-
- if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
- layoutRows++;
-
- return layoutRows;
- }
- }
-
- ///
- /// Returns the number of item rows per page.
- ///
- public int ItemRowsPerPage => MaximumRow - LayoutRows;
-
- ///
- /// Return the number of pages.
- ///
- public int PageCount
- {
- get
- {
- if (DataSource.RowCount == 0)
- return 1;
-
- //var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null);
-
- var max = DataSource.CalculateMax(EnableSearch ? SearchQuery : null);
-
- //if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
- //{
- // bf = bf.FilterDuplicate(this.SearchQuery);
- //}
-
- if (max == 0)
- return 1;
-
- return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage);
- }
- }
-
- public override Task Hidden(bool formClose)
- {
- //Prepare for opening Modal, and comming back
- if (!formClose)
- {
- Updated();
+ form.InsertButtonRow(2, SubHeadLayoutButtonRow);
}
else
{
- //Remove event handler
- Device.MessageDeleted -= Device_MessageDeleted;
+ form.InsertButtonRow(1, SubHeadLayoutButtonRow);
}
-
- return Task.CompletedTask;
}
- ///
- /// Tells the control that it has been updated.
- ///
- public void Updated()
+ Message m = null;
+
+ switch (KeyboardType)
{
- _renderNecessary = true;
- }
+ //Reply Keyboard could only be updated with a new keyboard.
+ case EKeyboardType.ReplyKeyboard:
- public override async Task Cleanup()
- {
- if (MessageId == null)
- return;
- switch (KeyboardType)
- {
- case EKeyboardType.InlineKeyBoard:
-
- await Device.DeleteMessage(MessageId.Value);
-
- MessageId = null;
-
- break;
- case EKeyboardType.ReplyKeyboard:
-
- if (HideKeyboardOnCleanup)
+ if (form.Count == 0)
+ {
+ if (MessageId != null)
{
await Device.HideReplyKeyboard();
+ MessageId = null;
}
- MessageId = null;
+ return;
+ }
- break;
- }
+ //if (this.MessageId != null)
+ //{
+ // if (form.Count == 0)
+ // {
+ // await this.Device.HideReplyKeyboard();
+ // this.MessageId = null;
+ // return;
+ // }
+ //}
+
+ //if (form.Count == 0)
+ // return;
+ var rkm = (ReplyKeyboardMarkup)form;
+ rkm.ResizeKeyboard = ResizeKeyboard;
+ rkm.OneTimeKeyboard = OneTimeKeyboard;
+ m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode,
+ markdownV2AutoEscape: false);
+ //Prevent flicker of keyboard
+ if (DeletePreviousMessage && MessageId != null)
+ {
+ await Device.DeleteMessage(MessageId.Value);
+ }
+ break;
+
+ case EKeyboardType.InlineKeyBoard:
+
+ //Try to edit message if message id is available
+ //When the returned message is null then the message has been already deleted, resend it
+ if (MessageId != null)
+ {
+ m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form);
+ if (m != null)
+ {
+ MessageId = m.MessageId;
+ return;
+ }
+ }
+
+ //When no message id is available or it has been deleted due the use of AutoCleanForm re-render automatically
+ m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true,
+ parseMode: MessageParseMode, markdownV2AutoEscape: false);
+
+ break;
}
+ if (m != null)
+ {
+ MessageId = m.MessageId;
+ }
}
+ private void IntegratePagingView(ButtonForm dataForm)
+ {
+ //No Items
+ if (dataForm.Rows == 0)
+ {
+ dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$"));
+ }
-}
+ if (IsNavigationBarVisible)
+ {
+ //🔍
+ var row = new ButtonRow();
+ row.Add(new ButtonBase(PreviousPageLabel, "$previous$"));
+ row.Add(new ButtonBase(
+ string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount),
+ "$site$"));
+ row.Add(new ButtonBase(NextPageLabel, "$next$"));
+
+ if (EnableSearch)
+ {
+ row.Insert(2, new ButtonBase("🔍 " + (SearchQuery ?? ""), "$search$"));
+ }
+
+ dataForm.InsertButtonRow(0, row);
+
+ dataForm.AddButtonRow(row);
+ }
+ }
+
+ public override Task Hidden(bool formClose)
+ {
+ //Prepare for opening Modal, and comming back
+ if (!formClose)
+ {
+ Updated();
+ }
+ else
+ //Remove event handler
+ {
+ Device.MessageDeleted -= Device_MessageDeleted;
+ }
+
+ return Task.CompletedTask;
+ }
+
+ ///
+ /// Tells the control that it has been updated.
+ ///
+ public void Updated()
+ {
+ _renderNecessary = true;
+ }
+
+ public override async Task Cleanup()
+ {
+ if (MessageId == null)
+ {
+ return;
+ }
+
+ switch (KeyboardType)
+ {
+ case EKeyboardType.InlineKeyBoard:
+
+ await Device.DeleteMessage(MessageId.Value);
+
+ MessageId = null;
+
+ break;
+ case EKeyboardType.ReplyKeyboard:
+
+ if (HideKeyboardOnCleanup)
+ {
+ await Device.HideReplyKeyboard();
+ }
+
+ MessageId = null;
+
+ break;
+ }
+ }
+}
\ No newline at end of file
diff --git a/TelegramBotBase/Controls/Hybrid/ButtonRow.cs b/TelegramBotBase/Controls/Hybrid/ButtonRow.cs
index c2ba68f..fbf6dee 100644
--- a/TelegramBotBase/Controls/Hybrid/ButtonRow.cs
+++ b/TelegramBotBase/Controls/Hybrid/ButtonRow.cs
@@ -4,93 +4,101 @@ using System.Diagnostics;
using System.Linq;
using TelegramBotBase.Form;
-namespace TelegramBotBase.Controls.Hybrid
+namespace TelegramBotBase.Controls.Hybrid;
+
+[DebuggerDisplay("{Count} columns")]
+public class ButtonRow
{
- [DebuggerDisplay("{Count} columns")]
- public class ButtonRow
+ private List _buttons = new();
+
+ public ButtonRow()
{
- private List _buttons = new List();
-
- public ButtonRow()
- {
-
-
- }
-
- public ButtonRow(params ButtonBase[] buttons)
- {
- _buttons = buttons.ToList();
- }
-
-
- public ButtonBase this[int index] => _buttons[index];
-
- public int Count => _buttons.Count;
-
- public void Add(ButtonBase button)
- {
- _buttons.Add(button);
- }
-
- public void AddRange(ButtonBase button)
- {
- _buttons.Add(button);
- }
-
- public void Insert(int index, ButtonBase button)
- {
- _buttons.Insert(index, button);
- }
-
- public IEnumerator