Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2db8e2cf63 | ||
|
|
6b7f2ca273 | ||
|
|
31d0d9890d | ||
|
|
b252829296 | ||
|
|
a483bc7c0b | ||
|
|
4635a96fc7 | ||
|
|
727375f7aa | ||
|
|
86792af214 | ||
|
|
b3edb95b55 | ||
|
|
946420f9c6 | ||
|
|
c8c56a42c0 | ||
|
|
6f930eee8c | ||
|
|
c4a589d476 | ||
|
|
1b14b7b3cf | ||
|
|
cb5fa35269 | ||
|
|
f60e1000c3 | ||
|
|
00dafd59a3 | ||
|
|
848b5d29cf | ||
|
|
9cac57b8e7 | ||
|
|
52517534f8 | ||
|
|
5e166db243 | ||
|
|
71aa0c3d91 | ||
|
|
e34c71b42b | ||
|
|
9927a034b0 | ||
|
|
2e454d7f5c | ||
|
|
339319ef2a | ||
|
|
c8b12e9168 | ||
|
|
cbc31b8ff5 | ||
|
|
c514ede03f | ||
|
|
c91fbaa16c | ||
|
|
b8125e9aed | ||
|
|
d4af8797fb | ||
|
|
93fda551e1 | ||
|
|
b14913362e | ||
|
|
8b22fd7b74 | ||
|
|
254c002d4a | ||
|
|
a632440efd | ||
|
|
194d8ba317 | ||
|
|
d833b1e088 | ||
|
|
084395e962 | ||
|
|
b20b3b2826 | ||
|
|
c1d1d5f543 | ||
|
|
078bdfb163 | ||
|
|
94c680e036 | ||
|
|
dbdc40582a | ||
|
|
cc4c743721 | ||
|
|
4e55fd42d6 | ||
|
|
83e09aec2a | ||
|
|
a63f71268c | ||
|
|
d56b26a788 | ||
|
|
121a788c17 |
@@ -1,16 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\TelegramBotBase\TelegramBotBase.csproj" />
|
||||
<ProjectReference Include="..\TelegramBotBase.Experiments\TelegramBotBase.Experiments.ActionManager.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
</Project>
|
||||
@@ -1,52 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace DemoBot.Forms
|
||||
{
|
||||
public class HiddenForm : AutoCleanForm
|
||||
{
|
||||
public String value { get; set; }
|
||||
|
||||
public HiddenForm() {
|
||||
|
||||
DeleteMode = TelegramBotBase.Enums.EDeleteMode.OnLeavingForm;
|
||||
DeleteSide = TelegramBotBase.Enums.EDeleteSide.Both;
|
||||
}
|
||||
|
||||
public override async Task Action(MessageResult message)
|
||||
{
|
||||
if (message.RawData != "start")
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await message.ConfirmAction("Lets go");
|
||||
|
||||
message.Handled = true;
|
||||
|
||||
var st = new StartForm();
|
||||
|
||||
await NavigateTo(st);
|
||||
}
|
||||
|
||||
public override async Task Render(MessageResult message)
|
||||
{
|
||||
|
||||
var bf = new ButtonForm();
|
||||
|
||||
bf.AddButtonRow("Goto Start", "start");
|
||||
|
||||
value = value.Replace("_", "\\_");
|
||||
|
||||
await Device.Send($"Welcome to Hidden form\n\nThe given value is {value}", bf);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace DemoBot.Forms
|
||||
{
|
||||
public class HiddenForm_EndsWith : AutoCleanForm
|
||||
{
|
||||
public String value { get; set; }
|
||||
|
||||
public HiddenForm_EndsWith() {
|
||||
|
||||
DeleteMode = TelegramBotBase.Enums.EDeleteMode.OnLeavingForm;
|
||||
DeleteSide = TelegramBotBase.Enums.EDeleteSide.Both;
|
||||
}
|
||||
|
||||
public override async Task Action(MessageResult message)
|
||||
{
|
||||
if (message.RawData != "start")
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await message.ConfirmAction("Lets go");
|
||||
|
||||
message.Handled = true;
|
||||
|
||||
var st = new StartForm();
|
||||
|
||||
await NavigateTo(st);
|
||||
}
|
||||
|
||||
public override async Task Render(MessageResult message)
|
||||
{
|
||||
|
||||
var bf = new ButtonForm();
|
||||
|
||||
bf.AddButtonRow("Goto Start", "start");
|
||||
|
||||
value = value.Replace("_", "\\_");
|
||||
|
||||
await Device.Send($"Welcome to Hidden ends with form\n\nThe given value is {value}", bf);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace DemoBot.Forms
|
||||
{
|
||||
public class HiddenLetterForm : AutoCleanForm
|
||||
{
|
||||
|
||||
public Guid letterId { get; set; }
|
||||
|
||||
public HiddenLetterForm()
|
||||
{
|
||||
|
||||
DeleteMode = TelegramBotBase.Enums.EDeleteMode.OnLeavingForm;
|
||||
DeleteSide = TelegramBotBase.Enums.EDeleteSide.Both;
|
||||
}
|
||||
|
||||
public override async Task Action(MessageResult message)
|
||||
{
|
||||
if (message.RawData != "start")
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
await message.ConfirmAction("Lets go");
|
||||
|
||||
message.Handled = true;
|
||||
|
||||
var st = new StartForm();
|
||||
|
||||
await NavigateTo(st);
|
||||
}
|
||||
|
||||
public override async Task Render(MessageResult message)
|
||||
{
|
||||
|
||||
var bf = new ButtonForm();
|
||||
|
||||
bf.AddButtonRow("Goto Start", "start");
|
||||
|
||||
await Device.Send($"Welcome to Hidden letter form\n\nYour letter Id is: {letterId}", bf);
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace DemoBot.Forms
|
||||
{
|
||||
public class HiddenOpenForm : AutoCleanForm
|
||||
{
|
||||
|
||||
public Guid guid { get; set; }
|
||||
|
||||
public HiddenOpenForm()
|
||||
{
|
||||
|
||||
DeleteMode = TelegramBotBase.Enums.EDeleteMode.OnLeavingForm;
|
||||
DeleteSide = TelegramBotBase.Enums.EDeleteSide.Both;
|
||||
}
|
||||
|
||||
public override async Task Action(MessageResult message)
|
||||
{
|
||||
if (message.RawData != "start")
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await message.ConfirmAction("Lets go");
|
||||
|
||||
message.Handled = true;
|
||||
|
||||
var st = new StartForm();
|
||||
|
||||
await NavigateTo(st);
|
||||
}
|
||||
|
||||
public override async Task Render(MessageResult message)
|
||||
{
|
||||
|
||||
var bf = new ButtonForm();
|
||||
|
||||
bf.AddButtonRow("Goto Start", "start");
|
||||
|
||||
await Device.Send($"Welcome to Hidden open form\n\nYour guid is: {guid}", bf);
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace DemoBot.Forms
|
||||
{
|
||||
public class HiddenTicketForm : AutoCleanForm
|
||||
{
|
||||
|
||||
public Guid ticketId { get; set; }
|
||||
|
||||
public HiddenTicketForm()
|
||||
{
|
||||
|
||||
DeleteMode = TelegramBotBase.Enums.EDeleteMode.OnLeavingForm;
|
||||
DeleteSide = TelegramBotBase.Enums.EDeleteSide.Both;
|
||||
}
|
||||
|
||||
public override async Task Action(MessageResult message)
|
||||
{
|
||||
if (message.RawData != "start")
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
await message.ConfirmAction("Lets go");
|
||||
|
||||
message.Handled = true;
|
||||
|
||||
var st = new StartForm();
|
||||
|
||||
await NavigateTo(st);
|
||||
}
|
||||
|
||||
public override async Task Render(MessageResult message)
|
||||
{
|
||||
|
||||
var bf = new ButtonForm();
|
||||
|
||||
bf.AddButtonRow("Goto Start", "start");
|
||||
|
||||
await Device.Send($"Welcome to Hidden ticket form\n\nYour ticket Id is: {ticketId}", bf);
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace DemoBot.Forms
|
||||
{
|
||||
internal class StartForm : AutoCleanForm
|
||||
{
|
||||
public StartForm()
|
||||
{
|
||||
|
||||
DeleteMode = TelegramBotBase.Enums.EDeleteMode.OnLeavingForm;
|
||||
DeleteSide = TelegramBotBase.Enums.EDeleteSide.Both;
|
||||
|
||||
Opened += StartForm_Opened;
|
||||
}
|
||||
|
||||
private async Task StartForm_Opened(object sender, EventArgs e)
|
||||
{
|
||||
await Device.Send("Hey!\r\n\r\nChoose the /test command to get a message from outside.", disableNotification: true);
|
||||
}
|
||||
|
||||
public override async Task Load(MessageResult message)
|
||||
{
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,310 +0,0 @@
|
||||
using DemoBot.Forms;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Types.ReplyMarkups;
|
||||
using TelegramBotBase.Builder;
|
||||
using TelegramBotBase.Commands;
|
||||
using TelegramBotBase.Form;
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Experiments.ActionManager;
|
||||
using TelegramBotBase.Experiments.ActionManager.Actions;
|
||||
using TelegramBotBase.Experiments.ActionManager.Navigation;
|
||||
using Telegram.Bot.Types;
|
||||
|
||||
namespace DemoBot
|
||||
{
|
||||
internal class Program
|
||||
{
|
||||
public static String Token = Environment.GetEnvironmentVariable("API_KEY") ?? throw new Exception("API_KEY is not set");
|
||||
|
||||
static async Task Main(string[] args)
|
||||
{
|
||||
|
||||
//Using a custom FormBase message loop which is based on the original FormBaseMessageLoop within the framework.
|
||||
//Would integrate this later into the BotBaseBuilder -> MessageLoop step.
|
||||
//var cfb = new CustomFormBaseMessageLoop();
|
||||
|
||||
//Example 1: Long version
|
||||
var eam = ExternalActionManager.Configure(config =>
|
||||
{
|
||||
//Waiting for input starting with 'n_'
|
||||
config.AddStartsWithNavigation<HiddenForm>("n_", (a, b) =>
|
||||
{
|
||||
a.value = b;
|
||||
});
|
||||
|
||||
|
||||
//Minimal version, using reflection right now
|
||||
config.AddStartsWithNavigation<HiddenForm>("a_", (a, b) =>
|
||||
{
|
||||
a.value = b;
|
||||
});
|
||||
|
||||
|
||||
//Waiting for input starting with 't_'
|
||||
config.AddStartsWithNavigation(typeof(HiddenForm), "t_", (a, b) =>
|
||||
{
|
||||
var hf = a as HiddenForm;
|
||||
if (hf == null)
|
||||
return;
|
||||
|
||||
hf.value = b;
|
||||
});
|
||||
|
||||
|
||||
//Minimal version, using reflection right now
|
||||
config.AddEndsWithNavigation<HiddenForm_EndsWith>("_u", (a, b) =>
|
||||
{
|
||||
a.value = b;
|
||||
});
|
||||
|
||||
|
||||
//Deserialize input and waiting for the method property to has value 'tickets'
|
||||
config.AddGuidNavigation<HiddenTicketForm>("tickets", (a, b) =>
|
||||
{
|
||||
a.ticketId = b;
|
||||
});
|
||||
|
||||
|
||||
//Minimal version, using reflection right now
|
||||
config.AddGuidNavigation<HiddenLetterForm>("letters", (a, b) =>
|
||||
{
|
||||
a.letterId = b;
|
||||
});
|
||||
|
||||
|
||||
//Deserialize input and waiting for the method property to has value 'open'
|
||||
config.AddGuidNavigation<HiddenOpenForm>("open", (a, b) =>
|
||||
{
|
||||
a.guid = b;
|
||||
});
|
||||
|
||||
|
||||
//Do custom action
|
||||
config.AddStartsWithAction("p_", StartsWithActionCallback_Demo);
|
||||
|
||||
//Do custom action
|
||||
config.AddStartsWithAction("p2_", async (value, update, message) =>
|
||||
{
|
||||
if (message.UpdateData.CallbackQuery == null)
|
||||
return;
|
||||
|
||||
await update.Device.ConfirmAction(message.UpdateData.CallbackQuery.Id, "Confirmed!");
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
//Example 2: Short version
|
||||
var eam2 = ExternalActionManager.Configure(config =>
|
||||
{
|
||||
//Waiting for input starting with 'n_'
|
||||
config.AddStartsWithNavigation<HiddenForm>("n_", a => a.value);
|
||||
|
||||
|
||||
//Waiting for input starting with 'a_'
|
||||
config.AddStartsWithNavigation<HiddenForm>("a_", a => a.value);
|
||||
|
||||
|
||||
//Waiting for input starting with 't_' (Non generic version)
|
||||
config.AddStartsWithNavigation(typeof(HiddenForm), "t_", a => ((HiddenForm)a).value);
|
||||
|
||||
|
||||
//Waiting for input ending with 'n_'
|
||||
config.AddEndsWithNavigation<HiddenForm_EndsWith>("_u", a => a.value);
|
||||
|
||||
|
||||
//Deserialize input and waiting for the method property to has value 'tickets'
|
||||
config.AddGuidNavigation<HiddenTicketForm>("tickets", a => a.ticketId);
|
||||
|
||||
|
||||
//Minimal version, using reflection right now
|
||||
config.AddGuidNavigation<HiddenLetterForm>("letters", a => a.letterId);
|
||||
|
||||
|
||||
//Deserialize input and waiting for the method property to has value 'open'
|
||||
config.AddGuidNavigation<HiddenOpenForm>("open", a => a.guid);
|
||||
|
||||
|
||||
//Do custom action
|
||||
config.AddStartsWithAction("p_", StartsWithActionCallback_Demo);
|
||||
|
||||
|
||||
//Do custom action
|
||||
config.AddStartsWithAction("p2_", async (value, update, message) =>
|
||||
{
|
||||
if (message.UpdateData.CallbackQuery == null)
|
||||
return;
|
||||
|
||||
await update.Device.ConfirmAction(message.UpdateData.CallbackQuery.Id, "Confirmed!");
|
||||
});
|
||||
|
||||
|
||||
config.AddGuidAction("guid.test.too.long", async (g, c, u, m) =>
|
||||
{
|
||||
if (m.UpdateData.CallbackQuery == null)
|
||||
return;
|
||||
|
||||
await u.Device.ConfirmAction(m.UpdateData.CallbackQuery.Id, "Confirmed!");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
var bb = BotBaseBuilder.Create()
|
||||
.WithAPIKey(Token)
|
||||
.ActionMessageLoop(eam2)
|
||||
.WithStartForm<Forms.StartForm>()
|
||||
.NoProxy()
|
||||
.CustomCommands(a =>
|
||||
{
|
||||
a.Start("Starts the bot");
|
||||
a.Add("test", "Sends a test notification");
|
||||
a.Add("invalid", "Try to send an invalid data message");
|
||||
|
||||
})
|
||||
.NoSerialization()
|
||||
.UseGerman()
|
||||
.UseSingleThread()
|
||||
.Build();
|
||||
|
||||
bb.BotCommand += Bb_BotCommand;
|
||||
|
||||
bb.UnhandledCall += Bb_UnhandledCall;
|
||||
|
||||
await bb.Start();
|
||||
|
||||
await bb.UploadBotCommands();
|
||||
|
||||
Console.WriteLine("Bot started.");
|
||||
|
||||
|
||||
Console.ReadLine();
|
||||
|
||||
|
||||
await bb.Stop();
|
||||
|
||||
|
||||
}
|
||||
|
||||
private static async Task StartsWithActionCallback_Demo(String value, UpdateResult ur, MessageResult mr)
|
||||
{
|
||||
if (mr.UpdateData.CallbackQuery == null)
|
||||
return;
|
||||
|
||||
await ur.Device.ConfirmAction(mr.UpdateData.CallbackQuery.Id, "Confirmed!");
|
||||
}
|
||||
|
||||
private static void Bb_UnhandledCall(object? sender, TelegramBotBase.Args.UnhandledCallEventArgs e)
|
||||
{
|
||||
|
||||
Console.WriteLine($"Unhandled call: {e.RawData}");
|
||||
|
||||
}
|
||||
|
||||
private static async Task Bb_BotCommand(object sender, TelegramBotBase.Args.BotCommandEventArgs e)
|
||||
{
|
||||
|
||||
var current_form = e.Device.ActiveForm;
|
||||
|
||||
switch (e.Command)
|
||||
{
|
||||
case "/start":
|
||||
|
||||
//Already on start form
|
||||
if (current_form.GetType() == typeof(Forms.StartForm))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var st = new Forms.StartForm();
|
||||
|
||||
await current_form.NavigateTo(st);
|
||||
|
||||
break;
|
||||
|
||||
case "/test":
|
||||
|
||||
//Send test notification
|
||||
|
||||
//Test values
|
||||
|
||||
String max_value = "n_".PadRight(32, '1'); //Starts with
|
||||
|
||||
String max_value2 = "t_".PadRight(32, '2'); //Starts with
|
||||
|
||||
String max_value3 = "a_".PadRight(32, '3'); //Starts with
|
||||
|
||||
String max_value4 = "_u".PadLeft(32, '4'); //Ends with
|
||||
|
||||
String max_value5 = "p_".PadRight(32, '5'); //Ends with
|
||||
|
||||
String max_value6 = "p2_".PadRight(32, '6'); //Ends with
|
||||
|
||||
Guid test_value = Guid.NewGuid(); //Unhandled caller
|
||||
|
||||
var callback_guid = GuidNavigation.GetCallback("open", Guid.NewGuid()); //HiddenOpenForm
|
||||
|
||||
var callback_tickets = GuidNavigation.GetCallback("tickets", Guid.NewGuid()); //HiddenTicketForm
|
||||
|
||||
var callback_letters = GuidNavigation.GetCallback("letters", Guid.NewGuid()); //HiddenLetterForm
|
||||
|
||||
|
||||
String message = $"Test notification from 'outside'\n\nTest values are:\n\nTest: {max_value}\nTest2: {max_value2}\nTest3: {max_value3}\nTest (Guid): {test_value.ToString()}\nTest (Callback Guid): {callback_guid.Value}\nTickets (Guid): {callback_tickets.Value}\nLetters (Guid): {callback_letters.Value}\n";
|
||||
|
||||
|
||||
var tb = new TelegramBotClient(Token);
|
||||
|
||||
var bf = new ButtonForm();
|
||||
|
||||
bf.AddButtonRow(new ButtonBase("Ok", "n_ok"), new ButtonBase("Later", "n_later"));
|
||||
|
||||
bf.AddButtonRow("Test (n_)", max_value);
|
||||
|
||||
bf.AddButtonRow("Test2 (t_)", max_value2);
|
||||
|
||||
bf.AddButtonRow("Test3 (a_)", max_value3);
|
||||
|
||||
bf.AddButtonRow("Test4 (_u)", max_value4);
|
||||
|
||||
bf.AddButtonRow("Test5 (p_)", max_value5);
|
||||
|
||||
bf.AddButtonRow("Test6 (p2_)", max_value6);
|
||||
|
||||
bf.AddButtonRow("Test (Guid)", test_value.ToString());
|
||||
|
||||
bf.AddButtonRow("Test (Callback Gui)", callback_guid);
|
||||
|
||||
bf.AddButtonRow("Tickets", callback_tickets);
|
||||
|
||||
bf.AddButtonRow("Letters", callback_letters);
|
||||
|
||||
bf.AddButtonRow("Close", "close");
|
||||
|
||||
await tb.SendTextMessageAsync(e.DeviceId, message, disableNotification: true, replyMarkup: (InlineKeyboardMarkup)bf);
|
||||
|
||||
break;
|
||||
|
||||
case "/invalid":
|
||||
|
||||
Guid g = Guid.NewGuid();
|
||||
|
||||
var tb2 = new TelegramBotClient(Token);
|
||||
|
||||
var bf2 = new ButtonForm();
|
||||
|
||||
bf2.AddButtonRow("Test test", GuidAction.GetCallback("guid.test.too.long", g));
|
||||
|
||||
String message2 = "This is an invalid test message.";
|
||||
|
||||
await tb2.SendTextMessageAsync(e.DeviceId, message2, disableNotification: true, replyMarkup: (InlineKeyboardMarkup)bf2);
|
||||
|
||||
|
||||
break;
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
# ExternalActionManager
|
||||
|
||||
Idea of this experiment is to find a good intuitive way for handling "Unhandled calls".
|
||||
Right now they are "thrown" into an event handler and you have to take care over them on yourself.
|
||||
|
||||
|
||||
Source of them would be in most cases Telegram Bot messages which has an Inlinekeyboard attached and comes from outside of the framework. (via webservice or other remote channels)
|
||||
|
||||
And the button press should navigate to a different form, or invoke a different action.
|
||||
|
||||
|
||||
## How does it work ?
|
||||
|
||||
|
||||
- Open the Bot
|
||||
- Run the "/start" command
|
||||
- Now you are on the only FormBase where you can get without interaction
|
||||
- Use the "/test" command to invoke an "outside" message with some different buttons.
|
||||
- Use them to navigate to different "hidden" forms
|
||||
|
||||
|
||||
## Future ideas
|
||||
|
||||
- adding an Action for int and/or long datatypes
|
||||
|
||||
|
||||
-
|
||||
|
||||
Begin: 18.01.2024
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
using TelegramBotBase.Base;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Actions
|
||||
{
|
||||
public static class EndsWithAction_Extensions
|
||||
{
|
||||
public static void AddEndsWithAction(this ExternalActionManager manager, string value, Func<String, UpdateResult, MessageResult, Task> action)
|
||||
{
|
||||
manager.Add(new EndsWithAction(value, action));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Actions
|
||||
{
|
||||
|
||||
public class EndsWithAction : IExternalAction
|
||||
{
|
||||
public string SearchForString { get; set; }
|
||||
|
||||
public Action<FormBase, string> SetProperty { get; set; }
|
||||
|
||||
Func<String, UpdateResult, MessageResult, Task> Action;
|
||||
|
||||
|
||||
public EndsWithAction(string searchFor, Func<String, UpdateResult, MessageResult, Task> action)
|
||||
{
|
||||
SearchForString = searchFor;
|
||||
Action = action;
|
||||
}
|
||||
|
||||
public bool DoesFit(string raw_data) => raw_data.EndsWith(SearchForString);
|
||||
|
||||
|
||||
public async Task DoAction(UpdateResult ur, MessageResult mr) => await Action(mr.RawData, ur, mr);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Actions
|
||||
{
|
||||
public static class GuidAction_Extensions
|
||||
{
|
||||
|
||||
public static void AddGuidAction(this ExternalActionManager manager, string method, Func<Guid, CallbackData, UpdateResult, MessageResult, Task> action)
|
||||
{
|
||||
manager.Add(new GuidAction(method, action));
|
||||
}
|
||||
}
|
||||
}
|
||||
-85
@@ -1,85 +0,0 @@
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Actions
|
||||
{
|
||||
public class GuidAction : IExternalAction
|
||||
{
|
||||
public string Method { get; set; }
|
||||
|
||||
CallbackData? _lastData { get; set; }
|
||||
|
||||
Guid? _lastValue { get; set; }
|
||||
|
||||
Func<Guid, CallbackData, UpdateResult, MessageResult, Task> Action;
|
||||
|
||||
public GuidAction(string method, Func<Guid, CallbackData, UpdateResult, MessageResult, Task> action)
|
||||
{
|
||||
Method = method;
|
||||
Action = action;
|
||||
}
|
||||
|
||||
public bool DoesFit(string raw_data)
|
||||
{
|
||||
var cd = CallbackData.Deserialize(raw_data);
|
||||
|
||||
if (cd == null)
|
||||
return false;
|
||||
|
||||
if (cd.Method != Method)
|
||||
return false;
|
||||
|
||||
Guid g;
|
||||
|
||||
if (Guid.TryParse(cd.Value, out g))
|
||||
_lastValue = g;
|
||||
|
||||
_lastData = cd;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public async Task DoAction(UpdateResult ur, MessageResult mr) => await Action(_lastValue.Value, _lastData, ur, mr);
|
||||
|
||||
public static CallbackData GetCallback(string method, Guid guid) => new CallbackData(method, guid.ToString());
|
||||
|
||||
}
|
||||
|
||||
public class GuidAction<TForm> : IExternalAction
|
||||
where TForm : FormBase
|
||||
{
|
||||
public string Method { get; set; }
|
||||
|
||||
Guid? _lastValue { get; set; }
|
||||
|
||||
Func<Guid, UpdateResult, MessageResult, Task> Action;
|
||||
|
||||
public GuidAction(string method, Func<Guid, UpdateResult, MessageResult, Task> action)
|
||||
{
|
||||
Method = method;
|
||||
Action = action;
|
||||
}
|
||||
|
||||
public bool DoesFit(string raw_data)
|
||||
{
|
||||
var cd = CallbackData.Deserialize(raw_data);
|
||||
|
||||
if (cd == null)
|
||||
return false;
|
||||
|
||||
if (cd.Method != Method)
|
||||
return false;
|
||||
|
||||
Guid g;
|
||||
|
||||
if (Guid.TryParse(cd.Value, out g))
|
||||
_lastValue = g;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public async Task DoAction(UpdateResult ur, MessageResult mr) => await Action(_lastValue.Value, ur, mr);
|
||||
}
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Actions
|
||||
{
|
||||
public static class Int32Action_Extensions
|
||||
{
|
||||
|
||||
public static void AddInt32Action(this ExternalActionManager manager, string method, Func<int, CallbackData, UpdateResult, MessageResult, Task> action)
|
||||
{
|
||||
manager.Add(new Int32Action(method, action));
|
||||
}
|
||||
}
|
||||
}
|
||||
-90
@@ -1,90 +0,0 @@
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Actions
|
||||
{
|
||||
public class Int32Action : IExternalAction
|
||||
{
|
||||
public string Method { get; set; }
|
||||
|
||||
CallbackData? _lastData { get; set; }
|
||||
|
||||
int? _lastValue { get; set; }
|
||||
|
||||
Func<int, CallbackData, UpdateResult, MessageResult, Task> Action;
|
||||
|
||||
public Int32Action(string method, Func<int, CallbackData, UpdateResult, MessageResult, Task> action)
|
||||
{
|
||||
Method = method;
|
||||
Action = action;
|
||||
}
|
||||
|
||||
|
||||
public bool DoesFit(string raw_data)
|
||||
{
|
||||
var cd = CallbackData.Deserialize(raw_data);
|
||||
|
||||
if (cd == null)
|
||||
return false;
|
||||
|
||||
if (cd.Method != Method)
|
||||
return false;
|
||||
|
||||
int i;
|
||||
|
||||
if (int.TryParse(cd.Value, out i))
|
||||
_lastValue = i;
|
||||
|
||||
_lastData = cd;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public async Task DoAction(UpdateResult ur, MessageResult mr) => await Action(_lastValue.Value, _lastData, ur, mr);
|
||||
|
||||
public static CallbackData GetCallback(string method, long l) => new CallbackData(method, l.ToString());
|
||||
|
||||
}
|
||||
|
||||
public class Int32Action<TForm> : IExternalAction
|
||||
where TForm : FormBase
|
||||
{
|
||||
public string Method { get; set; }
|
||||
|
||||
CallbackData? _lastData { get; set; }
|
||||
|
||||
int? _lastValue { get; set; }
|
||||
|
||||
Func<int, CallbackData, UpdateResult, MessageResult, Task> Action;
|
||||
|
||||
public Int32Action(string method, Func<int, CallbackData, UpdateResult, MessageResult, Task> action)
|
||||
{
|
||||
Method = method;
|
||||
Action = action;
|
||||
}
|
||||
|
||||
public bool DoesFit(string raw_data)
|
||||
{
|
||||
var cd = CallbackData.Deserialize(raw_data);
|
||||
|
||||
if (cd == null)
|
||||
return false;
|
||||
|
||||
if (cd.Method != Method)
|
||||
return false;
|
||||
|
||||
int i;
|
||||
|
||||
if (int.TryParse(cd.Value, out i))
|
||||
_lastValue = i;
|
||||
|
||||
_lastData = cd;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public async Task DoAction(UpdateResult ur, MessageResult mr) => await Action(_lastValue.Value, _lastData, ur, mr);
|
||||
}
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Actions
|
||||
{
|
||||
public static class Int64Action_Extensions
|
||||
{
|
||||
|
||||
public static void AddInt64Action(this ExternalActionManager manager, string method, Func<long, CallbackData, UpdateResult, MessageResult, Task> action)
|
||||
{
|
||||
manager.Add(new Int64Action(method, action));
|
||||
}
|
||||
}
|
||||
}
|
||||
-89
@@ -1,89 +0,0 @@
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Actions
|
||||
{
|
||||
public class Int64Action : IExternalAction
|
||||
{
|
||||
public string Method { get; set; }
|
||||
|
||||
CallbackData? _lastData { get; set; }
|
||||
|
||||
long? _lastValue { get; set; }
|
||||
|
||||
Func<long, CallbackData, UpdateResult, MessageResult, Task> Action;
|
||||
|
||||
public Int64Action(string method, Func<long, CallbackData, UpdateResult, MessageResult, Task> action)
|
||||
{
|
||||
Method = method;
|
||||
Action = action;
|
||||
}
|
||||
|
||||
public bool DoesFit(string raw_data)
|
||||
{
|
||||
var cd = CallbackData.Deserialize(raw_data);
|
||||
|
||||
if (cd == null)
|
||||
return false;
|
||||
|
||||
if (cd.Method != Method)
|
||||
return false;
|
||||
|
||||
long l;
|
||||
|
||||
if (long.TryParse(cd.Value, out l))
|
||||
_lastValue = l;
|
||||
|
||||
_lastData = cd;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public async Task DoAction(UpdateResult ur, MessageResult mr) => await Action(_lastValue.Value, _lastData, ur, mr);
|
||||
|
||||
public static CallbackData GetCallback(string method, long l) => new CallbackData(method, l.ToString());
|
||||
|
||||
}
|
||||
|
||||
public class Int64Action<TForm> : IExternalAction
|
||||
where TForm : FormBase
|
||||
{
|
||||
public string Method { get; set; }
|
||||
|
||||
CallbackData? _lastData { get; set; }
|
||||
|
||||
long? _lastValue { get; set; }
|
||||
|
||||
Func<long, CallbackData, UpdateResult, MessageResult, Task> Action;
|
||||
|
||||
public Int64Action(string method, Func<long, CallbackData, UpdateResult, MessageResult, Task> action)
|
||||
{
|
||||
Method = method;
|
||||
Action = action;
|
||||
}
|
||||
|
||||
public bool DoesFit(string raw_data)
|
||||
{
|
||||
var cd = CallbackData.Deserialize(raw_data);
|
||||
|
||||
if (cd == null)
|
||||
return false;
|
||||
|
||||
if (cd.Method != Method)
|
||||
return false;
|
||||
|
||||
long g;
|
||||
|
||||
if (long.TryParse(cd.Value, out g))
|
||||
_lastValue = g;
|
||||
|
||||
_lastData = cd;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public async Task DoAction(UpdateResult ur, MessageResult mr) => await Action(_lastValue.Value, _lastData, ur, mr);
|
||||
}
|
||||
}
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
using TelegramBotBase.Base;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Actions
|
||||
{
|
||||
public static class StartWithAction_Extensions
|
||||
{
|
||||
public static void AddStartsWithAction(this ExternalActionManager manager, string value, Func<String, UpdateResult, MessageResult, Task> action)
|
||||
{
|
||||
manager.Add(new StartWithAction(value, action));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Actions
|
||||
{
|
||||
|
||||
public class StartWithAction : IExternalAction
|
||||
{
|
||||
public string SearchForString { get; set; }
|
||||
|
||||
public Action<FormBase, string> SetProperty { get; set; }
|
||||
|
||||
Func<String, UpdateResult, MessageResult, Task> Action;
|
||||
|
||||
|
||||
public StartWithAction(string searchFor, Func<String, UpdateResult, MessageResult, Task> action)
|
||||
{
|
||||
SearchForString = searchFor;
|
||||
Action = action;
|
||||
}
|
||||
|
||||
public bool DoesFit(string raw_data) => raw_data.StartsWith(SearchForString);
|
||||
|
||||
|
||||
public async Task DoAction(UpdateResult ur, MessageResult mr) => await Action(mr.RawData, ur, mr);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Actions
|
||||
{
|
||||
public static class StringAction_Extensions
|
||||
{
|
||||
|
||||
public static void AddStringAction(this ExternalActionManager manager, string method, Func<String, CallbackData, UpdateResult, MessageResult, Task> action)
|
||||
{
|
||||
manager.Add(new StringAction(method, action));
|
||||
}
|
||||
}
|
||||
}
|
||||
-85
@@ -1,85 +0,0 @@
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Actions
|
||||
{
|
||||
public class StringAction : IExternalAction
|
||||
{
|
||||
public string Method { get; set; }
|
||||
|
||||
CallbackData? _lastData { get; set; }
|
||||
|
||||
String? _lastValue { get; set; }
|
||||
|
||||
Func<string, CallbackData, UpdateResult, MessageResult, Task> Action;
|
||||
|
||||
public StringAction(string method, Func<string, CallbackData, UpdateResult, MessageResult, Task> action)
|
||||
{
|
||||
Method = method;
|
||||
Action = action;
|
||||
}
|
||||
|
||||
|
||||
public bool DoesFit(string raw_data)
|
||||
{
|
||||
var cd = CallbackData.Deserialize(raw_data);
|
||||
|
||||
if (cd == null)
|
||||
return false;
|
||||
|
||||
if (cd.Method != Method)
|
||||
return false;
|
||||
|
||||
_lastValue = cd.Value;
|
||||
|
||||
_lastData = cd;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public async Task DoAction(UpdateResult ur, MessageResult mr) => await Action(_lastValue, _lastData, ur, mr);
|
||||
|
||||
public static CallbackData GetCallback(string method, string str) => new CallbackData(method, str);
|
||||
|
||||
}
|
||||
|
||||
public class StringAction<TForm> : IExternalAction
|
||||
where TForm : FormBase
|
||||
{
|
||||
public string Method { get; set; }
|
||||
|
||||
CallbackData? _lastData { get; set; }
|
||||
|
||||
String? _lastValue { get; set; }
|
||||
|
||||
Func<String, CallbackData, UpdateResult, MessageResult, Task> Action;
|
||||
|
||||
public StringAction(string method, Func<String, CallbackData, UpdateResult, MessageResult, Task> action)
|
||||
{
|
||||
Method = method;
|
||||
Action = action;
|
||||
}
|
||||
|
||||
public bool DoesFit(string raw_data)
|
||||
{
|
||||
var cd = CallbackData.Deserialize(raw_data);
|
||||
|
||||
if (cd == null)
|
||||
return false;
|
||||
|
||||
if (cd.Method != Method)
|
||||
return false;
|
||||
|
||||
_lastValue = cd.Value;
|
||||
|
||||
_lastData = cd;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public async Task DoAction(UpdateResult ur, MessageResult mr) => await Action(_lastValue, _lastData, ur, mr);
|
||||
|
||||
}
|
||||
}
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
using TelegramBotBase.Base;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager
|
||||
{
|
||||
public partial class ExternalActionManager
|
||||
{
|
||||
|
||||
List<IExternalAction> actions = new List<IExternalAction>();
|
||||
|
||||
public void Add(IExternalAction action)
|
||||
{
|
||||
actions.Add(action);
|
||||
}
|
||||
|
||||
public async Task<bool> ManageCall(UpdateResult ur, MessageResult mr)
|
||||
{
|
||||
|
||||
foreach (var action in actions)
|
||||
{
|
||||
if (!action.DoesFit(mr.RawData))
|
||||
continue;
|
||||
|
||||
await action.DoAction(ur, mr);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an instance of the ExternalActionManager for configuration.
|
||||
/// </summary>
|
||||
/// <param name="action"></param>
|
||||
/// <returns></returns>
|
||||
public static ExternalActionManager Configure(Action<ExternalActionManager> action)
|
||||
{
|
||||
var eam = new ExternalActionManager();
|
||||
|
||||
action(eam);
|
||||
|
||||
return eam;
|
||||
}
|
||||
}
|
||||
}
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
using TelegramBotBase.Base;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager
|
||||
{
|
||||
|
||||
public interface IExternalAction
|
||||
{
|
||||
bool DoesFit(string raw_data);
|
||||
|
||||
Task DoAction(UpdateResult ur, MessageResult mr);
|
||||
}
|
||||
|
||||
}
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
using System.Linq.Expressions;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Navigation
|
||||
{
|
||||
public static class EndsWithNavigation_Extensions
|
||||
{
|
||||
public static void AddEndsWithNavigation<TForm>(this ExternalActionManager manager, string method, Expression<Func<TForm, string>> propertySelector)
|
||||
where TForm : FormBase
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(typeof(TForm)))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(TForm)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
var newValue = Expression.Parameter(propertySelector.Body.Type);
|
||||
|
||||
var assign = Expression.Lambda<Action<TForm, string>>(Expression.Assign(propertySelector.Body, newValue), propertySelector.Parameters[0], newValue);
|
||||
|
||||
var setter = assign.Compile(true);
|
||||
|
||||
manager.Add(new EndsWithNavigation<TForm>(method, setter));
|
||||
}
|
||||
public static void AddEndsWithNavigation<TForm>(this ExternalActionManager manager, string value, Action<TForm, string> setProperty)
|
||||
where TForm : FormBase
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(typeof(TForm)))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(TForm)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
manager.Add(new EndsWithNavigation<TForm>(value, setProperty));
|
||||
}
|
||||
|
||||
public static void AddEndsWithNavigation(this ExternalActionManager manager, Type formType, string value, Expression<Func<FormBase, string>> propertySelector)
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(formType))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(formType)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
var newValue = Expression.Parameter(propertySelector.Body.Type);
|
||||
|
||||
var assign = Expression.Lambda<Action<FormBase, string>>(Expression.Assign(propertySelector.Body, newValue), propertySelector.Parameters[0], newValue);
|
||||
|
||||
var setter = assign.Compile(true);
|
||||
|
||||
manager.Add(new EndsWithNavigation(formType, value, setter));
|
||||
}
|
||||
|
||||
public static void AddEndsWithNavigation(this ExternalActionManager manager, Type formType, string value, Action<FormBase, string> setProperty)
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(formType))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(formType)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
manager.Add(new EndsWithNavigation(formType, value, setProperty));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-77
@@ -1,77 +0,0 @@
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Navigation
|
||||
{
|
||||
public class EndsWithNavigation : IExternalAction
|
||||
{
|
||||
public Type FormType { get; }
|
||||
|
||||
public string Value { get; set; }
|
||||
|
||||
public Action<FormBase, string> SetProperty { get; set; }
|
||||
|
||||
public EndsWithNavigation(Type formType, string value, Action<FormBase, string> setProperty)
|
||||
{
|
||||
FormType = formType;
|
||||
Value = value;
|
||||
SetProperty = setProperty;
|
||||
}
|
||||
|
||||
|
||||
public bool DoesFit(string raw_data) => raw_data.EndsWith(Value);
|
||||
|
||||
|
||||
public async Task DoAction(UpdateResult ur, MessageResult mr)
|
||||
{
|
||||
await mr.ConfirmAction();
|
||||
|
||||
var new_form = FormType.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as FormBase;
|
||||
|
||||
if (mr.RawData != null)
|
||||
{
|
||||
SetProperty(new_form, mr.RawData);
|
||||
}
|
||||
|
||||
await ur.Device.ActiveForm.NavigateTo(new_form);
|
||||
}
|
||||
}
|
||||
|
||||
public class EndsWithNavigation<TForm> : IExternalAction
|
||||
where TForm : FormBase
|
||||
{
|
||||
public string Value { get; set; }
|
||||
|
||||
public Action<TForm, string> SetProperty { get; set; }
|
||||
|
||||
public EndsWithNavigation(string value, Action<TForm, string> setProperty)
|
||||
{
|
||||
Value = value;
|
||||
SetProperty = setProperty;
|
||||
}
|
||||
|
||||
|
||||
public bool DoesFit(string raw_data) => raw_data.EndsWith(Value);
|
||||
|
||||
|
||||
public async Task DoAction(UpdateResult ur, MessageResult mr)
|
||||
{
|
||||
await mr.ConfirmAction();
|
||||
|
||||
var type = typeof(TForm);
|
||||
|
||||
TForm new_form = type.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as TForm;
|
||||
|
||||
if (mr.RawData != null)
|
||||
{
|
||||
SetProperty(new_form, mr.RawData);
|
||||
}
|
||||
|
||||
await ur.Device.ActiveForm.NavigateTo(new_form);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
using System.Linq.Expressions;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Navigation
|
||||
{
|
||||
public static class GuidNavigation_Extensions
|
||||
{
|
||||
|
||||
public static void AddGuidNavigation<TForm>(this ExternalActionManager manager, string method, Expression<Func<TForm, Guid>> propertySelector)
|
||||
where TForm : FormBase
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(typeof(TForm)))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(TForm)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
var newValue = Expression.Parameter(propertySelector.Body.Type);
|
||||
|
||||
var assign = Expression.Lambda<Action<TForm, Guid>>(Expression.Assign(propertySelector.Body, newValue), propertySelector.Parameters[0], newValue);
|
||||
|
||||
var setter = assign.Compile(true);
|
||||
|
||||
manager.Add(new GuidNavigation<TForm>(method, setter));
|
||||
}
|
||||
|
||||
public static void AddGuidNavigation<TForm>(this ExternalActionManager manager, string method, Action<TForm, Guid> action)
|
||||
where TForm : FormBase
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(typeof(TForm)))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(TForm)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
manager.Add(new GuidNavigation<TForm>(method, action));
|
||||
}
|
||||
|
||||
public static void AddGuidNavigation(this ExternalActionManager manager, Type formType, string value, Expression<Func<FormBase, Guid>> propertySelector)
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(formType))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(formType)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
var newValue = Expression.Parameter(propertySelector.Body.Type);
|
||||
|
||||
var assign = Expression.Lambda<Action<FormBase, Guid>>(Expression.Assign(propertySelector.Body, newValue), propertySelector.Parameters[0], newValue);
|
||||
|
||||
var setter = assign.Compile(true);
|
||||
|
||||
manager.Add(new GuidNavigation(formType, value, setter));
|
||||
}
|
||||
|
||||
public static void AddGuidNavigation(this ExternalActionManager manager, Type formType, string method, Action<FormBase, Guid> action)
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(formType))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(formType)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
manager.Add(new GuidNavigation(formType, method, action));
|
||||
}
|
||||
}
|
||||
}
|
||||
-106
@@ -1,106 +0,0 @@
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Navigation
|
||||
{
|
||||
public class GuidNavigation : IExternalAction
|
||||
{
|
||||
public Type FormType { get; }
|
||||
|
||||
public string Method { get; set; }
|
||||
|
||||
public Action<FormBase, Guid> SetProperty { get; set; }
|
||||
|
||||
Guid? _lastValue { get; set; }
|
||||
|
||||
public GuidNavigation(Type formType, string method, Action<FormBase, Guid> setProperty)
|
||||
{
|
||||
FormType = formType;
|
||||
Method = method;
|
||||
SetProperty = setProperty;
|
||||
}
|
||||
|
||||
public bool DoesFit(string raw_action)
|
||||
{
|
||||
var cd = CallbackData.Deserialize(raw_action);
|
||||
|
||||
if (cd == null)
|
||||
return false;
|
||||
|
||||
if (cd.Method != Method)
|
||||
return false;
|
||||
|
||||
Guid g;
|
||||
|
||||
if (Guid.TryParse(cd.Value, out g))
|
||||
_lastValue = g;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public async Task DoAction(UpdateResult ur, MessageResult mr)
|
||||
{
|
||||
await mr.ConfirmAction();
|
||||
|
||||
var new_form = FormType.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as FormBase;
|
||||
|
||||
if (_lastValue != null)
|
||||
SetProperty(new_form, _lastValue.Value);
|
||||
|
||||
await ur.Device.ActiveForm.NavigateTo(new_form);
|
||||
}
|
||||
|
||||
|
||||
public static CallbackData GetCallback(string method, Guid guid) => new CallbackData(method, guid.ToString());
|
||||
}
|
||||
|
||||
public class GuidNavigation<TForm> : IExternalAction
|
||||
where TForm : FormBase
|
||||
{
|
||||
public string Method { get; set; }
|
||||
|
||||
public Action<TForm, Guid> SetProperty { get; set; }
|
||||
|
||||
Guid? _lastValue { get; set; }
|
||||
|
||||
public GuidNavigation(string method, Action<TForm, Guid> setProperty)
|
||||
{
|
||||
Method = method;
|
||||
SetProperty = setProperty;
|
||||
}
|
||||
|
||||
public bool DoesFit(string raw_data)
|
||||
{
|
||||
var cd = CallbackData.Deserialize(raw_data);
|
||||
|
||||
if (cd == null)
|
||||
return false;
|
||||
|
||||
if (cd.Method != Method)
|
||||
return false;
|
||||
|
||||
Guid g;
|
||||
|
||||
if (Guid.TryParse(cd.Value, out g))
|
||||
_lastValue = g;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public async Task DoAction(UpdateResult ur, MessageResult mr)
|
||||
{
|
||||
await mr.ConfirmAction();
|
||||
|
||||
var type = typeof(TForm);
|
||||
|
||||
TForm new_form = type.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as TForm;
|
||||
|
||||
if (_lastValue != null)
|
||||
SetProperty(new_form, _lastValue.Value);
|
||||
|
||||
await ur.Device.ActiveForm.NavigateTo(new_form);
|
||||
}
|
||||
}
|
||||
}
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
using System.Linq.Expressions;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Navigation
|
||||
{
|
||||
public static class Int32Navigation_Extensions
|
||||
{
|
||||
|
||||
public static void AddInt32Navigation<TForm>(this ExternalActionManager manager, string method, Expression<Func<TForm, int>> propertySelector)
|
||||
where TForm : FormBase
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(typeof(TForm)))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(TForm)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
var newValue = Expression.Parameter(propertySelector.Body.Type);
|
||||
|
||||
var assign = Expression.Lambda<Action<TForm, int>>(Expression.Assign(propertySelector.Body, newValue), propertySelector.Parameters[0], newValue);
|
||||
|
||||
var setter = assign.Compile(true);
|
||||
|
||||
manager.Add(new Int32Navigation<TForm>(method, setter));
|
||||
}
|
||||
|
||||
public static void AddInt32Navigation<TForm>(this ExternalActionManager manager, string method, Action<TForm, int> action)
|
||||
where TForm : FormBase
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(typeof(TForm)))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(TForm)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
manager.Add(new Int32Navigation<TForm>(method, action));
|
||||
}
|
||||
|
||||
public static void AddInt32Navigation(this ExternalActionManager manager, Type formType, string value, Expression<Func<FormBase, int>> propertySelector)
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(formType))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(formType)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
var newValue = Expression.Parameter(propertySelector.Body.Type);
|
||||
|
||||
var assign = Expression.Lambda<Action<FormBase, int>>(Expression.Assign(propertySelector.Body, newValue), propertySelector.Parameters[0], newValue);
|
||||
|
||||
var setter = assign.Compile(true);
|
||||
|
||||
manager.Add(new Int32Navigation(formType, value, setter));
|
||||
}
|
||||
|
||||
public static void AddInt32Navigation(this ExternalActionManager manager, Type formType, string method, Action<FormBase, int> action)
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(formType))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(formType)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
manager.Add(new Int32Navigation(formType, method, action));
|
||||
}
|
||||
}
|
||||
}
|
||||
-106
@@ -1,106 +0,0 @@
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Navigation
|
||||
{
|
||||
public class Int32Navigation : IExternalAction
|
||||
{
|
||||
public Type FormType { get; }
|
||||
|
||||
public string Method { get; set; }
|
||||
|
||||
public Action<FormBase, int> SetProperty { get; set; }
|
||||
|
||||
int? _lastValue { get; set; }
|
||||
|
||||
public Int32Navigation(Type formType, string method, Action<FormBase, int> setProperty)
|
||||
{
|
||||
FormType = formType;
|
||||
Method = method;
|
||||
SetProperty = setProperty;
|
||||
}
|
||||
|
||||
public bool DoesFit(string raw_action)
|
||||
{
|
||||
var cd = CallbackData.Deserialize(raw_action);
|
||||
|
||||
if (cd == null)
|
||||
return false;
|
||||
|
||||
if (cd.Method != Method)
|
||||
return false;
|
||||
|
||||
int i;
|
||||
|
||||
if (int.TryParse(cd.Value, out i))
|
||||
_lastValue = i;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public async Task DoAction(UpdateResult ur, MessageResult mr)
|
||||
{
|
||||
await mr.ConfirmAction();
|
||||
|
||||
var new_form = FormType.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as FormBase;
|
||||
|
||||
if (_lastValue != null)
|
||||
SetProperty(new_form, _lastValue.Value);
|
||||
|
||||
await ur.Device.ActiveForm.NavigateTo(new_form);
|
||||
}
|
||||
|
||||
|
||||
public static CallbackData GetCallback(string method, int i) => new CallbackData(method, i.ToString());
|
||||
}
|
||||
|
||||
public class Int32Navigation<TForm> : IExternalAction
|
||||
where TForm : FormBase
|
||||
{
|
||||
public string Method { get; set; }
|
||||
|
||||
public Action<TForm, int> SetProperty { get; set; }
|
||||
|
||||
int? _lastValue { get; set; }
|
||||
|
||||
public Int32Navigation(string method, Action<TForm, int> setProperty)
|
||||
{
|
||||
Method = method;
|
||||
SetProperty = setProperty;
|
||||
}
|
||||
|
||||
public bool DoesFit(string raw_data)
|
||||
{
|
||||
var cd = CallbackData.Deserialize(raw_data);
|
||||
|
||||
if (cd == null)
|
||||
return false;
|
||||
|
||||
if (cd.Method != Method)
|
||||
return false;
|
||||
|
||||
int g;
|
||||
|
||||
if (int.TryParse(cd.Value, out g))
|
||||
_lastValue = g;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public async Task DoAction(UpdateResult ur, MessageResult mr)
|
||||
{
|
||||
await mr.ConfirmAction();
|
||||
|
||||
var type = typeof(TForm);
|
||||
|
||||
TForm new_form = type.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as TForm;
|
||||
|
||||
if (_lastValue != null)
|
||||
SetProperty(new_form, _lastValue.Value);
|
||||
|
||||
await ur.Device.ActiveForm.NavigateTo(new_form);
|
||||
}
|
||||
}
|
||||
}
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
using System.Linq.Expressions;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Navigation
|
||||
{
|
||||
public static class Int64Navigation_Extensions
|
||||
{
|
||||
|
||||
public static void AddInt64Navigation<TForm>(this ExternalActionManager manager, string method, Expression<Func<TForm, long>> propertySelector)
|
||||
where TForm : FormBase
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(typeof(TForm)))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(TForm)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
var newValue = Expression.Parameter(propertySelector.Body.Type);
|
||||
|
||||
var assign = Expression.Lambda<Action<TForm, long>>(Expression.Assign(propertySelector.Body, newValue), propertySelector.Parameters[0], newValue);
|
||||
|
||||
var setter = assign.Compile(true);
|
||||
|
||||
manager.Add(new Int64Navigation<TForm>(method, setter));
|
||||
}
|
||||
|
||||
public static void AddInt64Navigation<TForm>(this ExternalActionManager manager, string method, Action<TForm, long> action)
|
||||
where TForm : FormBase
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(typeof(TForm)))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(TForm)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
manager.Add(new Int64Navigation<TForm>(method, action));
|
||||
}
|
||||
|
||||
public static void AddInt64Navigation(this ExternalActionManager manager, Type formType, string value, Expression<Func<FormBase, long>> propertySelector)
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(formType))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(formType)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
var newValue = Expression.Parameter(propertySelector.Body.Type);
|
||||
|
||||
var assign = Expression.Lambda<Action<FormBase, long>>(Expression.Assign(propertySelector.Body, newValue), propertySelector.Parameters[0], newValue);
|
||||
|
||||
var setter = assign.Compile(true);
|
||||
|
||||
manager.Add(new Int64Navigation(formType, value, setter));
|
||||
}
|
||||
|
||||
public static void AddInt64Navigation(this ExternalActionManager manager, Type formType, string method, Action<FormBase, long> action)
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(formType))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(formType)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
manager.Add(new Int64Navigation(formType, method, action));
|
||||
}
|
||||
}
|
||||
}
|
||||
-106
@@ -1,106 +0,0 @@
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Navigation
|
||||
{
|
||||
public class Int64Navigation : IExternalAction
|
||||
{
|
||||
public Type FormType { get; }
|
||||
|
||||
public string Method { get; set; }
|
||||
|
||||
public Action<FormBase, long> SetProperty { get; set; }
|
||||
|
||||
long? _lastValue { get; set; }
|
||||
|
||||
public Int64Navigation(Type formType, string method, Action<FormBase, long> setProperty)
|
||||
{
|
||||
FormType = formType;
|
||||
Method = method;
|
||||
SetProperty = setProperty;
|
||||
}
|
||||
|
||||
public bool DoesFit(string raw_action)
|
||||
{
|
||||
var cd = CallbackData.Deserialize(raw_action);
|
||||
|
||||
if (cd == null)
|
||||
return false;
|
||||
|
||||
if (cd.Method != Method)
|
||||
return false;
|
||||
|
||||
long l;
|
||||
|
||||
if (long.TryParse(cd.Value, out l))
|
||||
_lastValue = l;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public async Task DoAction(UpdateResult ur, MessageResult mr)
|
||||
{
|
||||
await mr.ConfirmAction();
|
||||
|
||||
var new_form = FormType.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as FormBase;
|
||||
|
||||
if (_lastValue != null)
|
||||
SetProperty(new_form, _lastValue.Value);
|
||||
|
||||
await ur.Device.ActiveForm.NavigateTo(new_form);
|
||||
}
|
||||
|
||||
|
||||
public static CallbackData GetCallback(string method, long l) => new CallbackData(method, l.ToString());
|
||||
}
|
||||
|
||||
public class Int64Navigation<TForm> : IExternalAction
|
||||
where TForm : FormBase
|
||||
{
|
||||
public string Method { get; set; }
|
||||
|
||||
public Action<TForm, long> SetProperty { get; set; }
|
||||
|
||||
long? _lastValue { get; set; }
|
||||
|
||||
public Int64Navigation(string method, Action<TForm, long> setProperty)
|
||||
{
|
||||
Method = method;
|
||||
SetProperty = setProperty;
|
||||
}
|
||||
|
||||
public bool DoesFit(string raw_data)
|
||||
{
|
||||
var cd = CallbackData.Deserialize(raw_data);
|
||||
|
||||
if (cd == null)
|
||||
return false;
|
||||
|
||||
if (cd.Method != Method)
|
||||
return false;
|
||||
|
||||
long l;
|
||||
|
||||
if (long.TryParse(cd.Value, out l))
|
||||
_lastValue = l;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public async Task DoAction(UpdateResult ur, MessageResult mr)
|
||||
{
|
||||
await mr.ConfirmAction();
|
||||
|
||||
var type = typeof(TForm);
|
||||
|
||||
TForm new_form = type.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as TForm;
|
||||
|
||||
if (_lastValue != null)
|
||||
SetProperty(new_form, _lastValue.Value);
|
||||
|
||||
await ur.Device.ActiveForm.NavigateTo(new_form);
|
||||
}
|
||||
}
|
||||
}
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
using System.Linq.Expressions;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Navigation
|
||||
{
|
||||
public static class StartWithNavigation_Extensions
|
||||
{
|
||||
public static void AddStartsWithNavigation<TForm>(this ExternalActionManager manager, string method, Expression<Func<TForm, string>> propertySelector)
|
||||
where TForm : FormBase
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(typeof(TForm)))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(TForm)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
var newValue = Expression.Parameter(propertySelector.Body.Type);
|
||||
|
||||
var assign = Expression.Lambda<Action<TForm, string>>(Expression.Assign(propertySelector.Body, newValue), propertySelector.Parameters[0], newValue);
|
||||
|
||||
var setter = assign.Compile(true);
|
||||
|
||||
manager.Add(new StartWithNavigation<TForm>(method, setter));
|
||||
}
|
||||
public static void AddStartsWithNavigation<TForm>(this ExternalActionManager manager, string value, Action<TForm, string> setProperty)
|
||||
where TForm : FormBase
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(typeof(TForm)))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(TForm)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
manager.Add(new StartWithNavigation<TForm>(value, setProperty));
|
||||
}
|
||||
|
||||
public static void AddStartsWithNavigation(this ExternalActionManager manager, Type formType, string value, Expression<Func<FormBase, string>> propertySelector)
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(formType))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(formType)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
var newValue = Expression.Parameter(propertySelector.Body.Type);
|
||||
|
||||
var assign = Expression.Lambda<Action<FormBase, string>>(Expression.Assign(propertySelector.Body, newValue), propertySelector.Parameters[0], newValue);
|
||||
|
||||
var setter = assign.Compile(true);
|
||||
|
||||
manager.Add(new StartWithNavigation(formType, value, setter));
|
||||
}
|
||||
|
||||
public static void AddStartsWithNavigation(this ExternalActionManager manager, Type formType, string value, Action<FormBase, string> setProperty)
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(formType))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(formType)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
manager.Add(new StartWithNavigation(formType, value, setProperty));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-74
@@ -1,74 +0,0 @@
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Navigation
|
||||
{
|
||||
public class StartWithNavigation : IExternalAction
|
||||
{
|
||||
public Type FormType { get; }
|
||||
|
||||
public string Value { get; set; }
|
||||
|
||||
public Action<FormBase, string> SetProperty { get; set; }
|
||||
|
||||
|
||||
public StartWithNavigation(Type formType, string value, Action<FormBase, string> setProperty)
|
||||
{
|
||||
FormType = formType;
|
||||
Value = value;
|
||||
SetProperty = setProperty;
|
||||
}
|
||||
|
||||
public bool DoesFit(string raw_data) => raw_data.StartsWith(Value);
|
||||
|
||||
public async Task DoAction(UpdateResult ur, MessageResult mr)
|
||||
{
|
||||
await mr.ConfirmAction();
|
||||
|
||||
var new_form = FormType.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as FormBase;
|
||||
|
||||
if (mr.RawData != null)
|
||||
{
|
||||
SetProperty(new_form, mr.RawData);
|
||||
}
|
||||
|
||||
await ur.Device.ActiveForm.NavigateTo(new_form);
|
||||
}
|
||||
}
|
||||
|
||||
public class StartWithNavigation<TForm> : IExternalAction
|
||||
where TForm : FormBase
|
||||
{
|
||||
public string Value { get; set; }
|
||||
|
||||
public Action<TForm, string> SetProperty { get; set; }
|
||||
|
||||
public StartWithNavigation(string value, Action<TForm, string> setProperty)
|
||||
{
|
||||
Value = value;
|
||||
SetProperty = setProperty;
|
||||
}
|
||||
|
||||
|
||||
public bool DoesFit(string raw_data) => raw_data.StartsWith(Value);
|
||||
|
||||
|
||||
public async Task DoAction(UpdateResult ur, MessageResult mr)
|
||||
{
|
||||
await mr.ConfirmAction();
|
||||
|
||||
var type = typeof(TForm);
|
||||
|
||||
TForm new_form = type.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as TForm;
|
||||
|
||||
if (mr.RawData != null)
|
||||
{
|
||||
SetProperty(new_form, mr.RawData);
|
||||
}
|
||||
|
||||
await ur.Device.ActiveForm.NavigateTo(new_form);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
using System.Linq.Expressions;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Navigation
|
||||
{
|
||||
public static class StringNavigation_Extensions
|
||||
{
|
||||
|
||||
public static void AddStringNavigation<TForm>(this ExternalActionManager manager, string method, Expression<Func<TForm, String>> propertySelector)
|
||||
where TForm : FormBase
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(typeof(TForm)))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(TForm)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
var newValue = Expression.Parameter(propertySelector.Body.Type);
|
||||
|
||||
var assign = Expression.Lambda<Action<TForm, String>>(Expression.Assign(propertySelector.Body, newValue), propertySelector.Parameters[0], newValue);
|
||||
|
||||
var setter = assign.Compile(true);
|
||||
|
||||
manager.Add(new StringNavigation<TForm>(method, setter));
|
||||
}
|
||||
|
||||
public static void AddStringNavigation<TForm>(this ExternalActionManager manager, string method, Action<TForm, String> action)
|
||||
where TForm : FormBase
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(typeof(TForm)))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(TForm)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
manager.Add(new StringNavigation<TForm>(method, action));
|
||||
}
|
||||
|
||||
public static void AddStringNavigation(this ExternalActionManager manager, Type formType, string value, Expression<Func<FormBase, String>> propertySelector)
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(formType))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(formType)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
var newValue = Expression.Parameter(propertySelector.Body.Type);
|
||||
|
||||
var assign = Expression.Lambda<Action<FormBase, String>>(Expression.Assign(propertySelector.Body, newValue), propertySelector.Parameters[0], newValue);
|
||||
|
||||
var setter = assign.Compile(true);
|
||||
|
||||
manager.Add(new StringNavigation(formType, value, setter));
|
||||
}
|
||||
|
||||
public static void AddStringNavigation(this ExternalActionManager manager, Type formType, string method, Action<FormBase, String> action)
|
||||
{
|
||||
if (!typeof(FormBase).IsAssignableFrom(formType))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(formType)} argument must be a {nameof(FormBase)} type");
|
||||
}
|
||||
|
||||
manager.Add(new StringNavigation(formType, method, action));
|
||||
}
|
||||
}
|
||||
}
|
||||
-100
@@ -1,100 +0,0 @@
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager.Navigation
|
||||
{
|
||||
public class StringNavigation : IExternalAction
|
||||
{
|
||||
public Type FormType { get; }
|
||||
|
||||
public string Method { get; set; }
|
||||
|
||||
public Action<FormBase, String> SetProperty { get; set; }
|
||||
|
||||
String? _lastValue { get; set; }
|
||||
|
||||
public StringNavigation(Type formType, string method, Action<FormBase, String> setProperty)
|
||||
{
|
||||
FormType = formType;
|
||||
Method = method;
|
||||
SetProperty = setProperty;
|
||||
}
|
||||
|
||||
public bool DoesFit(string raw_action)
|
||||
{
|
||||
var cd = CallbackData.Deserialize(raw_action);
|
||||
|
||||
if (cd == null)
|
||||
return false;
|
||||
|
||||
if (cd.Method != Method)
|
||||
return false;
|
||||
|
||||
_lastValue = cd.Value;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public async Task DoAction(UpdateResult ur, MessageResult mr)
|
||||
{
|
||||
await mr.ConfirmAction();
|
||||
|
||||
var new_form = FormType.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as FormBase;
|
||||
|
||||
if (_lastValue != null)
|
||||
SetProperty(new_form, _lastValue);
|
||||
|
||||
await ur.Device.ActiveForm.NavigateTo(new_form);
|
||||
}
|
||||
|
||||
|
||||
public static CallbackData GetCallback(string method, String str) => new CallbackData(method, str);
|
||||
}
|
||||
|
||||
public class StringNavigation<TForm> : IExternalAction
|
||||
where TForm : FormBase
|
||||
{
|
||||
public string Method { get; set; }
|
||||
|
||||
public Action<TForm, String> SetProperty { get; set; }
|
||||
|
||||
String? _lastValue { get; set; }
|
||||
|
||||
public StringNavigation(string method, Action<TForm, String> setProperty)
|
||||
{
|
||||
Method = method;
|
||||
SetProperty = setProperty;
|
||||
}
|
||||
|
||||
public bool DoesFit(string raw_data)
|
||||
{
|
||||
var cd = CallbackData.Deserialize(raw_data);
|
||||
|
||||
if (cd == null)
|
||||
return false;
|
||||
|
||||
if (cd.Method != Method)
|
||||
return false;
|
||||
|
||||
_lastValue = cd.Value;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public async Task DoAction(UpdateResult ur, MessageResult mr)
|
||||
{
|
||||
await mr.ConfirmAction();
|
||||
|
||||
var type = typeof(TForm);
|
||||
|
||||
TForm new_form = type.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as TForm;
|
||||
|
||||
if (_lastValue != null)
|
||||
SetProperty(new_form, _lastValue);
|
||||
|
||||
await ur.Device.ActiveForm.NavigateTo(new_form);
|
||||
}
|
||||
}
|
||||
}
|
||||
-146
@@ -1,146 +0,0 @@
|
||||
using System.ComponentModel;
|
||||
using Telegram.Bot.Types.Enums;
|
||||
using TelegramBotBase;
|
||||
using TelegramBotBase.Args;
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Interfaces;
|
||||
using TelegramBotBase.Sessions;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager
|
||||
{
|
||||
public class CustomFormBaseMessageLoop : IMessageLoopFactory
|
||||
{
|
||||
private static readonly object EvUnhandledCall = new();
|
||||
|
||||
private readonly EventHandlerList _events = new();
|
||||
|
||||
public ExternalActionManager ExternalActionManager { get; set; }
|
||||
|
||||
public async Task MessageLoop(BotBase bot, DeviceSession s, UpdateResult ur, MessageResult mr)
|
||||
{
|
||||
var update = ur.RawData;
|
||||
|
||||
if (update.Type != UpdateType.Message
|
||||
&& update.Type != UpdateType.EditedMessage
|
||||
&& update.Type != UpdateType.CallbackQuery)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
//Remove unecessary parameter from method call in the future
|
||||
var session = ur.Device;
|
||||
|
||||
//Is this a bot command ?
|
||||
if (mr.IsFirstHandler && mr.IsBotCommand && bot.IsKnownBotCommand(mr.BotCommand))
|
||||
{
|
||||
var sce = new BotCommandEventArgs(mr.BotCommand, mr.BotCommandParameters, mr.Message, session.DeviceId,
|
||||
session);
|
||||
await bot.OnBotCommand(sce);
|
||||
|
||||
if (sce.Handled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
mr.Device = session;
|
||||
ur.Device = session;
|
||||
|
||||
var activeForm = session.ActiveForm;
|
||||
|
||||
//Pre Loading Event
|
||||
await activeForm.PreLoad(mr);
|
||||
|
||||
//Send Load event to controls
|
||||
await activeForm.LoadControls(mr);
|
||||
|
||||
//Loading Event
|
||||
await activeForm.Load(mr);
|
||||
|
||||
|
||||
//Is Attachment ? (Photo, Audio, Video, Contact, Location, Document) (Ignore Callback Queries)
|
||||
if (update.Type == UpdateType.Message)
|
||||
{
|
||||
if ((mr.MessageType == MessageType.Contact)
|
||||
| (mr.MessageType == MessageType.Document)
|
||||
| (mr.MessageType == MessageType.Location)
|
||||
| (mr.MessageType == MessageType.Photo)
|
||||
| (mr.MessageType == MessageType.Video)
|
||||
| (mr.MessageType == MessageType.Audio))
|
||||
{
|
||||
await activeForm.SentData(new DataResult(ur));
|
||||
}
|
||||
}
|
||||
|
||||
//Message edited ?
|
||||
if (update.Type == UpdateType.EditedMessage)
|
||||
{
|
||||
await activeForm.Edited(mr);
|
||||
}
|
||||
|
||||
//Action Event
|
||||
if (!session.FormSwitched && mr.IsAction)
|
||||
{
|
||||
//Send Action event to controls
|
||||
await activeForm.ActionControls(mr);
|
||||
|
||||
//Send Action event to form itself
|
||||
await activeForm.Action(mr);
|
||||
|
||||
if (!mr.Handled)
|
||||
{
|
||||
var handled = await ExternalActionManager?.ManageCall(ur, mr);
|
||||
|
||||
if (handled)
|
||||
{
|
||||
mr.Handled = true;
|
||||
if (!session.FormSwitched)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var uhc = new UnhandledCallEventArgs(ur.Message.Text, mr.RawData, session.DeviceId, mr.MessageId, ur.Message, session);
|
||||
|
||||
OnUnhandledCall(uhc);
|
||||
|
||||
if (uhc.Handled)
|
||||
{
|
||||
mr.Handled = true;
|
||||
if (!session.FormSwitched)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if (!session.FormSwitched)
|
||||
{
|
||||
//Render Event
|
||||
await activeForm.RenderControls(mr);
|
||||
|
||||
await activeForm.Render(mr);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Will be called if no form handled this call
|
||||
/// </summary>
|
||||
public event EventHandler<UnhandledCallEventArgs> UnhandledCall
|
||||
{
|
||||
add => _events.AddHandler(EvUnhandledCall, value);
|
||||
remove => _events.RemoveHandler(EvUnhandledCall, value);
|
||||
}
|
||||
|
||||
public void OnUnhandledCall(UnhandledCallEventArgs e)
|
||||
{
|
||||
(_events[EvUnhandledCall] as EventHandler<UnhandledCallEventArgs>)?.Invoke(this, e);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using TelegramBotBase.Builder.Interfaces;
|
||||
using TelegramBotBase.Interfaces;
|
||||
|
||||
namespace TelegramBotBase.Experiments.ActionManager
|
||||
{
|
||||
public static class StaticExtensions
|
||||
{
|
||||
public static IStartFormSelectionStage ActionMessageLoop(this IMessageLoopSelectionStage loopSelection, ExternalActionManager managerInstance)
|
||||
{
|
||||
var cfb = new CustomFormBaseMessageLoop();
|
||||
|
||||
cfb.ExternalActionManager = managerInstance;
|
||||
|
||||
return loopSelection.CustomMessageLoop(cfb);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\TelegramBotBase\TelegramBotBase.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,27 +1,6 @@
|
||||
# Development Lab
|
||||
|
||||
Attention: This is a lab for **experimental features**. Here we can try out different ideas and scenarios if they will work and what can be improved.
|
||||
There is no guarantee that any of these ideas comes in the main project.
|
||||
|
||||
Please try everything on your own. Nothing can work, so everything can as well.
|
||||
|
||||
You will find all experiments within the ["Experiments"](Experiments) sub folder.
|
||||
|
||||
For feedback please join our Telegram group.
|
||||
|
||||
**Support group: [@tgbotbase](https://t.me/tgbotbase)**
|
||||
|
||||
## current experiments
|
||||
|
||||
- [ExternalActionManager](Experiments/ExternalActionManager/DemoBot) => Manager for unhandled actions from "outside"
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
# .NET Telegram Bot Framework - Context based addon
|
||||
|
||||
[](https://www.nuget.org/packages/TelegramBotBase/)
|
||||
[](https://www.nuget.org/packages/TelegramBotBase/)
|
||||
[](https://www.t.me/tgbotbase)
|
||||
|
||||
[](https://raw.githubusercontent.com/MajMcCloud/TelegramBotFramework/master/LICENCE.md)
|
||||
@@ -744,6 +723,7 @@ The current available languages for controls are:
|
||||
- English
|
||||
- German
|
||||
- Persian
|
||||
- Russian
|
||||
|
||||
You can add other languages easily by creating a subclass of the [TelegramBotBase/Localizations/Localization.cs](TelegramBotBase/Localizations/Localization.cs) class.
|
||||
|
||||
@@ -1060,6 +1040,8 @@ again at 1 (due to `PopAsync` or `PopToRootAsync` calls) it will replace the con
|
||||
you
|
||||
have given to the constructor at the beginning.*
|
||||
|
||||
---
|
||||
|
||||
## Extensions
|
||||
|
||||
### TelegramBotBase.Extensions.Images
|
||||
@@ -1069,7 +1051,28 @@ Extends the base package with some additional image methods like SendPhoto (usin
|
||||
[](https://www.nuget.org/packages/TelegramBotBase.Extensions.Images/)
|
||||
[](https://www.nuget.org/packages/TelegramBotBase.Extensions.Images)
|
||||
|
||||
[https://www.nuget.org/packages/TelegramBotBase.Extensions.Images/](https://www.nuget.org/packages/TelegramBotBase.Extensions.Images/)
|
||||
Source code: [TelegramBotBase.Extensions.Images/](/TelegramBotBase.Extensions.Images/)
|
||||
|
||||
Nuget package: [https://www.nuget.org/packages/TelegramBotBase.Extensions.Images/](https://www.nuget.org/packages/TelegramBotBase.Extensions.Images/)
|
||||
|
||||
---
|
||||
|
||||
### TelegramBotBase.Extensions.Images.IronSoftware
|
||||
|
||||
Extends the base package with some additional image methods like SendPhoto (using Bitmap)
|
||||
|
||||
Important: This extension uses the IronSoftware drawing library.
|
||||
|
||||
[](https://www.nuget.org/packages/TelegramBotBase.Extensions.Images.IronSoftware/)
|
||||
[](https://www.nuget.org/packages/TelegramBotBase.Extensions.Images.IronSoftware)
|
||||
|
||||
[https://www.nuget.org/packages/TelegramBotBase.Extensions.Images.IronSoftware/](https://www.nuget.org/packages/TelegramBotBase.Extensions.Images.IronSoftware/)
|
||||
|
||||
Source code: [TelegramBotBase.Extensions.Images.IronSoftware/](TelegramBotBase.Extensions.Images.IronSoftware/)
|
||||
|
||||
Nuget package: [https://www.nuget.org/packages/TelegramBotBase.Extensions.IronSoftware/](https://www.nuget.org/packages/TelegramBotBase.Extensions.IronSoftware/)
|
||||
|
||||
---
|
||||
|
||||
Project: [open source](TelegramBotBase.Extensions.Images/)
|
||||
|
||||
@@ -1093,7 +1096,26 @@ A session serializer for Microsoft SQL Server.
|
||||
[](https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Database.MSSQL/)
|
||||
[](https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Database.MSSQL)
|
||||
|
||||
[https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Database.MSSQL/](https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Database.MSSQL/)
|
||||
Source code: [TelegramBotBase.Extensions.Serializer.Database.MSSQL/](/TelegramBotBase.Extensions.Serializer.Database.MSSQL/)
|
||||
|
||||
Nuget package: [https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Database.MSSQL/](https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Database.MSSQL/)
|
||||
|
||||
---
|
||||
|
||||
### TelegramBotBase.Extensions.Serializer.Database.PostgreSql
|
||||
|
||||
A session serializer for PostgreSql Server.
|
||||
|
||||
[](https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Database.PostgreSql/)
|
||||
[](https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Database.PostgreSql)
|
||||
|
||||
Source code: [TelegramBotBase.Extensions.Serializer.Database.PostgreSql/](/TelegramBotBase.Extensions.Serializer.Database.PostgreSql/)
|
||||
|
||||
Nuget package: [https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Database.PostgreSql/](https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Database.PostgreSql/)
|
||||
|
||||
Credits: [@Kataane](https://github.com/Kataane)
|
||||
|
||||
---
|
||||
|
||||
Project: [open source](TelegramBotBase.Extensions.Serializer.Database.MSSQL/)
|
||||
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
using System;
|
||||
using TelegramBotBase.Builder;
|
||||
using TelegramBotBase.Builder.Interfaces;
|
||||
|
||||
namespace TelegramBotBase.Extensions.Serializer.Database.PostgreSql
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides extension methods for configuring the use of PostgreSQL Server Database for session serialization.
|
||||
/// </summary>
|
||||
public static class BotBaseBuilderExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Uses an PostgreSQL Server Database to save and restore sessions.
|
||||
/// </summary>
|
||||
/// <param name="builder">The session serialization stage builder.</param>
|
||||
/// <param name="connectionString">The connection string to the PostgreSQL database.</param>
|
||||
/// <param name="fallbackForm">The fallback form type.</param>
|
||||
/// <param name="tablePrefix">The prefix for database table names (default is "tgb_").</param>
|
||||
/// <returns>The language selection stage builder.</returns>
|
||||
public static ILanguageSelectionStage UsePostgreSqlDatabase(
|
||||
this ISessionSerializationStage builder,
|
||||
string connectionString, Type fallbackForm = null,
|
||||
string tablePrefix = "tgb_")
|
||||
{
|
||||
var serializer = new PostgreSqlSerializer(connectionString, tablePrefix, fallbackForm);
|
||||
|
||||
builder.UseSerialization(serializer);
|
||||
|
||||
return builder as BotBaseBuilder;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Uses an PostgreSQL Server Database to save and restore sessions.
|
||||
/// </summary>
|
||||
/// <param name="builder">The session serialization stage builder.</param>
|
||||
/// <param name="hostOrIp">The host or IP address of the PostgreSQL server.</param>
|
||||
/// <param name="port">The port number for the PostgreSQL server.</param>
|
||||
/// <param name="databaseName">The name of the PostgreSQL database.</param>
|
||||
/// <param name="userId">The user ID for connecting to the PostgreSQL server.</param>
|
||||
/// <param name="password">The password for connecting to the PostgreSQL server.</param>
|
||||
/// <param name="fallbackForm">The fallback form type.</param>
|
||||
/// <param name="tablePrefix">The prefix for database table names (default is "tgb_").</param>
|
||||
/// <returns>The language selection stage builder.</returns>
|
||||
public static ILanguageSelectionStage UsePostgreSqlDatabase(
|
||||
this ISessionSerializationStage builder,
|
||||
string hostOrIp, int port,
|
||||
string databaseName, string userId,
|
||||
string password, Type fallbackForm = null,
|
||||
string tablePrefix = "tgb_")
|
||||
{
|
||||
var connectionString = $"Host={hostOrIp};Port={port};Database={databaseName};Username={userId};Password={password}";
|
||||
|
||||
var serializer = new PostgreSqlSerializer(connectionString, tablePrefix, fallbackForm);
|
||||
|
||||
builder.UseSerialization(serializer);
|
||||
|
||||
return builder as BotBaseBuilder;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Uses an PostgreSQL Server Database with Windows Authentication to save and restore sessions.
|
||||
/// </summary>
|
||||
/// <param name="builder">The session serialization stage builder.</param>
|
||||
/// <param name="hostOrIp">The host or IP address of the PostgreSQL server.</param>
|
||||
/// <param name="port">The port number for the PostgreSQL server.</param>
|
||||
/// <param name="databaseName">The name of the PostgreSQL database.</param>
|
||||
/// <param name="integratedSecurity">A flag indicating whether to use Windows Authentication (true) or not (false).</param>
|
||||
/// <param name="fallbackForm">The fallback form type.</param>
|
||||
/// <param name="tablePrefix">The prefix for database table names (default is "tgb_").</param>
|
||||
/// <returns>The language selection stage builder.</returns>
|
||||
public static ILanguageSelectionStage UsePostgreSqlDatabase(
|
||||
this ISessionSerializationStage builder,
|
||||
string hostOrIp, int port,
|
||||
string databaseName, bool integratedSecurity = true,
|
||||
Type fallbackForm = null, string tablePrefix = "tgb_")
|
||||
{
|
||||
if (!integratedSecurity)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException();
|
||||
}
|
||||
|
||||
var connectionString = $"Host={hostOrIp};Port={port};Database={databaseName};Integrated Security=true;";
|
||||
|
||||
var serializer = new PostgreSqlSerializer(connectionString, tablePrefix, fallbackForm);
|
||||
|
||||
builder.UseSerialization(serializer);
|
||||
|
||||
return builder as BotBaseBuilder;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
using Npgsql;
|
||||
using System;
|
||||
using System.Data;
|
||||
using NpgsqlTypes;
|
||||
using TelegramBotBase.Args;
|
||||
using TelegramBotBase.Base;
|
||||
using TelegramBotBase.Form;
|
||||
using TelegramBotBase.Interfaces;
|
||||
|
||||
namespace TelegramBotBase.Extensions.Serializer.Database.PostgreSql
|
||||
{
|
||||
/// <summary>
|
||||
/// Represents a PostgreSQL implementation of the <see cref="IStateMachine"/> for saving and loading form states.
|
||||
/// </summary>
|
||||
public class PostgreSqlSerializer : IStateMachine
|
||||
{
|
||||
private readonly string insertIntoSessionSql;
|
||||
private readonly string insertIntoSessionsDataSql;
|
||||
private readonly string selectAllDevicesSessionsSql;
|
||||
private readonly string selectAllDevicesSessionsDataSql;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PostgreSqlSerializer"/> class.
|
||||
/// </summary>
|
||||
/// <param name="connectionString">The connection string to the PostgreSQL database.</param>
|
||||
/// <param name="tablePrefix">The prefix for database table names (default is "tgb_").</param>
|
||||
/// <param name="fallbackStateForm">The fallback state form type.</param>
|
||||
/// <exception cref="ArgumentNullException">Thrown when <paramref name="connectionString"/> is null.</exception>
|
||||
/// <exception cref="ArgumentException">Thrown when <paramref name="fallbackStateForm"/> is not a subclass of <see cref="FormBase"/>.</exception>
|
||||
public PostgreSqlSerializer(string connectionString, string tablePrefix = "tgb_", Type fallbackStateForm = null)
|
||||
{
|
||||
ConnectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString));
|
||||
|
||||
TablePrefix = tablePrefix;
|
||||
|
||||
FallbackStateForm = fallbackStateForm;
|
||||
|
||||
if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase)))
|
||||
{
|
||||
throw new ArgumentException($"{nameof(FallbackStateForm)} is not a subclass of {nameof(FormBase)}");
|
||||
}
|
||||
|
||||
insertIntoSessionSql = "INSERT INTO " + TablePrefix +
|
||||
"devices_sessions (deviceId, deviceTitle, \"FormUri\", \"QualifiedName\") VALUES (@deviceId, @deviceTitle, @FormUri, @QualifiedName)";
|
||||
insertIntoSessionsDataSql = "INSERT INTO " + TablePrefix + "devices_sessions_data (deviceId, key, value, type) VALUES (@deviceId, @key, @value, @type)";
|
||||
|
||||
selectAllDevicesSessionsSql = "SELECT * FROM " + TablePrefix + "devices_sessions";
|
||||
selectAllDevicesSessionsDataSql = "SELECT * FROM " + TablePrefix + "devices_sessions_data WHERE deviceId = @deviceId";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the connection string to the PostgreSQL database.
|
||||
/// </summary>
|
||||
public string ConnectionString { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the table name prefix for database tables.
|
||||
/// </summary>
|
||||
public string TablePrefix { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the fallback state form type.
|
||||
/// </summary>
|
||||
public Type FallbackStateForm { get; set; }
|
||||
|
||||
/// <inheritdoc/>
|
||||
/// <summary>
|
||||
/// Saves form states to the PostgreSQL database.
|
||||
/// </summary>
|
||||
/// <param name="e">The <see cref="SaveStatesEventArgs"/> containing the states to be saved.</param>
|
||||
public void SaveFormStates(SaveStatesEventArgs e)
|
||||
{
|
||||
var container = e.States;
|
||||
|
||||
//Cleanup old Session data
|
||||
Cleanup();
|
||||
|
||||
using (var connection = new NpgsqlConnection(ConnectionString))
|
||||
{
|
||||
connection.Open();
|
||||
|
||||
//Store session data in database
|
||||
foreach (var state in container.States)
|
||||
{
|
||||
using (var sessionCommand = connection.CreateCommand())
|
||||
{
|
||||
sessionCommand.CommandText = insertIntoSessionSql;
|
||||
|
||||
sessionCommand.Parameters.Add(new NpgsqlParameter("@deviceId", NpgsqlDbType.Bigint){Value = state.DeviceId });
|
||||
sessionCommand.Parameters.Add(new NpgsqlParameter("@deviceTitle", DbType.StringFixedLength){Value = state.ChatTitle ?? string.Empty});
|
||||
sessionCommand.Parameters.Add(new NpgsqlParameter("@FormUri", DbType.StringFixedLength) {Value = state.FormUri});
|
||||
sessionCommand.Parameters.Add(new NpgsqlParameter("@QualifiedName", DbType.StringFixedLength){Value = state.QualifiedName });
|
||||
|
||||
sessionCommand.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
using (var connection = new NpgsqlConnection(ConnectionString))
|
||||
{
|
||||
connection.Open();
|
||||
|
||||
foreach (var state in container.States)
|
||||
{
|
||||
SaveSessionsData(state, connection);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
/// <summary>
|
||||
/// Loads form states from the PostgreSQL database.
|
||||
/// </summary>
|
||||
/// <returns>A <see cref="StateContainer"/> containing the loaded form states.</returns>
|
||||
public StateContainer LoadFormStates()
|
||||
{
|
||||
var stateContainer = new StateContainer();
|
||||
|
||||
using (var connection = new NpgsqlConnection(ConnectionString))
|
||||
{
|
||||
connection.Open();
|
||||
|
||||
using (var sessionCommand = connection.CreateCommand())
|
||||
{
|
||||
sessionCommand.CommandText = selectAllDevicesSessionsSql;
|
||||
|
||||
var sessionTable = new DataTable();
|
||||
using (var dataAdapter = new NpgsqlDataAdapter(sessionCommand))
|
||||
{
|
||||
dataAdapter.Fill(sessionTable);
|
||||
|
||||
foreach (DataRow row in sessionTable.Rows)
|
||||
{
|
||||
var stateEntry = new StateEntry
|
||||
{
|
||||
DeviceId = (long)row["deviceId"],
|
||||
ChatTitle = row["deviceTitle"].ToString(),
|
||||
FormUri = row["FormUri"].ToString(),
|
||||
QualifiedName = row["QualifiedName"].ToString()
|
||||
};
|
||||
|
||||
stateContainer.States.Add(stateEntry);
|
||||
|
||||
if (stateEntry.DeviceId > 0)
|
||||
{
|
||||
stateContainer.ChatIds.Add(stateEntry.DeviceId);
|
||||
}
|
||||
else
|
||||
{
|
||||
stateContainer.GroupIds.Add(stateEntry.DeviceId);
|
||||
}
|
||||
|
||||
LoadDataTable(connection, row, stateEntry);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return stateContainer;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cleans up old session data in the PostgreSQL database.
|
||||
/// </summary>
|
||||
private void Cleanup()
|
||||
{
|
||||
using (var connection = new NpgsqlConnection(ConnectionString))
|
||||
{
|
||||
connection.Open();
|
||||
|
||||
using (var clearCommand = connection.CreateCommand())
|
||||
{
|
||||
clearCommand.CommandText = $"DELETE FROM {TablePrefix}devices_sessions_data";
|
||||
clearCommand.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
using (var clearCommand = connection.CreateCommand())
|
||||
{
|
||||
clearCommand.CommandText = $"DELETE FROM {TablePrefix}devices_sessions";
|
||||
clearCommand.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves session data to the PostgreSQL database.
|
||||
/// </summary>
|
||||
/// <param name="state">The state entry containing session data to be saved.</param>
|
||||
/// <param name="connection">The NpgsqlConnection used for the database interaction.</param>
|
||||
private void SaveSessionsData(StateEntry state, NpgsqlConnection connection)
|
||||
{
|
||||
foreach (var data in state.Values)
|
||||
{
|
||||
using (var dataCommand = connection.CreateCommand())
|
||||
{
|
||||
dataCommand.CommandText = insertIntoSessionsDataSql;
|
||||
|
||||
dataCommand.Parameters.Add(new NpgsqlParameter("@deviceId", NpgsqlDbType.Bigint) { Value = state.DeviceId });
|
||||
dataCommand.Parameters.Add(new NpgsqlParameter("@key", DbType.StringFixedLength) { Value = data.Key });
|
||||
|
||||
var type = data.Value.GetType();
|
||||
|
||||
if (type.IsPrimitive || type == typeof(string))
|
||||
{
|
||||
dataCommand.Parameters.Add(new NpgsqlParameter("@value", NpgsqlDbType.Text) { Value = data.Value });
|
||||
}
|
||||
else
|
||||
{
|
||||
var json = System.Text.Json.JsonSerializer.Serialize(data.Value);
|
||||
dataCommand.Parameters.Add(new NpgsqlParameter("@value", NpgsqlDbType.Text) { Value = json });
|
||||
}
|
||||
|
||||
dataCommand.Parameters.Add(new NpgsqlParameter("@type", DbType.StringFixedLength) { Value = type.AssemblyQualifiedName });
|
||||
|
||||
dataCommand.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads session data from the PostgreSQL database.
|
||||
/// </summary>
|
||||
/// <param name="connection">The NpgsqlConnection used for the database interaction.</param>
|
||||
/// <param name="row">The DataRow representing a session entry in the main sessions table.</param>
|
||||
/// <param name="stateEntry">The StateEntry object to which session data will be loaded.</param>
|
||||
private void LoadDataTable(NpgsqlConnection connection, DataRow row, StateEntry stateEntry)
|
||||
{
|
||||
using (var sessionCommand = connection.CreateCommand())
|
||||
{
|
||||
sessionCommand.CommandText = selectAllDevicesSessionsDataSql;
|
||||
sessionCommand.Parameters.Add(new NpgsqlParameter("@deviceId", row["deviceId"]));
|
||||
|
||||
var dataCommandTable = new DataTable();
|
||||
using (var npgSqlDataAdapter = new NpgsqlDataAdapter(sessionCommand))
|
||||
{
|
||||
npgSqlDataAdapter.Fill(dataCommandTable);
|
||||
|
||||
foreach (DataRow dataRow in dataCommandTable.Rows)
|
||||
{
|
||||
var key = dataRow["key"].ToString();
|
||||
var type = Type.GetType(dataRow["type"].ToString());
|
||||
|
||||
var value = System.Text.Json.JsonSerializer.Deserialize(dataRow["value"].ToString(), type);
|
||||
|
||||
stateEntry.Values.Add(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
# TelegramBotBase.Extensions.Serializer.Database.PostgreSQL
|
||||
|
||||
[](https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Database.PostgreSQL/)
|
||||
[](https://www.t.me/tgbotbase)
|
||||
|
||||
[](https://raw.githubusercontent.com/MajMcCloud/TelegramBotFramework/master/LICENCE.md)
|
||||
[](https://www.nuget.org/packages/TelegramBotBase.Extensions.Serializer.Database.PostgreSQL)
|
||||
|
||||
## How to use
|
||||
|
||||
```csharp
|
||||
using TelegramBotBase.Extensions.Serializer.Database.PostgreSQL;
|
||||
|
||||
|
||||
var bot = BotBaseBuilder
|
||||
.Create()
|
||||
.WithAPIKey(APIKey)
|
||||
.DefaultMessageLoop()
|
||||
.WithStartForm<Start>()
|
||||
.NoProxy()
|
||||
.OnlyStart()
|
||||
.UsePostgreSqlDatabase("localhost", "8181", "telegram_bot")
|
||||
.UseEnglish()
|
||||
.Build();
|
||||
|
||||
bot.Start();
|
||||
```
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>netstandard2.0;netcoreapp3.1;net6</TargetFrameworks>
|
||||
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
|
||||
<RepositoryUrl>https://github.com/MajMcCloud/TelegramBotFramework</RepositoryUrl>
|
||||
<PackageProjectUrl>https://github.com/MajMcCloud/TelegramBotFramework</PackageProjectUrl>
|
||||
<Copyright>MIT</Copyright>
|
||||
<IncludeSymbols>true</IncludeSymbols>
|
||||
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
|
||||
<AssemblyVersion>1.0.1</AssemblyVersion>
|
||||
<FileVersion>1.0.1</FileVersion>
|
||||
<Version>1.0.1</Version>
|
||||
<Description>
|
||||
A session serializer for PostgreSQL Server.
|
||||
</Description>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="TelegramBotBase" Version="6.0.0" />
|
||||
<PackageReference Include="Npgsql" Version="8.0.1" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,25 @@
|
||||
-- Enable uuid-ossp extension
|
||||
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
|
||||
|
||||
-- Create table tgb_devices_sessions
|
||||
CREATE TABLE tgb_devices_sessions (
|
||||
deviceId bigint NOT NULL,
|
||||
deviceTitle character varying(512) NOT NULL,
|
||||
"FormUri" character varying(512) NOT NULL,
|
||||
"QualifiedName" character varying(512) NOT NULL,
|
||||
CONSTRAINT PK_tgb_devices_sessions_1 PRIMARY KEY (deviceId)
|
||||
);
|
||||
|
||||
-- Create table tgb_devices_sessions_data
|
||||
CREATE TABLE tgb_devices_sessions_data (
|
||||
Id uuid DEFAULT uuid_generate_v4() NOT NULL,
|
||||
deviceId bigint NOT NULL,
|
||||
key character varying(512) NOT NULL,
|
||||
"value" text NOT NULL,
|
||||
"type" character varying(512) NOT NULL,
|
||||
CONSTRAINT PK_tgb_devices_session_data PRIMARY KEY (Id)
|
||||
);
|
||||
|
||||
-- Add default constraint for Id column in tgb_devices_sessions_data
|
||||
ALTER TABLE tgb_devices_sessions_data
|
||||
ALTER COLUMN Id SET DEFAULT uuid_generate_v4();
|
||||
@@ -8,8 +8,11 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="TelegramBotBase" Version="6.4.0-preview.1" />
|
||||
<PackageReference Include="TelegramBotBase.Extensions.Images" Version="1.1.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\TelegramBotBase\TelegramBotBase.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Telegram.Bot;
|
||||
@@ -10,6 +11,7 @@ using Telegram.Bot.Exceptions;
|
||||
using Telegram.Bot.Polling;
|
||||
using Telegram.Bot.Types;
|
||||
|
||||
|
||||
namespace TelegramBotBase.Base;
|
||||
|
||||
/// <summary>
|
||||
@@ -17,22 +19,18 @@ namespace TelegramBotBase.Base;
|
||||
/// </summary>
|
||||
public class MessageClient
|
||||
{
|
||||
private EventHandlerList Events { get; } = new();
|
||||
|
||||
private static readonly object EvOnMessageLoop = new();
|
||||
private static readonly object EvOnReceiveError = new();
|
||||
|
||||
private static object __evOnMessage = new();
|
||||
|
||||
private static object __evOnMessageEdit = new();
|
||||
|
||||
private static object __evCallbackQuery = new();
|
||||
|
||||
private CancellationTokenSource _cancellationTokenSource;
|
||||
protected CancellationTokenSource _cancellationTokenSource;
|
||||
|
||||
public string ApiKey { get; }
|
||||
|
||||
public ITelegramBotClient TelegramClient { get; set; }
|
||||
|
||||
private EventHandlerList Events { get; } = new();
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Indicates if all pending Telegram.Bot.Types.Updates should be thrown out before
|
||||
@@ -42,27 +40,17 @@ public class MessageClient
|
||||
/// </summary>
|
||||
public bool ThrowPendingUpdates { get; set; }
|
||||
|
||||
public bool UseThreadPool { get; set; } = false;
|
||||
|
||||
public int ThreadPool_WorkerThreads { get; set; } = 1;
|
||||
|
||||
public int ThreadPool_IOThreads { get; set; } = 1;
|
||||
|
||||
|
||||
public MessageClient(string apiKey)
|
||||
{
|
||||
ApiKey = apiKey;
|
||||
TelegramClient = new TelegramBotClient(apiKey);
|
||||
|
||||
Prepare();
|
||||
}
|
||||
|
||||
public MessageClient(string apiKey, HttpClient proxy)
|
||||
{
|
||||
ApiKey = apiKey;
|
||||
TelegramClient = new TelegramBotClient(apiKey, proxy);
|
||||
|
||||
Prepare();
|
||||
}
|
||||
|
||||
|
||||
@@ -80,8 +68,6 @@ public class MessageClient
|
||||
);
|
||||
|
||||
TelegramClient = new TelegramBotClient(apiKey, httpClient);
|
||||
|
||||
Prepare();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -101,8 +87,6 @@ public class MessageClient
|
||||
);
|
||||
|
||||
TelegramClient = new TelegramBotClient(apiKey, httpClient);
|
||||
|
||||
Prepare();
|
||||
}
|
||||
|
||||
|
||||
@@ -110,20 +94,10 @@ public class MessageClient
|
||||
{
|
||||
ApiKey = apiKey;
|
||||
TelegramClient = client;
|
||||
|
||||
Prepare();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public void Prepare()
|
||||
{
|
||||
TelegramClient.Timeout = new TimeSpan(0, 0, 30);
|
||||
}
|
||||
|
||||
|
||||
public void StartReceiving()
|
||||
public virtual void StartReceiving()
|
||||
{
|
||||
_cancellationTokenSource = new CancellationTokenSource();
|
||||
|
||||
@@ -131,66 +105,30 @@ public class MessageClient
|
||||
|
||||
receiverOptions.ThrowPendingUpdates = ThrowPendingUpdates;
|
||||
|
||||
if (UseThreadPool)
|
||||
{
|
||||
ThreadPool.SetMaxThreads(ThreadPool_WorkerThreads, ThreadPool_IOThreads);
|
||||
|
||||
TelegramClient.StartReceiving(HandleUpdateAsyncThreadPool, HandleErrorAsyncThreadPool, receiverOptions,
|
||||
_cancellationTokenSource.Token);
|
||||
}
|
||||
else
|
||||
{
|
||||
TelegramClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, receiverOptions,
|
||||
_cancellationTokenSource.Token);
|
||||
TelegramClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, receiverOptions, _cancellationTokenSource.Token);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void StopReceiving()
|
||||
public virtual void StopReceiving()
|
||||
{
|
||||
_cancellationTokenSource.Cancel();
|
||||
}
|
||||
|
||||
#region "Single Thread"
|
||||
|
||||
public async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
|
||||
private async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
|
||||
{
|
||||
await OnMessageLoop(new UpdateResult(update, null));
|
||||
}
|
||||
|
||||
public async Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception,
|
||||
|
||||
private async Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await OnReceiveError(new ErrorResult(exception));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region "Thread Pool"
|
||||
|
||||
public Task HandleUpdateAsyncThreadPool(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
|
||||
{
|
||||
ThreadPool.QueueUserWorkItem(async a =>
|
||||
{
|
||||
await OnMessageLoop(new UpdateResult(update, null));
|
||||
});
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task HandleErrorAsyncThreadPool(ITelegramBotClient botClient, Exception exception,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ThreadPool.QueueUserWorkItem(async a =>
|
||||
{
|
||||
await OnReceiveError(new ErrorResult(exception));
|
||||
});
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region "BotCommands"
|
||||
/// <summary>
|
||||
/// This will return the current list of bot commands.
|
||||
/// </summary>
|
||||
@@ -222,6 +160,8 @@ public class MessageClient
|
||||
await TelegramClient.DeleteMyCommandsAsync(scope, languageCode);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
#region "Events"
|
||||
|
||||
@@ -231,6 +171,7 @@ public class MessageClient
|
||||
remove => Events.RemoveHandler(EvOnMessageLoop, value);
|
||||
}
|
||||
|
||||
|
||||
public async Task OnMessageLoop(UpdateResult update)
|
||||
{
|
||||
var eventHandlers = (Events[EvOnMessageLoop] as Async.AsyncEventHandler<UpdateResult>)?.Invoke(this, update);
|
||||
@@ -248,6 +189,7 @@ public class MessageClient
|
||||
remove => Events.RemoveHandler(EvOnReceiveError, value);
|
||||
}
|
||||
|
||||
|
||||
public async Task OnReceiveError(ErrorResult update)
|
||||
{
|
||||
var eventHandlers = (Events[EvOnReceiveError] as Async.AsyncEventHandler<ErrorResult>)?.Invoke(this, update);
|
||||
@@ -271,4 +213,5 @@ public class MessageClient
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Telegram.Bot;
|
||||
using Telegram.Bot.Exceptions;
|
||||
using Telegram.Bot.Polling;
|
||||
using Telegram.Bot.Types;
|
||||
using TelegramBotBase.Interfaces;
|
||||
|
||||
namespace TelegramBotBase.Base;
|
||||
|
||||
/// <summary>
|
||||
/// Base class for message handling
|
||||
/// </summary>
|
||||
public class ThreadPoolMessageClient : MessageClient
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Indicates if all pending Telegram.Bot.Types.Updates should be thrown out before
|
||||
// start polling. If set to true Telegram.Bot.Polling.ReceiverOptions.AllowedUpdates
|
||||
// should be set to not null, otherwise Telegram.Bot.Polling.ReceiverOptions.AllowedUpdates
|
||||
// will effectively be set to receive all Telegram.Bot.Types.Updates.
|
||||
/// </summary>
|
||||
|
||||
public int ThreadPool_WorkerThreads { get; set; } = 1;
|
||||
|
||||
public int ThreadPool_IOThreads { get; set; } = 1;
|
||||
|
||||
|
||||
public ThreadPoolMessageClient(string apiKey) : base(apiKey)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public ThreadPoolMessageClient(string apiKey, HttpClient proxy) : base(apiKey, proxy)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
|
||||
public ThreadPoolMessageClient(string apiKey, Uri proxyUrl, NetworkCredential credential = null) : base(apiKey, proxyUrl, credential)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes the client with a proxy
|
||||
/// </summary>
|
||||
/// <param name="apiKey"></param>
|
||||
/// <param name="proxyHost">i.e. 127.0.0.1</param>
|
||||
/// <param name="proxyPort">i.e. 10000</param>
|
||||
public ThreadPoolMessageClient(string apiKey, string proxyHost, int proxyPort) : base(apiKey, proxyHost, proxyPort)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
|
||||
public ThreadPoolMessageClient(string apiKey, TelegramBotClient client) : base(apiKey, client)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
public override void StartReceiving()
|
||||
{
|
||||
_cancellationTokenSource = new CancellationTokenSource();
|
||||
|
||||
var receiverOptions = new ReceiverOptions();
|
||||
|
||||
receiverOptions.ThrowPendingUpdates = ThrowPendingUpdates;
|
||||
|
||||
ThreadPool.SetMaxThreads(ThreadPool_WorkerThreads, ThreadPool_IOThreads);
|
||||
|
||||
TelegramClient.StartReceiving(HandleUpdateAsyncThreadPool, HandleErrorAsyncThreadPool, receiverOptions, _cancellationTokenSource.Token);
|
||||
}
|
||||
|
||||
public override void StopReceiving()
|
||||
{
|
||||
_cancellationTokenSource.Cancel();
|
||||
}
|
||||
|
||||
|
||||
public Task HandleUpdateAsyncThreadPool(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
|
||||
{
|
||||
ThreadPool.QueueUserWorkItem(async a =>
|
||||
{
|
||||
await OnMessageLoop(new UpdateResult(update, null));
|
||||
});
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task HandleErrorAsyncThreadPool(ITelegramBotClient botClient, Exception exception,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ThreadPool.QueueUserWorkItem(async a =>
|
||||
{
|
||||
await OnReceiveError(new ErrorResult(exception));
|
||||
});
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -211,7 +211,6 @@ public sealed class BotBase
|
||||
try
|
||||
{
|
||||
var ds = Sessions.GetSession(deviceId);
|
||||
|
||||
e.Device = ds;
|
||||
|
||||
await MessageLoopFactory.MessageLoop(this, ds, new UpdateResult(e.UpdateData, ds), e);
|
||||
|
||||
@@ -32,6 +32,7 @@ public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage,
|
||||
|
||||
private BotBaseBuilder()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -213,14 +214,14 @@ public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage,
|
||||
|
||||
#region "Step 4 (Network Settings)"
|
||||
|
||||
public IBotCommandsStage WithProxy(string proxyAddress, bool throwPendingUpdates = false)
|
||||
public IBotCommandsStage WithProxy(string proxyAddress, bool throwPendingUpdates = false, int timeoutInSeconds = 60)
|
||||
{
|
||||
var url = new Uri(proxyAddress);
|
||||
_client = new MessageClient(_apiKey, url)
|
||||
{
|
||||
TelegramClient =
|
||||
{
|
||||
Timeout = new TimeSpan(0, 1, 0)
|
||||
Timeout = TimeSpan.FromSeconds(timeoutInSeconds)
|
||||
},
|
||||
};
|
||||
_client.ThrowPendingUpdates = throwPendingUpdates;
|
||||
@@ -228,13 +229,13 @@ public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage,
|
||||
}
|
||||
|
||||
|
||||
public IBotCommandsStage NoProxy(bool throwPendingUpdates = false)
|
||||
public IBotCommandsStage NoProxy(bool throwPendingUpdates = false, int timeoutInSeconds = 60)
|
||||
{
|
||||
_client = new MessageClient(_apiKey)
|
||||
{
|
||||
TelegramClient =
|
||||
{
|
||||
Timeout = new TimeSpan(0, 1, 0)
|
||||
Timeout = TimeSpan.FromSeconds(timeoutInSeconds)// new TimeSpan(0, 1, 0)
|
||||
}
|
||||
};
|
||||
_client.ThrowPendingUpdates = throwPendingUpdates;
|
||||
@@ -242,13 +243,13 @@ public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage,
|
||||
}
|
||||
|
||||
|
||||
public IBotCommandsStage WithBotClient(TelegramBotClient tgclient, bool throwPendingUpdates = false)
|
||||
public IBotCommandsStage WithBotClient(TelegramBotClient tgclient, bool throwPendingUpdates = false, int timeoutInSeconds = 60)
|
||||
{
|
||||
_client = new MessageClient(_apiKey, tgclient)
|
||||
{
|
||||
TelegramClient =
|
||||
{
|
||||
Timeout = new TimeSpan(0, 1, 0)
|
||||
Timeout = TimeSpan.FromSeconds(timeoutInSeconds)// new TimeSpan(0, 1, 0)
|
||||
}
|
||||
};
|
||||
_client.ThrowPendingUpdates = throwPendingUpdates;
|
||||
@@ -256,26 +257,26 @@ public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage,
|
||||
}
|
||||
|
||||
|
||||
public IBotCommandsStage WithHostAndPort(string proxyHost, int proxyPort, bool throwPendingUpdates = false)
|
||||
public IBotCommandsStage WithHostAndPort(string proxyHost, int proxyPort, bool throwPendingUpdates = false, int timeoutInSeconds = 60)
|
||||
{
|
||||
_client = new MessageClient(_apiKey, proxyHost, proxyPort)
|
||||
{
|
||||
TelegramClient =
|
||||
{
|
||||
Timeout = new TimeSpan(0, 1, 0)
|
||||
Timeout = TimeSpan.FromSeconds(timeoutInSeconds)// new TimeSpan(0, 1, 0)
|
||||
}
|
||||
};
|
||||
_client.ThrowPendingUpdates = throwPendingUpdates;
|
||||
return this;
|
||||
}
|
||||
|
||||
public IBotCommandsStage WithHttpClient(HttpClient tgclient, bool throwPendingUpdates = false)
|
||||
public IBotCommandsStage WithHttpClient(HttpClient tgclient, bool throwPendingUpdates = false, int timeoutInSeconds = 60)
|
||||
{
|
||||
_client = new MessageClient(_apiKey, tgclient)
|
||||
{
|
||||
TelegramClient =
|
||||
{
|
||||
Timeout = new TimeSpan(0, 1, 0)
|
||||
Timeout = TimeSpan.FromSeconds(timeoutInSeconds)// new TimeSpan(0, 1, 0)
|
||||
}
|
||||
};
|
||||
_client.ThrowPendingUpdates = throwPendingUpdates;
|
||||
@@ -397,30 +398,42 @@ public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage,
|
||||
|
||||
#region "Step 7 (Language)"
|
||||
|
||||
public IThreadingStage DefaultLanguage()
|
||||
/// <inheritdoc cref="ILanguageSelectionStage.DefaultLanguage"/>
|
||||
public IBuildingStage DefaultLanguage()
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
public IThreadingStage UseEnglish()
|
||||
/// <inheritdoc cref="ILanguageSelectionStage.UseEnglish"/>
|
||||
public IBuildingStage UseEnglish()
|
||||
{
|
||||
Default.Language = new English();
|
||||
return this;
|
||||
}
|
||||
|
||||
public IThreadingStage UseGerman()
|
||||
/// <inheritdoc cref="ILanguageSelectionStage.UseGerman"/>
|
||||
public IBuildingStage UseGerman()
|
||||
{
|
||||
Default.Language = new German();
|
||||
return this;
|
||||
}
|
||||
|
||||
public IThreadingStage UsePersian()
|
||||
/// <inheritdoc cref="ILanguageSelectionStage.UsePersian"/>
|
||||
public IBuildingStage UsePersian()
|
||||
{
|
||||
Default.Language = new Persian();
|
||||
return this;
|
||||
}
|
||||
|
||||
public IThreadingStage Custom(Localization language)
|
||||
/// <inheritdoc cref="ILanguageSelectionStage.UseRussian"/>
|
||||
public IBuildingStage UseRussian()
|
||||
{
|
||||
Default.Language = new Russian();
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="ILanguageSelectionStage.Custom"/>
|
||||
public IBuildingStage Custom(Localization language)
|
||||
{
|
||||
Default.Language = language;
|
||||
return this;
|
||||
@@ -429,26 +442,27 @@ public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage,
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
#region "Step 8 (Threading)"
|
||||
|
||||
public IBuildingStage UseSingleThread()
|
||||
{
|
||||
_client.UseThreadPool = false;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public IBuildingStage UseThreadPool(int workerThreads = 2, int ioThreads = 1)
|
||||
{
|
||||
_client.UseThreadPool = true;
|
||||
_client.ThreadPool_WorkerThreads = workerThreads;
|
||||
_client.ThreadPool_IOThreads = ioThreads;
|
||||
var c = new ThreadPoolMessageClient(_apiKey, (TelegramBotClient)_client.TelegramClient);
|
||||
|
||||
c.ThreadPool_WorkerThreads = workerThreads;
|
||||
c.ThreadPool_IOThreads = ioThreads;
|
||||
c.ThrowPendingUpdates = _client.ThrowPendingUpdates;
|
||||
|
||||
_client = c;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
|
||||
#endregion
|
||||
|
||||
}
|
||||
|
||||
@@ -2,35 +2,44 @@
|
||||
|
||||
namespace TelegramBotBase.Builder.Interfaces;
|
||||
|
||||
/// <summary>
|
||||
/// Represents the language selection stage in the localization process.
|
||||
/// </summary>
|
||||
public interface ILanguageSelectionStage
|
||||
{
|
||||
/// <summary>
|
||||
/// Selects the default language for control usage. (English)
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
IThreadingStage DefaultLanguage();
|
||||
/// <returns>The next stage in the building process.</returns>
|
||||
IBuildingStage DefaultLanguage();
|
||||
|
||||
/// <summary>
|
||||
/// Selects english as the default language for control labels.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
IThreadingStage UseEnglish();
|
||||
/// <returns>The next stage in the building process.</returns>
|
||||
IBuildingStage UseEnglish();
|
||||
|
||||
/// <summary>
|
||||
/// Selects german as the default language for control labels.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
IThreadingStage UseGerman();
|
||||
/// <returns>The next stage in the building process.</returns>
|
||||
IBuildingStage UseGerman();
|
||||
|
||||
/// <summary>
|
||||
/// Selects persian as the default language for control labels.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
IThreadingStage UsePersian();
|
||||
/// <returns>The next stage in the building process.</returns>
|
||||
IBuildingStage UsePersian();
|
||||
|
||||
/// <summary>
|
||||
/// Selects russian as the default language for control labels.
|
||||
/// </summary>
|
||||
/// <returns>The next stage in the building process.</returns>
|
||||
IBuildingStage UseRussian();
|
||||
|
||||
/// <summary>
|
||||
/// Selects a custom language as the default language for control labels.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
IThreadingStage Custom(Localization language);
|
||||
/// <returns>The next stage in the building process.</returns>
|
||||
IBuildingStage Custom(Localization language);
|
||||
}
|
||||
@@ -11,14 +11,14 @@ public interface INetworkingSelectionStage
|
||||
/// <param name="proxyAddress"></param>
|
||||
/// <param name="throwPendingUpdates">Indicates if all pending Telegram.Bot.Types.Updates should be thrown out before start polling.</param>
|
||||
/// <returns></returns>
|
||||
IBotCommandsStage WithProxy(string proxyAddress, bool throwPendingUpdates = false);
|
||||
IBotCommandsStage WithProxy(string proxyAddress, bool throwPendingUpdates = false, int timeoutInSeconds = 60);
|
||||
|
||||
/// <summary>
|
||||
/// Do not choose a proxy as network configuration.
|
||||
/// </summary>
|
||||
/// <param name="throwPendingUpdates">Indicates if all pending Telegram.Bot.Types.Updates should be thrown out before start polling.</param>
|
||||
/// <returns></returns>
|
||||
IBotCommandsStage NoProxy(bool throwPendingUpdates = false);
|
||||
IBotCommandsStage NoProxy(bool throwPendingUpdates = false, int timeoutInSeconds = 60);
|
||||
|
||||
|
||||
/// <summary>
|
||||
@@ -27,7 +27,7 @@ public interface INetworkingSelectionStage
|
||||
/// <param name="client"></param>
|
||||
/// <param name="throwPendingUpdates">Indicates if all pending Telegram.Bot.Types.Updates should be thrown out before start polling.</param>
|
||||
/// <returns></returns>
|
||||
IBotCommandsStage WithBotClient(TelegramBotClient client, bool throwPendingUpdates = false);
|
||||
IBotCommandsStage WithBotClient(TelegramBotClient client, bool throwPendingUpdates = false, int timeoutInSeconds = 60);
|
||||
|
||||
|
||||
/// <summary>
|
||||
@@ -37,7 +37,7 @@ public interface INetworkingSelectionStage
|
||||
/// <param name="Port"></param>
|
||||
/// <param name="throwPendingUpdates">Indicates if all pending Telegram.Bot.Types.Updates should be thrown out before start polling.</param>
|
||||
/// <returns></returns>
|
||||
IBotCommandsStage WithHostAndPort(string proxyHost, int Port, bool throwPendingUpdates = false);
|
||||
IBotCommandsStage WithHostAndPort(string proxyHost, int Port, bool throwPendingUpdates = false, int timeoutInSeconds = 60);
|
||||
|
||||
/// <summary>
|
||||
/// Uses a custom http client.
|
||||
@@ -45,5 +45,5 @@ public interface INetworkingSelectionStage
|
||||
/// <param name="client"></param>
|
||||
/// <param name="throwPendingUpdates">Indicates if all pending Telegram.Bot.Types.Updates should be thrown out before start polling.</param>
|
||||
/// <returns></returns>
|
||||
IBotCommandsStage WithHttpClient(HttpClient client, bool throwPendingUpdates = false);
|
||||
IBotCommandsStage WithHttpClient(HttpClient client, bool throwPendingUpdates = false, int timeoutInSeconds = 60);
|
||||
}
|
||||
@@ -16,9 +16,4 @@ public static class Telegram
|
||||
public const int MaxReplyKeyboardCols = 12;
|
||||
|
||||
public const int MessageDeletionsPerSecond = 30;
|
||||
|
||||
/// <summary>
|
||||
/// The maximum length of callback data. Will raise an exception of it exceeds it.
|
||||
/// </summary>
|
||||
public const int MaxCallBackDataBytes = 64;
|
||||
}
|
||||
@@ -426,8 +426,6 @@ public class ButtonGrid : ControlBase
|
||||
return;
|
||||
}
|
||||
|
||||
await result.ConfirmAction(ConfirmationText ?? "");
|
||||
|
||||
ButtonRow match = null;
|
||||
var index = -1;
|
||||
|
||||
@@ -462,6 +460,8 @@ public class ButtonGrid : ControlBase
|
||||
check:
|
||||
if (match != null)
|
||||
{
|
||||
await result.ConfirmAction(ConfirmationText ?? "");
|
||||
|
||||
await OnButtonClicked(new ButtonClickedEventArgs(match.GetButtonMatch(result.RawData, false), index,
|
||||
match));
|
||||
|
||||
|
||||
@@ -29,8 +29,6 @@ public class TaggedButtonGrid : MultiView
|
||||
|
||||
public string BackLabel = Default.Language["ButtonGrid_Back"];
|
||||
|
||||
public string CheckAllLabel = Default.Language["ButtonGrid_CheckAll"];
|
||||
|
||||
public string NextPageLabel = Default.Language["ButtonGrid_NextPage"];
|
||||
|
||||
public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"];
|
||||
@@ -39,11 +37,17 @@ public class TaggedButtonGrid : MultiView
|
||||
|
||||
public string SearchLabel = Default.Language["ButtonGrid_SearchFeature"];
|
||||
|
||||
public string UncheckAllLabel = Default.Language["ButtonGrid_UncheckAll"];
|
||||
public string TotalTagsLabel = Default.Language["TaggedButtonGrid_TotalTags"];
|
||||
|
||||
public string CheckedTagsLabel = Default.Language["TaggedButtonGrid_CheckedTags"];
|
||||
|
||||
public string CheckAllLabel = Default.Language["TaggedButtonGrid_CheckAll"];
|
||||
|
||||
public string UncheckAllLabel = Default.Language["TaggedButtonGrid_UncheckAll"];
|
||||
|
||||
public string SearchIcon = Default.Language["ButtonGrid_SearchIcon"];
|
||||
|
||||
public string TagIcon = Default.Language["ButtonGrid_TagIcon"];
|
||||
public string TagIcon = Default.Language["TaggedButtonGrid_TagIcon"];
|
||||
|
||||
public TaggedButtonGrid()
|
||||
{
|
||||
@@ -379,14 +383,6 @@ public class TaggedButtonGrid : MultiView
|
||||
index = br.Item2;
|
||||
}
|
||||
|
||||
|
||||
//var button = HeadLayoutButtonRow?. .FirstOrDefault(a => a.Text.Trim() == result.MessageText)
|
||||
// ?? SubHeadLayoutButtonRow?.FirstOrDefault(a => a.Text.Trim() == result.MessageText);
|
||||
|
||||
// bf.ToList().FirstOrDefault(a => a.Text.Trim() == result.MessageText)
|
||||
|
||||
//var index = bf.FindRowByButton(button);
|
||||
|
||||
check:
|
||||
|
||||
|
||||
@@ -490,10 +486,16 @@ public class TaggedButtonGrid : MultiView
|
||||
if (result.MessageText == CheckAllLabel)
|
||||
{
|
||||
CheckAllTags();
|
||||
Updated();
|
||||
result.Handled = true;
|
||||
return;
|
||||
}
|
||||
else if (result.MessageText == UncheckAllLabel)
|
||||
{
|
||||
UncheckAllTags();
|
||||
Updated();
|
||||
result.Handled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
var i = result.MessageText.LastIndexOf(" ");
|
||||
@@ -569,15 +571,6 @@ public class TaggedButtonGrid : MultiView
|
||||
index = br.Item2;
|
||||
}
|
||||
|
||||
|
||||
//var bf = DataSource.ButtonForm;
|
||||
|
||||
//var button = HeadLayoutButtonRow?.FirstOrDefault(a => a.Value == result.RawData)
|
||||
// ?? SubHeadLayoutButtonRow?.FirstOrDefault(a => a.Value == result.RawData)
|
||||
// ?? bf.ToList().FirstOrDefault(a => a.Value == result.RawData);
|
||||
|
||||
//var index = bf.FindRowByButton(button);
|
||||
|
||||
check:
|
||||
if (match != null)
|
||||
{
|
||||
@@ -619,23 +612,48 @@ public class TaggedButtonGrid : MultiView
|
||||
|
||||
break;
|
||||
|
||||
|
||||
default:
|
||||
|
||||
if (SelectedViewIndex != 1)
|
||||
return;
|
||||
|
||||
|
||||
switch (result.RawData)
|
||||
{
|
||||
case "$back$":
|
||||
|
||||
SelectedViewIndex = 0;
|
||||
Updated();
|
||||
|
||||
break;
|
||||
return;
|
||||
|
||||
case "$checkall$":
|
||||
|
||||
CheckAllTags();
|
||||
|
||||
break;
|
||||
return;
|
||||
|
||||
case "$uncheckall$":
|
||||
|
||||
UncheckAllTags();
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
if (SelectedTags.Contains(result.RawData))
|
||||
{
|
||||
SelectedTags.Remove(result.RawData);
|
||||
}
|
||||
else
|
||||
{
|
||||
SelectedTags.Add(result.RawData);
|
||||
}
|
||||
|
||||
Updated();
|
||||
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -723,8 +741,10 @@ public class TaggedButtonGrid : MultiView
|
||||
|
||||
if (EnableCheckAllTools)
|
||||
{
|
||||
TagsSubHeadLayoutButtonRow = new ButtonRow(new ButtonBase(CheckAllLabel, "$checkall$"),
|
||||
new ButtonBase(UncheckAllLabel, "$uncheckall$"));
|
||||
TagsSubHeadLayoutButtonRow = new ButtonRow(new ButtonBase(string.Format(TotalTagsLabel, Tags.Count), "$total$"),
|
||||
new ButtonBase(CheckAllLabel, "$checkall$"),
|
||||
new ButtonBase(UncheckAllLabel, "$uncheckall$"),
|
||||
new ButtonBase(string.Format(CheckedTagsLabel, SelectedTags.Count), "checked$"));
|
||||
bf.AddButtonRow(TagsSubHeadLayoutButtonRow);
|
||||
}
|
||||
|
||||
@@ -756,10 +776,6 @@ public class TaggedButtonGrid : MultiView
|
||||
return;
|
||||
}
|
||||
|
||||
//if (bf.Count == 0)
|
||||
// return;
|
||||
|
||||
|
||||
var rkm = (ReplyKeyboardMarkup)bf;
|
||||
rkm.ResizeKeyboard = ResizeKeyboard;
|
||||
rkm.OneTimeKeyboard = OneTimeKeyboard;
|
||||
@@ -881,21 +897,20 @@ public class TaggedButtonGrid : MultiView
|
||||
{
|
||||
Message m = null;
|
||||
|
||||
var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage,
|
||||
EnableSearch ? SearchQuery : null);
|
||||
|
||||
//if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
|
||||
//{
|
||||
// form = form.FilterDuplicate(this.SearchQuery, true);
|
||||
//}
|
||||
//else
|
||||
//{
|
||||
// form = form.Duplicate();
|
||||
//}
|
||||
ButtonForm form = null;
|
||||
|
||||
if (Tags != null && SelectedTags != null)
|
||||
{
|
||||
form = DataSource.PickAllItems(EnableSearch ? SearchQuery : null); //CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage,
|
||||
|
||||
form = form.TagDuplicate(SelectedTags);
|
||||
|
||||
form = new ButtonForm(form.ToRowList().Skip(CurrentPageIndex * ItemRowsPerPage).Take(ItemRowsPerPage));
|
||||
}
|
||||
else
|
||||
{
|
||||
form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage,
|
||||
EnableSearch ? SearchQuery : null);
|
||||
}
|
||||
|
||||
if (EnablePaging)
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
using System;
|
||||
using Telegram.Bot.Exceptions;
|
||||
|
||||
namespace TelegramBotBase.Exceptions;
|
||||
|
||||
public sealed class CallbackDataTooLongException : Exception
|
||||
{
|
||||
//public override string Message =>
|
||||
// $"You have exceeded the maximum {Constants.Telegram.MaxCallBackDataBytes} bytes.";
|
||||
|
||||
static ApiRequestException _innerException = new Telegram.Bot.Exceptions.ApiRequestException("Bad Request: BUTTON_DATA_INVALID", 400);
|
||||
|
||||
static String _message = $"You have exceeded the maximum {Constants.Telegram.MaxCallBackDataBytes} bytes of callback data.\r\nThis is a pre-sending message from the TelegramBotBase framework.\r\nread more: https://core.telegram.org/bots/api#inlinekeyboardbutton";
|
||||
|
||||
public CallbackDataTooLongException() : base(_message, _innerException)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -23,6 +23,11 @@ public class ButtonForm
|
||||
DependencyControl = control;
|
||||
}
|
||||
|
||||
public ButtonForm(IEnumerable<ButtonRow> rows)
|
||||
{
|
||||
_buttons = rows.ToList();
|
||||
}
|
||||
|
||||
|
||||
public IReplyMarkup Markup { get; set; }
|
||||
|
||||
@@ -149,6 +154,11 @@ public class ButtonForm
|
||||
.Aggregate((a, b) => a.Union(b).ToList());
|
||||
}
|
||||
|
||||
public List<ButtonRow> ToRowList()
|
||||
{
|
||||
return _buttons;
|
||||
}
|
||||
|
||||
public InlineKeyboardButton[][] ToInlineButtonArray()
|
||||
{
|
||||
var ikb = _buttons.Select(a => a.ToArray().Select(b => b.ToInlineButton(this)).ToArray()).ToArray();
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
using Newtonsoft.Json;
|
||||
using System.Text;
|
||||
using TelegramBotBase.Exceptions;
|
||||
|
||||
namespace TelegramBotBase.Form;
|
||||
|
||||
@@ -32,7 +30,7 @@ public class CallbackData
|
||||
/// Serializes data to json string
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public string Serialize(bool throwExceptionOnOverflow = false)
|
||||
public string Serialize()
|
||||
{
|
||||
var s = "";
|
||||
try
|
||||
@@ -43,16 +41,6 @@ public class CallbackData
|
||||
{
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
|
||||
//Data is over 64 bytes
|
||||
if(throwExceptionOnOverflow && Encoding.UTF8.GetByteCount(s) > Constants.Telegram.MaxCallBackDataBytes)
|
||||
{
|
||||
throw new CallbackDataTooLongException();
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -77,5 +65,5 @@ public class CallbackData
|
||||
return null;
|
||||
}
|
||||
|
||||
public static implicit operator string(CallbackData callbackData) => callbackData.Serialize(true);
|
||||
public static implicit operator string(CallbackData callbackData) => callbackData.Serialize();
|
||||
}
|
||||
|
||||
@@ -12,8 +12,10 @@ public sealed class English : Localization
|
||||
Values["ButtonGrid_CurrentPage"] = "Page {0} of {1}";
|
||||
Values["ButtonGrid_SearchFeature"] = "💡 Send a message to filter the list. Click the 🔍 to reset the filter.";
|
||||
Values["ButtonGrid_Back"] = "Back";
|
||||
Values["ButtonGrid_CheckAll"] = "Check all";
|
||||
Values["ButtonGrid_UncheckAll"] = "Uncheck all";
|
||||
Values["TaggedButtonGrid_TotalTags"] = "Total: {0}";
|
||||
Values["TaggedButtonGrid_CheckedTags"] = "Checked: {0}";
|
||||
Values["TaggedButtonGrid_CheckAll"] = "Check all";
|
||||
Values["TaggedButtonGrid_UncheckAll"] = "Uncheck all";
|
||||
Values["CalendarPicker_Title"] = "Pick date";
|
||||
Values["CalendarPicker_PreviousPage"] = "◀️";
|
||||
Values["CalendarPicker_NextPage"] = "▶️";
|
||||
@@ -31,6 +33,6 @@ public sealed class English : Localization
|
||||
Values["PromptDialog_Back"] = "Back";
|
||||
Values["ToggleButton_Changed"] = "Setting changed";
|
||||
Values["ButtonGrid_SearchIcon"] = "🔍";
|
||||
Values["ButtonGrid_TagIcon"] = "📁";
|
||||
Values["TaggedButtonGrid_TagIcon"] = "📁";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,11 +10,12 @@ public sealed class German : Localization
|
||||
Values["ButtonGrid_PreviousPage"] = "◀️";
|
||||
Values["ButtonGrid_NextPage"] = "▶️";
|
||||
Values["ButtonGrid_CurrentPage"] = "Seite {0} von {1}";
|
||||
Values["ButtonGrid_SearchFeature"] =
|
||||
"💡 Sende eine Nachricht um die Liste zu filtern. Klicke die 🔍 um den Filter zurückzusetzen.";
|
||||
Values["ButtonGrid_SearchFeature"] = "💡 Sende eine Nachricht um die Liste zu filtern. Klicke die 🔍 um den Filter zurückzusetzen.";
|
||||
Values["ButtonGrid_Back"] = "Zurück";
|
||||
Values["ButtonGrid_CheckAll"] = "Alle auswählen";
|
||||
Values["ButtonGrid_UncheckAll"] = "Keine auswählen";
|
||||
Values["TaggedButtonGrid_TotalTags"] = "Gesamt: {0}";
|
||||
Values["TaggedButtonGrid_CheckedTags"] = "Ausgewählt: {0}";
|
||||
Values["TaggedButtonGrid_CheckAll"] = "Alle auswählen";
|
||||
Values["TaggedButtonGrid_UncheckAll"] = "Keine auswählen";
|
||||
Values["CalendarPicker_Title"] = "Datum auswählen";
|
||||
Values["CalendarPicker_PreviousPage"] = "◀️";
|
||||
Values["CalendarPicker_NextPage"] = "▶️";
|
||||
@@ -31,5 +32,7 @@ public sealed class German : Localization
|
||||
Values["MultiToggleButton_Changed"] = "Ausgewählt";
|
||||
Values["PromptDialog_Back"] = "Zurück";
|
||||
Values["ToggleButton_Changed"] = "Einstellung geändert";
|
||||
Values["ButtonGrid_SearchIcon"] = "🔍";
|
||||
Values["TaggedButtonGrid_TagIcon"] = "📁";
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
namespace TelegramBotBase.Localizations
|
||||
namespace TelegramBotBase.Localizations;
|
||||
|
||||
public sealed class Persian : Localization
|
||||
{
|
||||
public sealed class Persian : Localization
|
||||
{
|
||||
public Persian()
|
||||
{
|
||||
Values["Language"] = "فارسی";
|
||||
@@ -12,8 +12,10 @@
|
||||
Values["ButtonGrid_CurrentPage"] = "صفحه ی {0} از {1}";
|
||||
Values["ButtonGrid_SearchFeature"] = "💡 برای فیلتر کردن لیست پیام ارسال کنید. برای بازنشانی فیلتر روی 🔍 کلیک کنید.";
|
||||
Values["ButtonGrid_Back"] = "بازگشت";
|
||||
Values["ButtonGrid_CheckAll"] = "بررسی کردن همه";
|
||||
Values["ButtonGrid_UncheckAll"] = "بررسی نکردن همه";
|
||||
Values["TaggedButtonGrid_TotalTags"] = "Total: {0}";
|
||||
Values["TaggedButtonGrid_CheckedTags"] = "Checked: {0}";
|
||||
Values["TaggedButtonGrid_CheckAll"] = "بررسی کردن همه";
|
||||
Values["TaggedButtonGrid_UncheckAll"] = "بررسی نکردن همه";
|
||||
Values["CalendarPicker_Title"] = "تاریخ را انتخاب کنید";
|
||||
Values["CalendarPicker_PreviousPage"] = "◀️";
|
||||
Values["CalendarPicker_NextPage"] = "▶️";
|
||||
@@ -31,7 +33,7 @@
|
||||
Values["PromptDialog_Back"] = "بازگشت";
|
||||
Values["ToggleButton_Changed"] = "تنظیمات تغییر کرد";
|
||||
Values["ButtonGrid_SearchIcon"] = "🔍";
|
||||
Values["ButtonGrid_TagIcon"] = "📁";
|
||||
}
|
||||
Values["TaggedButtonGrid_TagIcon"] = "📁";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
namespace TelegramBotBase.Localizations;
|
||||
|
||||
public sealed class Russian : Localization
|
||||
{
|
||||
public Russian()
|
||||
{
|
||||
Values["Language"] = "Русский (Russian)";
|
||||
Values["ButtonGrid_Title"] = "Меню";
|
||||
Values["ButtonGrid_NoItems"] = "Нет доступных элементов.";
|
||||
Values["ButtonGrid_PreviousPage"] = "◀️";
|
||||
Values["ButtonGrid_NextPage"] = "▶️";
|
||||
Values["ButtonGrid_CurrentPage"] = "Страница {0} из {1}";
|
||||
Values["ButtonGrid_SearchFeature"] = "💡 Отправьте сообщение, чтобы отфильтровать список. Нажмите на 🔍, чтобы сбросить фильтр.";
|
||||
Values["ButtonGrid_Back"] = "Назад";
|
||||
Values["TaggedButtonGrid_TotalTags"] = "Всего: {0}";
|
||||
Values["TaggedButtonGrid_CheckedTags"] = "Отмечено: {0}";
|
||||
Values["TaggedButtonGrid_CheckAll"] = "Выделить все";
|
||||
Values["TaggedButtonGrid_UncheckAll"] = "Отменить выбор";
|
||||
Values["CalendarPicker_Title"] = "Календарь / Выберите дату";
|
||||
Values["CalendarPicker_PreviousPage"] = "◀️";
|
||||
Values["CalendarPicker_NextPage"] = "▶️";
|
||||
Values["TreeView_Title"] = "Выберите пункт";
|
||||
Values["TreeView_LevelUp"] = "🔼 Обратно";
|
||||
Values["ToggleButton_On"] = "Вкл";
|
||||
Values["ToggleButton_Off"] = "Выкл";
|
||||
Values["ToggleButton_OnIcon"] = "⚫";
|
||||
Values["ToggleButton_OffIcon"] = "⚪";
|
||||
Values["ToggleButton_Title"] = "Переключить";
|
||||
Values["ToggleButton_Changed"] = "Выбрано";
|
||||
Values["MultiToggleButton_SelectedIcon"] = "✅";
|
||||
Values["MultiToggleButton_Title"] = "Множественный выбор";
|
||||
Values["MultiToggleButton_Changed"] = "Выбрано";
|
||||
Values["PromptDialog_Back"] = "Назад";
|
||||
Values["ToggleButton_Changed"] = "Настройки изменены";
|
||||
Values["ButtonGrid_SearchIcon"] = "🔍";
|
||||
Values["TaggedButtonGrid_TagIcon"] = "📁";
|
||||
}
|
||||
}
|
||||
@@ -34,16 +34,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "InlineAndReplyCombination",
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DependencyInjection", "Examples\DependencyInjection\DependencyInjection.csproj", "{689B16BC-200E-4C68-BB2E-8B209070849B}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TelegramBotBase.Extensions.Serializer.Database.PostgreSql", "TelegramBotBase.Extensions.Serializer.Database.PostgreSql\TelegramBotBase.Extensions.Serializer.Database.PostgreSql.csproj", "{7C55D9FF-7DC1-41D0-809C-469EBFA20992}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TelegramBotBase.Extensions.Images.IronSoftware", "TelegramBotBase.Extensions.Images.IronSoftware\TelegramBotBase.Extensions.Images.IronSoftware.csproj", "{DC521A4C-7446-46F7-845B-AAF10EDCF8C6}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Experiments", "Experiments", "{2E1FF127-4DC2-40A1-849C-ED1432204E8A}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DemoBot", "Experiments\ExternalActionManager\DemoBot\DemoBot.csproj", "{5184D3F8-8526-413D-8EB0-23636EA7A4EF}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TelegramBotBase.Experiments.ActionManager", "Experiments\ExternalActionManager\TelegramBotBase.Experiments\TelegramBotBase.Experiments.ActionManager.csproj", "{625F84FE-6809-4CA4-9C58-3453382D1C65}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ExternalActionManager", "ExternalActionManager", "{359F7D60-362C-4F42-9606-A138FB1293E9}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -94,18 +88,14 @@ Global
|
||||
{689B16BC-200E-4C68-BB2E-8B209070849B}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{689B16BC-200E-4C68-BB2E-8B209070849B}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{689B16BC-200E-4C68-BB2E-8B209070849B}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{7C55D9FF-7DC1-41D0-809C-469EBFA20992}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{7C55D9FF-7DC1-41D0-809C-469EBFA20992}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{7C55D9FF-7DC1-41D0-809C-469EBFA20992}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{7C55D9FF-7DC1-41D0-809C-469EBFA20992}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{DC521A4C-7446-46F7-845B-AAF10EDCF8C6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{DC521A4C-7446-46F7-845B-AAF10EDCF8C6}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{DC521A4C-7446-46F7-845B-AAF10EDCF8C6}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{DC521A4C-7446-46F7-845B-AAF10EDCF8C6}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{5184D3F8-8526-413D-8EB0-23636EA7A4EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{5184D3F8-8526-413D-8EB0-23636EA7A4EF}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{5184D3F8-8526-413D-8EB0-23636EA7A4EF}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{5184D3F8-8526-413D-8EB0-23636EA7A4EF}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{625F84FE-6809-4CA4-9C58-3453382D1C65}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{625F84FE-6809-4CA4-9C58-3453382D1C65}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{625F84FE-6809-4CA4-9C58-3453382D1C65}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{625F84FE-6809-4CA4-9C58-3453382D1C65}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
@@ -120,10 +110,8 @@ Global
|
||||
{52EA3201-02E8-46F5-87C4-B4752C8A815C} = {BFA71E3F-31C0-4FC1-A320-4DCF704768C5}
|
||||
{067E8EBE-F90A-4AFF-A0FF-20578216486E} = {BFA71E3F-31C0-4FC1-A320-4DCF704768C5}
|
||||
{689B16BC-200E-4C68-BB2E-8B209070849B} = {BFA71E3F-31C0-4FC1-A320-4DCF704768C5}
|
||||
{7C55D9FF-7DC1-41D0-809C-469EBFA20992} = {E3193182-6FDA-4FA3-AD26-A487291E7681}
|
||||
{DC521A4C-7446-46F7-845B-AAF10EDCF8C6} = {E3193182-6FDA-4FA3-AD26-A487291E7681}
|
||||
{5184D3F8-8526-413D-8EB0-23636EA7A4EF} = {359F7D60-362C-4F42-9606-A138FB1293E9}
|
||||
{625F84FE-6809-4CA4-9C58-3453382D1C65} = {359F7D60-362C-4F42-9606-A138FB1293E9}
|
||||
{359F7D60-362C-4F42-9606-A138FB1293E9} = {2E1FF127-4DC2-40A1-849C-ED1432204E8A}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {59CB40E1-9FA7-4867-A56F-4F418286F057}
|
||||
|
||||
Reference in New Issue
Block a user