Compare commits

...
43 Commits
Author SHA1 Message Date
Florian Dahn 567a9f937f Update README.md 2020-11-23 13:51:25 +01:00
FlorianDahn 95b4ff77c5 Update README.md 2020-11-23 13:48:13 +01:00
FlorianDahn ba82c11d66 Update README.md 2020-11-23 13:46:28 +01:00
FlorianDahn c2e33da277 Adding SaveSessionState to SessionBase
Feature request: https://github.com/MajMcCloud/TelegramBotFramework/issues/2
2020-11-22 23:15:31 +01:00
FlorianDahn 259fa54236 Update ModalDialog.cs
- Adding await keyword
2020-11-03 23:52:35 +01:00
FlorianDahn f790a16e85 Merge branch 'master' of https://github.com/MajMcCloud/TelegramBotFramework 2020-11-03 20:38:40 +01:00
FlorianDahn 97fea333f7 Update ConfirmDialog.cs
- adding additional checks to ConfirmDialog
- adding AutoCloseOnClick property, to close this modal form after button click
2020-11-03 20:38:36 +01:00
FlorianDahn e1b31b0b9a Update PromptDialog.cs
- adding additional checks to promptdialog
2020-11-03 20:38:07 +01:00
Florian Dahn 7aca5a648f Update README.md 2020-10-31 16:22:47 +01:00
FlorianDahn f24c309f63 Update DeviceSession.cs
- adding ParseMode to Edit functions
- adding a Send method which the parameter of the DeviceId
2020-10-22 22:14:40 +02:00
FlorianDahn ba9fd8062c Update PromptDialog.cs
- added ReceivedMessage for further use
2020-10-20 19:11:04 +02:00
FlorianDahn b37c31f2bd Update BotBase.cs
- Bugfix, Unhandled actions has been producing a loop
2020-10-20 19:10:30 +02:00
FlorianDahn 2c34a178ee Update DeviceSession.cs
- adding caption parameter
2020-10-12 23:16:42 +02:00
FlorianDahn 2f030f3c12 Updates to ButtonGrid
- adding IsNavigationBarVisible property to ButtonGrid
- adding SubHeadLayout row for column "descriptions" like a table design
- uses FilterDuplicate with ByRow enabled to keep the full row on matches
2020-10-05 14:24:34 +02:00
FlorianDahn a364562fd3 Update ButtonForm.cs
- Modifying FilterDuplicate to allow full row filter or not
This will keep only the matches, or the full row where it matches.
2020-10-05 14:22:47 +02:00
FlorianDahn 8ef8733a2b Update DeviceSession.cs
- Adding the name parameter to SendPhoto methods
- Adding caption parameter to SendVideo methods
2020-10-05 14:21:57 +02:00
FlorianDahn 049b2081ec Update SessionBase.cs
Use of Fallback form has been missed in Session loading. Added now.
2020-09-15 23:46:30 +02:00
FlorianDahn 48b76a84be Update SessionBase.cs
- improving handling for Sessions loading with no default constructors available.
2020-09-15 16:42:40 +02:00
FlorianDahn 31c8231b2d Adding NavigationBarVisibility property to hide/show navigation buttons auto/never/always 2020-09-15 16:38:36 +02:00
FlorianDahn e9504f3b36 Update ButtonForm.cs
- adding method for adding one single button row
- fix for ToList method if no buttons are available
2020-09-15 16:36:54 +02:00
FlorianDahn 8592f4279d Update ButtonGrid.cs
Fix "Page 1 of 0" when no rows are existing.
2020-09-08 15:32:04 +02:00
FlorianDahn 2457773a12 Merge branch 'master' of https://github.com/MajMcCloud/TelegramBotFramework 2020-09-05 02:08:28 +02:00
FlorianDahn 46e65faf31 Adding Enum deserialization
Fixing issue in SessionBase where it does not correctly deserialize Enum's
2020-09-05 02:08:19 +02:00
FlorianDahn 193a4811bf Simplifiy AutoCleanForm
Improving serialization by replacing the message with just the ID
2020-09-05 02:07:48 +02:00
Florian Dahn 08a0de8087 Update README.md 2020-09-01 19:00:11 +02:00
FlorianDahn 82469cff70 - Adding not about search feature 2020-08-30 20:48:44 +02:00
Florian Dahn 81eafe1219 Merge pull request #1 from JTOne123/master
[PR] The proj files have been updated to enable SourceLink
2020-08-09 17:25:00 +02:00
FlorianDahn 183e89c36f Adding paging/search example 2020-08-09 17:22:19 +02:00
FlorianDahn ad6cf9539c Adding filter functionality to ButtonGrid
Adding filter functionality
2020-08-09 17:00:04 +02:00
FlorianDahn 46576eb819 Update ButtonForm.cs
adding method to create a ButtonForm duplicate and filter the single buttons, used for ButtonGrid
2020-08-09 16:59:25 +02:00
FlorianDahn cf9e2285f1 Adding DynamicButton for Button with dynamic Text updates
For use, call the ButtonGrid.Updated() method
2020-07-25 15:11:15 +02:00
FlorianDahn ecfacdadbb Update AssemblyInfo.cs 2020-07-25 15:09:01 +02:00
FlorianDahn c00c2e8d8f Update DeviceSession.cs
- adding Unban method
2020-07-25 15:08:55 +02:00
FlorianDahn bfd905d590 Update TelegramBotBase.csproj 2020-07-25 15:08:41 +02:00
FlorianDahn 7b1bf75dde Update ToggleButton
- adding ChangedString variable for custom message
2020-07-25 15:08:22 +02:00
FlorianDahn 7a7a65c3a7 Update FormBase.cs
- adding RemoveAllControls method
2020-07-25 15:07:36 +02:00
Pavlo Datsiuk 8a42a861cf [COMMIT] The proj files have been updated to enable SourceLink [TelegramBotBase.csproj] 2020-06-25 15:54:40 +03:00
FlorianDahn 47876681e0 IgnoreState and SaveState addings for better session serialization
- adding IgnoreState to all ModalDialogs to prevent them get saved.
- adding SaveState to AutoCleanForm to keep state
- change OldMessages property of AutoCleanForm to public
2020-05-07 23:49:08 +02:00
FlorianDahn 9314b4c0e5 Update ButtonGrid.cs
- Fix for async event timings, button click got sometimes fired after Render event
2020-05-06 20:56:38 +02:00
FlorianDahn 01c19b9900 Update README.md 2020-05-04 15:33:50 +02:00
FlorianDahn 0af587d27f Updating readme and test project 2020-05-04 15:33:21 +02:00
FlorianDahn 97b9176c3a Updating packages 2020-05-04 15:22:33 +02:00
FlorianDahn dfa479d409 Fix in StateMachines 2020-05-04 15:18:48 +02:00
32 changed files with 697 additions and 126 deletions
+1 -1
View File
@@ -6,7 +6,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="TelegramBotBase" Version="3.0.0" />
<PackageReference Include="TelegramBotBase" Version="3.1.1" />
</ItemGroup>
</Project>
@@ -7,7 +7,7 @@
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="TelegramBotBase" Version="3.0.0" />
<PackageReference Include="TelegramBotBase" Version="3.1.1" />
</ItemGroup>
</Project>
+34 -30
View File
@@ -70,6 +70,8 @@ Thanks !
* [ToggleButton](#toggle-button)
* [ButtonGrid](#button-grid)
* [Paging and Searching](#paging--searching)
- [Groups](#groups)
* [SplitterForm](#splitter-form)
@@ -118,7 +120,7 @@ It gives you features which will look/feel like WinForms or have a good way to c
## How to start:
Within your empty App your need to put some initial lines including your APIKey to get things started.
The "BotBase" Class will manage a lot of things for you, like system calls, action events and so on.
The "BotBase" Class will manage a lot of things for you, like bot commands, action events and so on.
"StartForm" is your first Formular which every user will get internally redirected to, like a start page, you could redirect from there later in code, so users won't recognize it.
It needs to be a subclass of "FormBase" you will find in Namespace TelegramBotBase.Base
@@ -129,7 +131,10 @@ It needs to be a subclass of "FormBase" you will find in Namespace TelegramBotBa
BotBase<StartForm> bb = new BotBase<StartForm>("{YOUR API KEY}");
//Add Systemcommands if you like, you could catch them later
bb.SystemCalls.Add("/start");
bb.BotCommands.Add(new BotCommand() { Command = "start", Description = "Starts the bot" });
//Update bot commands to botfather
bb.UploadBotCommands().Wait();
//Start your Bot
bb.Start();
@@ -154,17 +159,10 @@ public class StartForm : FormBase
}
//Gets invoked if the form gets opened (with Form.NavigateTo(NewForm))
public override async Task Opened()
{
//Opened() got replaced with event handler
}
//Gets invoked if the form gets leaved
public override async Task Closed()
{
//Closed() got replaced with event handler
}
//Gets invoked on every Message/Action/Data in this context
public override async Task Load(MessageResult message)
@@ -221,10 +219,10 @@ await this.NavigateTo(tf);
All examples are within the test project, so just try it out on your own.
### Add some system calls (Example #0 - System Calls)
### Add some system calls (Example #0 - Bot Commands)
Inside of the BotFather you are able to add "Commands" to your TelegramBot. The user will see them, depending on the application as options he could choose.
I'm calling them Systemcalls. Before start (and later for sure) you could add them to your BotBase. Every time a message comes in they will get checked if they are one of them.
Before start (and later for sure) you could add them to your BotBase. Every time a message comes in they will get checked if they are one of them.
If so, a special event Handler will get raised where you are easier able to manage the action behind.
Below we have 4 options.
@@ -242,13 +240,12 @@ Below we have 4 options.
```
BotBase<Start> bb = new BotBase<Start>("{YOUR API KEY}");
bb.SystemCalls.Add("/start");
bb.SystemCalls.Add("/form1");
bb.SystemCalls.Add("/form2");
bb.BotCommands.Add(new BotCommand() { Command = "start", Description = "Starts the bot" });
bb.BotCommands.Add(new BotCommand() { Command = "form1", Description = "Opens test form 1" });
bb.BotCommands.Add(new BotCommand() { Command = "form2", Description = "Opens test form 2" });
bb.BotCommands.Add(new BotCommand() { Command = "params", Description = "Returns all send parameters as a message." });
bb.SystemCalls.Add("/params");
bb.SystemCall += async (s, en) =>
bb.BotCommand += async (s, en) =>
{
switch (en.Command)
{
@@ -279,6 +276,9 @@ bb.SystemCall += async (s, en) =>
};
//Update Bot commands to botfather
bb.UploadBotCommands().Wait();
bb.Start();
```
@@ -293,19 +293,21 @@ On every input the user is sending back to the bot the Action event gets raised.
```
public class SimpleForm : AutoCleanForm
{
public SimpleForm()
{
this.DeleteSide = eSide.Both;
this.DeleteMode = eDeleteMode.OnLeavingForm;
}
public SimpleForm()
{
this.DeleteSide = TelegramBotBase.Enums.eDeleteSide.Both;
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm;
this.Opened += SimpleForm_Opened;
}
public override async Task Opened()
{
await this.Device.Send("Hello world! (send 'back' to get back to Start)\r\nOr\r\nhi, hello, maybe, bye and ciao");
}
private async Task SimpleForm_Opened(object sender, EventArgs e)
{
await this.Device.Send("Hello world! (send 'back' to get back to Start)\r\nOr\r\nhi, hello, maybe, bye and ciao");
}
public override async Task Load(MessageResult message)
public override async Task Load(MessageResult message)
{
//message.MessageText will work also, cause it is a string you could manage a lot different scenerios here
@@ -680,7 +682,7 @@ public async override Task Render(MessageResult message)
```
There is also a second example, where every of these 3 inputs gets requested by a different formular (class). Just for imagination of the possiblites.
Cause its to much Text, i didnt have added it here. You will find it under [TelegramBaseTest/Tests/Register/PerStep.cs](TelegramBaseTest/Tests/Register/PerStep.cs)
Cause its to much Text, i didnt have added it here. You will find it under [TelegramBotBaseTest/Tests/Register/PerStep.cs](TelegramBotBaseTest/Tests/Register/PerStep.cs)
Beginn there and navigate your way through these Steps in the subfolder.
@@ -799,6 +801,8 @@ await this.NavigateTo(cd);
### Button Grid
<img src="images/buttongrid.gif?raw=true" />
#### Paging & Searching
<img src="images/buttongrid_pagingfilter.gif?raw=true" />
## Groups
+5 -5
View File
@@ -33,14 +33,14 @@ namespace TelegramBotBase.Base
{
}
public virtual async Task Action(MessageResult result, String value = null)
{
}
@@ -50,18 +50,18 @@ namespace TelegramBotBase.Base
}
public virtual async Task Hidden(bool FormClose)
{
}
public virtual async Task Cleanup()
{
}
}
+13
View File
@@ -410,6 +410,19 @@ namespace TelegramBotBase.Form
this.Controls.Remove(control);
}
/// <summary>
/// Removes all controls.
/// </summary>
public void RemoveAllControls()
{
foreach(var c in this.Controls)
{
c.Cleanup().Wait();
this.Controls.Remove(c);
}
}
/// <summary>
/// Cleanup
/// </summary>
+6 -11
View File
@@ -33,7 +33,7 @@ namespace TelegramBotBase
/// <summary>
/// List of all running/active sessions
/// </summary>
public SessionBase Sessions { get; set; }
public SessionBase<T> Sessions { get; set; }
/// <summary>
/// Contains System commands which will be available at everytime and didnt get passed to forms, i.e. /start
@@ -79,7 +79,8 @@ namespace TelegramBotBase
this.BotCommands = new List<BotCommand>();
this.Sessions = new SessionBase();
this.Sessions = new SessionBase<T>();
this.Sessions.BotBase = this;
}
/// <summary>
@@ -193,10 +194,7 @@ namespace TelegramBotBase
this.Client.TelegramClient.StopReceiving();
if (this.StateMachine != null)
{
this.Sessions.SaveSessionStates(this.StateMachine);
}
this.Sessions.SaveSessionStates();
}
/// <summary>
@@ -442,11 +440,8 @@ namespace TelegramBotBase
if (uhc.Handled)
{
if (ds.FormSwitched)
{
continue;
}
else
e.Handled = true;
if (!ds.FormSwitched)
{
break;
}
+162 -29
View File
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.SymbolStore;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -12,6 +13,7 @@ using TelegramBotBase.Base;
using TelegramBotBase.Enums;
using TelegramBotBase.Exceptions;
using TelegramBotBase.Form;
using static TelegramBotBase.Base.Async;
namespace TelegramBotBase.Controls
{
@@ -55,6 +57,17 @@ namespace TelegramBotBase.Controls
/// </summary>
public bool EnablePaging { get; set; } = false;
/// <summary>
/// Enabled a search function.
/// </summary>
public bool EnableSearch { get; set; } = false;
public String SearchQuery { get; set; }
public eNavigationBarVisibility NavigationBarVisibility { get; set; } = eNavigationBarVisibility.always;
/// <summary>
/// Index of the current page
/// </summary>
@@ -66,11 +79,18 @@ namespace TelegramBotBase.Controls
public String NoItemsLabel = Localizations.Default.Language["ButtonGrid_NoItems"];
public String SearchLabel = Localizations.Default.Language["ButtonGrid_SearchFeature"];
/// <summary>
/// Layout of the buttons which should be displayed always on top.
/// </summary>
public List<ButtonBase> HeadLayoutButtonRow { get; set; }
/// <summary>
/// Layout of columns which should be displayed below the header
/// </summary>
public List<ButtonBase> SubHeadLayoutButtonRow { get; set; }
/// <summary>
/// Defines which type of Button Keyboard should be rendered.
/// </summary>
@@ -115,7 +135,7 @@ namespace TelegramBotBase.Controls
}
public event EventHandler<ButtonClickedEventArgs> ButtonClicked
public event AsyncEventHandler<ButtonClickedEventArgs> ButtonClicked
{
add
{
@@ -127,9 +147,13 @@ namespace TelegramBotBase.Controls
}
}
public void OnButtonClicked(ButtonClickedEventArgs e)
public async Task OnButtonClicked(ButtonClickedEventArgs e)
{
(this.Events[__evButtonClicked] as EventHandler<ButtonClickedEventArgs>)?.Invoke(this, e);
var handler = this.Events[__evButtonClicked].GetInvocationList().Cast<AsyncEventHandler<ButtonClickedEventArgs>>();
foreach (var h in handler)
{
await Async.InvokeAllAsync<ButtonClickedEventArgs>(h, this, e);
}
}
public async override Task Load(MessageResult result)
@@ -140,33 +164,61 @@ namespace TelegramBotBase.Controls
if (!result.IsFirstHandler)
return;
var button = HeadLayoutButtonRow?.FirstOrDefault(a => a.Text.Trim() == result.MessageText) ?? ButtonsForm.ToList().FirstOrDefault(a => a.Text.Trim() == result.MessageText);
var button = HeadLayoutButtonRow?.FirstOrDefault(a => a.Text.Trim() == result.MessageText)
?? SubHeadLayoutButtonRow?.FirstOrDefault(a => a.Text.Trim() == result.MessageText)
?? ButtonsForm.ToList().FirstOrDefault(a => a.Text.Trim() == result.MessageText);
if (button == null)
{
if (result.MessageText != null)
if (result.MessageText == null)
return;
if (result.MessageText == PreviousPageLabel)
{
if (result.MessageText == PreviousPageLabel)
{
if (this.CurrentPageIndex > 0)
this.CurrentPageIndex--;
if (this.CurrentPageIndex > 0)
this.CurrentPageIndex--;
this.Updated();
}
else if (result.MessageText == NextPageLabel)
{
if (this.CurrentPageIndex < this.PageCount - 1)
this.CurrentPageIndex++;
this.Updated();
}
this.Updated();
}
else if (result.MessageText == NextPageLabel)
{
if (this.CurrentPageIndex < this.PageCount - 1)
this.CurrentPageIndex++;
this.Updated();
}
else if (this.EnableSearch)
{
if (result.MessageText.StartsWith("🔍"))
{
//Sent note about searching
if (this.SearchQuery == null)
{
await this.Device.Send(this.SearchLabel);
}
this.SearchQuery = null;
this.Updated();
return;
}
this.SearchQuery = result.MessageText;
if (this.SearchQuery != null && this.SearchQuery != "")
{
this.CurrentPageIndex = 0;
this.Updated();
}
}
return;
}
OnButtonClicked(new ButtonClickedEventArgs(button));
await OnButtonClicked(new ButtonClickedEventArgs(button));
//Remove button click message
if (this.DeletePreviousMessage)
@@ -191,7 +243,9 @@ namespace TelegramBotBase.Controls
{
case eKeyboardType.InlineKeyBoard:
var button = HeadLayoutButtonRow?.FirstOrDefault(a => a.Value == result.RawData) ?? ButtonsForm.ToList().FirstOrDefault(a => a.Value == result.RawData);
var button = HeadLayoutButtonRow?.FirstOrDefault(a => a.Value == result.RawData)
?? SubHeadLayoutButtonRow?.FirstOrDefault(a => a.Value == result.RawData)
?? ButtonsForm.ToList().FirstOrDefault(a => a.Value == result.RawData);
if (button == null)
{
@@ -219,7 +273,7 @@ namespace TelegramBotBase.Controls
return;
}
OnButtonClicked(new ButtonClickedEventArgs(button));
await OnButtonClicked(new ButtonClickedEventArgs(button));
result.Handled = true;
@@ -277,8 +331,16 @@ namespace TelegramBotBase.Controls
Message m = null;
ButtonForm form = this.ButtonsForm.Duplicate();
ButtonForm form = this.ButtonsForm;
if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
{
form = form.FilterDuplicate(this.SearchQuery, true);
}
else
{
form = form.Duplicate();
}
if (this.EnablePaging)
{
@@ -290,6 +352,18 @@ namespace TelegramBotBase.Controls
form.InsertButtonRow(0, this.HeadLayoutButtonRow);
}
if (this.SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
{
if (this.IsNavigationBarVisible)
{
form.InsertButtonRow(2, this.SubHeadLayoutButtonRow);
}
else
{
form.InsertButtonRow(1, this.SubHeadLayoutButtonRow);
}
}
switch (this.KeyboardType)
{
//Reply Keyboard could only be updated with a new keyboard.
@@ -362,11 +436,24 @@ namespace TelegramBotBase.Controls
{
bf.AddButtonRow(new ButtonBase(NoItemsLabel, "$"));
}
bf.InsertButtonRow(0, new ButtonBase(PreviousPageLabel, "$previous$"), new ButtonBase(String.Format(Localizations.Default.Language["ButtonGrid_CurrentPage"], this.CurrentPageIndex + 1, this.PageCount), "$site$"), new ButtonBase(NextPageLabel, "$next$"));
bf.AddButtonRow(new ButtonBase(PreviousPageLabel, "$previous$"), new ButtonBase(String.Format(Localizations.Default.Language["ButtonGrid_CurrentPage"], this.CurrentPageIndex + 1, this.PageCount), "$site$"), new ButtonBase(NextPageLabel, "$next$"));
if (this.IsNavigationBarVisible)
{
//🔍
List<ButtonBase> lst = new List<ButtonBase>();
lst.Add(new ButtonBase(PreviousPageLabel, "$previous$"));
lst.Add(new ButtonBase(String.Format(Localizations.Default.Language["ButtonGrid_CurrentPage"], this.CurrentPageIndex + 1, this.PageCount), "$site$"));
lst.Add(new ButtonBase(NextPageLabel, "$next$"));
if (this.EnableSearch)
{
lst.Insert(2, new ButtonBase("🔍 " + (this.SearchQuery ?? ""), "$search$"));
}
bf.InsertButtonRow(0, lst);
bf.AddButtonRow(lst);
}
return bf;
}
@@ -375,7 +462,25 @@ namespace TelegramBotBase.Controls
{
get
{
if ((this.KeyboardType == eKeyboardType.InlineKeyBoard && ButtonsForm.Rows > Constants.Telegram.MaxInlineKeyBoardRows) | (this.KeyboardType == eKeyboardType.ReplyKeyboard && ButtonsForm.Rows > Constants.Telegram.MaxReplyKeyboardRows))
if (this.KeyboardType == eKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows)
{
return true;
}
if (this.KeyboardType == eKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows)
{
return true;
}
return false;
}
}
public bool IsNavigationBarVisible
{
get
{
if (this.NavigationBarVisibility == eNavigationBarVisibility.always | (this.NavigationBarVisibility == eNavigationBarVisibility.auto && PagingNecessary))
{
return true;
}
@@ -405,6 +510,18 @@ namespace TelegramBotBase.Controls
}
}
/// <summary>
/// Returns the number of all rows (layout + navigation + content);
/// </summary>
public int TotalRows
{
get
{
return this.LayoutRows + ButtonsForm.Rows;
}
}
/// <summary>
/// Contains the Number of Rows which are used by the layout.
/// </summary>
@@ -412,11 +529,17 @@ namespace TelegramBotBase.Controls
{
get
{
int layoutRows = 2;
int layoutRows = 0;
if (this.NavigationBarVisibility == eNavigationBarVisibility.always | this.NavigationBarVisibility == eNavigationBarVisibility.auto)
layoutRows += 2;
if (this.HeadLayoutButtonRow != null && this.HeadLayoutButtonRow.Count > 0)
layoutRows++;
if (this.SubHeadLayoutButtonRow != null && this.SubHeadLayoutButtonRow.Count > 0)
layoutRows++;
return layoutRows;
}
}
@@ -428,7 +551,17 @@ namespace TelegramBotBase.Controls
if (this.ButtonsForm.Count == 0)
return 1;
return (int)Math.Ceiling((decimal)(this.ButtonsForm.Rows / (decimal)(MaximumRow - 3)));
var bf = this.ButtonsForm;
if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
{
bf = bf.FilterDuplicate(this.SearchQuery);
}
if (bf.Rows == 0)
return 1;
return (int)Math.Ceiling((decimal)(bf.Rows / (decimal)(MaximumRow - 3)));
}
}
+3 -1
View File
@@ -20,6 +20,8 @@ namespace TelegramBotBase.Controls
public String UncheckedString { get; set; } = Localizations.Default.Language["ToggleButton_Off"];
public String ChangedString { get; set; } = Localizations.Default.Language["ToggleButton_Changed"];
public String Title { get; set; } = Localizations.Default.Language["ToggleButton_Title"];
public int? MessageId { get; set; }
@@ -68,7 +70,7 @@ namespace TelegramBotBase.Controls
if (result.Handled)
return;
await result.ConfirmAction();
await result.ConfirmAction(this.ChangedString);
switch (value ?? "unknown")
{
@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace TelegramBotBase.Enums
{
public enum eNavigationBarVisibility
{
/// <summary>
/// Shows it depending on the amount of items.
/// </summary>
auto = 0,
/// <summary>
/// Will not show it at any time.
/// </summary>
never = 1,
/// <summary>
/// Will show it at any time.
/// </summary>
always = 2
}
}
+2
View File
@@ -4,6 +4,7 @@ using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Attributes;
using TelegramBotBase.Base;
namespace TelegramBotBase.Form
@@ -11,6 +12,7 @@ namespace TelegramBotBase.Form
/// <summary>
/// A simple prompt dialog with one ok Button
/// </summary>
[IgnoreState]
public class AlertDialog : ConfirmDialog
{
public String ButtonText { get; set; }
+2 -1
View File
@@ -5,6 +5,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Attributes;
using TelegramBotBase.Base;
namespace TelegramBotBase.Form
@@ -12,11 +13,11 @@ namespace TelegramBotBase.Form
/// <summary>
/// A prompt with a lot of buttons
/// </summary>
[IgnoreState]
public class ArrayPromptDialog : FormBase
{
public String Message { get; set; }
public ButtonBase[][] Buttons { get; set; }
[Obsolete]
+21 -11
View File
@@ -5,6 +5,7 @@ using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using TelegramBotBase.Args;
using TelegramBotBase.Attributes;
using TelegramBotBase.Base;
using TelegramBotBase.Enums;
@@ -15,17 +16,20 @@ namespace TelegramBotBase.Form
/// </summary>
public class AutoCleanForm : FormBase
{
List<Message> OldMessages { get; set; }
[SaveState]
public List<int> OldMessages { get; set; }
[SaveState]
public eDeleteMode DeleteMode { get; set; }
[SaveState]
public eDeleteSide DeleteSide { get; set; }
public AutoCleanForm()
{
this.OldMessages = new List<Message>();
this.OldMessages = new List<int>();
this.DeleteMode = eDeleteMode.OnEveryCall;
this.DeleteSide = eDeleteSide.BotOnly;
@@ -52,7 +56,7 @@ namespace TelegramBotBase.Form
if (this.DeleteSide == eDeleteSide.BotOnly)
return;
this.OldMessages.Add(e.Message);
this.OldMessages.Add(e.Message.MessageId);
}
private void Device_MessageSent(object sender, MessageSentEventArgs e)
@@ -60,7 +64,7 @@ namespace TelegramBotBase.Form
if (this.DeleteSide == eDeleteSide.UserOnly)
return;
this.OldMessages.Add(e.Message);
this.OldMessages.Add(e.Message.MessageId);
}
public override async Task PreLoad(MessageResult message)
@@ -77,7 +81,17 @@ namespace TelegramBotBase.Form
/// <param name="Id"></param>
public void AddMessage(Message m)
{
this.OldMessages.Add(m);
this.OldMessages.Add(m.MessageId);
}
/// <summary>
/// Adds a message to this of removable ones
/// </summary>
/// <param name="Id"></param>
public void AddMessage(int messageId)
{
this.OldMessages.Add(messageId);
}
/// <summary>
@@ -86,11 +100,7 @@ namespace TelegramBotBase.Form
/// <param name="Id"></param>
public void LeaveMessage(int Id)
{
var m = this.OldMessages.FirstOrDefault(a => a.MessageId == Id);
if (m == null)
return;
this.OldMessages.Remove(m);
this.OldMessages.Remove(Id);
}
/// <summary>
@@ -120,7 +130,7 @@ namespace TelegramBotBase.Form
{
while (this.OldMessages.Count > 0)
{
if (!await this.Device.DeleteMessage(this.OldMessages[0].MessageId))
if (!await this.Device.DeleteMessage(this.OldMessages[0]))
{
//Message can't be deleted cause it seems not to exist anymore
if (this.OldMessages.Count > 0)
+1 -1
View File
@@ -12,7 +12,7 @@ namespace TelegramBotBase.Form
/// </summary>
public class ButtonBase
{
public String Text { get; set; }
public virtual String Text { get; set; }
public String Value { get; set; }
+47 -3
View File
@@ -61,6 +61,11 @@ namespace TelegramBotBase.Form
this.DependencyControl = control;
}
public void AddButtonRow(String Text, String Value, String Url = null)
{
Buttons.Add(new List<ButtonBase>() { new ButtonBase(Text, Value, Url) });
}
public void AddButtonRow(IEnumerable<ButtonBase> row)
{
Buttons.Add(row.ToList());
@@ -129,7 +134,7 @@ namespace TelegramBotBase.Form
public List<ButtonBase> ToList()
{
return this.Buttons.Aggregate((a, b) => a.Union(b).ToList());
return this.Buttons.DefaultIfEmpty(new List<ButtonBase>()).Aggregate((a, b) => a.Union(b).ToList());
}
public InlineKeyboardButton[][] ToInlineButtonArray()
@@ -188,10 +193,10 @@ namespace TelegramBotBase.Form
DependencyControl = this.DependencyControl
};
foreach(var b in Buttons)
foreach (var b in Buttons)
{
var lst = new List<ButtonBase>();
foreach(var b2 in b)
foreach (var b2 in b)
{
lst.Add(b2);
}
@@ -200,5 +205,44 @@ namespace TelegramBotBase.Form
return bf;
}
/// <summary>
/// Creates a copy of this form and filters by the parameter.
/// </summary>
/// <returns></returns>
public ButtonForm FilterDuplicate(String filter, bool ByRow = false)
{
var bf = new ButtonForm()
{
Markup = this.Markup,
DependencyControl = this.DependencyControl
};
foreach (var b in Buttons)
{
var lst = new List<ButtonBase>();
foreach (var b2 in b)
{
if (b2.Text.IndexOf(filter, StringComparison.InvariantCultureIgnoreCase) == -1)
continue;
//Copy full row, when at least one match has found.
if (ByRow)
{
lst.AddRange(b);
break;
}
else
{
lst.Add(b2);
}
}
if (lst.Count > 0)
bf.Buttons.Add(lst);
}
return bf;
}
}
}
+15
View File
@@ -5,14 +5,20 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Attributes;
using TelegramBotBase.Base;
namespace TelegramBotBase.Form
{
[IgnoreState]
public class ConfirmDialog : ModalDialog
{
public String Message { get; set; }
/// <summary>
/// Automatically close form on button click
/// </summary>
public bool AutoCloseOnClick { get; set; } = true;
public List<ButtonBase> Buttons { get; set; }
@@ -48,6 +54,12 @@ namespace TelegramBotBase.Form
public override async Task Action(MessageResult message)
{
if (message.Handled)
return;
if (!message.IsFirstHandler)
return;
var call = message.GetData<CallbackData>();
if (call == null)
return;
@@ -66,6 +78,9 @@ namespace TelegramBotBase.Form
}
OnButtonClicked(new ButtonClickedEventArgs(button));
if (AutoCloseOnClick)
await CloseForm();
}
+41
View File
@@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace TelegramBotBase.Form
{
public class DynamicButton : ButtonBase
{
public override string Text
{
get
{
return GetText?.Invoke() ?? m_text;
}
set
{
m_text = value;
}
}
private String m_text = "";
private Func<String> GetText;
public DynamicButton(String Text, String Value, String Url = null)
{
this.Text = Text;
this.Value = Value;
this.Url = Url;
}
public DynamicButton(Func<String> GetText, String Value, String Url = null)
{
this.GetText = GetText;
this.Value = Value;
this.Url = Url;
}
}
}
+1 -1
View File
@@ -22,7 +22,7 @@ namespace TelegramBotBase.Form
await this.OnClosed(new EventArgs());
this.ParentForm?.ReturnFromModal(this);
await this.ParentForm?.ReturnFromModal(this);
}
}
}
+15
View File
@@ -4,11 +4,14 @@ using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using Telegram.Bot.Types.ReplyMarkups;
using TelegramBotBase.Attributes;
using TelegramBotBase.Base;
namespace TelegramBotBase.Form
{
[IgnoreState]
public class PromptDialog : ModalDialog
{
public String Message { get; set; }
@@ -23,6 +26,11 @@ namespace TelegramBotBase.Form
public String BackLabel { get; set; } = Localizations.Default.Language["PromptDialog_Back"];
/// <summary>
/// Contains the RAW received message.
/// </summary>
public Message ReceivedMessage { get; set; }
public PromptDialog()
{
@@ -38,6 +46,9 @@ namespace TelegramBotBase.Form
if (message.Handled)
return;
if (!message.IsFirstHandler)
return;
if (this.ShowBackButton && message.MessageText == BackLabel)
{
await this.CloseForm();
@@ -48,6 +59,8 @@ namespace TelegramBotBase.Form
if (this.Value == null)
{
this.Value = message.MessageText;
ReceivedMessage = message.Message;
}
@@ -71,6 +84,8 @@ namespace TelegramBotBase.Form
}
message.Handled = true;
OnCompleted(new EventArgs());
await this.CloseForm();
+9
View File
@@ -11,13 +11,22 @@ namespace TelegramBotBase.Localizations
Values["Language"] = "English";
Values["ButtonGrid_Title"] = "Menu";
Values["ButtonGrid_NoItems"] = "There are no items.";
Values["ButtonGrid_PreviousPage"] = "◀️";
Values["ButtonGrid_NextPage"] = "▶️";
Values["ButtonGrid_CurrentPage"] = "Page {0} of {1}";
Values["ButtonGrid_SearchFeature"] = "💡 Send a message to filter the list. Click the 🔍 to reset the filter.";
Values["CalendarPicker_Title"] = "Pick date";
Values["CalendarPicker_PreviousPage"] = "◀️";
Values["CalendarPicker_NextPage"] = "▶️";
Values["TreeView_Title"] = "Select node";
Values["TreeView_LevelUp"] = "🔼 level up";
Values["ToggleButton_On"] = "On";
Values["ToggleButton_Off"] = "Off";
Values["ToggleButton_OnIcon"] = "⚫";
Values["ToggleButton_OffIcon"] = "⚪";
Values["ToggleButton_Title"] = "Toggle";
Values["PromptDialog_Back"] = "Back";
Values["ToggleButton_Changed"] = "Setting changed";
}
@@ -24,6 +24,7 @@ namespace TelegramBotBase.Localizations
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["CalendarPicker_Title"] = "Datum auswählen";
Values["CalendarPicker_PreviousPage"] = "◀️";
Values["CalendarPicker_NextPage"] = "▶️";
@@ -35,6 +36,7 @@ namespace TelegramBotBase.Localizations
Values["ToggleButton_OffIcon"] = "⚪";
Values["ToggleButton_Title"] = "Schalter";
Values["PromptDialog_Back"] = "Zurück";
Values["ToggleButton_Changed"] = "Einstellung geändert";
}
+3 -3
View File
@@ -10,7 +10,7 @@ using System.Runtime.InteropServices;
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Florian Dahn")]
[assembly: AssemblyProduct("TelegramBotBase Framework")]
[assembly: AssemblyCopyright("Copyright © Florian Dahn 2019")]
[assembly: AssemblyCopyright("Copyright © Florian Dahn 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
[assembly: AssemblyVersion("3.1.0.0")]
[assembly: AssemblyFileVersion("3.1.0.0")]
+44 -2
View File
@@ -1,6 +1,8 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Args;
@@ -14,12 +16,15 @@ namespace TelegramBotBase
/// <summary>
/// Base class for managing all active sessions
/// </summary>
public class SessionBase
public class SessionBase<T>
where T : FormBase
{
public MessageClient Client { get; set; }
public Dictionary<long, DeviceSession> SessionList { get; set; }
public BotBase<T> BotBase { get; set; }
public SessionBase()
{
@@ -130,7 +135,22 @@ namespace TelegramBotBase
continue;
}
var form = t.GetConstructor(new Type[] { }).Invoke(new object[] { }) as FormBase;
var form = t.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as FormBase;
//No default constructor, fallback
if (form == null)
{
if (!statemachine.FallbackStateForm.IsSubclassOf(typeof(FormBase)))
continue;
form = statemachine.FallbackStateForm.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as FormBase;
//Fallback failed, due missing default constructor
if (form == null)
continue;
}
if (s.Values != null && s.Values.Count > 0)
{
@@ -145,6 +165,16 @@ namespace TelegramBotBase
try
{
if (f.PropertyType.IsEnum)
{
var ent = Enum.Parse(f.PropertyType, p.Value.ToString());
f.SetValue(form, ent);
continue;
}
f.SetValue(form, p.Value);
}
catch (ArgumentException ex)
@@ -268,5 +298,17 @@ namespace TelegramBotBase
statemachine.SaveFormStates(new SaveStatesEventArgs(sc));
}
/// <summary>
/// Saves all open states into the machine.
/// </summary>
public void SaveSessionStates()
{
if (this.BotBase.StateMachine == null)
return;
this.SaveSessionStates(this.BotBase.StateMachine);
}
}
}
+46 -19
View File
@@ -41,9 +41,9 @@ namespace TelegramBotBase.Sessions
/// <returns></returns>
public String GetChatTitle()
{
return LastMessage?.Chat.Title
?? LastMessage?.Chat.Username
?? LastMessage?.Chat.FirstName
return LastMessage?.Chat.Title
?? LastMessage?.Chat.Username
?? LastMessage?.Chat.FirstName
?? ChatTitle;
}
@@ -135,6 +135,7 @@ namespace TelegramBotBase.Sessions
this.ActiveForm.Device = this;
}
/// <summary>
/// Edits the text message
/// </summary>
@@ -142,7 +143,7 @@ namespace TelegramBotBase.Sessions
/// <param name="text"></param>
/// <param name="buttons"></param>
/// <returns></returns>
public async Task<Message> Edit(int messageId, String text, ButtonForm buttons = null)
public async Task<Message> Edit(int messageId, String text, ButtonForm buttons = null, ParseMode parseMode = ParseMode.Default)
{
InlineKeyboardMarkup markup = buttons;
@@ -153,7 +154,7 @@ namespace TelegramBotBase.Sessions
try
{
return await this.Client.TelegramClient.EditMessageTextAsync(this.DeviceId, messageId, text, replyMarkup: markup);
return await this.Client.TelegramClient.EditMessageTextAsync(this.DeviceId, messageId, text, parseMode, replyMarkup: markup);
}
catch
{
@@ -171,7 +172,7 @@ namespace TelegramBotBase.Sessions
/// <param name="text"></param>
/// <param name="buttons"></param>
/// <returns></returns>
public async Task<Message> Edit(int messageId, String text, InlineKeyboardMarkup markup)
public async Task<Message> Edit(int messageId, String text, InlineKeyboardMarkup markup, ParseMode parseMode = ParseMode.Default)
{
if (text.Length > Constants.Telegram.MaxMessageLength)
{
@@ -180,7 +181,7 @@ namespace TelegramBotBase.Sessions
try
{
return await this.Client.TelegramClient.EditMessageTextAsync(this.DeviceId, messageId, text, replyMarkup: markup);
return await this.Client.TelegramClient.EditMessageTextAsync(this.DeviceId, messageId, text, parseMode, replyMarkup: markup);
}
catch
{
@@ -198,7 +199,7 @@ namespace TelegramBotBase.Sessions
/// <param name="text"></param>
/// <param name="buttons"></param>
/// <returns></returns>
public async Task<Message> Edit(Message message, ButtonForm buttons = null)
public async Task<Message> Edit(Message message, ButtonForm buttons = null, ParseMode parseMode = ParseMode.Default)
{
InlineKeyboardMarkup markup = buttons;
@@ -209,7 +210,7 @@ namespace TelegramBotBase.Sessions
try
{
return await this.Client.TelegramClient.EditMessageTextAsync(this.DeviceId, message.MessageId, message.Text, replyMarkup: markup);
return await this.Client.TelegramClient.EditMessageTextAsync(this.DeviceId, message.MessageId, message.Text, parseMode, replyMarkup: markup);
}
catch
{
@@ -249,7 +250,7 @@ namespace TelegramBotBase.Sessions
/// <param name="replyTo"></param>
/// <param name="disableNotification"></param>
/// <returns></returns>
public async Task<Message> Send(String text, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Default, bool MarkdownV2AutoEscape = true)
public async Task<Message> Send(long deviceId, String text, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Default, bool MarkdownV2AutoEscape = true)
{
if (this.ActiveForm == null)
return null;
@@ -270,7 +271,7 @@ namespace TelegramBotBase.Sessions
try
{
m = await (this.Client.TelegramClient.SendTextMessageAsync(this.DeviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
m = await (this.Client.TelegramClient.SendTextMessageAsync(deviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
OnMessageSent(new MessageSentEventArgs(m));
}
@@ -286,6 +287,19 @@ namespace TelegramBotBase.Sessions
return m;
}
/// <summary>
/// Sends a simple text message
/// </summary>
/// <param name="text"></param>
/// <param name="buttons"></param>
/// <param name="replyTo"></param>
/// <param name="disableNotification"></param>
/// <returns></returns>
public async Task<Message> Send(String text, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Default, bool MarkdownV2AutoEscape = true)
{
return await Send(this.DeviceId, text, buttons, replyTo, disableNotification, parseMode, MarkdownV2AutoEscape);
}
/// <summary>
/// Sends a simple text message
/// </summary>
@@ -380,7 +394,7 @@ namespace TelegramBotBase.Sessions
/// <param name="replyTo"></param>
/// <param name="disableNotification"></param>
/// <returns></returns>
public async Task<Message> SendPhoto(InputOnlineFile file, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Default)
public async Task<Message> SendPhoto(InputOnlineFile file, String caption = null, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Default)
{
if (this.ActiveForm == null)
return null;
@@ -391,7 +405,7 @@ namespace TelegramBotBase.Sessions
try
{
m = await this.Client.TelegramClient.SendPhotoAsync(this.DeviceId, file, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification);
m = await this.Client.TelegramClient.SendPhotoAsync(this.DeviceId, file, caption: caption, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification);
OnMessageSent(new MessageSentEventArgs(m));
}
@@ -416,13 +430,13 @@ namespace TelegramBotBase.Sessions
/// <param name="replyTo"></param>
/// <param name="disableNotification"></param>
/// <returns></returns>
public async Task<Message> SendPhoto(Image image, String name, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false)
public async Task<Message> SendPhoto(Image image, String name, String caption, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false)
{
using (var fileStream = Tools.Images.ToStream(image, ImageFormat.Png))
{
InputOnlineFile fts = new InputOnlineFile(fileStream, name);
return await SendPhoto(fts, buttons, replyTo, disableNotification);
return await SendPhoto(fts, caption: caption, buttons, replyTo, disableNotification);
}
}
@@ -435,13 +449,13 @@ namespace TelegramBotBase.Sessions
/// <param name="replyTo"></param>
/// <param name="disableNotification"></param>
/// <returns></returns>
public async Task<Message> SendPhoto(Bitmap image, String name, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false)
public async Task<Message> SendPhoto(Bitmap image, String name, String caption, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false)
{
using (var fileStream = Tools.Images.ToStream(image, ImageFormat.Png))
{
InputOnlineFile fts = new InputOnlineFile(fileStream, name);
return await SendPhoto(fts, buttons, replyTo, disableNotification);
return await SendPhoto(fts, caption: caption, buttons, replyTo, disableNotification);
}
}
@@ -453,7 +467,7 @@ namespace TelegramBotBase.Sessions
/// <param name="replyTo"></param>
/// <param name="disableNotification"></param>
/// <returns></returns>
public async Task<Message> SendVideo(InputOnlineFile file, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Default)
public async Task<Message> SendVideo(InputOnlineFile file, String caption = null, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Default)
{
if (this.ActiveForm == null)
return null;
@@ -464,7 +478,7 @@ namespace TelegramBotBase.Sessions
try
{
m = await this.Client.TelegramClient.SendVideoAsync(this.DeviceId, file, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification);
m = await this.Client.TelegramClient.SendVideoAsync(this.DeviceId, file, caption: caption, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification);
OnMessageSent(new MessageSentEventArgs(m));
}
@@ -723,6 +737,19 @@ namespace TelegramBotBase.Sessions
}
}
public virtual async Task UnbanUser(int userId)
{
try
{
await this.Client.TelegramClient.UnbanChatMemberAsync(this.DeviceId, userId);
}
catch
{
}
}
/// <summary>
/// Eventhandler for sent messages
+1 -1
View File
@@ -36,7 +36,7 @@ namespace TelegramBotBase.States
this.FallbackStateForm = fallbackStateForm;
if (!this.FallbackStateForm.IsSubclassOf(typeof(FormBase)))
if (this.FallbackStateForm != null && !this.FallbackStateForm.IsSubclassOf(typeof(FormBase)))
{
throw new ArgumentException("FallbackStateForm is not a subclass of FormBase");
}
@@ -36,7 +36,7 @@ namespace TelegramBotBase.States
this.FallbackStateForm = fallbackStateForm;
if (!this.FallbackStateForm.IsSubclassOf(typeof(FormBase)))
if (this.FallbackStateForm != null && !this.FallbackStateForm.IsSubclassOf(typeof(FormBase)))
{
throw new ArgumentException("FallbackStateForm is not a subclass of FormBase");
}
+1 -1
View File
@@ -35,7 +35,7 @@ namespace TelegramBotBase.States
this.FallbackStateForm = fallbackStateForm;
if (!this.FallbackStateForm.IsSubclassOf(typeof(FormBase)))
if (this.FallbackStateForm != null && !this.FallbackStateForm.IsSubclassOf(typeof(FormBase)))
{
throw new ArgumentException("FallbackStateForm is not a subclass of FormBase");
}
+17 -3
View File
@@ -1,20 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net461;netcoreapp3.1</TargetFrameworks>
<TargetFrameworks>netstandard2.1;net461;netcoreapp3.1</TargetFrameworks>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<GeneratePackageOnBuild>false</GeneratePackageOnBuild>
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>
<PackageProjectUrl>https://github.com/MajMcCloud/TelegramBotFramework</PackageProjectUrl>
<RepositoryUrl>https://github.com/MajMcCloud/TelegramBotFramework</RepositoryUrl>
<PackageReleaseNotes>- moving from .Net Framework 4.7.2 to .Net Standard 2.1 for the Library and .Net Core 3.0 for the test project!</PackageReleaseNotes>
<PackageReleaseNotes>- moving from .Net Framework 4.7.2 to .Net Standard 2.1 for the Library and .Net Core 3.1 for the test project!</PackageReleaseNotes>
<Configurations>Debug;Release;</Configurations>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<RunAnalyzersDuringBuild>false</RunAnalyzersDuringBuild>
<RunAnalyzersDuringLiveAnalysis>false</RunAnalyzersDuringLiveAnalysis>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />
</ItemGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
@@ -56,6 +64,7 @@
<ItemGroup>
<None Remove="cpack.ps1" />
<None Remove="cpack_bak.ps1" />
<None Remove="cpush.ps1" />
<None Remove="nuget.exe" />
<None Remove="TelegramBotBase.1.5.0.nupkg" />
@@ -64,6 +73,11 @@
<None Remove="TelegramBotBase.1.5.1.zip" />
<None Remove="TelegramBotBase.1.5.2.nupkg" />
<None Remove="TelegramBotBase.1.5.2.zip" />
<None Remove="TelegramBotBase.2.0.0.nupkg" />
<None Remove="TelegramBotBase.2.1.0.nupkg" />
<None Remove="TelegramBotBase.2.1.0.zip" />
<None Remove="TelegramBotBase.3.0.0.nupkg" />
<None Remove="TelegramBotBase.3.0.0.zip" />
<None Remove="TelegramBotBase.nuspec" />
</ItemGroup>
+92
View File
@@ -0,0 +1,92 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using TelegramBotBase;
using TelegramBotBase.Form;
using TelegramBotBaseTest.Tests;
namespace TelegramBotBaseTest
{
class Program
{
static void Main(string[] args)
{
BotBase<Start> bb = new BotBase<Start>(APIKey);
bb.BotCommands.Add(new BotCommand() { Command = "start", Description = "Starts the bot" });
bb.BotCommands.Add(new BotCommand() { Command = "form1", Description = "Opens test form 1" });
bb.BotCommands.Add(new BotCommand() { Command = "form2", Description = "Opens test form 2" });
bb.BotCommands.Add(new BotCommand() { Command = "params", Description = "Returns all send parameters as a message." });
bb.BotCommand += async (s, en) =>
{
switch (en.Command)
{
case "/start":
var start = new Menu();
await en.Device.ActiveForm.NavigateTo(start);
break;
case "/form1":
var form1 = new TestForm();
await en.Device.ActiveForm.NavigateTo(form1);
break;
case "/form2":
var form2 = new TestForm2();
await en.Device.ActiveForm.NavigateTo(form2);
break;
case "/params":
String m = en.Parameters.DefaultIfEmpty("").Aggregate((a, b) => a + " and " + b);
await en.Device.Send("Your parameters are: " + m, replyTo: en.Device.LastMessageId);
en.Handled = true;
break;
}
};
//Update Bot commands to botfather
bb.UploadBotCommands().Wait();
bb.SetSetting(TelegramBotBase.Enums.eSettings.LogAllMessages, true);
bb.Message += (s,en) =>
{
Console.WriteLine(en.DeviceId + " " + en.Message.MessageText + " " + (en.Message.RawData ?? ""));
};
bb.Start();
Console.WriteLine("Telegram Bot started...");
Console.WriteLine("Press q to quit application.");
Console.ReadLine();
bb.Stop();
}
}
}
@@ -44,7 +44,7 @@ namespace TelegramBotBaseTest.Tests.Controls
}
private async void Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
{
if (e.Button == null)
return;
@@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Controls;
using TelegramBotBase.Form;
namespace TelegramBotBaseTest.Tests.Controls
{
public class ButtonGridPagingForm : AutoCleanForm
{
ButtonGrid m_Buttons = null;
public ButtonGridPagingForm()
{
this.DeleteMode = TelegramBotBase.Enums.eDeleteMode.OnLeavingForm;
this.Init += ButtonGridForm_Init;
}
private async Task ButtonGridForm_Init(object sender, InitEventArgs e)
{
m_Buttons = new ButtonGrid();
m_Buttons.KeyboardType = TelegramBotBase.Enums.eKeyboardType.ReplyKeyboard;
m_Buttons.EnablePaging = true;
m_Buttons.EnableSearch = true;
m_Buttons.HeadLayoutButtonRow = new List<ButtonBase>() { new ButtonBase("Back", "back") };
var countries = CultureInfo.GetCultures(CultureTypes.SpecificCultures);
ButtonForm bf = new ButtonForm();
foreach (var c in countries)
{
bf.AddButtonRow(new ButtonBase(c.EnglishName, c.EnglishName));
}
m_Buttons.ButtonsForm = bf;
m_Buttons.ButtonClicked += Bg_ButtonClicked;
this.AddControl(m_Buttons);
}
private async Task Bg_ButtonClicked(object sender, ButtonClickedEventArgs e)
{
if (e.Button == null)
return;
if (e.Button.Value == "back")
{
var start = new Menu();
await this.NavigateTo(start);
}
else
{
await this.Device.Send($"Button clicked with Text: {e.Button.Text} and Value {e.Button.Value}");
}
}
}
}
+12
View File
@@ -146,6 +146,16 @@ namespace TelegramBotBaseTest.Tests
await this.NavigateTo(bg);
break;
case "buttongridfilter":
message.Handled = true;
var bg2 = new Controls.ButtonGridPagingForm();
await this.NavigateTo(bg2);
break;
}
@@ -175,6 +185,8 @@ namespace TelegramBotBaseTest.Tests
btn.AddButtonRow(new ButtonBase("#12 ButtonGrid", new CallbackData("a", "buttongrid").Serialize()));
btn.AddButtonRow(new ButtonBase("#13 ButtonGrid Paging & Filter", new CallbackData("a", "buttongridfilter").Serialize()));
await this.Device.Send("Choose your test:", btn);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB