fix: some build & linter warnings

This commit is contained in:
ZavaruKitsu
2022-10-08 19:15:51 +03:00
parent 3f0d109fe2
commit a731e2a8d0
159 changed files with 2738 additions and 3742 deletions
+8 -11
View File
@@ -1,8 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using TelegramBotBase.Sessions;
@@ -13,9 +10,9 @@ namespace TelegramBotBase.Args
/// </summary>
public class BotCommandEventArgs : EventArgs
{
public String Command { get; set; }
public string Command { get; set; }
public List<String> Parameters { get; set; }
public List<string> Parameters { get; set; }
public long DeviceId { get; set; }
@@ -32,13 +29,13 @@ namespace TelegramBotBase.Args
}
public BotCommandEventArgs(String Command, List<String> Parameters, Message Message, long DeviceId, DeviceSession Device)
public BotCommandEventArgs(string command, List<string> parameters, Message message, long deviceId, DeviceSession device)
{
this.Command = Command;
this.Parameters = Parameters;
this.OriginalMessage = Message;
this.DeviceId = DeviceId;
this.Device = Device;
this.Command = command;
this.Parameters = parameters;
OriginalMessage = message;
this.DeviceId = deviceId;
this.Device = device;
}
}
+9 -13
View File
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Form;
@@ -29,21 +25,21 @@ namespace TelegramBotBase.Args
public ButtonClickedEventArgs(ButtonBase button)
{
this.Button = button;
this.Index = -1;
Button = button;
Index = -1;
}
public ButtonClickedEventArgs(ButtonBase button, int Index)
public ButtonClickedEventArgs(ButtonBase button, int index)
{
this.Button = button;
this.Index = Index;
Button = button;
this.Index = index;
}
public ButtonClickedEventArgs(ButtonBase button, int Index, ButtonRow row)
public ButtonClickedEventArgs(ButtonBase button, int index, ButtonRow row)
{
this.Button = button;
this.Index = Index;
this.Row = row;
Button = button;
this.Index = index;
Row = row;
}
}
}
@@ -1,15 +1,12 @@
using System;
using System.Collections.Generic;
using System.Text;
using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Form;
namespace TelegramBotBase.Args
{
public class CheckedChangedEventArgs : EventArgs
{
/// <summary>
/// Contains the index of the row where the button is inside.
/// Contains the index of the row where the button is inside.
/// Contains -1 when it is a layout button or not found.
/// </summary>
public int Index { get; set; }
@@ -32,11 +29,11 @@ namespace TelegramBotBase.Args
}
public CheckedChangedEventArgs(ButtonRow row, int Index, bool Checked)
public CheckedChangedEventArgs(ButtonRow row, int index, bool @checked)
{
this.Row = row;
this.Index = Index;
this.Checked = Checked;
Row = row;
this.Index = index;
this.Checked = @checked;
}
@@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
using Telegram.Bot.Types.Enums;
using TelegramBotBase.Base;
@@ -14,8 +12,8 @@ namespace TelegramBotBase.Args
public GroupChangedEventArgs(MessageType type, MessageResult message)
{
this.Type = type;
this.OriginalMessage = message;
Type = type;
OriginalMessage = message;
}
+1 -5
View File
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TelegramBotBase.Args
{
@@ -12,7 +8,7 @@ namespace TelegramBotBase.Args
public InitEventArgs(params object[] args)
{
this.Args = args;
Args = args;
}
}
}
+10 -18
View File
@@ -1,42 +1,34 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TelegramBotBase.Args
{
public class LoadStateEventArgs
{
public Dictionary<String,object> Values { get; set; }
public Dictionary<string,object> Values { get; set; }
public LoadStateEventArgs()
{
Values = new Dictionary<string, object>();
}
public List<String> Keys
{
get
{
return Values.Keys.ToList();
}
}
public List<string> Keys => Values.Keys.ToList();
public String Get(String key)
public string Get(string key)
{
return Values[key].ToString();
}
public int GetInt(String key)
public int GetInt(string key)
{
int i = 0;
var i = 0;
if (int.TryParse(Values[key].ToString(), out i))
return i;
return 0;
}
public double GetDouble(String key)
public double GetDouble(string key)
{
double d = 0;
if (double.TryParse(Values[key].ToString(), out d))
@@ -45,16 +37,16 @@ namespace TelegramBotBase.Args
return 0;
}
public bool GetBool(String key)
public bool GetBool(string key)
{
bool b = false;
var b = false;
if (bool.TryParse(Values[key].ToString(), out b))
return b;
return false;
}
public object GetObject(String key)
public object GetObject(string key)
{
return Values[key];
}
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using TelegramBotBase.Base;
@@ -18,15 +17,15 @@ namespace TelegramBotBase.Args
public MemberChangeEventArgs()
{
this.Members = new List<User>();
Members = new List<User>();
}
public MemberChangeEventArgs(MessageType type, MessageResult result, params User[] members)
{
this.Type = type;
this.Result = result;
this.Members = members.ToList();
Type = type;
Result = result;
Members = members.ToList();
}
@@ -1,11 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
namespace TelegramBotBase.Args
namespace TelegramBotBase.Args
{
public class MessageDeletedEventArgs
{
@@ -16,7 +9,7 @@ namespace TelegramBotBase.Args
public MessageDeletedEventArgs(int messageId)
{
this.MessageId = messageId;
MessageId = messageId;
}
}
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Sessions;
namespace TelegramBotBase.Base
@@ -16,11 +12,11 @@ namespace TelegramBotBase.Base
public MessageResult Message { get; set; }
public MessageIncomeEventArgs(long DeviceId, DeviceSession Device, MessageResult message)
public MessageIncomeEventArgs(long deviceId, DeviceSession device, MessageResult message)
{
this.DeviceId = DeviceId;
this.Device = Device;
this.Message = message;
this.DeviceId = deviceId;
this.Device = device;
Message = message;
}
@@ -1,27 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using Telegram.Bot.Types;
namespace TelegramBotBase.Args
{
public class MessageReceivedEventArgs
{
public int MessageId
{
get
{
return this.Message.MessageId;
}
}
public int MessageId => Message.MessageId;
public Message Message { get; set; }
public MessageReceivedEventArgs(Message m)
{
this.Message = m;
Message = m;
}
}
+4 -14
View File
@@ -1,21 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
namespace TelegramBotBase.Args
{
public class MessageSentEventArgs : EventArgs
{
public int MessageId
{
get
{
return this.Message.MessageId;
}
}
public int MessageId => Message.MessageId;
public Message Message { get; set; }
@@ -25,10 +15,10 @@ namespace TelegramBotBase.Args
public Type Origin { get; set; }
public MessageSentEventArgs(Message message, Type Origin)
public MessageSentEventArgs(Message message, Type origin)
{
this.Message = message;
this.Origin = Origin;
Message = message;
this.Origin = origin;
}
@@ -1,14 +1,10 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace TelegramBotBase.Args
namespace TelegramBotBase.Args
{
public class PromptDialogCompletedEventArgs
{
public object Tag { get; set; }
public String Value { get; set; }
public string Value { get; set; }
}
}
+2 -4
View File
@@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace TelegramBotBase.Args
{
@@ -9,10 +7,10 @@ namespace TelegramBotBase.Args
public int CurrentView { get; set; }
public RenderViewEventArgs(int ViewIndex)
public RenderViewEventArgs(int viewIndex)
{
CurrentView = ViewIndex;
CurrentView = viewIndex;
}
+7 -9
View File
@@ -1,38 +1,36 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Generic;
namespace TelegramBotBase.Args
{
public class SaveStateEventArgs
{
public Dictionary<String, object> Values { get; set; }
public Dictionary<string, object> Values { get; set; }
public SaveStateEventArgs()
{
Values = new Dictionary<string, object>();
}
public void Set(String key, String value)
public void Set(string key, string value)
{
Values[key] = value;
}
public void SetInt(String key, int value)
public void SetInt(string key, int value)
{
Values[key] = value;
}
public void SetBool(String key, bool value)
public void SetBool(string key, bool value)
{
Values[key] = value;
}
public void SetDouble(String key, double value)
public void SetDouble(string key, double value)
{
Values[key] = value;
}
public void SetObject(String key, object value)
public void SetObject(string key, object value)
{
Values[key] = value;
}
+2 -7
View File
@@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TelegramBotBase.Base;
using TelegramBotBase.Sessions;
using TelegramBotBase.Base;
namespace TelegramBotBase.Args
{
@@ -14,7 +9,7 @@ namespace TelegramBotBase.Args
public SaveStatesEventArgs(StateContainer states)
{
this.States = states;
States = states;
}
}
}
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Sessions;
namespace TelegramBotBase.Base
@@ -13,10 +9,10 @@ namespace TelegramBotBase.Base
public DeviceSession Device { get; set; }
public SessionBeginEventArgs(long DeviceId, DeviceSession Device)
public SessionBeginEventArgs(long deviceId, DeviceSession device)
{
this.DeviceId = DeviceId;
this.Device = Device;
this.DeviceId = deviceId;
this.Device = device;
}
}
}
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Sessions;
namespace TelegramBotBase.Args
@@ -10,7 +6,7 @@ namespace TelegramBotBase.Args
public class SystemExceptionEventArgs : EventArgs
{
public String Command { get; set; }
public string Command { get; set; }
public long DeviceId { get; set; }
@@ -24,12 +20,12 @@ namespace TelegramBotBase.Args
}
public SystemExceptionEventArgs(String Command, long DeviceId, DeviceSession Device, Exception error)
public SystemExceptionEventArgs(string command, long deviceId, DeviceSession device, Exception error)
{
this.Command = Command;
this.DeviceId = DeviceId;
this.Device = Device;
this.Error = error;
this.Command = command;
this.DeviceId = deviceId;
this.Device = device;
Error = error;
}
}
+10 -14
View File
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using TelegramBotBase.Sessions;
@@ -10,13 +6,13 @@ namespace TelegramBotBase.Args
{
public class UnhandledCallEventArgs : EventArgs
{
public String Command { get; set; }
public string Command { get; set; }
public long DeviceId { get; set; }
public DeviceSession Device {get;set;}
public String RawData { get; set; }
public string RawData { get; set; }
public int MessageId { get; set; }
@@ -27,18 +23,18 @@ namespace TelegramBotBase.Args
public UnhandledCallEventArgs()
{
this.Handled = false;
Handled = false;
}
public UnhandledCallEventArgs(String Command,String RawData, long DeviceId, int MessageId, Message message, DeviceSession Device) : this()
public UnhandledCallEventArgs(string command,string rawData, long deviceId, int messageId, Message message, DeviceSession device) : this()
{
this.Command = Command;
this.RawData = RawData;
this.DeviceId = DeviceId;
this.MessageId = MessageId;
this.Message = message;
this.Device = Device;
this.Command = command;
this.RawData = rawData;
this.DeviceId = deviceId;
this.MessageId = messageId;
Message = message;
this.Device = device;
}
}
@@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace TelegramBotBase.Attributes
{
+1 -3
View File
@@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace TelegramBotBase.Attributes
{
@@ -9,7 +7,7 @@ namespace TelegramBotBase.Attributes
/// </summary>
public class SaveState : Attribute
{
public String Key { get; set; }
public string Key { get; set; }
}
}
-1
View File
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TelegramBotBase.Base
+15 -32
View File
@@ -1,8 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using TelegramBotBase.Sessions;
namespace TelegramBotBase.Base
{
@@ -11,17 +8,11 @@ namespace TelegramBotBase.Base
/// </summary>
public class ControlBase
{
public Sessions.DeviceSession Device { get; set; }
public DeviceSession Device { get; set; }
public int ID { get; set; }
public int Id { get; set; }
public String ControlID
{
get
{
return "#c" + this.ID.ToString();
}
}
public string ControlId => "#c" + Id;
/// <summary>
/// Defines if the control should be rendered and invoked with actions
@@ -37,43 +28,35 @@ namespace TelegramBotBase.Base
}
public virtual async Task Load(MessageResult result)
public virtual Task Load(MessageResult result)
{
return Task.CompletedTask;
}
public virtual async Task Action(MessageResult result, String value = null)
public virtual Task Action(MessageResult result, string value = null)
{
return Task.CompletedTask;
}
public virtual async Task Render(MessageResult result)
public virtual Task Render(MessageResult result)
{
return Task.CompletedTask;
}
public virtual async Task Hidden(bool FormClose)
public virtual Task Hidden(bool formClose)
{
return Task.CompletedTask;
}
/// <summary>
/// Will be called on a cleanup.
/// </summary>
/// <returns></returns>
public virtual async Task Cleanup()
public virtual Task Cleanup()
{
return Task.CompletedTask;
}
}
+46 -100
View File
@@ -1,11 +1,10 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.InputFiles;
namespace TelegramBotBase.Base
@@ -21,98 +20,45 @@ namespace TelegramBotBase.Base
public UpdateResult UpdateData { get; set; }
public Contact Contact
{
get
{
return this.Message.Contact;
}
}
public Contact Contact => Message.Contact;
public Location Location
{
get
{
return this.Message.Location;
}
}
public Location Location => Message.Location;
public Document Document
{
get
{
return this.Message.Document;
}
}
public Document Document => Message.Document;
public Audio Audio
{
get
{
return this.Message.Audio;
}
}
public Audio Audio => Message.Audio;
public Video Video
{
get
{
return this.Message.Video;
}
}
public Video Video => Message.Video;
public PhotoSize[] Photos
{
get
{
return this.Message.Photo;
}
}
public PhotoSize[] Photos => Message.Photo;
public Telegram.Bot.Types.Enums.MessageType Type
{
get
{
return this.Message?.Type ?? Telegram.Bot.Types.Enums.MessageType.Unknown;
}
}
public MessageType Type => Message?.Type ?? MessageType.Unknown;
public override Message Message
{
get
{
return this.UpdateData?.Message;
}
}
public override Message Message => UpdateData?.Message;
/// <summary>
/// Returns the FileId of the first reachable element.
/// </summary>
public String FileId
{
get
{
return (this.Document?.FileId ??
this.Audio?.FileId ??
this.Video?.FileId ??
this.Photos.FirstOrDefault()?.FileId);
}
}
public string FileId =>
(Document?.FileId ??
Audio?.FileId ??
Video?.FileId ??
Photos.FirstOrDefault()?.FileId);
public DataResult(UpdateResult update)
{
this.UpdateData = update;
UpdateData = update;
}
public async Task<InputOnlineFile> DownloadDocument()
{
var encryptedContent = new System.IO.MemoryStream();
encryptedContent.SetLength(this.Document.FileSize.Value);
var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Document.FileId, encryptedContent);
var encryptedContent = new MemoryStream();
encryptedContent.SetLength(Document.FileSize.Value);
var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, encryptedContent);
return new InputOnlineFile(encryptedContent, this.Document.FileName);
return new InputOnlineFile(encryptedContent, Document.FileName);
}
@@ -121,10 +67,10 @@ namespace TelegramBotBase.Base
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public async Task DownloadDocument(String path)
public async Task DownloadDocument(string path)
{
var file = await Device.Client.TelegramClient.GetFileAsync(this.Document.FileId);
FileStream fs = new FileStream(path, FileMode.Create);
var file = await Device.Client.TelegramClient.GetFileAsync(Document.FileId);
var fs = new FileStream(path, FileMode.Create);
await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
fs.Close();
fs.Dispose();
@@ -136,8 +82,8 @@ namespace TelegramBotBase.Base
/// <returns></returns>
public async Task<byte[]> DownloadRawDocument()
{
MemoryStream ms = new MemoryStream();
await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Document.FileId, ms);
var ms = new MemoryStream();
await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, ms);
return ms.ToArray();
}
@@ -145,7 +91,7 @@ namespace TelegramBotBase.Base
/// Downloads a document and returns it as string. (txt,csv,etc) Default encoding ist UTF8.
/// </summary>
/// <returns></returns>
public async Task<String> DownloadRawTextDocument()
public async Task<string> DownloadRawTextDocument()
{
return await DownloadRawTextDocument(Encoding.UTF8);
}
@@ -154,10 +100,10 @@ namespace TelegramBotBase.Base
/// Downloads a document and returns it as string. (txt,csv,etc)
/// </summary>
/// <returns></returns>
public async Task<String> DownloadRawTextDocument(Encoding encoding)
public async Task<string> DownloadRawTextDocument(Encoding encoding)
{
MemoryStream ms = new MemoryStream();
await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Document.FileId, ms);
var ms = new MemoryStream();
await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Document.FileId, ms);
ms.Position = 0;
@@ -168,17 +114,17 @@ namespace TelegramBotBase.Base
public async Task<InputOnlineFile> DownloadVideo()
{
var encryptedContent = new System.IO.MemoryStream();
encryptedContent.SetLength(this.Video.FileSize.Value);
var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Video.FileId, encryptedContent);
var encryptedContent = new MemoryStream();
encryptedContent.SetLength(Video.FileSize.Value);
var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Video.FileId, encryptedContent);
return new InputOnlineFile(encryptedContent, "");
}
public async Task DownloadVideo(String path)
public async Task DownloadVideo(string path)
{
var file = await Device.Client.TelegramClient.GetFileAsync(this.Video.FileId);
FileStream fs = new FileStream(path, FileMode.Create);
var file = await Device.Client.TelegramClient.GetFileAsync(Video.FileId);
var fs = new FileStream(path, FileMode.Create);
await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
fs.Close();
fs.Dispose();
@@ -186,17 +132,17 @@ namespace TelegramBotBase.Base
public async Task<InputOnlineFile> DownloadAudio()
{
var encryptedContent = new System.IO.MemoryStream();
encryptedContent.SetLength(this.Audio.FileSize.Value);
var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Audio.FileId, encryptedContent);
var encryptedContent = new MemoryStream();
encryptedContent.SetLength(Audio.FileSize.Value);
var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(Audio.FileId, encryptedContent);
return new InputOnlineFile(encryptedContent, "");
}
public async Task DownloadAudio(String path)
public async Task DownloadAudio(string path)
{
var file = await Device.Client.TelegramClient.GetFileAsync(this.Audio.FileId);
FileStream fs = new FileStream(path, FileMode.Create);
var file = await Device.Client.TelegramClient.GetFileAsync(Audio.FileId);
var fs = new FileStream(path, FileMode.Create);
await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
fs.Close();
fs.Dispose();
@@ -204,19 +150,19 @@ namespace TelegramBotBase.Base
public async Task<InputOnlineFile> DownloadPhoto(int index)
{
var photo = this.Photos[index];
var encryptedContent = new System.IO.MemoryStream();
var photo = Photos[index];
var encryptedContent = new MemoryStream();
encryptedContent.SetLength(photo.FileSize.Value);
var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(photo.FileId, encryptedContent);
return new InputOnlineFile(encryptedContent, "");
}
public async Task DownloadPhoto(int index, String path)
public async Task DownloadPhoto(int index, string path)
{
var photo = this.Photos[index];
var photo = Photos[index];
var file = await Device.Client.TelegramClient.GetFileAsync(photo.FileId);
FileStream fs = new FileStream(path, FileMode.Create);
var fs = new FileStream(path, FileMode.Create);
await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
fs.Close();
fs.Dispose();
+66 -82
View File
@@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
@@ -27,7 +26,7 @@ namespace TelegramBotBase.Form
/// <summary>
/// has this formular already been disposed ?
/// </summary>
public bool IsDisposed { get; set; } = false;
public bool IsDisposed { get; set; }
public List<ControlBase> Controls { get; set; }
@@ -35,33 +34,33 @@ namespace TelegramBotBase.Form
public EventHandlerList Events = new EventHandlerList();
private static object __evInit = new object();
private static readonly object EvInit = new object();
private static object __evOpened = new object();
private static readonly object EvOpened = new object();
private static object __evClosed = new object();
private static readonly object EvClosed = new object();
public FormBase()
{
this.Controls = new List<Base.ControlBase>();
Controls = new List<ControlBase>();
}
public FormBase(MessageClient Client) : this()
public FormBase(MessageClient client) : this()
{
this.Client = Client;
this.Client = client;
}
public async Task OnInit(InitEventArgs e)
{
var handler = this.Events[__evInit]?.GetInvocationList().Cast<AsyncEventHandler<InitEventArgs>>();
var handler = Events[EvInit]?.GetInvocationList().Cast<AsyncEventHandler<InitEventArgs>>();
if (handler == null)
return;
foreach (var h in handler)
{
await Async.InvokeAllAsync<InitEventArgs>(h, this, e);
await h.InvokeAllAsync(this, e);
}
}
@@ -70,27 +69,21 @@ namespace TelegramBotBase.Form
///// </summary>
public event AsyncEventHandler<InitEventArgs> Init
{
add
{
this.Events.AddHandler(__evInit, value);
}
remove
{
this.Events.RemoveHandler(__evInit, value);
}
add => Events.AddHandler(EvInit, value);
remove => Events.RemoveHandler(EvInit, value);
}
public async Task OnOpened(EventArgs e)
{
var handler = this.Events[__evOpened]?.GetInvocationList().Cast<AsyncEventHandler<EventArgs>>();
var handler = Events[EvOpened]?.GetInvocationList().Cast<AsyncEventHandler<EventArgs>>();
if (handler == null)
return;
foreach (var h in handler)
{
await Async.InvokeAllAsync<EventArgs>(h, this, e);
await h.InvokeAllAsync(this, e);
}
}
@@ -100,27 +93,21 @@ namespace TelegramBotBase.Form
/// <returns></returns>
public event AsyncEventHandler<EventArgs> Opened
{
add
{
this.Events.AddHandler(__evOpened, value);
}
remove
{
this.Events.RemoveHandler(__evOpened, value);
}
add => Events.AddHandler(EvOpened, value);
remove => Events.RemoveHandler(EvOpened, value);
}
public async Task OnClosed(EventArgs e)
{
var handler = this.Events[__evClosed]?.GetInvocationList().Cast<AsyncEventHandler<EventArgs>>();
var handler = Events[EvClosed]?.GetInvocationList().Cast<AsyncEventHandler<EventArgs>>();
if (handler == null)
return;
foreach (var h in handler)
{
await Async.InvokeAllAsync<EventArgs>(h, this, e);
await h.InvokeAllAsync(this, e);
}
}
@@ -131,14 +118,8 @@ namespace TelegramBotBase.Form
/// <returns></returns>
public event AsyncEventHandler<EventArgs> Closed
{
add
{
this.Events.AddHandler(__evClosed, value);
}
remove
{
this.Events.RemoveHandler(__evClosed, value);
}
add => Events.AddHandler(EvClosed, value);
remove => Events.RemoveHandler(EvClosed, value);
}
/// <summary>
@@ -146,9 +127,9 @@ namespace TelegramBotBase.Form
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public virtual async Task ReturnFromModal(ModalDialog modal)
public virtual Task ReturnFromModal(ModalDialog modal)
{
return Task.CompletedTask;
}
@@ -156,17 +137,19 @@ namespace TelegramBotBase.Form
/// Pre to form close, cleanup all controls
/// </summary>
/// <returns></returns>
public async Task CloseControls()
public Task CloseControls()
{
foreach (var b in this.Controls)
foreach (var b in Controls)
{
b.Cleanup().Wait();
}
return Task.CompletedTask;
}
public virtual async Task PreLoad(MessageResult message)
public virtual Task PreLoad(MessageResult message)
{
return Task.CompletedTask;
}
/// <summary>
@@ -179,7 +162,7 @@ namespace TelegramBotBase.Form
//Looking for the control by id, if not listened, raise event for all
if (message.RawData?.StartsWith("#c") ?? false)
{
var c = this.Controls.FirstOrDefault(a => a.ControlID == message.RawData.Split('_')[0]);
var c = Controls.FirstOrDefault(a => a.ControlId == message.RawData.Split('_')[0]);
if (c != null)
{
await c.Load(message);
@@ -187,7 +170,7 @@ namespace TelegramBotBase.Form
}
}
foreach (var b in this.Controls)
foreach (var b in Controls)
{
if (!b.Enabled)
continue;
@@ -201,9 +184,9 @@ namespace TelegramBotBase.Form
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public virtual async Task Load(MessageResult message)
public virtual Task Load(MessageResult message)
{
return Task.CompletedTask;
}
/// <summary>
@@ -211,9 +194,9 @@ namespace TelegramBotBase.Form
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public virtual async Task Edited(MessageResult message)
public virtual Task Edited(MessageResult message)
{
return Task.CompletedTask;
}
@@ -227,7 +210,7 @@ namespace TelegramBotBase.Form
//Looking for the control by id, if not listened, raise event for all
if (message.RawData.StartsWith("#c"))
{
var c = this.Controls.FirstOrDefault(a => a.ControlID == message.RawData.Split('_')[0]);
var c = Controls.FirstOrDefault(a => a.ControlId == message.RawData.Split('_')[0]);
if (c != null)
{
await c.Action(message, message.RawData.Split('_')[1]);
@@ -235,7 +218,7 @@ namespace TelegramBotBase.Form
}
}
foreach (var b in this.Controls)
foreach (var b in Controls)
{
if (!b.Enabled)
continue;
@@ -252,9 +235,9 @@ namespace TelegramBotBase.Form
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public virtual async Task Action(MessageResult message)
public virtual Task Action(MessageResult message)
{
return Task.CompletedTask;
}
/// <summary>
@@ -262,9 +245,9 @@ namespace TelegramBotBase.Form
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public virtual async Task SentData(DataResult message)
public virtual Task SentData(DataResult message)
{
return Task.CompletedTask;
}
/// <summary>
@@ -274,7 +257,7 @@ namespace TelegramBotBase.Form
/// <returns></returns>
public virtual async Task RenderControls(MessageResult message)
{
foreach (var b in this.Controls)
foreach (var b in Controls)
{
if (!b.Enabled)
continue;
@@ -288,9 +271,9 @@ namespace TelegramBotBase.Form
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public virtual async Task Render(MessageResult message)
public virtual Task Render(MessageResult message)
{
return Task.CompletedTask;
}
@@ -302,7 +285,7 @@ namespace TelegramBotBase.Form
/// <returns></returns>
public virtual async Task NavigateTo(FormBase newForm, params object[] args)
{
DeviceSession ds = this.Device;
var ds = Device;
if (ds == null)
return;
@@ -311,11 +294,11 @@ namespace TelegramBotBase.Form
ds.PreviousForm = ds.ActiveForm;
ds.ActiveForm = newForm;
newForm.Client = this.Client;
newForm.Client = Client;
newForm.Device = ds;
//Notify prior to close
foreach (var b in this.Controls)
foreach (var b in Controls)
{
if (!b.Enabled)
continue;
@@ -323,13 +306,13 @@ namespace TelegramBotBase.Form
await b.Hidden(true);
}
this.CloseControls().Wait();
CloseControls().Wait();
await this.OnClosed(new EventArgs());
await OnClosed(EventArgs.Empty);
await newForm.OnInit(new InitEventArgs(args));
await newForm.OnOpened(new EventArgs());
await newForm.OnOpened(EventArgs.Empty);
}
/// <summary>
@@ -339,7 +322,7 @@ namespace TelegramBotBase.Form
/// <returns></returns>
public virtual async Task OpenModal(ModalDialog newForm, params object[] args)
{
DeviceSession ds = this.Device;
var ds = Device;
if (ds == null)
return;
@@ -359,7 +342,7 @@ namespace TelegramBotBase.Form
await CloseModal(newForm, parentForm);
};
foreach (var b in this.Controls)
foreach (var b in Controls)
{
if (!b.Enabled)
continue;
@@ -369,14 +352,14 @@ namespace TelegramBotBase.Form
await newForm.OnInit(new InitEventArgs(args));
await newForm.OnOpened(new EventArgs());
await newForm.OnOpened(EventArgs.Empty);
}
public async Task CloseModal(ModalDialog modalForm, FormBase oldForm)
public Task CloseModal(ModalDialog modalForm, FormBase oldForm)
{
DeviceSession ds = this.Device;
var ds = Device;
if (ds == null)
return;
return Task.CompletedTask;
if (modalForm == null)
throw new Exception("No modal form");
@@ -386,6 +369,7 @@ namespace TelegramBotBase.Form
ds.PreviousForm = ds.ActiveForm;
ds.ActiveForm = oldForm;
return Task.CompletedTask;
}
/// <summary>
@@ -395,12 +379,12 @@ namespace TelegramBotBase.Form
public void AddControl(ControlBase control)
{
//Duplicate check
if (this.Controls.Contains(control))
if (Controls.Contains(control))
throw new ArgumentException("Control has been already added.");
control.ID = this.Controls.Count + 1;
control.Device = this.Device;
this.Controls.Add(control);
control.Id = Controls.Count + 1;
control.Device = Device;
Controls.Add(control);
control.Init();
}
@@ -411,12 +395,12 @@ namespace TelegramBotBase.Form
/// <param name="control"></param>
public void RemoveControl(ControlBase control)
{
if (!this.Controls.Contains(control))
if (!Controls.Contains(control))
return;
control.Cleanup().Wait();
this.Controls.Remove(control);
Controls.Remove(control);
}
/// <summary>
@@ -424,11 +408,11 @@ namespace TelegramBotBase.Form
/// </summary>
public void RemoveAllControls()
{
foreach(var c in this.Controls)
foreach(var c in Controls)
{
c.Cleanup().Wait();
this.Controls.Remove(c);
Controls.Remove(c);
}
}
@@ -437,9 +421,9 @@ namespace TelegramBotBase.Form
/// </summary>
public void Dispose()
{
this.Client = null;
this.Device = null;
this.IsDisposed = true;
Client = null;
Device = null;
IsDisposed = true;
}
}
}
+38 -50
View File
@@ -1,17 +1,14 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Telegram.Bot.Exceptions;
using Telegram.Bot;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Extensions.Polling;
using Telegram.Bot.Types;
namespace TelegramBotBase.Base
{
@@ -22,13 +19,13 @@ namespace TelegramBotBase.Base
{
public String APIKey { get; set; }
public string ApiKey { get; set; }
public ITelegramBotClient TelegramClient { get; set; }
private EventHandlerList __Events { get; set; } = new EventHandlerList();
private EventHandlerList Events { get; set; } = new EventHandlerList();
private static object __evOnMessageLoop = new object();
private static readonly object EvOnMessageLoop = new object();
private static object __evOnMessage = new object();
@@ -36,21 +33,21 @@ namespace TelegramBotBase.Base
private static object __evCallbackQuery = new object();
CancellationTokenSource __cancellationTokenSource;
private CancellationTokenSource _cancellationTokenSource;
public MessageClient(String APIKey)
public MessageClient(string apiKey)
{
this.APIKey = APIKey;
this.TelegramClient = new Telegram.Bot.TelegramBotClient(APIKey);
this.ApiKey = apiKey;
TelegramClient = new TelegramBotClient(apiKey);
Prepare();
}
public MessageClient(String APIKey, HttpClient proxy)
public MessageClient(string apiKey, HttpClient proxy)
{
this.APIKey = APIKey;
this.TelegramClient = new Telegram.Bot.TelegramBotClient(APIKey, proxy);
this.ApiKey = apiKey;
TelegramClient = new TelegramBotClient(apiKey, proxy);
Prepare();
@@ -58,9 +55,9 @@ namespace TelegramBotBase.Base
public MessageClient(String APIKey, Uri proxyUrl, NetworkCredential credential = null)
public MessageClient(string apiKey, Uri proxyUrl, NetworkCredential credential = null)
{
this.APIKey = APIKey;
this.ApiKey = apiKey;
var proxy = new WebProxy(proxyUrl)
{
@@ -71,7 +68,7 @@ namespace TelegramBotBase.Base
new HttpClientHandler { Proxy = proxy, UseProxy = true }
);
this.TelegramClient = new Telegram.Bot.TelegramBotClient(APIKey, httpClient);
TelegramClient = new TelegramBotClient(apiKey, httpClient);
Prepare();
}
@@ -79,12 +76,12 @@ namespace TelegramBotBase.Base
/// <summary>
/// Initializes the client with a proxy
/// </summary>
/// <param name="APIKey"></param>
/// <param name="apiKey"></param>
/// <param name="proxyHost">i.e. 127.0.0.1</param>
/// <param name="proxyPort">i.e. 10000</param>
public MessageClient(String APIKey, String proxyHost, int proxyPort)
public MessageClient(string apiKey, string proxyHost, int proxyPort)
{
this.APIKey = APIKey;
this.ApiKey = apiKey;
var proxy = new WebProxy(proxyHost, proxyPort);
@@ -92,17 +89,17 @@ namespace TelegramBotBase.Base
new HttpClientHandler { Proxy = proxy, UseProxy = true }
);
this.TelegramClient = new Telegram.Bot.TelegramBotClient(APIKey, httpClient);
TelegramClient = new TelegramBotClient(apiKey, httpClient);
Prepare();
}
public MessageClient(String APIKey, Telegram.Bot.TelegramBotClient Client)
public MessageClient(string apiKey, TelegramBotClient client)
{
this.APIKey = APIKey;
this.TelegramClient = Client;
this.ApiKey = apiKey;
TelegramClient = client;
Prepare();
}
@@ -110,7 +107,7 @@ namespace TelegramBotBase.Base
public void Prepare()
{
this.TelegramClient.Timeout = new TimeSpan(0, 0, 30);
TelegramClient.Timeout = new TimeSpan(0, 0, 30);
}
@@ -118,19 +115,16 @@ namespace TelegramBotBase.Base
public void StartReceiving()
{
__cancellationTokenSource = new CancellationTokenSource();
_cancellationTokenSource = new CancellationTokenSource();
var receiverOptions = new ReceiverOptions
{
AllowedUpdates = { } // receive all update types
};
var receiverOptions = new ReceiverOptions();
this.TelegramClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, receiverOptions, __cancellationTokenSource.Token);
TelegramClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, receiverOptions, _cancellationTokenSource.Token);
}
public void StopReceiving()
{
__cancellationTokenSource.Cancel();
_cancellationTokenSource.Cancel();
}
@@ -143,9 +137,9 @@ namespace TelegramBotBase.Base
public Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
{
if (exception is ApiRequestException exAPI)
if (exception is ApiRequestException exApi)
{
Console.WriteLine($"Telegram API Error:\n[{exAPI.ErrorCode}]\n{exAPI.Message}");
Console.WriteLine($"Telegram API Error:\n[{exApi.ErrorCode}]\n{exApi.Message}");
}
else
{
@@ -159,9 +153,9 @@ namespace TelegramBotBase.Base
/// This will return the current list of bot commands.
/// </summary>
/// <returns></returns>
public async Task<BotCommand[]> GetBotCommands(BotCommandScope scope = null, String languageCode = null)
public async Task<BotCommand[]> GetBotCommands(BotCommandScope scope = null, string languageCode = null)
{
return await this.TelegramClient.GetMyCommandsAsync(scope, languageCode);
return await TelegramClient.GetMyCommandsAsync(scope, languageCode);
}
@@ -170,18 +164,18 @@ namespace TelegramBotBase.Base
/// </summary>
/// <param name="botcommands"></param>
/// <returns></returns>
public async Task SetBotCommands(List<BotCommand> botcommands, BotCommandScope scope = null, String languageCode = null)
public async Task SetBotCommands(List<BotCommand> botcommands, BotCommandScope scope = null, string languageCode = null)
{
await this.TelegramClient.SetMyCommandsAsync(botcommands, scope, languageCode);
await TelegramClient.SetMyCommandsAsync(botcommands, scope, languageCode);
}
/// <summary>
/// This will delete the current list of bot commands.
/// </summary>
/// <returns></returns>
public async Task DeleteBotCommands(BotCommandScope scope = null, String languageCode = null)
public async Task DeleteBotCommands(BotCommandScope scope = null, string languageCode = null)
{
await this.TelegramClient.DeleteMyCommandsAsync(scope, languageCode);
await TelegramClient.DeleteMyCommandsAsync(scope, languageCode);
}
@@ -191,19 +185,13 @@ namespace TelegramBotBase.Base
public event Async.AsyncEventHandler<UpdateResult> MessageLoop
{
add
{
this.__Events.AddHandler(__evOnMessageLoop, value);
}
remove
{
this.__Events.RemoveHandler(__evOnMessageLoop, value);
}
add => Events.AddHandler(EvOnMessageLoop, value);
remove => Events.RemoveHandler(EvOnMessageLoop, value);
}
public void OnMessageLoop(UpdateResult update)
{
(this.__Events[__evOnMessageLoop] as Async.AsyncEventHandler<UpdateResult>)?.Invoke(this, update);
(Events[EvOnMessageLoop] as Async.AsyncEventHandler<UpdateResult>)?.Invoke(this, update);
}
+31 -91
View File
@@ -1,110 +1,56 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot;
using Newtonsoft.Json;
using Telegram.Bot.Types;
using TelegramBotBase.Sessions;
using Telegram.Bot.Types.Enums;
namespace TelegramBotBase.Base
{
public class MessageResult : ResultBase
{
public Telegram.Bot.Types.Update UpdateData { get; set; }
public Update UpdateData { get; set; }
/// <summary>
/// Returns the Device/ChatId
/// </summary>
public override long DeviceId
{
get
{
return this.UpdateData?.Message?.Chat?.Id
?? this.UpdateData?.EditedMessage?.Chat.Id
?? this.UpdateData?.CallbackQuery.Message?.Chat.Id
?? Device?.DeviceId
?? 0;
}
}
public override long DeviceId =>
UpdateData?.Message?.Chat?.Id
?? UpdateData?.EditedMessage?.Chat.Id
?? UpdateData?.CallbackQuery.Message?.Chat.Id
?? Device?.DeviceId
?? 0;
/// <summary>
/// The message id
/// </summary>
public new int MessageId
{
get
{
return this.UpdateData?.Message?.MessageId
?? this.Message?.MessageId
?? this.UpdateData?.CallbackQuery?.Message?.MessageId
?? 0;
}
}
public new int MessageId =>
UpdateData?.Message?.MessageId
?? Message?.MessageId
?? UpdateData?.CallbackQuery?.Message?.MessageId
?? 0;
public String Command
{
get
{
return this.UpdateData?.Message?.Text ?? "";
}
}
public string Command => UpdateData?.Message?.Text ?? "";
public String MessageText
{
get
{
return this.UpdateData?.Message?.Text ?? "";
}
}
public string MessageText => UpdateData?.Message?.Text ?? "";
public Telegram.Bot.Types.Enums.MessageType MessageType
{
get
{
return Message?.Type ?? Telegram.Bot.Types.Enums.MessageType.Unknown;
}
}
public Message Message
{
get
{
return this.UpdateData?.Message
?? this.UpdateData?.EditedMessage
?? this.UpdateData?.ChannelPost
?? this.UpdateData?.EditedChannelPost
?? this.UpdateData?.CallbackQuery?.Message;
}
}
public MessageType MessageType => Message?.Type ?? MessageType.Unknown;
/// <summary>
/// Is this an action ? (i.e. button click)
/// </summary>
public bool IsAction
{
get
{
return (this.UpdateData.CallbackQuery != null);
}
}
public bool IsAction => (UpdateData.CallbackQuery != null);
/// <summary>
/// Is this a command ? Starts with a slash '/' and a command
/// </summary>
public bool IsBotCommand
{
get
{
return (this.MessageText.StartsWith("/"));
}
}
public bool IsBotCommand => (MessageText.StartsWith("/"));
/// <summary>
/// Returns a List of all parameters which has been sent with the command itself (i.e. /start 123 456 789 => 123,456,789)
/// </summary>
public List<String> BotCommandParameters
public List<string> BotCommandParameters
{
get
{
@@ -112,21 +58,21 @@ namespace TelegramBotBase.Base
return new List<string>();
//Split by empty space and skip first entry (command itself), return as list
return this.MessageText.Split(' ').Skip(1).ToList();
return MessageText.Split(' ').Skip(1).ToList();
}
}
/// <summary>
/// Returns just the command (i.e. /start 1 2 3 => /start)
/// </summary>
public String BotCommand
public string BotCommand
{
get
{
if (!IsBotCommand)
return null;
return this.MessageText.Split(' ')[0];
return MessageText.Split(' ')[0];
}
}
@@ -137,13 +83,7 @@ namespace TelegramBotBase.Base
public bool Handled { get; set; } = false;
public String RawData
{
get
{
return this.UpdateData?.CallbackQuery?.Data;
}
}
public string RawData => UpdateData?.CallbackQuery?.Data;
public T GetData<T>()
where T : class
@@ -151,7 +91,7 @@ namespace TelegramBotBase.Base
T cd = null;
try
{
cd = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(this.RawData);
cd = JsonConvert.DeserializeObject<T>(RawData);
return cd;
}
@@ -168,16 +108,16 @@ namespace TelegramBotBase.Base
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public async Task ConfirmAction(String message = "", bool showAlert = false, String urlToOpen = null)
public async Task ConfirmAction(string message = "", bool showAlert = false, string urlToOpen = null)
{
await this.Device.ConfirmAction(this.UpdateData.CallbackQuery.Id, message, showAlert, urlToOpen);
await Device.ConfirmAction(UpdateData.CallbackQuery.Id, message, showAlert, urlToOpen);
}
public override async Task DeleteMessage()
{
try
{
await base.DeleteMessage(this.MessageId);
await base.DeleteMessage(MessageId);
}
catch
{
@@ -190,9 +130,9 @@ namespace TelegramBotBase.Base
}
public MessageResult(Telegram.Bot.Types.Update update)
public MessageResult(Update update)
{
this.UpdateData = update;
UpdateData = update;
}
+5 -13
View File
@@ -1,9 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot;
using Telegram.Bot.Types;
using TelegramBotBase.Sessions;
namespace TelegramBotBase.Base
@@ -18,15 +16,9 @@ namespace TelegramBotBase.Base
public virtual long DeviceId { get; set; }
public int MessageId
{
get
{
return this.Message.MessageId;
}
}
public int MessageId => Message.MessageId;
public virtual Telegram.Bot.Types.Message Message { get; set; }
public virtual Message Message { get; set; }
/// <summary>
/// Deletes the current message
@@ -35,7 +27,7 @@ namespace TelegramBotBase.Base
/// <returns></returns>
public virtual async Task DeleteMessage()
{
await DeleteMessage(this.MessageId);
await DeleteMessage(MessageId);
}
/// <summary>
@@ -47,7 +39,7 @@ namespace TelegramBotBase.Base
{
try
{
await Device.Client.TelegramClient.DeleteMessageAsync(this.DeviceId, (messageId == -1 ? this.MessageId : messageId));
await Device.Client.TelegramClient.DeleteMessageAsync(DeviceId, (messageId == -1 ? MessageId : messageId));
}
catch
{
+3 -5
View File
@@ -1,11 +1,9 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TelegramBotBase.Base
{
public partial class StateContainer
public class StateContainer
{
public List<StateEntry> States { get; set; }
@@ -27,7 +25,7 @@ namespace TelegramBotBase.Base
public StateContainer()
{
this.States = new List<StateEntry>();
States = new List<StateEntry>();
}
}
+6 -9
View File
@@ -1,8 +1,5 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Text;
namespace TelegramBotBase.Base
{
@@ -18,26 +15,26 @@ namespace TelegramBotBase.Base
/// <summary>
/// Contains the Username (on privat chats) or Group title on groups/channels.
/// </summary>
public String ChatTitle { get; set; }
public string ChatTitle { get; set; }
/// <summary>
/// Contains additional values to save.
/// </summary>
public Dictionary<String, object> Values { get; set; }
public Dictionary<string, object> Values { get; set; }
/// <summary>
/// Contains the full qualified namespace of the form to used for reload it via reflection.
/// </summary>
public String FormUri {get;set;}
public string FormUri {get;set;}
/// <summary>
/// Contains the assembly, where to find that form.
/// </summary>
public String QualifiedName { get; set; }
public string QualifiedName { get; set; }
public StateEntry()
{
this.Values = new Dictionary<string, object>();
Values = new Dictionary<string, object>();
}
}
+13 -37
View File
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Telegram.Bot.Types;
using Telegram.Bot.Types;
using TelegramBotBase.Sessions;
namespace TelegramBotBase.Base
@@ -14,46 +10,26 @@ namespace TelegramBotBase.Base
RawData = rawData;
Device = device;
}
/// <summary>
/// Returns the Device/ChatId
/// </summary>
public override long DeviceId
{
get
{
return this.RawData?.Message?.Chat?.Id
?? this.RawData?.CallbackQuery?.Message?.Chat?.Id
?? Device?.DeviceId
?? 0;
}
}
public override long DeviceId =>
RawData?.Message?.Chat?.Id
?? RawData?.CallbackQuery?.Message?.Chat?.Id
?? Device?.DeviceId
?? 0;
public Update RawData { get; set; }
public override Message Message
{
get
{
return RawData?.Message
?? RawData?.EditedMessage
?? RawData?.ChannelPost
?? RawData?.EditedChannelPost
?? RawData?.CallbackQuery?.Message;
}
}
public DeviceSession Device
{
get;
set;
}
public override Message Message =>
RawData?.Message
?? RawData?.EditedMessage
?? RawData?.ChannelPost
?? RawData?.EditedChannelPost
?? RawData?.CallbackQuery?.Message;
}
}
+83 -104
View File
@@ -31,7 +31,7 @@ namespace TelegramBotBase
/// <summary>
/// Your TelegramBot APIKey
/// </summary>
public String APIKey { get; set; } = "";
public string ApiKey { get; set; } = "";
/// <summary>
/// List of all running/active sessions
@@ -46,19 +46,19 @@ namespace TelegramBotBase
#region "Events"
private EventHandlerList __Events = new EventHandlerList();
private readonly EventHandlerList _events = new EventHandlerList();
private static object __evSessionBegins = new object();
private static readonly object EvSessionBegins = new object();
private static object __evMessage = new object();
private static readonly object EvMessage = new object();
private static object __evSystemCall = new object();
public delegate Task BotCommandEventHandler(object sender, BotCommandEventArgs e);
private static object __evException = new object();
private static readonly object EvException = new object();
private static object __evUnhandledCall = new object();
private static readonly object EvUnhandledCall = new object();
#endregion
@@ -81,22 +81,24 @@ namespace TelegramBotBase
/// <summary>
/// All internal used settings.
/// </summary>
public Dictionary<eSettings, uint> SystemSettings { get; private set; }
public Dictionary<ESettings, uint> SystemSettings { get; private set; }
public BotBase()
{
this.SystemSettings = new Dictionary<eSettings, uint>();
SystemSettings = new Dictionary<ESettings, uint>();
SetSetting(eSettings.MaxNumberOfRetries, 5);
SetSetting(eSettings.NavigationMaximum, 10);
SetSetting(eSettings.LogAllMessages, false);
SetSetting(eSettings.SkipAllMessages, false);
SetSetting(eSettings.SaveSessionsOnConsoleExit, false);
SetSetting(ESettings.MaxNumberOfRetries, 5);
SetSetting(ESettings.NavigationMaximum, 10);
SetSetting(ESettings.LogAllMessages, false);
SetSetting(ESettings.SkipAllMessages, false);
SetSetting(ESettings.SaveSessionsOnConsoleExit, false);
this.BotCommandScopes = new Dictionary<BotCommandScope, List<BotCommand>>();
BotCommandScopes = new Dictionary<BotCommandScope, List<BotCommand>>();
this.Sessions = new SessionBase();
this.Sessions.BotBase = this;
Sessions = new SessionBase
{
BotBase = this
};
}
@@ -106,38 +108,38 @@ namespace TelegramBotBase
/// </summary>
public void Start()
{
if (this.Client == null)
if (Client == null)
return;
this.Client.MessageLoop += Client_MessageLoop;
Client.MessageLoop += Client_MessageLoop;
if (this.StateMachine != null)
if (StateMachine != null)
{
this.Sessions.LoadSessionStates(this.StateMachine);
Sessions.LoadSessionStates(StateMachine);
}
//Enable auto session saving
if (this.GetSetting(eSettings.SaveSessionsOnConsoleExit, false))
if (GetSetting(ESettings.SaveSessionsOnConsoleExit, false))
{
TelegramBotBase.Tools.Console.SetHandler(() =>
Tools.Console.SetHandler(() =>
{
this.Sessions.SaveSessionStates();
Sessions.SaveSessionStates();
});
}
DeviceSession.MaxNumberOfRetries = this.GetSetting(eSettings.MaxNumberOfRetries, 5);
DeviceSession.MaxNumberOfRetries = GetSetting(ESettings.MaxNumberOfRetries, 5);
this.Client.StartReceiving();
Client.StartReceiving();
}
private async Task Client_MessageLoop(object sender, UpdateResult e)
{
DeviceSession ds = this.Sessions.GetSession(e.DeviceId);
var ds = Sessions.GetSession(e.DeviceId);
if (ds == null)
{
ds = this.Sessions.StartSession(e.DeviceId).GetAwaiter().GetResult();
ds = Sessions.StartSession(e.DeviceId).GetAwaiter().GetResult();
e.Device = ds;
ds.LastMessage = e.RawData.Message;
@@ -146,7 +148,7 @@ namespace TelegramBotBase
var mr = new MessageResult(e.RawData);
int i = 0;
var i = 0;
//Should formulars get navigated (allow maximum of 10, to dont get loops)
do
@@ -160,7 +162,7 @@ namespace TelegramBotBase
mr.IsFirstHandler = false;
} while (ds.FormSwitched && i < this.GetSetting(eSettings.NavigationMaximum, 10));
} while (ds.FormSwitched && i < GetSetting(ESettings.NavigationMaximum, 10));
}
@@ -169,15 +171,15 @@ namespace TelegramBotBase
/// </summary>
public void Stop()
{
if (this.Client == null)
if (Client == null)
return;
this.Client.MessageLoop -= Client_MessageLoop;
Client.MessageLoop -= Client_MessageLoop;
this.Client.StopReceiving();
Client.StopReceiving();
this.Sessions.SaveSessionStates();
Sessions.SaveSessionStates();
}
/// <summary>
@@ -185,14 +187,14 @@ namespace TelegramBotBase
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public async Task SentToAll(String message)
public async Task SentToAll(string message)
{
if (this.Client == null)
if (Client == null)
return;
foreach (var s in this.Sessions.SessionList)
foreach (var s in Sessions.SessionList)
{
await this.Client.TelegramClient.SendTextMessageAsync(s.Key, message);
await Client.TelegramClient.SendTextMessageAsync(s.Key, message);
}
}
@@ -201,29 +203,30 @@ namespace TelegramBotBase
/// <summary>
/// This will invoke the full message loop for the device even when no "userevent" like message or action has been raised.
/// </summary>
/// <param name="DeviceId">Contains the device/chat id of the device to update.</param>
public async Task InvokeMessageLoop(long DeviceId)
/// <param name="deviceId">Contains the device/chat id of the device to update.</param>
public async Task InvokeMessageLoop(long deviceId)
{
var mr = new MessageResult();
mr.UpdateData = new Update()
var mr = new MessageResult
{
Message = new Message()
UpdateData = new Update()
{
Message = new Message()
}
};
await InvokeMessageLoop(DeviceId, mr);
await InvokeMessageLoop(deviceId, mr);
}
/// <summary>
/// This will invoke the full message loop for the device even when no "userevent" like message or action has been raised.
/// </summary>
/// <param name="DeviceId">Contains the device/chat id of the device to update.</param>
/// <param name="deviceId">Contains the device/chat id of the device to update.</param>
/// <param name="e"></param>
public async Task InvokeMessageLoop(long DeviceId, MessageResult e)
public async Task InvokeMessageLoop(long deviceId, MessageResult e)
{
try
{
DeviceSession ds = this.Sessions.GetSession(DeviceId);
var ds = Sessions.GetSession(deviceId);
e.Device = ds;
await MessageLoopFactory.MessageLoop(this, ds, new UpdateResult(e.UpdateData, ds), e);
@@ -231,8 +234,8 @@ namespace TelegramBotBase
}
catch (Exception ex)
{
DeviceSession ds = this.Sessions.GetSession(DeviceId);
OnException(new SystemExceptionEventArgs(e.Message.Text, DeviceId, ds, ex));
var ds = Sessions.GetSession(deviceId);
OnException(new SystemExceptionEventArgs(e.Message.Text, deviceId, ds, ex));
}
}
@@ -252,17 +255,17 @@ namespace TelegramBotBase
/// </summary>
public async Task UploadBotCommands()
{
foreach (var bs in this.BotCommandScopes)
foreach (var bs in BotCommandScopes)
{
if(bs.Value !=null)
{
await this.Client.SetBotCommands(bs.Value, bs.Key);
await Client.SetBotCommands(bs.Value, bs.Key);
}
else
{
await this.Client.DeleteBotCommands(bs.Key);
await Client.DeleteBotCommands(bs.Key);
}
}
}
@@ -271,9 +274,9 @@ namespace TelegramBotBase
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
public bool IsKnownBotCommand(String command)
public bool IsKnownBotCommand(string command)
{
foreach (var scope in this.BotCommandScopes)
foreach (var scope in BotCommandScopes)
{
if (scope.Value.Any(a => "/" + a.Command == command))
return true;
@@ -286,20 +289,20 @@ namespace TelegramBotBase
/// Could set a variety of settings to improve the bot handling.
/// </summary>
/// <param name="set"></param>
/// <param name="Value"></param>
public void SetSetting(eSettings set, uint Value)
/// <param name="value"></param>
public void SetSetting(ESettings set, uint value)
{
this.SystemSettings[set] = Value;
SystemSettings[set] = value;
}
/// <summary>
/// Could set a variety of settings to improve the bot handling.
/// </summary>
/// <param name="set"></param>
/// <param name="Value"></param>
public void SetSetting(eSettings set, bool Value)
/// <param name="value"></param>
public void SetSetting(ESettings set, bool value)
{
this.SystemSettings[set] = (Value ? 1u : 0u);
SystemSettings[set] = (value ? 1u : 0u);
}
/// <summary>
@@ -308,12 +311,12 @@ namespace TelegramBotBase
/// <param name="set"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public uint GetSetting(eSettings set, uint defaultValue)
public uint GetSetting(ESettings set, uint defaultValue)
{
if (!this.SystemSettings.ContainsKey(set))
if (!SystemSettings.ContainsKey(set))
return defaultValue;
return this.SystemSettings[set];
return SystemSettings[set];
}
/// <summary>
@@ -322,12 +325,12 @@ namespace TelegramBotBase
/// <param name="set"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public bool GetSetting(eSettings set, bool defaultValue)
public bool GetSetting(ESettings set, bool defaultValue)
{
if (!this.SystemSettings.ContainsKey(set))
if (!SystemSettings.ContainsKey(set))
return defaultValue;
return this.SystemSettings[set] == 0u ? false : true;
return SystemSettings[set] == 0u ? false : true;
}
#region "Events"
@@ -338,19 +341,13 @@ namespace TelegramBotBase
public event EventHandler<SessionBeginEventArgs> SessionBegins
{
add
{
this.__Events.AddHandler(__evSessionBegins, value);
}
remove
{
this.__Events.RemoveHandler(__evSessionBegins, value);
}
add => _events.AddHandler(EvSessionBegins, value);
remove => _events.RemoveHandler(EvSessionBegins, value);
}
public void OnSessionBegins(SessionBeginEventArgs e)
{
(this.__Events[__evSessionBegins] as EventHandler<SessionBeginEventArgs>)?.Invoke(this, e);
(_events[EvSessionBegins] as EventHandler<SessionBeginEventArgs>)?.Invoke(this, e);
}
@@ -359,19 +356,13 @@ namespace TelegramBotBase
/// </summary>
public event EventHandler<MessageIncomeEventArgs> Message
{
add
{
this.__Events.AddHandler(__evMessage, value);
}
remove
{
this.__Events.RemoveHandler(__evMessage, value);
}
add => _events.AddHandler(EvMessage, value);
remove => _events.RemoveHandler(EvMessage, value);
}
public void OnMessage(MessageIncomeEventArgs e)
{
(this.__Events[__evMessage] as EventHandler<MessageIncomeEventArgs>)?.Invoke(this, e);
(_events[EvMessage] as EventHandler<MessageIncomeEventArgs>)?.Invoke(this, e);
}
@@ -383,7 +374,7 @@ namespace TelegramBotBase
public async Task OnBotCommand(BotCommandEventArgs e)
{
if (this.BotCommand != null)
if (BotCommand != null)
await BotCommand(this, e);
}
@@ -392,19 +383,13 @@ namespace TelegramBotBase
/// </summary>
public event EventHandler<SystemExceptionEventArgs> Exception
{
add
{
this.__Events.AddHandler(__evException, value);
}
remove
{
this.__Events.RemoveHandler(__evException, value);
}
add => _events.AddHandler(EvException, value);
remove => _events.RemoveHandler(EvException, value);
}
public void OnException(SystemExceptionEventArgs e)
{
(this.__Events[__evException] as EventHandler<SystemExceptionEventArgs>)?.Invoke(this, e);
(_events[EvException] as EventHandler<SystemExceptionEventArgs>)?.Invoke(this, e);
}
@@ -413,19 +398,13 @@ namespace TelegramBotBase
/// </summary>
public event EventHandler<UnhandledCallEventArgs> UnhandledCall
{
add
{
this.__Events.AddHandler(__evUnhandledCall, value);
}
remove
{
this.__Events.RemoveHandler(__evUnhandledCall, value);
}
add => _events.AddHandler(EvUnhandledCall, value);
remove => _events.RemoveHandler(EvUnhandledCall, value);
}
public void OnUnhandledCall(UnhandledCallEventArgs e)
{
(this.__Events[__evUnhandledCall] as EventHandler<UnhandledCallEventArgs>)?.Invoke(this, e);
(_events[EvUnhandledCall] as EventHandler<UnhandledCallEventArgs>)?.Invoke(this, e);
}
+78 -56
View File
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using Telegram.Bot;
using Telegram.Bot.Types;
using TelegramBotBase.Base;
@@ -11,29 +10,27 @@ using TelegramBotBase.Factories;
using TelegramBotBase.Form;
using TelegramBotBase.Interfaces;
using TelegramBotBase.Localizations;
using TelegramBotBase.MessageLoops;
using TelegramBotBase.States;
namespace TelegramBotBase.Builder
{
public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, IStartFormSelectionStage, IBuildingStage, INetworkingSelectionStage, IBotCommandsStage, ISessionSerializationStage, ILanguageSelectionStage
{
private string _apiKey;
String _apiKey = null;
private IStartFormFactory _factory;
IStartFormFactory _factory = null;
MessageClient _client = null;
private MessageClient _client;
/// <summary>
/// Contains different Botcommands for different areas.
/// </summary>
Dictionary<BotCommandScope, List<BotCommand>> _BotCommandScopes { get; set; } = new Dictionary<BotCommandScope, List<BotCommand>>();
private Dictionary<BotCommandScope, List<BotCommand>> BotCommandScopes { get; set; } = new Dictionary<BotCommandScope, List<BotCommand>>();
//List<BotCommand> _botcommands = new List<BotCommand>();
private IStateMachine _statemachine;
IStateMachine _statemachine = null;
IMessageLoopFactory _messageloopfactory = null;
private IMessageLoopFactory _messageLoopFactory;
private BotBaseBuilder()
{
@@ -49,15 +46,15 @@ namespace TelegramBotBase.Builder
public IMessageLoopSelectionStage WithAPIKey(string apiKey)
{
this._apiKey = apiKey;
_apiKey = apiKey;
return this;
}
public IBuildingStage QuickStart(string apiKey, Type StartForm)
{
this._apiKey = apiKey;
this._factory = new Factories.DefaultStartFormFactory(StartForm);
_apiKey = apiKey;
_factory = new DefaultStartFormFactory(StartForm);
DefaultMessageLoop();
@@ -76,8 +73,8 @@ namespace TelegramBotBase.Builder
public IBuildingStage QuickStart<T>(string apiKey)
where T : FormBase
{
this._apiKey = apiKey;
this._factory = new Factories.DefaultStartFormFactory(typeof(T));
_apiKey = apiKey;
_factory = new DefaultStartFormFactory(typeof(T));
DefaultMessageLoop();
@@ -94,8 +91,8 @@ namespace TelegramBotBase.Builder
public IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory)
{
this._apiKey = apiKey;
this._factory = StartFormFactory;
_apiKey = apiKey;
_factory = StartFormFactory;
DefaultMessageLoop();
@@ -117,7 +114,7 @@ namespace TelegramBotBase.Builder
public IStartFormSelectionStage DefaultMessageLoop()
{
_messageloopfactory = new MessageLoops.FormBaseMessageLoop();
_messageLoopFactory = new FormBaseMessageLoop();
return this;
}
@@ -125,7 +122,7 @@ namespace TelegramBotBase.Builder
public IStartFormSelectionStage MinimalMessageLoop()
{
_messageloopfactory = new MessageLoops.MinimalMessageLoop();
_messageLoopFactory = new MinimalMessageLoop();
return this;
}
@@ -133,7 +130,7 @@ namespace TelegramBotBase.Builder
public IStartFormSelectionStage CustomMessageLoop(IMessageLoopFactory messageLoopClass)
{
_messageloopfactory = messageLoopClass;
_messageLoopFactory = messageLoopClass;
return this;
}
@@ -141,7 +138,7 @@ namespace TelegramBotBase.Builder
public IStartFormSelectionStage CustomMessageLoop<T>()
where T : class, new()
{
_messageloopfactory = typeof(T).GetConstructor(new Type[] { })?.Invoke(new object[] { }) as IMessageLoopFactory;
_messageLoopFactory = typeof(T).GetConstructor(new Type[] { })?.Invoke(new object[] { }) as IMessageLoopFactory;
return this;
}
@@ -153,33 +150,33 @@ namespace TelegramBotBase.Builder
public INetworkingSelectionStage WithStartForm(Type startFormClass)
{
this._factory = new Factories.DefaultStartFormFactory(startFormClass);
_factory = new DefaultStartFormFactory(startFormClass);
return this;
}
public INetworkingSelectionStage WithStartForm<T>()
where T : FormBase, new()
{
this._factory = new Factories.DefaultStartFormFactory(typeof(T));
_factory = new DefaultStartFormFactory(typeof(T));
return this;
}
public INetworkingSelectionStage WithServiceProvider(Type startFormClass, IServiceProvider serviceProvider)
{
this._factory = new ServiceProviderStartFormFactory(startFormClass, serviceProvider);
_factory = new ServiceProviderStartFormFactory(startFormClass, serviceProvider);
return this;
}
public INetworkingSelectionStage WithServiceProvider<T>(IServiceProvider serviceProvider)
where T : FormBase
{
this._factory = new ServiceProviderStartFormFactory<T>(serviceProvider);
_factory = new ServiceProviderStartFormFactory<T>(serviceProvider);
return this;
}
public INetworkingSelectionStage WithStartFormFactory(IStartFormFactory factory)
{
this._factory = factory;
_factory = factory;
return this;
}
@@ -191,39 +188,64 @@ namespace TelegramBotBase.Builder
public IBotCommandsStage WithProxy(string proxyAddress)
{
var url = new Uri(proxyAddress);
_client = new MessageClient(_apiKey, url);
_client.TelegramClient.Timeout = new TimeSpan(0, 1, 0);
_client = new MessageClient(_apiKey, url)
{
TelegramClient =
{
Timeout = new TimeSpan(0, 1, 0)
}
};
return this;
}
public IBotCommandsStage NoProxy()
{
_client = new MessageClient(_apiKey);
_client.TelegramClient.Timeout = new TimeSpan(0, 1, 0);
_client = new MessageClient(_apiKey)
{
TelegramClient =
{
Timeout = new TimeSpan(0, 1, 0)
}
};
return this;
}
public IBotCommandsStage WithBotClient(TelegramBotClient tgclient)
{
_client = new MessageClient(_apiKey, tgclient);
_client.TelegramClient.Timeout = new TimeSpan(0, 1, 0);
_client = new MessageClient(_apiKey, tgclient)
{
TelegramClient =
{
Timeout = new TimeSpan(0, 1, 0)
}
};
return this;
}
public IBotCommandsStage WithHostAndPort(string proxyHost, int proxyPort)
{
_client = new MessageClient(_apiKey, proxyHost, proxyPort);
_client.TelegramClient.Timeout = new TimeSpan(0, 1, 0);
_client = new MessageClient(_apiKey, proxyHost, proxyPort)
{
TelegramClient =
{
Timeout = new TimeSpan(0, 1, 0)
}
};
return this;
}
public IBotCommandsStage WithHttpClient(HttpClient tgclient)
{
_client = new MessageClient(_apiKey, tgclient);
_client.TelegramClient.Timeout = new TimeSpan(0, 1, 0);
_client = new MessageClient(_apiKey, tgclient)
{
TelegramClient =
{
Timeout = new TimeSpan(0, 1, 0)
}
};
return this;
}
@@ -240,7 +262,7 @@ namespace TelegramBotBase.Builder
public ISessionSerializationStage OnlyStart()
{
_BotCommandScopes.Start("Starts the bot");
BotCommandScopes.Start("Starts the bot");
return this;
@@ -248,15 +270,15 @@ namespace TelegramBotBase.Builder
public ISessionSerializationStage DefaultCommands()
{
_BotCommandScopes.Start("Starts the bot");
_BotCommandScopes.Help("Should show you some help");
_BotCommandScopes.Settings("Should show you some settings");
BotCommandScopes.Start("Starts the bot");
BotCommandScopes.Help("Should show you some help");
BotCommandScopes.Settings("Should show you some settings");
return this;
}
public ISessionSerializationStage CustomCommands(Action<Dictionary<BotCommandScope, List<BotCommand>>> action)
{
action?.Invoke(_BotCommandScopes);
action?.Invoke(BotCommandScopes);
return this;
}
@@ -272,26 +294,26 @@ namespace TelegramBotBase.Builder
public ILanguageSelectionStage UseSerialization(IStateMachine machine)
{
this._statemachine = machine;
_statemachine = machine;
return this;
}
public ILanguageSelectionStage UseJSON(string path)
{
this._statemachine = new JSONStateMachine(path);
_statemachine = new JsonStateMachine(path);
return this;
}
public ILanguageSelectionStage UseSimpleJSON(string path)
{
this._statemachine = new SimpleJSONStateMachine(path);
_statemachine = new SimpleJsonStateMachine(path);
return this;
}
public ILanguageSelectionStage UseXML(string path)
{
this._statemachine = new XMLStateMachine(path);
_statemachine = new XmlStateMachine(path);
return this;
}
@@ -307,19 +329,19 @@ namespace TelegramBotBase.Builder
public IBuildingStage UseEnglish()
{
Localizations.Default.Language = new Localizations.English();
Default.Language = new English();
return this;
}
public IBuildingStage UseGerman()
{
Localizations.Default.Language = new Localizations.German();
Default.Language = new German();
return this;
}
public IBuildingStage Custom(Localization language)
{
Localizations.Default.Language = language;
Default.Language = language;
return this;
}
@@ -328,20 +350,20 @@ namespace TelegramBotBase.Builder
public BotBase Build()
{
var bb = new BotBase();
bb.APIKey = _apiKey;
bb.StartFormFactory = _factory;
bb.Client = _client;
var bb = new BotBase
{
ApiKey = _apiKey,
StartFormFactory = _factory,
Client = _client
};
bb.Sessions.Client = bb.Client;
bb.BotCommandScopes = _BotCommandScopes;
bb.BotCommandScopes = BotCommandScopes;
bb.StateMachine = _statemachine;
bb.MessageLoopFactory = _messageloopfactory;
bb.MessageLoopFactory = _messageLoopFactory;
bb.MessageLoopFactory.UnhandledCall += bb.MessageLoopFactory_UnhandledCall;
@@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
using TelegramBotBase.Form;
using TelegramBotBase.Interfaces;
@@ -13,7 +11,7 @@ namespace TelegramBotBase.Builder.Interfaces
/// </summary>
/// <param name="apiKey"></param>
/// <returns></returns>
IMessageLoopSelectionStage WithAPIKey(String apiKey);
IMessageLoopSelectionStage WithAPIKey(string apiKey);
/// <summary>
@@ -23,7 +21,7 @@ namespace TelegramBotBase.Builder.Interfaces
/// <param name="apiKey"></param>
/// <param name="StartForm"></param>
/// <returns></returns>
IBuildingStage QuickStart(String apiKey, Type StartForm);
IBuildingStage QuickStart(string apiKey, Type StartForm);
/// <summary>
/// Quick and easy way to create a BotBase instance.
@@ -31,7 +29,7 @@ namespace TelegramBotBase.Builder.Interfaces
/// </summary>
/// <param name="apiKey"></param>
/// <returns></returns>
IBuildingStage QuickStart<T>(String apiKey) where T : FormBase;
IBuildingStage QuickStart<T>(string apiKey) where T : FormBase;
/// <summary>
/// Quick and easy way to create a BotBase instance.
@@ -40,6 +38,6 @@ namespace TelegramBotBase.Builder.Interfaces
/// <param name="apiKey"></param>
/// <param name="StartFormFactory"></param>
/// <returns></returns>
IBuildingStage QuickStart(String apiKey, IStartFormFactory StartFormFactory);
IBuildingStage QuickStart(string apiKey, IStartFormFactory StartFormFactory);
}
}
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Text;
using Telegram.Bot.Types;
namespace TelegramBotBase.Builder.Interfaces
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace TelegramBotBase.Builder.Interfaces
namespace TelegramBotBase.Builder.Interfaces
{
public interface IBuildingStage
{
@@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
using TelegramBotBase.Localizations;
using TelegramBotBase.Localizations;
namespace TelegramBotBase.Builder.Interfaces
{
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
using TelegramBotBase.Form;
using TelegramBotBase.Interfaces;
using TelegramBotBase.Interfaces;
namespace TelegramBotBase.Builder.Interfaces
{
@@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Net.Http;
using Telegram.Bot;
namespace TelegramBotBase.Builder.Interfaces
@@ -14,7 +11,7 @@ namespace TelegramBotBase.Builder.Interfaces
/// </summary>
/// <param name="proxyAddress"></param>
/// <returns></returns>
IBotCommandsStage WithProxy(String proxyAddress);
IBotCommandsStage WithProxy(string proxyAddress);
/// <summary>
/// Do not choose a proxy as network configuration.
@@ -37,7 +34,7 @@ namespace TelegramBotBase.Builder.Interfaces
/// <param name="proxyHost"></param>
/// <param name="Port"></param>
/// <returns></returns>
IBotCommandsStage WithHostAndPort(String proxyHost, int Port);
IBotCommandsStage WithHostAndPort(string proxyHost, int Port);
/// <summary>
/// Uses a custom http client.
@@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
using TelegramBotBase.Interfaces;
using TelegramBotBase.Interfaces;
namespace TelegramBotBase.Builder.Interfaces
{
@@ -27,7 +24,7 @@ namespace TelegramBotBase.Builder.Interfaces
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
ILanguageSelectionStage UseJSON(String path);
ILanguageSelectionStage UseJSON(string path);
/// <summary>
@@ -35,7 +32,7 @@ namespace TelegramBotBase.Builder.Interfaces
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
ILanguageSelectionStage UseSimpleJSON(String path);
ILanguageSelectionStage UseSimpleJSON(string path);
/// <summary>
@@ -43,7 +40,7 @@ namespace TelegramBotBase.Builder.Interfaces
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
ILanguageSelectionStage UseXML(String path);
ILanguageSelectionStage UseXML(string path);
}
}
@@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
using TelegramBotBase.Form;
using TelegramBotBase.Interfaces;
+13 -16
View File
@@ -1,8 +1,5 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Telegram.Bot.Types;
namespace TelegramBotBase.Commands
@@ -15,7 +12,7 @@ namespace TelegramBotBase.Commands
/// <param name="cmds"></param>
/// <param name="command"></param>
/// <param name="description"></param>
public static void Add(this Dictionary<BotCommandScope, List<BotCommand>> cmds, String command, String description, BotCommandScope scope = null)
public static void Add(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string command, string description, BotCommandScope scope = null)
{
if (scope == null)
{
@@ -26,11 +23,11 @@ namespace TelegramBotBase.Commands
if (item.Value != null)
{
item.Value.Add(new BotCommand() { Command = command, Description = description });
item.Value.Add(new BotCommand { Command = command, Description = description });
}
else
{
cmds.Add(scope, new List<BotCommand> { new BotCommand() { Command = command, Description = description } });
cmds.Add(scope, new List<BotCommand> { new BotCommand { Command = command, Description = description } });
}
}
@@ -64,33 +61,33 @@ namespace TelegramBotBase.Commands
/// </summary>
/// <param name="cmds"></param>
/// <param name="description"></param>
public static void Start(this Dictionary<BotCommandScope, List<BotCommand>> cmds, String description) => Add(cmds, "start", description, null);
public static void Start(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string description) => Add(cmds, "start", description);
/// <summary>
/// Adding the default /help command with a description.
/// </summary>
/// <param name="cmds"></param>
/// <param name="description"></param>
public static void Help(this Dictionary<BotCommandScope, List<BotCommand>> cmds, String description) => Add(cmds, "help", description, null);
public static void Help(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string description) => Add(cmds, "help", description);
/// <summary>
/// Adding the default /settings command with a description.
/// </summary>
/// <param name="cmds"></param>
/// <param name="description"></param>
public static void Settings(this Dictionary<BotCommandScope, List<BotCommand>> cmds, String description) => Add(cmds, "settings", description, null);
public static void Settings(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string description) => Add(cmds, "settings", description);
/// <summary>
/// Clears all default commands.
/// </summary>
/// <param name="cmds"></param>
public static void ClearDefaultCommands(this Dictionary<BotCommandScope, List<BotCommand>> cmds) => Clear(cmds, null);
public static void ClearDefaultCommands(this Dictionary<BotCommandScope, List<BotCommand>> cmds) => Clear(cmds);
/// <summary>
/// Clears all commands of a specific device.
/// </summary>
/// <param name="cmds"></param>
public static void ClearChatCommands(this Dictionary<BotCommandScope, List<BotCommand>> cmds, long DeviceId) => Clear(cmds, new BotCommandScopeChat() { ChatId = DeviceId });
public static void ClearChatCommands(this Dictionary<BotCommandScope, List<BotCommand>> cmds, long deviceId) => Clear(cmds, new BotCommandScopeChat { ChatId = deviceId });
/// <summary>
/// Adding a chat command with a description.
@@ -98,7 +95,7 @@ namespace TelegramBotBase.Commands
/// <param name="cmds"></param>
/// <param name="command"></param>
/// <param name="description"></param>
public static void AddChatCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, long DeviceId, String command, String description) => Add(cmds, command, description, new BotCommandScopeChat() { ChatId = DeviceId });
public static void AddChatCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, long deviceId, string command, string description) => Add(cmds, command, description, new BotCommandScopeChat { ChatId = deviceId });
/// <summary>
/// Adding a group command with a description.
@@ -106,7 +103,7 @@ namespace TelegramBotBase.Commands
/// <param name="cmds"></param>
/// <param name="command"></param>
/// <param name="description"></param>
public static void AddGroupCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, String command, String description) => Add(cmds, command, description, new BotCommandScopeAllGroupChats());
public static void AddGroupCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string command, string description) => Add(cmds, command, description, new BotCommandScopeAllGroupChats());
/// <summary>
/// Clears all group commands.
@@ -120,7 +117,7 @@ namespace TelegramBotBase.Commands
/// <param name="cmds"></param>
/// <param name="command"></param>
/// <param name="description"></param>
public static void AddGroupAdminCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, String command, String description) => Add(cmds, command, description, new BotCommandScopeAllChatAdministrators());
public static void AddGroupAdminCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string command, string description) => Add(cmds, command, description, new BotCommandScopeAllChatAdministrators());
/// <summary>
/// Clears all group admin commands.
@@ -134,7 +131,7 @@ namespace TelegramBotBase.Commands
/// <param name="cmds"></param>
/// <param name="command"></param>
/// <param name="description"></param>
public static void AddPrivateChatCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, String command, String description) => Add(cmds, command, description, new BotCommandScopeAllPrivateChats());
public static void AddPrivateChatCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds, string command, string description) => Add(cmds, command, description, new BotCommandScopeAllPrivateChats());
/// <summary>
/// Clears all private commands.
+1 -7
View File
@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TelegramBotBase.Constants
namespace TelegramBotBase.Constants
{
public static class Telegram
{
+140 -171
View File
@@ -1,50 +1,43 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.SymbolStore;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Datasources;
using TelegramBotBase.DataSources;
using TelegramBotBase.Enums;
using TelegramBotBase.Exceptions;
using TelegramBotBase.Form;
using TelegramBotBase.Localizations;
using static TelegramBotBase.Base.Async;
namespace TelegramBotBase.Controls.Hybrid
{
public class ButtonGrid : Base.ControlBase
public class ButtonGrid : ControlBase
{
public String Title { get; set; } = Localizations.Default.Language["ButtonGrid_Title"];
public string Title { get; set; } = Default.Language["ButtonGrid_Title"];
public String ConfirmationText { get; set; } = "";
public string ConfirmationText { get; set; } = "";
private bool RenderNecessary = true;
private bool _renderNecessary = true;
private static readonly object __evButtonClicked = new object();
private static readonly object EvButtonClicked = new object();
private readonly EventHandlerList Events = new EventHandlerList();
private readonly EventHandlerList _events = new EventHandlerList();
/// <summary>
///
///
/// </summary>
[Obsolete("This property is obsolete. Please use the DataSource property instead.")]
public ButtonForm ButtonsForm
{
get
{
return DataSource.ButtonForm;
}
set
{
DataSource = new ButtonFormDataSource(value);
}
get => DataSource.ButtonForm;
set => DataSource = new ButtonFormDataSource(value);
}
/// <summary>
@@ -88,23 +81,23 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
public bool EnableSearch { get; set; } = false;
public String SearchQuery { get; set; }
public string SearchQuery { get; set; }
public eNavigationBarVisibility NavigationBarVisibility { get; set; } = eNavigationBarVisibility.always;
public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always;
/// <summary>
/// Index of the current page
/// </summary>
public int CurrentPageIndex { get; set; } = 0;
public int CurrentPageIndex { get; set; }
public String PreviousPageLabel = Localizations.Default.Language["ButtonGrid_PreviousPage"];
public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"];
public String NextPageLabel = Localizations.Default.Language["ButtonGrid_NextPage"];
public string NextPageLabel = Default.Language["ButtonGrid_NextPage"];
public String NoItemsLabel = Localizations.Default.Language["ButtonGrid_NoItems"];
public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"];
public String SearchLabel = Localizations.Default.Language["ButtonGrid_SearchFeature"];
public string SearchLabel = Default.Language["ButtonGrid_SearchFeature"];
/// <summary>
/// Layout of the buttons which should be displayed always on top.
@@ -119,89 +112,80 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary>
/// Defines which type of Button Keyboard should be rendered.
/// </summary>
public eKeyboardType KeyboardType
public EKeyboardType KeyboardType
{
get
{
return m_eKeyboardType;
}
get => _mEKeyboardType;
set
{
if (m_eKeyboardType != value)
if (_mEKeyboardType != value)
{
this.RenderNecessary = true;
_renderNecessary = true;
Cleanup().Wait();
m_eKeyboardType = value;
_mEKeyboardType = value;
}
}
}
private eKeyboardType m_eKeyboardType = eKeyboardType.ReplyKeyboard;
private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard;
public ButtonGrid()
{
this.DataSource = new ButtonFormDataSource();
DataSource = new ButtonFormDataSource();
}
public ButtonGrid(eKeyboardType type) : this()
public ButtonGrid(EKeyboardType type) : this()
{
m_eKeyboardType = type;
_mEKeyboardType = type;
}
public ButtonGrid(ButtonForm form)
{
this.DataSource = new ButtonFormDataSource(form);
DataSource = new ButtonFormDataSource(form);
}
public event AsyncEventHandler<ButtonClickedEventArgs> ButtonClicked
{
add
{
this.Events.AddHandler(__evButtonClicked, value);
}
remove
{
this.Events.RemoveHandler(__evButtonClicked, value);
}
add => _events.AddHandler(EvButtonClicked, value);
remove => _events.RemoveHandler(EvButtonClicked, value);
}
public async Task OnButtonClicked(ButtonClickedEventArgs e)
{
var handler = this.Events[__evButtonClicked]?.GetInvocationList().Cast<AsyncEventHandler<ButtonClickedEventArgs>>();
var handler = _events[EvButtonClicked]?.GetInvocationList().Cast<AsyncEventHandler<ButtonClickedEventArgs>>();
if (handler == null)
return;
foreach (var h in handler)
{
await Async.InvokeAllAsync<ButtonClickedEventArgs>(h, this, e);
await h.InvokeAllAsync(this, e);
}
}
public override void Init()
{
this.Device.MessageDeleted += Device_MessageDeleted;
Device.MessageDeleted += Device_MessageDeleted;
}
private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e)
{
if (this.MessageId == null)
if (MessageId == null)
return;
if (e.MessageId != this.MessageId)
if (e.MessageId != MessageId)
return;
this.MessageId = null;
MessageId = null;
}
public async override Task Load(MessageResult result)
public override async Task Load(MessageResult result)
{
if (this.KeyboardType != eKeyboardType.ReplyKeyboard)
if (KeyboardType != EKeyboardType.ReplyKeyboard)
return;
if (!result.IsFirstHandler)
@@ -212,7 +196,7 @@ namespace TelegramBotBase.Controls.Hybrid
var matches = new List<ButtonRow>();
ButtonRow match = null;
int index = -1;
var index = -1;
if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false)
{
@@ -244,7 +228,7 @@ namespace TelegramBotBase.Controls.Hybrid
check:
//Remove button click message
if (this.DeleteReplyMessage)
if (DeleteReplyMessage)
await Device.DeleteMessage(result.MessageId);
if (match != null)
@@ -258,39 +242,39 @@ namespace TelegramBotBase.Controls.Hybrid
if (result.MessageText == PreviousPageLabel)
{
if (this.CurrentPageIndex > 0)
this.CurrentPageIndex--;
if (CurrentPageIndex > 0)
CurrentPageIndex--;
this.Updated();
Updated();
}
else if (result.MessageText == NextPageLabel)
{
if (this.CurrentPageIndex < this.PageCount - 1)
this.CurrentPageIndex++;
if (CurrentPageIndex < PageCount - 1)
CurrentPageIndex++;
this.Updated();
Updated();
}
else if (this.EnableSearch)
else if (EnableSearch)
{
if (result.MessageText.StartsWith("🔍"))
{
//Sent note about searching
if (this.SearchQuery == null)
if (SearchQuery == null)
{
await this.Device.Send(this.SearchLabel);
await Device.Send(SearchLabel);
}
this.SearchQuery = null;
this.Updated();
SearchQuery = null;
Updated();
return;
}
this.SearchQuery = result.MessageText;
SearchQuery = result.MessageText;
if (this.SearchQuery != null && this.SearchQuery != "")
if (SearchQuery != null && SearchQuery != "")
{
this.CurrentPageIndex = 0;
this.Updated();
CurrentPageIndex = 0;
Updated();
}
}
@@ -299,7 +283,7 @@ namespace TelegramBotBase.Controls.Hybrid
}
public async override Task Action(MessageResult result, string value = null)
public override async Task Action(MessageResult result, string value = null)
{
if (result.Handled)
return;
@@ -308,13 +292,13 @@ namespace TelegramBotBase.Controls.Hybrid
return;
//Find clicked button depending on Text or Value (depending on markup type)
if (this.KeyboardType != eKeyboardType.InlineKeyBoard)
if (KeyboardType != EKeyboardType.InlineKeyBoard)
return;
await result.ConfirmAction(this.ConfirmationText ?? "");
await result.ConfirmAction(ConfirmationText ?? "");
ButtonRow match = null;
int index = -1;
var index = -1;
if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false)
{
@@ -358,18 +342,18 @@ namespace TelegramBotBase.Controls.Hybrid
{
case "$previous$":
if (this.CurrentPageIndex > 0)
this.CurrentPageIndex--;
if (CurrentPageIndex > 0)
CurrentPageIndex--;
this.Updated();
Updated();
break;
case "$next$":
if (this.CurrentPageIndex < this.PageCount - 1)
this.CurrentPageIndex++;
if (CurrentPageIndex < PageCount - 1)
CurrentPageIndex++;
this.Updated();
Updated();
break;
}
@@ -381,49 +365,49 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
private void CheckGrid()
{
switch (m_eKeyboardType)
switch (_mEKeyboardType)
{
case eKeyboardType.InlineKeyBoard:
case EKeyboardType.InlineKeyBoard:
if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !this.EnablePaging)
if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging)
{
throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows };
throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows };
}
if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols)
{
throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols };
throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols };
}
break;
case eKeyboardType.ReplyKeyboard:
case EKeyboardType.ReplyKeyboard:
if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !this.EnablePaging)
if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging)
{
throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows };
throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows };
}
if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols)
{
throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols };
throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols };
}
break;
}
}
public async override Task Render(MessageResult result)
public override async Task Render(MessageResult result)
{
if (!this.RenderNecessary)
if (!_renderNecessary)
return;
//Check for rows and column limits
CheckGrid();
this.RenderNecessary = false;
_renderNecessary = false;
ButtonForm form = this.DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (this.EnableSearch ? this.SearchQuery : null));
var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (EnableSearch ? SearchQuery : null));
//if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
@@ -435,42 +419,42 @@ namespace TelegramBotBase.Controls.Hybrid
// form = form.Duplicate();
//}
if (this.EnablePaging)
if (EnablePaging)
{
IntegratePagingView(form);
}
if (this.HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
{
form.InsertButtonRow(0, this.HeadLayoutButtonRow);
form.InsertButtonRow(0, HeadLayoutButtonRow);
}
if (this.SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
{
if (this.IsNavigationBarVisible)
if (IsNavigationBarVisible)
{
form.InsertButtonRow(2, this.SubHeadLayoutButtonRow);
form.InsertButtonRow(2, SubHeadLayoutButtonRow);
}
else
{
form.InsertButtonRow(1, this.SubHeadLayoutButtonRow);
form.InsertButtonRow(1, SubHeadLayoutButtonRow);
}
}
Message m = null;
switch (this.KeyboardType)
switch (KeyboardType)
{
//Reply Keyboard could only be updated with a new keyboard.
case eKeyboardType.ReplyKeyboard:
case EKeyboardType.ReplyKeyboard:
if (form.Count == 0)
{
if (this.MessageId != null)
if (MessageId != null)
{
await this.Device.HideReplyKeyboard();
this.MessageId = null;
await Device.HideReplyKeyboard();
MessageId = null;
}
return;
@@ -491,39 +475,39 @@ namespace TelegramBotBase.Controls.Hybrid
var rkm = (ReplyKeyboardMarkup)form;
rkm.ResizeKeyboard = this.ResizeKeyboard;
rkm.OneTimeKeyboard = this.OneTimeKeyboard;
m = await this.Device.Send(this.Title, rkm, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false);
rkm.ResizeKeyboard = ResizeKeyboard;
rkm.OneTimeKeyboard = OneTimeKeyboard;
m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
//Prevent flicker of keyboard
if (this.DeletePreviousMessage && this.MessageId != null)
await this.Device.DeleteMessage(this.MessageId.Value);
if (DeletePreviousMessage && MessageId != null)
await Device.DeleteMessage(MessageId.Value);
break;
case eKeyboardType.InlineKeyBoard:
case EKeyboardType.InlineKeyBoard:
//Try to edit message if message id is available
//When the returned message is null then the message has been already deleted, resend it
if (this.MessageId != null)
if (MessageId != null)
{
m = await this.Device.Edit(this.MessageId.Value, this.Title, (InlineKeyboardMarkup)form);
m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form);
if (m != null)
{
this.MessageId = m.MessageId;
MessageId = m.MessageId;
return;
}
}
//When no message id is available or it has been deleted due the use of AutoCleanForm re-render automatically
m = await this.Device.Send(this.Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false);
m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
break;
}
if (m != null)
{
this.MessageId = m.MessageId;
MessageId = m.MessageId;
}
@@ -531,23 +515,23 @@ namespace TelegramBotBase.Controls.Hybrid
private void IntegratePagingView(ButtonForm dataForm)
{
//No Items
//No Items
if (dataForm.Rows == 0)
{
dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$"));
}
if (this.IsNavigationBarVisible)
if (IsNavigationBarVisible)
{
//🔍
ButtonRow row = new ButtonRow();
var row = new ButtonRow();
row.Add(new ButtonBase(PreviousPageLabel, "$previous$"));
row.Add(new ButtonBase(String.Format(Localizations.Default.Language["ButtonGrid_CurrentPage"], this.CurrentPageIndex + 1, this.PageCount), "$site$"));
row.Add(new ButtonBase(string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), "$site$"));
row.Add(new ButtonBase(NextPageLabel, "$next$"));
if (this.EnableSearch)
if (EnableSearch)
{
row.Insert(2, new ButtonBase("🔍 " + (this.SearchQuery ?? ""), "$search$"));
row.Insert(2, new ButtonBase("🔍 " + (SearchQuery ?? ""), "$search$"));
}
dataForm.InsertButtonRow(0, row);
@@ -560,12 +544,12 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
if (this.KeyboardType == eKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows)
if (KeyboardType == EKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows)
{
return true;
}
if (this.KeyboardType == eKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows)
if (KeyboardType == EKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows)
{
return true;
}
@@ -578,7 +562,7 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
if (this.NavigationBarVisibility == eNavigationBarVisibility.always | (this.NavigationBarVisibility == eNavigationBarVisibility.auto && PagingNecessary))
if (NavigationBarVisibility == ENavigationBarVisibility.always | (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary))
{
return true;
}
@@ -594,30 +578,19 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
switch (this.KeyboardType)
return KeyboardType switch
{
case eKeyboardType.InlineKeyBoard:
return Constants.Telegram.MaxInlineKeyBoardRows;
case eKeyboardType.ReplyKeyboard:
return Constants.Telegram.MaxReplyKeyboardRows;
default:
return 0;
}
EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows,
EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows,
_ => 0
};
}
}
/// <summary>
/// Returns the number of all rows (layout + navigation + content);
/// </summary>
public int TotalRows
{
get
{
return this.LayoutRows + DataSource.RowCount;
}
}
public int TotalRows => LayoutRows + DataSource.RowCount;
/// <summary>
@@ -627,15 +600,15 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
int layoutRows = 0;
var layoutRows = 0;
if (this.NavigationBarVisibility == eNavigationBarVisibility.always | this.NavigationBarVisibility == eNavigationBarVisibility.auto)
if (NavigationBarVisibility == ENavigationBarVisibility.always | NavigationBarVisibility == ENavigationBarVisibility.auto)
layoutRows += 2;
if (this.HeadLayoutButtonRow != null && this.HeadLayoutButtonRow.Count > 0)
if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
layoutRows++;
if (this.SubHeadLayoutButtonRow != null && this.SubHeadLayoutButtonRow.Count > 0)
if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
layoutRows++;
return layoutRows;
@@ -645,13 +618,7 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary>
/// Returns the number of item rows per page.
/// </summary>
public int ItemRowsPerPage
{
get
{
return this.MaximumRow - this.LayoutRows;
}
}
public int ItemRowsPerPage => MaximumRow - LayoutRows;
/// <summary>
/// Return the number of pages.
@@ -665,7 +632,7 @@ namespace TelegramBotBase.Controls.Hybrid
//var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null);
var max = this.DataSource.CalculateMax(this.EnableSearch ? this.SearchQuery : null);
var max = DataSource.CalculateMax(EnableSearch ? SearchQuery : null);
//if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
//{
@@ -675,22 +642,24 @@ namespace TelegramBotBase.Controls.Hybrid
if (max == 0)
return 1;
return (int)Math.Ceiling((decimal)((decimal)max / (decimal)ItemRowsPerPage));
return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage);
}
}
public override async Task Hidden(bool FormClose)
public override Task Hidden(bool formClose)
{
//Prepare for opening Modal, and comming back
if (!FormClose)
if (!formClose)
{
this.Updated();
Updated();
}
else
{
//Remove event handler
this.Device.MessageDeleted -= Device_MessageDeleted;
Device.MessageDeleted -= Device_MessageDeleted;
}
return Task.CompletedTask;
}
/// <summary>
@@ -698,31 +667,31 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
public void Updated()
{
this.RenderNecessary = true;
_renderNecessary = true;
}
public async override Task Cleanup()
public override async Task Cleanup()
{
if (this.MessageId == null)
if (MessageId == null)
return;
switch (this.KeyboardType)
switch (KeyboardType)
{
case eKeyboardType.InlineKeyBoard:
case EKeyboardType.InlineKeyBoard:
await this.Device.DeleteMessage(this.MessageId.Value);
await Device.DeleteMessage(MessageId.Value);
this.MessageId = null;
MessageId = null;
break;
case eKeyboardType.ReplyKeyboard:
case EKeyboardType.ReplyKeyboard:
if (this.HideKeyboardOnCleanup)
if (HideKeyboardOnCleanup)
{
await this.Device.HideReplyKeyboard();
await Device.HideReplyKeyboard();
}
this.MessageId = null;
MessageId = null;
break;
}
+15 -31
View File
@@ -1,10 +1,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using TelegramBotBase.Form;
namespace TelegramBotBase.Controls.Hybrid
@@ -12,8 +9,7 @@ namespace TelegramBotBase.Controls.Hybrid
[DebuggerDisplay("{Count} columns")]
public class ButtonRow
{
List<ButtonBase> __buttons = new List<ButtonBase>();
private List<ButtonBase> _buttons = new List<ButtonBase>();
public ButtonRow()
{
@@ -23,59 +19,47 @@ namespace TelegramBotBase.Controls.Hybrid
public ButtonRow(params ButtonBase[] buttons)
{
__buttons = buttons.ToList();
_buttons = buttons.ToList();
}
public ButtonBase this[int index]
{
get
{
return __buttons[index];
}
}
public ButtonBase this[int index] => _buttons[index];
public int Count
{
get
{
return __buttons.Count;
}
}
public int Count => _buttons.Count;
public void Add(ButtonBase button)
{
__buttons.Add(button);
_buttons.Add(button);
}
public void AddRange(ButtonBase button)
{
__buttons.Add(button);
_buttons.Add(button);
}
public void Insert(int index, ButtonBase button)
{
__buttons.Insert(index, button);
_buttons.Insert(index, button);
}
public IEnumerator<ButtonBase> GetEnumerator()
{
return __buttons.GetEnumerator();
return _buttons.GetEnumerator();
}
public ButtonBase[] ToArray()
{
return __buttons.ToArray();
return _buttons.ToArray();
}
public List<ButtonBase> ToList()
{
return __buttons.ToList();
return _buttons.ToList();
}
public bool Matches(String text, bool useText = true)
public bool Matches(string text, bool useText = true)
{
foreach (var b in __buttons)
foreach (var b in _buttons)
{
if (useText && b.Text.Trim().Equals(text, StringComparison.InvariantCultureIgnoreCase))
return true;
@@ -92,9 +76,9 @@ namespace TelegramBotBase.Controls.Hybrid
/// <param name="text"></param>
/// <param name="useText"></param>
/// <returns></returns>
public ButtonBase GetButtonMatch(String text, bool useText = true)
public ButtonBase GetButtonMatch(string text, bool useText = true)
{
foreach (var b in __buttons)
foreach (var b in _buttons)
{
if (useText && b.Text.Trim().Equals(text, StringComparison.InvariantCultureIgnoreCase))
return b;
@@ -106,7 +90,7 @@ namespace TelegramBotBase.Controls.Hybrid
public static implicit operator ButtonRow(List<ButtonBase> list)
{
return new ButtonRow() { __buttons = list };
return new ButtonRow { _buttons = list };
}
}
}
@@ -1,49 +1,42 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.SymbolStore;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.ReplyMarkups;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Datasources;
using TelegramBotBase.DataSources;
using TelegramBotBase.Enums;
using TelegramBotBase.Exceptions;
using TelegramBotBase.Form;
using TelegramBotBase.Localizations;
using static TelegramBotBase.Base.Async;
namespace TelegramBotBase.Controls.Hybrid
{
public class CheckedButtonList : Base.ControlBase
public class CheckedButtonList : ControlBase
{
public String Title { get; set; } = Localizations.Default.Language["ButtonGrid_Title"];
public string Title { get; set; } = Default.Language["ButtonGrid_Title"];
public String ConfirmationText { get; set; } = "";
public string ConfirmationText { get; set; } = "";
private bool RenderNecessary = true;
private bool _renderNecessary = true;
private static readonly object __evButtonClicked = new object();
private static readonly object EvButtonClicked = new object();
private static readonly object __evCheckedChanged = new object();
private static readonly object EvCheckedChanged = new object();
private readonly EventHandlerList Events = new EventHandlerList();
private readonly EventHandlerList _events = new EventHandlerList();
[Obsolete("This property is obsolete. Please use the DataSource property instead.")]
public ButtonForm ButtonsForm
{
get
{
return DataSource.ButtonForm;
}
set
{
DataSource = new ButtonFormDataSource(value);
}
get => DataSource.ButtonForm;
set => DataSource = new ButtonFormDataSource(value);
}
/// <summary>
@@ -51,7 +44,7 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
public ButtonFormDataSource DataSource { get; set; }
List<int> CheckedRows { get; set; } = new List<int>();
private List<int> CheckedRows { get; set; } = new List<int>();
public int? MessageId { get; set; }
@@ -91,25 +84,25 @@ namespace TelegramBotBase.Controls.Hybrid
//public String SearchQuery { get; set; }
public eNavigationBarVisibility NavigationBarVisibility { get; set; } = eNavigationBarVisibility.always;
public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always;
/// <summary>
/// Index of the current page
/// </summary>
public int CurrentPageIndex { get; set; } = 0;
public int CurrentPageIndex { get; set; }
public String PreviousPageLabel = Localizations.Default.Language["ButtonGrid_PreviousPage"];
public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"];
public String NextPageLabel = Localizations.Default.Language["ButtonGrid_NextPage"];
public string NextPageLabel = Default.Language["ButtonGrid_NextPage"];
public String NoItemsLabel = Localizations.Default.Language["ButtonGrid_NoItems"];
public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"];
//public String SearchLabel = Localizations.Default.Language["ButtonGrid_SearchFeature"];
public String CheckedIconLabel { get; set; } = "✅";
public string CheckedIconLabel { get; set; } = "✅";
public String UncheckedIconLabel { get; set; } = "◻️";
public string UncheckedIconLabel { get; set; } = "◻️";
/// <summary>
/// Layout of the buttons which should be displayed always on top.
@@ -124,97 +117,82 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary>
/// Defines which type of Button Keyboard should be rendered.
/// </summary>
public eKeyboardType KeyboardType
public EKeyboardType KeyboardType
{
get
{
return m_eKeyboardType;
}
get => _mEKeyboardType;
set
{
if (m_eKeyboardType != value)
if (_mEKeyboardType != value)
{
this.RenderNecessary = true;
_renderNecessary = true;
Cleanup().Wait();
m_eKeyboardType = value;
_mEKeyboardType = value;
}
}
}
private eKeyboardType m_eKeyboardType = eKeyboardType.ReplyKeyboard;
private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard;
public CheckedButtonList()
{
this.DataSource = new ButtonFormDataSource();
DataSource = new ButtonFormDataSource();
}
public CheckedButtonList(eKeyboardType type) : this()
public CheckedButtonList(EKeyboardType type) : this()
{
m_eKeyboardType = type;
_mEKeyboardType = type;
}
public CheckedButtonList(ButtonForm form)
{
this.DataSource = new ButtonFormDataSource(form);
DataSource = new ButtonFormDataSource(form);
}
public event AsyncEventHandler<ButtonClickedEventArgs> ButtonClicked
{
add
{
this.Events.AddHandler(__evButtonClicked, value);
}
remove
{
this.Events.RemoveHandler(__evButtonClicked, value);
}
add => _events.AddHandler(EvButtonClicked, value);
remove => _events.RemoveHandler(EvButtonClicked, value);
}
public async Task OnButtonClicked(ButtonClickedEventArgs e)
{
var handler = this.Events[__evButtonClicked]?.GetInvocationList().Cast<AsyncEventHandler<ButtonClickedEventArgs>>();
var handler = _events[EvButtonClicked]?.GetInvocationList().Cast<AsyncEventHandler<ButtonClickedEventArgs>>();
if (handler == null)
return;
foreach (var h in handler)
{
await Async.InvokeAllAsync<ButtonClickedEventArgs>(h, this, e);
await h.InvokeAllAsync(this, e);
}
}
public event AsyncEventHandler<CheckedChangedEventArgs> CheckedChanged
{
add
{
this.Events.AddHandler(__evCheckedChanged, value);
}
remove
{
this.Events.RemoveHandler(__evCheckedChanged, value);
}
add => _events.AddHandler(EvCheckedChanged, value);
remove => _events.RemoveHandler(EvCheckedChanged, value);
}
public async Task OnCheckedChanged(CheckedChangedEventArgs e)
{
var handler = this.Events[__evCheckedChanged]?.GetInvocationList().Cast<AsyncEventHandler<CheckedChangedEventArgs>>();
var handler = _events[EvCheckedChanged]?.GetInvocationList().Cast<AsyncEventHandler<CheckedChangedEventArgs>>();
if (handler == null)
return;
foreach (var h in handler)
{
await Async.InvokeAllAsync<CheckedChangedEventArgs>(h, this, e);
await h.InvokeAllAsync(this, e);
}
}
public async override Task Load(MessageResult result)
public override async Task Load(MessageResult result)
{
if (this.KeyboardType != eKeyboardType.ReplyKeyboard)
if (KeyboardType != EKeyboardType.ReplyKeyboard)
return;
if (!result.IsFirstHandler)
@@ -225,7 +203,7 @@ namespace TelegramBotBase.Controls.Hybrid
var matches = new List<ButtonRow>();
ButtonRow match = null;
int index = -1;
var index = -1;
if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false)
{
@@ -260,36 +238,36 @@ namespace TelegramBotBase.Controls.Hybrid
//Remove button click message
if (this.DeleteReplyMessage)
if (DeleteReplyMessage)
await Device.DeleteMessage(result.MessageId);
if (match == null)
{
if (result.MessageText == PreviousPageLabel)
{
if (this.CurrentPageIndex > 0)
this.CurrentPageIndex--;
if (CurrentPageIndex > 0)
CurrentPageIndex--;
this.Updated();
Updated();
}
else if (result.MessageText == NextPageLabel)
{
if (this.CurrentPageIndex < this.PageCount - 1)
this.CurrentPageIndex++;
if (CurrentPageIndex < PageCount - 1)
CurrentPageIndex++;
this.Updated();
Updated();
}
else if (result.MessageText.EndsWith(CheckedIconLabel))
{
var s = result.MessageText.Split(' ', '.');
index = int.Parse(s[0]) - 1;
if (!this.CheckedRows.Contains(index))
if (!CheckedRows.Contains(index))
return;
this.CheckedRows.Remove(index);
CheckedRows.Remove(index);
this.Updated();
Updated();
await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, false));
@@ -299,13 +277,13 @@ namespace TelegramBotBase.Controls.Hybrid
var s = result.MessageText.Split(' ', '.');
index = int.Parse(s[0]) - 1;
if (this.CheckedRows.Contains(index))
if (CheckedRows.Contains(index))
return;
this.CheckedRows.Add(index);
CheckedRows.Add(index);
this.Updated();
Updated();
await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, true));
@@ -355,7 +333,7 @@ namespace TelegramBotBase.Controls.Hybrid
}
public async override Task Action(MessageResult result, string value = null)
public override async Task Action(MessageResult result, string value = null)
{
if (result.Handled)
return;
@@ -364,13 +342,13 @@ namespace TelegramBotBase.Controls.Hybrid
return;
//Find clicked button depending on Text or Value (depending on markup type)
if (this.KeyboardType != eKeyboardType.InlineKeyBoard)
if (KeyboardType != EKeyboardType.InlineKeyBoard)
return;
await result.ConfirmAction(this.ConfirmationText ?? "");
await result.ConfirmAction(ConfirmationText ?? "");
ButtonRow match = null;
int index = -1;
var index = -1;
if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false)
{
@@ -422,18 +400,18 @@ namespace TelegramBotBase.Controls.Hybrid
{
case "$previous$":
if (this.CurrentPageIndex > 0)
this.CurrentPageIndex--;
if (CurrentPageIndex > 0)
CurrentPageIndex--;
this.Updated();
Updated();
break;
case "$next$":
if (this.CurrentPageIndex < this.PageCount - 1)
this.CurrentPageIndex++;
if (CurrentPageIndex < PageCount - 1)
CurrentPageIndex++;
this.Updated();
Updated();
break;
@@ -448,11 +426,11 @@ namespace TelegramBotBase.Controls.Hybrid
index = int.Parse(s[1]);
if (!this.CheckedRows.Contains(index))
if (!CheckedRows.Contains(index))
{
this.CheckedRows.Add(index);
CheckedRows.Add(index);
this.Updated();
Updated();
await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, true));
}
@@ -463,11 +441,11 @@ namespace TelegramBotBase.Controls.Hybrid
index = int.Parse(s[1]);
if (this.CheckedRows.Contains(index))
if (CheckedRows.Contains(index))
{
this.CheckedRows.Remove(index);
CheckedRows.Remove(index);
this.Updated();
Updated();
await OnCheckedChanged(new CheckedChangedEventArgs(ButtonsForm[index], index, false));
}
@@ -487,51 +465,51 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
private void CheckGrid()
{
switch (m_eKeyboardType)
switch (_mEKeyboardType)
{
case eKeyboardType.InlineKeyBoard:
case EKeyboardType.InlineKeyBoard:
if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !this.EnablePaging)
if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging)
{
throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows };
throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows };
}
if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols)
{
throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols };
throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols };
}
break;
case eKeyboardType.ReplyKeyboard:
case EKeyboardType.ReplyKeyboard:
if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !this.EnablePaging)
if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging)
{
throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows };
throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows };
}
if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols)
{
throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols };
throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols };
}
break;
}
}
public async override Task Render(MessageResult result)
public override async Task Render(MessageResult result)
{
if (!this.RenderNecessary)
if (!_renderNecessary)
return;
//Check for rows and column limits
CheckGrid();
this.RenderNecessary = false;
_renderNecessary = false;
Message m = null;
ButtonForm form = this.DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, null);
var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage);
//if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
//{
@@ -542,7 +520,7 @@ namespace TelegramBotBase.Controls.Hybrid
//form = form.Duplicate();
//}
if (this.EnablePaging)
if (EnablePaging)
{
IntegratePagingView(form);
}
@@ -551,34 +529,34 @@ namespace TelegramBotBase.Controls.Hybrid
form = PrepareCheckableLayout(form);
}
if (this.HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
{
form.InsertButtonRow(0, this.HeadLayoutButtonRow.ToArray());
form.InsertButtonRow(0, HeadLayoutButtonRow.ToArray());
}
if (this.SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
{
if (this.IsNavigationBarVisible)
if (IsNavigationBarVisible)
{
form.InsertButtonRow(2, this.SubHeadLayoutButtonRow.ToArray());
form.InsertButtonRow(2, SubHeadLayoutButtonRow.ToArray());
}
else
{
form.InsertButtonRow(1, this.SubHeadLayoutButtonRow.ToArray());
form.InsertButtonRow(1, SubHeadLayoutButtonRow.ToArray());
}
}
switch (this.KeyboardType)
switch (KeyboardType)
{
//Reply Keyboard could only be updated with a new keyboard.
case eKeyboardType.ReplyKeyboard:
case EKeyboardType.ReplyKeyboard:
if (form.Count == 0)
{
if (this.MessageId != null)
if (MessageId != null)
{
await this.Device.HideReplyKeyboard();
this.MessageId = null;
await Device.HideReplyKeyboard();
MessageId = null;
}
return;
@@ -589,25 +567,25 @@ namespace TelegramBotBase.Controls.Hybrid
var rkm = (ReplyKeyboardMarkup)form;
rkm.ResizeKeyboard = this.ResizeKeyboard;
rkm.OneTimeKeyboard = this.OneTimeKeyboard;
m = await this.Device.Send(this.Title, rkm, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false);
rkm.ResizeKeyboard = ResizeKeyboard;
rkm.OneTimeKeyboard = OneTimeKeyboard;
m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
//Prevent flicker of keyboard
if (this.DeletePreviousMessage && this.MessageId != null)
await this.Device.DeleteMessage(this.MessageId.Value);
if (DeletePreviousMessage && MessageId != null)
await Device.DeleteMessage(MessageId.Value);
break;
case eKeyboardType.InlineKeyBoard:
case EKeyboardType.InlineKeyBoard:
if (this.MessageId != null)
if (MessageId != null)
{
m = await this.Device.Edit(this.MessageId.Value, this.Title, (InlineKeyboardMarkup)form);
m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form);
}
else
{
m = await this.Device.Send(this.Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false);
m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
}
break;
@@ -615,7 +593,7 @@ namespace TelegramBotBase.Controls.Hybrid
if (m != null)
{
this.MessageId = m.MessageId;
MessageId = m.MessageId;
}
@@ -623,23 +601,23 @@ namespace TelegramBotBase.Controls.Hybrid
private void IntegratePagingView(ButtonForm dataForm)
{
//No Items
//No Items
if (dataForm.Rows == 0)
{
dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$"));
}
ButtonForm bf = new ButtonForm();
var bf = new ButtonForm();
bf = PrepareCheckableLayout(dataForm);
if (this.IsNavigationBarVisible)
if (IsNavigationBarVisible)
{
//🔍
ButtonRow row = new ButtonRow();
var row = new ButtonRow();
row.Add(new ButtonBase(PreviousPageLabel, "$previous$"));
row.Add(new ButtonBase(String.Format(Localizations.Default.Language["ButtonGrid_CurrentPage"], this.CurrentPageIndex + 1, this.PageCount), "$site$"));
row.Add(new ButtonBase(string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), "$site$"));
row.Add(new ButtonBase(NextPageLabel, "$next$"));
@@ -652,30 +630,30 @@ namespace TelegramBotBase.Controls.Hybrid
private ButtonForm PrepareCheckableLayout(ButtonForm dataForm)
{
var bf = new ButtonForm();
for (int i = 0; i < dataForm.Rows; i++)
for (var i = 0; i < dataForm.Rows; i++)
{
int it = (this.CurrentPageIndex * (this.MaximumRow - LayoutRows)) + i;
var it = (CurrentPageIndex * (MaximumRow - LayoutRows)) + i;
//if (it > dataForm.Rows - 1)
// break;
var r = dataForm[i];
String s = CheckedRows.Contains(it) ? this.CheckedIconLabel : this.UncheckedIconLabel;
var s = CheckedRows.Contains(it) ? CheckedIconLabel : UncheckedIconLabel;
//On reply keyboards we need a unique text.
if (this.KeyboardType == eKeyboardType.ReplyKeyboard)
if (KeyboardType == EKeyboardType.ReplyKeyboard)
{
s = $"{it + 1}. " + s;
}
if (CheckedRows.Contains(it))
{
r.Insert(0, new ButtonBase(s, "uncheck$" + it.ToString()));
r.Insert(0, new ButtonBase(s, "uncheck$" + it));
}
else
{
r.Insert(0, new ButtonBase(s, "check$" + it.ToString()));
r.Insert(0, new ButtonBase(s, "check$" + it));
}
bf.AddButtonRow(r);
@@ -688,12 +666,12 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
if (this.KeyboardType == eKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows)
if (KeyboardType == EKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows)
{
return true;
}
if (this.KeyboardType == eKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows)
if (KeyboardType == EKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows)
{
return true;
}
@@ -706,7 +684,7 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
if (this.NavigationBarVisibility == eNavigationBarVisibility.always | (this.NavigationBarVisibility == eNavigationBarVisibility.auto && PagingNecessary))
if (NavigationBarVisibility == ENavigationBarVisibility.always | (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary))
{
return true;
}
@@ -722,30 +700,19 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
switch (this.KeyboardType)
return KeyboardType switch
{
case eKeyboardType.InlineKeyBoard:
return Constants.Telegram.MaxInlineKeyBoardRows;
case eKeyboardType.ReplyKeyboard:
return Constants.Telegram.MaxReplyKeyboardRows;
default:
return 0;
}
EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows,
EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows,
_ => 0
};
}
}
/// <summary>
/// Returns the number of all rows (layout + navigation + content);
/// </summary>
public int TotalRows
{
get
{
return this.LayoutRows + DataSource.RowCount;
}
}
public int TotalRows => LayoutRows + DataSource.RowCount;
/// <summary>
@@ -755,15 +722,15 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
int layoutRows = 0;
var layoutRows = 0;
if (this.NavigationBarVisibility == eNavigationBarVisibility.always | this.NavigationBarVisibility == eNavigationBarVisibility.auto)
if (NavigationBarVisibility == ENavigationBarVisibility.always | NavigationBarVisibility == ENavigationBarVisibility.auto)
layoutRows += 2;
if (this.HeadLayoutButtonRow != null && this.HeadLayoutButtonRow.Count > 0)
if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
layoutRows++;
if (this.SubHeadLayoutButtonRow != null && this.SubHeadLayoutButtonRow.Count > 0)
if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
layoutRows++;
return layoutRows;
@@ -773,13 +740,7 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary>
/// Returns the number of item rows per page.
/// </summary>
public int ItemRowsPerPage
{
get
{
return this.MaximumRow - this.LayoutRows;
}
}
public int ItemRowsPerPage => MaximumRow - LayoutRows;
public int PageCount
{
@@ -790,7 +751,7 @@ namespace TelegramBotBase.Controls.Hybrid
//var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null);
var max = this.DataSource.RowCount;
var max = DataSource.RowCount;
//if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
//{
@@ -800,28 +761,30 @@ namespace TelegramBotBase.Controls.Hybrid
if (max == 0)
return 1;
return (int)Math.Ceiling((decimal)((decimal)max / (decimal)ItemRowsPerPage));
return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage);
}
}
public override async Task Hidden(bool FormClose)
public override Task Hidden(bool formClose)
{
//Prepare for opening Modal, and comming back
if (!FormClose)
if (!formClose)
{
this.Updated();
Updated();
}
return Task.CompletedTask;
}
public List<ButtonBase> CheckedItems
{
get
{
List<ButtonBase> lst = new List<ButtonBase>();
var lst = new List<ButtonBase>();
foreach (var c in CheckedRows)
{
lst.Add(this.ButtonsForm[c][0]);
lst.Add(ButtonsForm[c][0]);
}
return lst;
@@ -834,31 +797,31 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
public void Updated()
{
this.RenderNecessary = true;
_renderNecessary = true;
}
public async override Task Cleanup()
public override async Task Cleanup()
{
if (this.MessageId == null)
if (MessageId == null)
return;
switch (this.KeyboardType)
switch (KeyboardType)
{
case eKeyboardType.InlineKeyBoard:
case EKeyboardType.InlineKeyBoard:
await this.Device.DeleteMessage(this.MessageId.Value);
await Device.DeleteMessage(MessageId.Value);
this.MessageId = null;
MessageId = null;
break;
case eKeyboardType.ReplyKeyboard:
case EKeyboardType.ReplyKeyboard:
if (this.HideKeyboardOnCleanup)
if (HideKeyboardOnCleanup)
{
await this.Device.HideReplyKeyboard();
await Device.HideReplyKeyboard();
}
this.MessageId = null;
MessageId = null;
break;
}
+25 -31
View File
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
@@ -13,33 +9,30 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary>
/// This Control is for having a basic form content switching control.
/// </summary>
public abstract class MultiView : Base.ControlBase
public abstract class MultiView : ControlBase
{
/// <summary>
/// Index of the current View.
/// </summary>
public int SelectedViewIndex
{
get
{
return m_iSelectedViewIndex;
}
get => _mISelectedViewIndex;
set
{
m_iSelectedViewIndex = value;
_mISelectedViewIndex = value;
//Already rendered? Re-Render
if (_Rendered)
if (_rendered)
ForceRender().Wait();
}
}
private int m_iSelectedViewIndex = 0;
private int _mISelectedViewIndex;
/// <summary>
/// Hold if the View has been rendered already.
/// </summary>
private bool _Rendered = false;
private bool _rendered;
private List<int> Messages { get; set; }
@@ -50,12 +43,13 @@ namespace TelegramBotBase.Controls.Hybrid
}
private async Task Device_MessageSent(object sender, MessageSentEventArgs e)
private Task Device_MessageSent(object sender, MessageSentEventArgs e)
{
if (e.Origin == null || !e.Origin.IsSubclassOf(typeof(MultiView)))
return;
return Task.CompletedTask;
this.Messages.Add(e.MessageId);
Messages.Add(e.MessageId);
return Task.CompletedTask;
}
public override void Init()
@@ -63,23 +57,24 @@ namespace TelegramBotBase.Controls.Hybrid
Device.MessageSent += Device_MessageSent;
}
public override async Task Load(MessageResult result)
public override Task Load(MessageResult result)
{
_Rendered = false;
_rendered = false;
return Task.CompletedTask;
}
public override async Task Render(MessageResult result)
{
//When already rendered, skip rendering
if (_Rendered)
if (_rendered)
return;
await CleanUpView();
await RenderView(new RenderViewEventArgs(this.SelectedViewIndex));
await RenderView(new RenderViewEventArgs(SelectedViewIndex));
_Rendered = true;
_rendered = true;
}
@@ -87,25 +82,24 @@ namespace TelegramBotBase.Controls.Hybrid
/// Will get invoked on rendering the current controls view.
/// </summary>
/// <param name="e"></param>
public virtual async Task RenderView(RenderViewEventArgs e)
public virtual Task RenderView(RenderViewEventArgs e)
{
return Task.CompletedTask;
}
async Task CleanUpView()
private async Task CleanUpView()
{
var tasks = new List<Task>();
foreach (var msg in this.Messages)
foreach (var msg in Messages)
{
tasks.Add(this.Device.DeleteMessage(msg));
tasks.Add(Device.DeleteMessage(msg));
}
await Task.WhenAll(tasks);
this.Messages.Clear();
Messages.Clear();
}
@@ -116,9 +110,9 @@ namespace TelegramBotBase.Controls.Hybrid
{
await CleanUpView();
await RenderView(new RenderViewEventArgs(this.SelectedViewIndex));
await RenderView(new RenderViewEventArgs(SelectedViewIndex));
_Rendered = true;
_rendered = true;
}
public override async Task Cleanup()
@@ -1,20 +1,18 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.SymbolStore;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.InlineQueryResults;
using Telegram.Bot.Types.ReplyMarkups;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Datasources;
using TelegramBotBase.DataSources;
using TelegramBotBase.Enums;
using TelegramBotBase.Exceptions;
using TelegramBotBase.Form;
using TelegramBotBase.Localizations;
using static TelegramBotBase.Base.Async;
namespace TelegramBotBase.Controls.Hybrid
@@ -22,27 +20,21 @@ namespace TelegramBotBase.Controls.Hybrid
public class TaggedButtonGrid : MultiView
{
public String Title { get; set; } = Localizations.Default.Language["ButtonGrid_Title"];
public string Title { get; set; } = Default.Language["ButtonGrid_Title"];
public String ConfirmationText { get; set; }
public string ConfirmationText { get; set; }
private bool RenderNecessary = true;
private bool _renderNecessary = true;
private static readonly object __evButtonClicked = new object();
private static readonly object EvButtonClicked = new object();
private readonly EventHandlerList Events = new EventHandlerList();
private readonly EventHandlerList _events = new EventHandlerList();
[Obsolete("This property is obsolete. Please use the DataSource property instead.")]
public ButtonForm ButtonsForm
{
get
{
return DataSource.ButtonForm;
}
set
{
DataSource = new ButtonFormDataSource(value);
}
get => DataSource.ButtonForm;
set => DataSource = new ButtonFormDataSource(value);
}
/// <summary>
@@ -90,29 +82,29 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
public bool EnableSearch { get; set; } = false;
public String SearchQuery { get; set; }
public string SearchQuery { get; set; }
public eNavigationBarVisibility NavigationBarVisibility { get; set; } = eNavigationBarVisibility.always;
public ENavigationBarVisibility NavigationBarVisibility { get; set; } = ENavigationBarVisibility.always;
/// <summary>
/// Index of the current page
/// </summary>
public int CurrentPageIndex { get; set; } = 0;
public int CurrentPageIndex { get; set; }
public String PreviousPageLabel = Localizations.Default.Language["ButtonGrid_PreviousPage"];
public string PreviousPageLabel = Default.Language["ButtonGrid_PreviousPage"];
public String NextPageLabel = Localizations.Default.Language["ButtonGrid_NextPage"];
public string NextPageLabel = Default.Language["ButtonGrid_NextPage"];
public String NoItemsLabel = Localizations.Default.Language["ButtonGrid_NoItems"];
public string NoItemsLabel = Default.Language["ButtonGrid_NoItems"];
public String SearchLabel = Localizations.Default.Language["ButtonGrid_SearchFeature"];
public string SearchLabel = Default.Language["ButtonGrid_SearchFeature"];
public String BackLabel = Localizations.Default.Language["ButtonGrid_Back"];
public string BackLabel = Default.Language["ButtonGrid_Back"];
public String CheckAllLabel = Localizations.Default.Language["ButtonGrid_CheckAll"];
public string CheckAllLabel = Default.Language["ButtonGrid_CheckAll"];
public String UncheckAllLabel = Localizations.Default.Language["ButtonGrid_UncheckAll"];
public string UncheckAllLabel = Default.Language["ButtonGrid_UncheckAll"];
/// <summary>
/// Layout of the buttons which should be displayed always on top.
@@ -132,100 +124,91 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary>
/// List of Tags which will be allowed to filter by.
/// </summary>
public List<String> Tags { get; set; }
public List<string> Tags { get; set; }
/// <summary>
/// List of Tags selected by the User.
/// </summary>
public List<String> SelectedTags { get; set; }
public List<string> SelectedTags { get; set; }
/// <summary>
/// Defines which type of Button Keyboard should be rendered.
/// </summary>
public eKeyboardType KeyboardType
public EKeyboardType KeyboardType
{
get
{
return m_eKeyboardType;
}
get => _mEKeyboardType;
set
{
if (m_eKeyboardType != value)
if (_mEKeyboardType != value)
{
this.RenderNecessary = true;
_renderNecessary = true;
Cleanup().Wait();
m_eKeyboardType = value;
_mEKeyboardType = value;
}
}
}
private eKeyboardType m_eKeyboardType = eKeyboardType.ReplyKeyboard;
private EKeyboardType _mEKeyboardType = EKeyboardType.ReplyKeyboard;
public TaggedButtonGrid()
{
this.DataSource = new ButtonFormDataSource();
DataSource = new ButtonFormDataSource();
this.SelectedViewIndex = 0;
SelectedViewIndex = 0;
}
public TaggedButtonGrid(eKeyboardType type) : this()
public TaggedButtonGrid(EKeyboardType type) : this()
{
m_eKeyboardType = type;
_mEKeyboardType = type;
}
public TaggedButtonGrid(ButtonForm form)
{
this.DataSource = new ButtonFormDataSource(form);
DataSource = new ButtonFormDataSource(form);
}
public event AsyncEventHandler<ButtonClickedEventArgs> ButtonClicked
{
add
{
this.Events.AddHandler(__evButtonClicked, value);
}
remove
{
this.Events.RemoveHandler(__evButtonClicked, value);
}
add => _events.AddHandler(EvButtonClicked, value);
remove => _events.RemoveHandler(EvButtonClicked, value);
}
public async Task OnButtonClicked(ButtonClickedEventArgs e)
{
var handler = this.Events[__evButtonClicked]?.GetInvocationList().Cast<AsyncEventHandler<ButtonClickedEventArgs>>();
var handler = _events[EvButtonClicked]?.GetInvocationList().Cast<AsyncEventHandler<ButtonClickedEventArgs>>();
if (handler == null)
return;
foreach (var h in handler)
{
await Async.InvokeAllAsync<ButtonClickedEventArgs>(h, this, e);
await h.InvokeAllAsync(this, e);
}
}
public override void Init()
{
this.Device.MessageDeleted += Device_MessageDeleted;
Device.MessageDeleted += Device_MessageDeleted;
}
private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e)
{
if (this.MessageId == null)
if (MessageId == null)
return;
if (e.MessageId != this.MessageId)
if (e.MessageId != MessageId)
return;
this.MessageId = null;
MessageId = null;
}
public async override Task Load(MessageResult result)
public override async Task Load(MessageResult result)
{
if (this.KeyboardType != eKeyboardType.ReplyKeyboard)
if (KeyboardType != EKeyboardType.ReplyKeyboard)
return;
if (!result.IsFirstHandler)
@@ -236,7 +219,7 @@ namespace TelegramBotBase.Controls.Hybrid
var matches = new List<ButtonRow>();
ButtonRow match = null;
int index = -1;
var index = -1;
if (HeadLayoutButtonRow?.Matches(result.MessageText) ?? false)
{
@@ -275,12 +258,12 @@ namespace TelegramBotBase.Controls.Hybrid
switch (this.SelectedViewIndex)
switch (SelectedViewIndex)
{
case 0:
//Remove button click message
if (this.DeleteReplyMessage)
if (DeleteReplyMessage)
await Device.DeleteMessage(result.MessageId);
if (match != null)
@@ -293,59 +276,57 @@ namespace TelegramBotBase.Controls.Hybrid
if (result.MessageText == PreviousPageLabel)
{
if (this.CurrentPageIndex > 0)
this.CurrentPageIndex--;
if (CurrentPageIndex > 0)
CurrentPageIndex--;
this.Updated();
Updated();
result.Handled = true;
}
else if (result.MessageText == NextPageLabel)
{
if (this.CurrentPageIndex < this.PageCount - 1)
this.CurrentPageIndex++;
if (CurrentPageIndex < PageCount - 1)
CurrentPageIndex++;
this.Updated();
Updated();
result.Handled = true;
}
else if (this.EnableSearch)
else if (EnableSearch)
{
if (result.MessageText.StartsWith("🔍"))
{
//Sent note about searching
if (this.SearchQuery == null)
if (SearchQuery == null)
{
await this.Device.Send(this.SearchLabel);
await Device.Send(SearchLabel);
}
this.SearchQuery = null;
this.Updated();
SearchQuery = null;
Updated();
result.Handled = true;
return;
}
this.SearchQuery = result.MessageText;
SearchQuery = result.MessageText;
if (this.SearchQuery != null && this.SearchQuery != "")
if (SearchQuery != null && SearchQuery != "")
{
this.CurrentPageIndex = 0;
this.Updated();
CurrentPageIndex = 0;
Updated();
result.Handled = true;
return;
}
}
else if (this.Tags != null)
else if (Tags != null)
{
if (result.MessageText == "📁")
{
//Remove button click message
if (this.DeletePreviousMessage)
if (DeletePreviousMessage)
await Device.DeleteMessage(result.MessageId);
this.SelectedViewIndex = 1;
this.Updated();
SelectedViewIndex = 1;
Updated();
result.Handled = true;
return;
}
}
@@ -353,23 +334,24 @@ namespace TelegramBotBase.Controls.Hybrid
case 1:
//Remove button click message
if (this.DeleteReplyMessage)
if (DeleteReplyMessage)
await Device.DeleteMessage(result.MessageId);
if (result.MessageText == this.BackLabel)
if (result.MessageText == BackLabel)
{
this.SelectedViewIndex = 0;
this.Updated();
SelectedViewIndex = 0;
Updated();
result.Handled = true;
return;
}
else if (result.MessageText == this.CheckAllLabel)
if (result.MessageText == CheckAllLabel)
{
this.CheckAllTags();
CheckAllTags();
}
else if (result.MessageText == this.UncheckAllLabel)
else if (result.MessageText == UncheckAllLabel)
{
this.UncheckAllTags();
UncheckAllTags();
}
var i = result.MessageText.LastIndexOf(" ");
@@ -378,16 +360,16 @@ namespace TelegramBotBase.Controls.Hybrid
var t = result.MessageText.Substring(0, i);
if (this.SelectedTags.Contains(t))
if (SelectedTags.Contains(t))
{
this.SelectedTags.Remove(t);
SelectedTags.Remove(t);
}
else
{
this.SelectedTags.Add(t);
SelectedTags.Add(t);
}
this.Updated();
Updated();
result.Handled = true;
@@ -399,7 +381,7 @@ namespace TelegramBotBase.Controls.Hybrid
}
public async override Task Action(MessageResult result, string value = null)
public override async Task Action(MessageResult result, string value = null)
{
if (result.Handled)
return;
@@ -408,13 +390,13 @@ namespace TelegramBotBase.Controls.Hybrid
return;
//Find clicked button depending on Text or Value (depending on markup type)
if (this.KeyboardType != eKeyboardType.InlineKeyBoard)
if (KeyboardType != EKeyboardType.InlineKeyBoard)
return;
await result.ConfirmAction(this.ConfirmationText ?? "");
await result.ConfirmAction(ConfirmationText ?? "");
ButtonRow match = null;
int index = -1;
var index = -1;
if (HeadLayoutButtonRow?.Matches(result.RawData, false) ?? false)
{
@@ -464,45 +446,45 @@ namespace TelegramBotBase.Controls.Hybrid
{
case "$previous$":
if (this.CurrentPageIndex > 0)
this.CurrentPageIndex--;
if (CurrentPageIndex > 0)
CurrentPageIndex--;
this.Updated();
Updated();
break;
case "$next$":
if (this.CurrentPageIndex < this.PageCount - 1)
this.CurrentPageIndex++;
if (CurrentPageIndex < PageCount - 1)
CurrentPageIndex++;
this.Updated();
Updated();
break;
case "$filter$":
this.SelectedViewIndex = 1;
this.Updated();
SelectedViewIndex = 1;
Updated();
break;
case "$back$":
this.SelectedViewIndex = 0;
this.Updated();
SelectedViewIndex = 0;
Updated();
break;
case "$checkall$":
this.CheckAllTags();
CheckAllTags();
break;
case "$uncheckall$":
this.UncheckAllTags();
UncheckAllTags();
break;
}
@@ -514,49 +496,49 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
private void CheckGrid()
{
switch (m_eKeyboardType)
switch (_mEKeyboardType)
{
case eKeyboardType.InlineKeyBoard:
case EKeyboardType.InlineKeyBoard:
if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !this.EnablePaging)
if (DataSource.RowCount > Constants.Telegram.MaxInlineKeyBoardRows && !EnablePaging)
{
throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows };
throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxInlineKeyBoardRows };
}
if (DataSource.ColumnCount > Constants.Telegram.MaxInlineKeyBoardCols)
{
throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols };
throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxInlineKeyBoardCols };
}
break;
case eKeyboardType.ReplyKeyboard:
case EKeyboardType.ReplyKeyboard:
if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !this.EnablePaging)
if (DataSource.RowCount > Constants.Telegram.MaxReplyKeyboardRows && !EnablePaging)
{
throw new MaximumRowsReachedException() { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows };
throw new MaximumRowsReachedException { Value = DataSource.RowCount, Maximum = Constants.Telegram.MaxReplyKeyboardRows };
}
if (DataSource.ColumnCount > Constants.Telegram.MaxReplyKeyboardCols)
{
throw new MaximumColsException() { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols };
throw new MaximumColsException { Value = DataSource.ColumnCount, Maximum = Constants.Telegram.MaxReplyKeyboardCols };
}
break;
}
}
public async override Task Render(MessageResult result)
public override async Task Render(MessageResult result)
{
if (!this.RenderNecessary)
if (!_renderNecessary)
return;
//Check for rows and column limits
CheckGrid();
this.RenderNecessary = false;
_renderNecessary = false;
switch (this.SelectedViewIndex)
switch (SelectedViewIndex)
{
case 0:
@@ -586,7 +568,7 @@ namespace TelegramBotBase.Controls.Hybrid
{
Message m = null;
ButtonForm form = this.DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (this.EnableSearch ? this.SearchQuery : null));
var form = DataSource.PickItems(CurrentPageIndex * ItemRowsPerPage, ItemRowsPerPage, (EnableSearch ? SearchQuery : null));
//if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
//{
@@ -597,111 +579,111 @@ namespace TelegramBotBase.Controls.Hybrid
// form = form.Duplicate();
//}
if (this.Tags != null && this.SelectedTags != null)
if (Tags != null && SelectedTags != null)
{
form = form.TagDuplicate(this.SelectedTags);
form = form.TagDuplicate(SelectedTags);
}
if (this.EnablePaging)
if (EnablePaging)
{
IntegratePagingView(form);
}
if (this.HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
{
form.InsertButtonRow(0, this.HeadLayoutButtonRow.ToArray());
form.InsertButtonRow(0, HeadLayoutButtonRow.ToArray());
}
if (this.SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
{
if (this.IsNavigationBarVisible)
if (IsNavigationBarVisible)
{
form.InsertButtonRow(2, this.SubHeadLayoutButtonRow.ToArray());
form.InsertButtonRow(2, SubHeadLayoutButtonRow.ToArray());
}
else
{
form.InsertButtonRow(1, this.SubHeadLayoutButtonRow.ToArray());
form.InsertButtonRow(1, SubHeadLayoutButtonRow.ToArray());
}
}
switch (this.KeyboardType)
switch (KeyboardType)
{
//Reply Keyboard could only be updated with a new keyboard.
case eKeyboardType.ReplyKeyboard:
case EKeyboardType.ReplyKeyboard:
if (form.Count == 0)
{
if (this.MessageId != null)
if (MessageId != null)
{
await this.Device.HideReplyKeyboard();
this.MessageId = null;
await Device.HideReplyKeyboard();
MessageId = null;
}
return;
}
var rkm = (ReplyKeyboardMarkup)form;
rkm.ResizeKeyboard = this.ResizeKeyboard;
rkm.OneTimeKeyboard = this.OneTimeKeyboard;
m = await this.Device.Send(this.Title, rkm, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false);
rkm.ResizeKeyboard = ResizeKeyboard;
rkm.OneTimeKeyboard = OneTimeKeyboard;
m = await Device.Send(Title, rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
//Prevent flicker of keyboard
if (this.DeletePreviousMessage && this.MessageId != null)
await this.Device.DeleteMessage(this.MessageId.Value);
if (DeletePreviousMessage && MessageId != null)
await Device.DeleteMessage(MessageId.Value);
break;
case eKeyboardType.InlineKeyBoard:
case EKeyboardType.InlineKeyBoard:
//Try to edit message if message id is available
//When the returned message is null then the message has been already deleted, resend it
if (this.MessageId != null)
if (MessageId != null)
{
m = await this.Device.Edit(this.MessageId.Value, this.Title, (InlineKeyboardMarkup)form);
m = await Device.Edit(MessageId.Value, Title, (InlineKeyboardMarkup)form);
if (m != null)
{
this.MessageId = m.MessageId;
MessageId = m.MessageId;
return;
}
}
//When no message id is available or it has been deleted due the use of AutoCleanForm re-render automatically
m = await this.Device.Send(this.Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false);
m = await Device.Send(Title, (InlineKeyboardMarkup)form, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
break;
}
if (m != null)
{
this.MessageId = m.MessageId;
MessageId = m.MessageId;
}
}
private void IntegratePagingView(ButtonForm dataForm)
{
//No Items
//No Items
if (dataForm.Rows == 0)
{
dataForm.AddButtonRow(new ButtonBase(NoItemsLabel, "$"));
}
if (this.IsNavigationBarVisible)
if (IsNavigationBarVisible)
{
//🔍
ButtonRow row = new ButtonRow();
var row = new ButtonRow();
row.Add(new ButtonBase(PreviousPageLabel, "$previous$"));
row.Add(new ButtonBase(String.Format(Localizations.Default.Language["ButtonGrid_CurrentPage"], this.CurrentPageIndex + 1, this.PageCount), "$site$"));
row.Add(new ButtonBase(string.Format(Default.Language["ButtonGrid_CurrentPage"], CurrentPageIndex + 1, PageCount), "$site$"));
if (this.Tags != null && this.Tags.Count > 0)
if (Tags != null && Tags.Count > 0)
{
row.Add(new ButtonBase("📁", "$filter$"));
}
row.Add(new ButtonBase(NextPageLabel, "$next$"));
if (this.EnableSearch)
if (EnableSearch)
{
row.Insert(2, new ButtonBase("🔍 " + (this.SearchQuery ?? ""), "$search$"));
row.Insert(2, new ButtonBase("🔍 " + (SearchQuery ?? ""), "$search$"));
}
dataForm.InsertButtonRow(0, row);
@@ -719,22 +701,22 @@ namespace TelegramBotBase.Controls.Hybrid
private async Task RenderTagView()
{
Message m = null;
ButtonForm bf = new ButtonForm();
var bf = new ButtonForm();
bf.AddButtonRow(this.BackLabel, "$back$");
bf.AddButtonRow(BackLabel, "$back$");
if (EnableCheckAllTools)
{
this.TagsSubHeadLayoutButtonRow = new ButtonRow(new ButtonBase(CheckAllLabel, "$checkall$"), new ButtonBase(UncheckAllLabel, "$uncheckall$"));
TagsSubHeadLayoutButtonRow = new ButtonRow(new ButtonBase(CheckAllLabel, "$checkall$"), new ButtonBase(UncheckAllLabel, "$uncheckall$"));
bf.AddButtonRow(TagsSubHeadLayoutButtonRow);
}
foreach (var t in this.Tags)
foreach (var t in Tags)
{
String s = t;
var s = t;
if (this.SelectedTags?.Contains(t) ?? false)
if (SelectedTags?.Contains(t) ?? false)
{
s += " ✅";
}
@@ -743,17 +725,17 @@ namespace TelegramBotBase.Controls.Hybrid
}
switch (this.KeyboardType)
switch (KeyboardType)
{
//Reply Keyboard could only be updated with a new keyboard.
case eKeyboardType.ReplyKeyboard:
case EKeyboardType.ReplyKeyboard:
if (bf.Count == 0)
{
if (this.MessageId != null)
if (MessageId != null)
{
await this.Device.HideReplyKeyboard();
this.MessageId = null;
await Device.HideReplyKeyboard();
MessageId = null;
}
return;
}
@@ -763,25 +745,25 @@ namespace TelegramBotBase.Controls.Hybrid
var rkm = (ReplyKeyboardMarkup)bf;
rkm.ResizeKeyboard = this.ResizeKeyboard;
rkm.OneTimeKeyboard = this.OneTimeKeyboard;
m = await this.Device.Send("Choose category", rkm, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false);
rkm.ResizeKeyboard = ResizeKeyboard;
rkm.OneTimeKeyboard = OneTimeKeyboard;
m = await Device.Send("Choose category", rkm, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
//Prevent flicker of keyboard
if (this.DeletePreviousMessage && this.MessageId != null)
await this.Device.DeleteMessage(this.MessageId.Value);
if (DeletePreviousMessage && MessageId != null)
await Device.DeleteMessage(MessageId.Value);
break;
case eKeyboardType.InlineKeyBoard:
case EKeyboardType.InlineKeyBoard:
if (this.MessageId != null)
if (MessageId != null)
{
m = await this.Device.Edit(this.MessageId.Value, "Choose category", (InlineKeyboardMarkup)bf);
m = await Device.Edit(MessageId.Value, "Choose category", (InlineKeyboardMarkup)bf);
}
else
{
m = await this.Device.Send("Choose category", (InlineKeyboardMarkup)bf, disableNotification: true, parseMode: MessageParseMode, MarkdownV2AutoEscape: false);
m = await Device.Send("Choose category", (InlineKeyboardMarkup)bf, disableNotification: true, parseMode: MessageParseMode, markdownV2AutoEscape: false);
}
break;
@@ -790,7 +772,7 @@ namespace TelegramBotBase.Controls.Hybrid
if (m != null)
this.MessageId = m.MessageId;
MessageId = m.MessageId;
}
@@ -802,12 +784,12 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
if (this.KeyboardType == eKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows)
if (KeyboardType == EKeyboardType.InlineKeyBoard && TotalRows > Constants.Telegram.MaxInlineKeyBoardRows)
{
return true;
}
if (this.KeyboardType == eKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows)
if (KeyboardType == EKeyboardType.ReplyKeyboard && TotalRows > Constants.Telegram.MaxReplyKeyboardRows)
{
return true;
}
@@ -820,7 +802,7 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
if (this.NavigationBarVisibility == eNavigationBarVisibility.always | (this.NavigationBarVisibility == eNavigationBarVisibility.auto && PagingNecessary))
if (NavigationBarVisibility == ENavigationBarVisibility.always | (NavigationBarVisibility == ENavigationBarVisibility.auto && PagingNecessary))
{
return true;
}
@@ -836,30 +818,19 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
switch (this.KeyboardType)
return KeyboardType switch
{
case eKeyboardType.InlineKeyBoard:
return Constants.Telegram.MaxInlineKeyBoardRows;
case eKeyboardType.ReplyKeyboard:
return Constants.Telegram.MaxReplyKeyboardRows;
default:
return 0;
}
EKeyboardType.InlineKeyBoard => Constants.Telegram.MaxInlineKeyBoardRows,
EKeyboardType.ReplyKeyboard => Constants.Telegram.MaxReplyKeyboardRows,
_ => 0
};
}
}
/// <summary>
/// Returns the number of all rows (layout + navigation + content);
/// </summary>
public int TotalRows
{
get
{
return this.LayoutRows + DataSource.RowCount;
}
}
public int TotalRows => LayoutRows + DataSource.RowCount;
/// <summary>
@@ -869,18 +840,18 @@ namespace TelegramBotBase.Controls.Hybrid
{
get
{
int layoutRows = 0;
var layoutRows = 0;
if (this.NavigationBarVisibility == eNavigationBarVisibility.always | this.NavigationBarVisibility == eNavigationBarVisibility.auto)
if (NavigationBarVisibility == ENavigationBarVisibility.always | NavigationBarVisibility == ENavigationBarVisibility.auto)
layoutRows += 2;
if (this.HeadLayoutButtonRow != null && this.HeadLayoutButtonRow.Count > 0)
if (HeadLayoutButtonRow != null && HeadLayoutButtonRow.Count > 0)
layoutRows++;
if (this.SubHeadLayoutButtonRow != null && this.SubHeadLayoutButtonRow.Count > 0)
if (SubHeadLayoutButtonRow != null && SubHeadLayoutButtonRow.Count > 0)
layoutRows++;
if (EnableCheckAllTools && this.SelectedViewIndex == 1)
if (EnableCheckAllTools && SelectedViewIndex == 1)
{
layoutRows++;
}
@@ -892,13 +863,7 @@ namespace TelegramBotBase.Controls.Hybrid
/// <summary>
/// Returns the number of item rows per page.
/// </summary>
public int ItemRowsPerPage
{
get
{
return this.MaximumRow - this.LayoutRows;
}
}
public int ItemRowsPerPage => MaximumRow - LayoutRows;
public int PageCount
{
@@ -909,7 +874,7 @@ namespace TelegramBotBase.Controls.Hybrid
//var bf = this.DataSource.PickAllItems(this.EnableSearch ? this.SearchQuery : null);
var max = this.DataSource.CalculateMax(this.EnableSearch ? this.SearchQuery : null);
var max = DataSource.CalculateMax(EnableSearch ? SearchQuery : null);
//if (this.EnableSearch && this.SearchQuery != null && this.SearchQuery != "")
//{
@@ -919,22 +884,24 @@ namespace TelegramBotBase.Controls.Hybrid
if (max == 0)
return 1;
return (int)Math.Ceiling((decimal)((decimal)max / (decimal)ItemRowsPerPage));
return (int)Math.Ceiling(max / (decimal)ItemRowsPerPage);
}
}
public override async Task Hidden(bool FormClose)
public override Task Hidden(bool formClose)
{
//Prepare for opening Modal, and comming back
if (!FormClose)
if (!formClose)
{
this.Updated();
Updated();
}
else
{
//Remove event handler
this.Device.MessageDeleted -= Device_MessageDeleted;
Device.MessageDeleted -= Device_MessageDeleted;
}
return Task.CompletedTask;
}
/// <summary>
@@ -942,31 +909,31 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
public void Updated()
{
this.RenderNecessary = true;
_renderNecessary = true;
}
public async override Task Cleanup()
public override async Task Cleanup()
{
if (this.MessageId == null)
if (MessageId == null)
return;
switch (this.KeyboardType)
switch (KeyboardType)
{
case eKeyboardType.InlineKeyBoard:
case EKeyboardType.InlineKeyBoard:
await this.Device.DeleteMessage(this.MessageId.Value);
await Device.DeleteMessage(MessageId.Value);
this.MessageId = null;
MessageId = null;
break;
case eKeyboardType.ReplyKeyboard:
case EKeyboardType.ReplyKeyboard:
if (this.HideKeyboardOnCleanup)
if (HideKeyboardOnCleanup)
{
await this.Device.HideReplyKeyboard();
await Device.HideReplyKeyboard();
}
this.MessageId = null;
MessageId = null;
break;
}
@@ -979,11 +946,11 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
public void CheckAllTags()
{
this.SelectedTags.Clear();
SelectedTags.Clear();
this.SelectedTags = this.Tags.Select(a => a).ToList();
SelectedTags = Tags.Select(a => a).ToList();
this.Updated();
Updated();
}
@@ -992,9 +959,9 @@ namespace TelegramBotBase.Controls.Hybrid
/// </summary>
public void UncheckAllTags()
{
this.SelectedTags.Clear();
SelectedTags.Clear();
this.Updated();
Updated();
}
}
@@ -2,18 +2,17 @@
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
using TelegramBotBase.Tools;
using TelegramBotBase.Localizations;
using static TelegramBotBase.Tools.Arrays;
using static TelegramBotBase.Tools.Time;
namespace TelegramBotBase.Controls.Inline
{
public class CalendarPicker : Base.ControlBase
public class CalendarPicker : ControlBase
{
public DateTime SelectedDate { get; set; }
@@ -27,31 +26,31 @@ namespace TelegramBotBase.Controls.Inline
private int? MessageId { get; set; }
public String Title { get; set; } = Localizations.Default.Language["CalendarPicker_Title"];
public string Title { get; set; } = Default.Language["CalendarPicker_Title"];
public eMonthPickerMode PickerMode { get; set; }
public EMonthPickerMode PickerMode { get; set; }
public bool EnableDayView { get; set; } = true;
public bool EnableMonthView { get; set; } = true;
public bool EnableYearView { get; set; } = true;
public CalendarPicker(CultureInfo culture)
{
this.SelectedDate = DateTime.Today;
this.VisibleMonth = DateTime.Today;
this.FirstDayOfWeek = DayOfWeek.Monday;
this.Culture = culture;
this.PickerMode = eMonthPickerMode.day;
SelectedDate = DateTime.Today;
VisibleMonth = DateTime.Today;
FirstDayOfWeek = DayOfWeek.Monday;
Culture = culture;
PickerMode = EMonthPickerMode.day;
}
public CalendarPicker() : this(new CultureInfo("en-en")) { }
public override async Task Action(MessageResult result, String value = null)
public override async Task Action(MessageResult result, string value = null)
{
await result.ConfirmAction();
@@ -59,99 +58,84 @@ namespace TelegramBotBase.Controls.Inline
{
case "$next$":
switch (this.PickerMode)
VisibleMonth = PickerMode switch
{
case eMonthPickerMode.day:
this.VisibleMonth = this.VisibleMonth.AddMonths(1);
break;
case eMonthPickerMode.month:
this.VisibleMonth = this.VisibleMonth.AddYears(1);
break;
case eMonthPickerMode.year:
this.VisibleMonth = this.VisibleMonth.AddYears(10);
break;
}
EMonthPickerMode.day => VisibleMonth.AddMonths(1),
EMonthPickerMode.month => VisibleMonth.AddYears(1),
EMonthPickerMode.year => VisibleMonth.AddYears(10),
_ => VisibleMonth
};
break;
case "$prev$":
switch (this.PickerMode)
VisibleMonth = PickerMode switch
{
case eMonthPickerMode.day:
this.VisibleMonth = this.VisibleMonth.AddMonths(-1);
break;
case eMonthPickerMode.month:
this.VisibleMonth = this.VisibleMonth.AddYears(-1);
break;
case eMonthPickerMode.year:
this.VisibleMonth = this.VisibleMonth.AddYears(-10);
break;
}
EMonthPickerMode.day => VisibleMonth.AddMonths(-1),
EMonthPickerMode.month => VisibleMonth.AddYears(-1),
EMonthPickerMode.year => VisibleMonth.AddYears(-10),
_ => VisibleMonth
};
break;
case "$monthtitle$":
if (this.EnableMonthView)
if (EnableMonthView)
{
this.PickerMode = eMonthPickerMode.month;
PickerMode = EMonthPickerMode.month;
}
break;
case "$yeartitle$":
if (this.EnableYearView)
if (EnableYearView)
{
this.PickerMode = eMonthPickerMode.year;
PickerMode = EMonthPickerMode.year;
}
break;
case "$yearstitle$":
if (this.EnableMonthView)
if (EnableMonthView)
{
this.PickerMode = eMonthPickerMode.month;
PickerMode = EMonthPickerMode.month;
}
this.VisibleMonth = this.SelectedDate;
VisibleMonth = SelectedDate;
break;
default:
int day = 0;
if (result.RawData.StartsWith("d-") && TryParseDay(result.RawData.Split('-')[1], this.SelectedDate, out day))
var day = 0;
if (result.RawData.StartsWith("d-") && TryParseDay(result.RawData.Split('-')[1], SelectedDate, out day))
{
this.SelectedDate = new DateTime(this.VisibleMonth.Year, this.VisibleMonth.Month, day);
SelectedDate = new DateTime(VisibleMonth.Year, VisibleMonth.Month, day);
}
int month = 0;
var month = 0;
if (result.RawData.StartsWith("m-") && TryParseMonth(result.RawData.Split('-')[1], out month))
{
this.SelectedDate = new DateTime(this.VisibleMonth.Year, month, 1);
this.VisibleMonth = this.SelectedDate;
SelectedDate = new DateTime(VisibleMonth.Year, month, 1);
VisibleMonth = SelectedDate;
if (this.EnableDayView)
if (EnableDayView)
{
this.PickerMode = eMonthPickerMode.day;
PickerMode = EMonthPickerMode.day;
}
}
int year = 0;
var year = 0;
if (result.RawData.StartsWith("y-") && TryParseYear(result.RawData.Split('-')[1], out year))
{
this.SelectedDate = new DateTime(year, SelectedDate.Month, SelectedDate.Day);
this.VisibleMonth = this.SelectedDate;
SelectedDate = new DateTime(year, SelectedDate.Month, SelectedDate.Day);
VisibleMonth = SelectedDate;
if (this.EnableMonthView)
if (EnableMonthView)
{
this.PickerMode = eMonthPickerMode.month;
PickerMode = EMonthPickerMode.month;
}
}
@@ -170,18 +154,18 @@ namespace TelegramBotBase.Controls.Inline
ButtonForm bf = new ButtonForm();
var bf = new ButtonForm();
switch (this.PickerMode)
switch (PickerMode)
{
case eMonthPickerMode.day:
case EMonthPickerMode.day:
var month = this.VisibleMonth;
var month = VisibleMonth;
string[] dayNamesNormal = this.Culture.DateTimeFormat.ShortestDayNames;
string[] dayNamesShifted = Shift(dayNamesNormal, (int)this.FirstDayOfWeek);
var dayNamesNormal = Culture.DateTimeFormat.ShortestDayNames;
var dayNamesShifted = Shift(dayNamesNormal, (int)FirstDayOfWeek);
bf.AddButtonRow(new ButtonBase(Localizations.Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase(this.Culture.DateTimeFormat.MonthNames[month.Month - 1] + " " + month.Year.ToString(), "$monthtitle$"), new ButtonBase(Localizations.Default.Language["CalendarPicker_NextPage"], "$next$"));
bf.AddButtonRow(new ButtonBase(Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase(Culture.DateTimeFormat.MonthNames[month.Month - 1] + " " + month.Year, "$monthtitle$"), new ButtonBase(Default.Language["CalendarPicker_NextPage"], "$next$"));
bf.AddButtonRow(dayNamesShifted.Select(a => new ButtonBase(a, a)).ToList());
@@ -192,20 +176,20 @@ namespace TelegramBotBase.Controls.Inline
var lastDay = firstDay.LastDayOfMonth();
//Start of Week where first day of month is (left border)
var start = firstDay.StartOfWeek(this.FirstDayOfWeek);
var start = firstDay.StartOfWeek(FirstDayOfWeek);
//End of week where last day of month is (right border)
var end = lastDay.EndOfWeek(this.FirstDayOfWeek);
var end = lastDay.EndOfWeek(FirstDayOfWeek);
for (int i = 0; i <= ((end - start).Days / 7); i++)
for (var i = 0; i <= ((end - start).Days / 7); i++)
{
var lst = new List<ButtonBase>();
for (int id = 0; id < 7; id++)
for (var id = 0; id < 7; id++)
{
var d = start.AddDays((i * 7) + id);
if (d < firstDay | d > lastDay)
{
lst.Add(new ButtonBase("-", "m-" + d.Day.ToString()));
lst.Add(new ButtonBase("-", "m-" + d.Day));
continue;
}
@@ -216,35 +200,35 @@ namespace TelegramBotBase.Controls.Inline
day = "(" + day + ")";
}
lst.Add(new ButtonBase((this.SelectedDate == d ? "[" + day + "]" : day), "d-" + d.Day.ToString()));
lst.Add(new ButtonBase((SelectedDate == d ? "[" + day + "]" : day), "d-" + d.Day));
}
bf.AddButtonRow(lst);
}
break;
case eMonthPickerMode.month:
case EMonthPickerMode.month:
bf.AddButtonRow(new ButtonBase(Localizations.Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase(this.VisibleMonth.Year.ToString("0000"), "$yeartitle$"), new ButtonBase(Localizations.Default.Language["CalendarPicker_NextPage"], "$next$"));
bf.AddButtonRow(new ButtonBase(Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase(VisibleMonth.Year.ToString("0000"), "$yeartitle$"), new ButtonBase(Default.Language["CalendarPicker_NextPage"], "$next$"));
var months = this.Culture.DateTimeFormat.MonthNames;
var months = Culture.DateTimeFormat.MonthNames;
var buttons = months.Select((a, b) => new ButtonBase((b == this.SelectedDate.Month - 1 && this.SelectedDate.Year == this.VisibleMonth.Year ? "[ " + a + " ]" : a), "m-" + (b + 1).ToString()));
var buttons = months.Select((a, b) => new ButtonBase((b == SelectedDate.Month - 1 && SelectedDate.Year == VisibleMonth.Year ? "[ " + a + " ]" : a), "m-" + (b + 1)));
bf.AddSplitted(buttons, 2);
bf.AddSplitted(buttons);
break;
case eMonthPickerMode.year:
case EMonthPickerMode.year:
bf.AddButtonRow(new ButtonBase(Localizations.Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase("Year", "$yearstitle$"), new ButtonBase(Localizations.Default.Language["CalendarPicker_NextPage"], "$next$"));
bf.AddButtonRow(new ButtonBase(Default.Language["CalendarPicker_PreviousPage"], "$prev$"), new ButtonBase("Year", "$yearstitle$"), new ButtonBase(Default.Language["CalendarPicker_NextPage"], "$next$"));
var starti = Math.Floor(this.VisibleMonth.Year / 10f) * 10;
var starti = Math.Floor(VisibleMonth.Year / 10f) * 10;
for (int i = 0; i < 10; i++)
for (var i = 0; i < 10; i++)
{
var m = starti + (i * 2);
bf.AddButtonRow(new ButtonBase((this.SelectedDate.Year == m ? "[ " + m.ToString() + " ]" : m.ToString()), "y-" + m.ToString()), new ButtonBase((this.SelectedDate.Year == (m + 1) ? "[ " + (m + 1).ToString() + " ]" : (m + 1).ToString()), "y-" + (m + 1).ToString()));
bf.AddButtonRow(new ButtonBase((SelectedDate.Year == m ? "[ " + m + " ]" : m.ToString()), "y-" + m), new ButtonBase((SelectedDate.Year == (m + 1) ? "[ " + (m + 1) + " ]" : (m + 1).ToString()), "y-" + (m + 1)));
}
break;
@@ -252,14 +236,14 @@ namespace TelegramBotBase.Controls.Inline
}
if (this.MessageId != null)
if (MessageId != null)
{
var m = await this.Device.Edit(this.MessageId.Value, this.Title, bf);
var m = await Device.Edit(MessageId.Value, Title, bf);
}
else
{
var m = await this.Device.Send(this.Title, bf);
this.MessageId = m.MessageId;
var m = await Device.Send(Title, bf);
MessageId = m.MessageId;
}
}
@@ -268,9 +252,9 @@ namespace TelegramBotBase.Controls.Inline
public override async Task Cleanup()
{
if (this.MessageId != null)
if (MessageId != null)
{
await this.Device.DeleteMessage(this.MessageId.Value);
await Device.DeleteMessage(MessageId.Value);
}
}
+3 -11
View File
@@ -1,12 +1,4 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Enums;
using TelegramBotBase.Form;
using TelegramBotBase.Enums;
namespace TelegramBotBase.Controls.Inline
{
@@ -17,8 +9,8 @@ namespace TelegramBotBase.Controls.Inline
public MonthPicker()
{
this.PickerMode = eMonthPickerMode.month;
this.EnableDayView = false;
PickerMode = EMonthPickerMode.month;
EnableDayView = false;
}
@@ -1,11 +1,10 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
using TelegramBotBase.Localizations;
namespace TelegramBotBase.Controls.Inline
{
@@ -14,25 +13,25 @@ namespace TelegramBotBase.Controls.Inline
/// <summary>
/// This contains the selected icon.
/// </summary>
public String SelectedIcon { get; set; } = Localizations.Default.Language["MultiToggleButton_SelectedIcon"];
public string SelectedIcon { get; set; } = Default.Language["MultiToggleButton_SelectedIcon"];
/// <summary>
/// This will appear on the ConfirmAction message (if not empty)
/// </summary>
public String ChangedString { get; set; } = Localizations.Default.Language["MultiToggleButton_Changed"];
public string ChangedString { get; set; } = Default.Language["MultiToggleButton_Changed"];
/// <summary>
/// This holds the title of the control.
/// </summary>
public String Title { get; set; } = Localizations.Default.Language["MultiToggleButton_Title"];
public string Title { get; set; } = Default.Language["MultiToggleButton_Title"];
public int? MessageId { get; set; }
private bool RenderNecessary = true;
private bool _renderNecessary = true;
private static readonly object __evToggled = new object();
private static readonly object EvToggled = new object();
private readonly EventHandlerList Events = new EventHandlerList();
private readonly EventHandlerList _events = new EventHandlerList();
/// <summary>
/// This will hold all options available.
@@ -52,27 +51,21 @@ namespace TelegramBotBase.Controls.Inline
public event EventHandler Toggled
{
add
{
this.Events.AddHandler(__evToggled, value);
}
remove
{
this.Events.RemoveHandler(__evToggled, value);
}
add => _events.AddHandler(EvToggled, value);
remove => _events.RemoveHandler(EvToggled, value);
}
public void OnToggled(EventArgs e)
{
(this.Events[__evToggled] as EventHandler)?.Invoke(this, e);
(_events[EvToggled] as EventHandler)?.Invoke(this, e);
}
public override async Task Action(MessageResult result, String value = null)
public override async Task Action(MessageResult result, string value = null)
{
if (result.Handled)
return;
await result.ConfirmAction(this.ChangedString);
await result.ConfirmAction(ChangedString);
switch (value ?? "unknown")
{
@@ -82,30 +75,30 @@ namespace TelegramBotBase.Controls.Inline
if (s[0] == "check" && s.Length > 1)
{
int index = 0;
var index = 0;
if (!int.TryParse(s[1], out index))
{
return;
}
if(SelectedOption== null || SelectedOption != this.Options[index])
if(SelectedOption== null || SelectedOption != Options[index])
{
this.SelectedOption = this.Options[index];
OnToggled(new EventArgs());
SelectedOption = Options[index];
OnToggled(EventArgs.Empty);
}
else if(this.AllowEmptySelection)
else if(AllowEmptySelection)
{
this.SelectedOption = null;
OnToggled(new EventArgs());
SelectedOption = null;
OnToggled(EventArgs.Empty);
}
RenderNecessary = true;
_renderNecessary = true;
return;
}
RenderNecessary = false;
_renderNecessary = false;
break;
@@ -117,16 +110,16 @@ namespace TelegramBotBase.Controls.Inline
public override async Task Render(MessageResult result)
{
if (!RenderNecessary)
if (!_renderNecessary)
return;
var bf = new ButtonForm(this);
var lst = new List<ButtonBase>();
foreach (var o in this.Options)
foreach (var o in Options)
{
var index = this.Options.IndexOf(o);
if (o == this.SelectedOption)
var index = Options.IndexOf(o);
if (o == SelectedOption)
{
lst.Add(new ButtonBase(SelectedIcon + " " + o.Text, "check$" + index));
continue;
@@ -137,20 +130,20 @@ namespace TelegramBotBase.Controls.Inline
bf.AddButtonRow(lst);
if (this.MessageId != null)
if (MessageId != null)
{
var m = await this.Device.Edit(this.MessageId.Value, this.Title, bf);
var m = await Device.Edit(MessageId.Value, Title, bf);
}
else
{
var m = await this.Device.Send(this.Title, bf, disableNotification: true);
var m = await Device.Send(Title, bf, disableNotification: true);
if (m != null)
{
this.MessageId = m.MessageId;
MessageId = m.MessageId;
}
}
this.RenderNecessary = false;
_renderNecessary = false;
}
+90 -119
View File
@@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
@@ -10,9 +7,9 @@ namespace TelegramBotBase.Controls.Inline
/// <summary>
/// A simple control for show and managing progress.
/// </summary>
public class ProgressBar : Base.ControlBase
public class ProgressBar : ControlBase
{
public enum eProgressStyle
public enum EProgressStyle
{
standard = 0,
squares = 1,
@@ -22,104 +19,78 @@ namespace TelegramBotBase.Controls.Inline
custom = 10
}
public eProgressStyle ProgressStyle
public EProgressStyle ProgressStyle
{
get
{
return m_eStyle;
}
get => _mEStyle;
set
{
m_eStyle = value;
_mEStyle = value;
LoadStyle();
}
}
private eProgressStyle m_eStyle = eProgressStyle.standard;
private EProgressStyle _mEStyle = EProgressStyle.standard;
public int Value
{
get
{
return this.m_iValue;
}
get => _mIValue;
set
{
if (value > this.Max)
if (value > Max)
{
return;
}
if (this.m_iValue != value)
if (_mIValue != value)
{
this.RenderNecessary = true;
RenderNecessary = true;
}
this.m_iValue = value;
_mIValue = value;
}
}
private int m_iValue = 0;
private int _mIValue;
public int Max
{
get
{
return this.m_iMax;
}
get => _mIMax;
set
{
if (this.m_iMax != value)
if (_mIMax != value)
{
this.RenderNecessary = true;
RenderNecessary = true;
}
this.m_iMax = value;
_mIMax = value;
}
}
private int m_iMax = 100;
private int _mIMax = 100;
public int? MessageId { get; set; }
private bool RenderNecessary { get; set; } = false;
private bool RenderNecessary { get; set; }
public int Steps
{
get
{
switch (this.ProgressStyle)
return ProgressStyle switch
{
case eProgressStyle.standard:
return 1;
case eProgressStyle.squares:
return 10;
case eProgressStyle.circles:
return 10;
case eProgressStyle.lines:
return 5;
case eProgressStyle.squaredLines:
return 5;
default:
return 1;
}
EProgressStyle.standard => 1,
EProgressStyle.squares => 10,
EProgressStyle.circles => 10,
EProgressStyle.lines => 5,
EProgressStyle.squaredLines => 5,
_ => 1
};
}
}
/// <summary>
/// Filled block (reached percentage)
/// </summary>
public String BlockChar
public string BlockChar
{
get; set;
}
@@ -127,7 +98,7 @@ namespace TelegramBotBase.Controls.Inline
/// <summary>
/// Unfilled block (not reached yet)
/// </summary>
public String EmptyBlockChar
public string EmptyBlockChar
{
get; set;
}
@@ -135,7 +106,7 @@ namespace TelegramBotBase.Controls.Inline
/// <summary>
/// String at the beginning of the progress bar
/// </summary>
public String StartChar
public string StartChar
{
get; set;
}
@@ -143,133 +114,133 @@ namespace TelegramBotBase.Controls.Inline
/// <summary>
/// String at the end of the progress bar
/// </summary>
public String EndChar
public string EndChar
{
get; set;
}
public ProgressBar()
{
this.ProgressStyle = eProgressStyle.standard;
ProgressStyle = EProgressStyle.standard;
this.Value = 0;
this.Max = 100;
Value = 0;
Max = 100;
this.RenderNecessary = true;
RenderNecessary = true;
}
public ProgressBar(int Value, int Max, eProgressStyle Style)
public ProgressBar(int value, int max, EProgressStyle style)
{
this.Value = Value;
this.Max = Max;
this.ProgressStyle = Style;
this.Value = value;
this.Max = max;
ProgressStyle = style;
this.RenderNecessary = true;
RenderNecessary = true;
}
public override async Task Cleanup()
{
if (this.MessageId == null || this.MessageId == -1)
if (MessageId == null || MessageId == -1)
return;
await this.Device.DeleteMessage(this.MessageId.Value);
await Device.DeleteMessage(MessageId.Value);
}
public void LoadStyle()
{
this.StartChar = "";
this.EndChar = "";
StartChar = "";
EndChar = "";
switch (this.ProgressStyle)
switch (ProgressStyle)
{
case eProgressStyle.circles:
case EProgressStyle.circles:
this.BlockChar = "⚫️ ";
this.EmptyBlockChar = "⚪️ ";
BlockChar = "⚫️ ";
EmptyBlockChar = "⚪️ ";
break;
case eProgressStyle.squares:
case EProgressStyle.squares:
this.BlockChar = "⬛️ ";
this.EmptyBlockChar = "⬜️ ";
BlockChar = "⬛️ ";
EmptyBlockChar = "⬜️ ";
break;
case eProgressStyle.lines:
case EProgressStyle.lines:
this.BlockChar = "█";
this.EmptyBlockChar = "▁";
BlockChar = "█";
EmptyBlockChar = "▁";
break;
case eProgressStyle.squaredLines:
case EProgressStyle.squaredLines:
this.BlockChar = "▇";
this.EmptyBlockChar = "—";
BlockChar = "▇";
EmptyBlockChar = "—";
this.StartChar = "[";
this.EndChar = "]";
StartChar = "[";
EndChar = "]";
break;
case eProgressStyle.standard:
case eProgressStyle.custom:
case EProgressStyle.standard:
case EProgressStyle.custom:
this.BlockChar = "";
this.EmptyBlockChar = "";
BlockChar = "";
EmptyBlockChar = "";
break;
}
}
public async override Task Render(MessageResult result)
public override async Task Render(MessageResult result)
{
if (!this.RenderNecessary)
if (!RenderNecessary)
{
return;
}
if (this.Device == null)
if (Device == null)
{
return;
}
String message = "";
int blocks = 0;
int maxBlocks = 0;
var message = "";
var blocks = 0;
var maxBlocks = 0;
switch (this.ProgressStyle)
switch (ProgressStyle)
{
case eProgressStyle.standard:
case EProgressStyle.standard:
message = this.Value.ToString("0") + "%";
message = Value.ToString("0") + "%";
break;
case eProgressStyle.squares:
case eProgressStyle.circles:
case eProgressStyle.lines:
case eProgressStyle.squaredLines:
case eProgressStyle.custom:
case EProgressStyle.squares:
case EProgressStyle.circles:
case EProgressStyle.lines:
case EProgressStyle.squaredLines:
case EProgressStyle.custom:
blocks = (int)Math.Floor((decimal)this.Value / this.Steps);
blocks = (int)Math.Floor((decimal)Value / Steps);
maxBlocks = (this.Max / this.Steps);
maxBlocks = (Max / Steps);
message += this.StartChar;
message += StartChar;
for (int i = 0; i < blocks; i++)
for (var i = 0; i < blocks; i++)
{
message += this.BlockChar;
message += BlockChar;
}
for (int i = 0; i < (maxBlocks - blocks); i++)
for (var i = 0; i < (maxBlocks - blocks); i++)
{
message += this.EmptyBlockChar;
message += EmptyBlockChar;
}
message += this.EndChar;
message += EndChar;
message += " " + this.Value.ToString("0") + "%";
message += " " + Value.ToString("0") + "%";
break;
@@ -278,18 +249,18 @@ namespace TelegramBotBase.Controls.Inline
return;
}
if (this.MessageId == null)
if (MessageId == null)
{
var m = await this.Device.Send(message);
var m = await Device.Send(message);
this.MessageId = m.MessageId;
MessageId = m.MessageId;
}
else
{
await this.Device.Edit(this.MessageId.Value, message);
await Device.Edit(MessageId.Value, message);
}
this.RenderNecessary = false;
RenderNecessary = false;
}
}
+35 -43
View File
@@ -1,38 +1,36 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
using TelegramBotBase.Localizations;
namespace TelegramBotBase.Controls.Inline
{
public class ToggleButton : ControlBase
{
public String UncheckedIcon { get; set; } = Localizations.Default.Language["ToggleButton_OffIcon"];
public string UncheckedIcon { get; set; } = Default.Language["ToggleButton_OffIcon"];
public String CheckedIcon { get; set; } = Localizations.Default.Language["ToggleButton_OnIcon"];
public string CheckedIcon { get; set; } = Default.Language["ToggleButton_OnIcon"];
public String CheckedString { get; set; } = Localizations.Default.Language["ToggleButton_On"];
public string CheckedString { get; set; } = Default.Language["ToggleButton_On"];
public String UncheckedString { get; set; } = Localizations.Default.Language["ToggleButton_Off"];
public string UncheckedString { get; set; } = Default.Language["ToggleButton_Off"];
public String ChangedString { get; set; } = Localizations.Default.Language["ToggleButton_Changed"];
public string ChangedString { get; set; } = Default.Language["ToggleButton_Changed"];
public String Title { get; set; } = Localizations.Default.Language["ToggleButton_Title"];
public string Title { get; set; } = Default.Language["ToggleButton_Title"];
public int? MessageId { get; set; }
public bool Checked { get; set; }
private bool RenderNecessary = true;
private bool _renderNecessary = true;
private static readonly object __evToggled = new object();
private static readonly object EvToggled = new object();
private readonly EventHandlerList Events = new EventHandlerList();
private readonly EventHandlerList _events = new EventHandlerList();
public ToggleButton()
@@ -41,68 +39,62 @@ namespace TelegramBotBase.Controls.Inline
}
public ToggleButton(String CheckedString, String UncheckedString)
public ToggleButton(string checkedString, string uncheckedString)
{
this.CheckedString = CheckedString;
this.UncheckedString = UncheckedString;
this.CheckedString = checkedString;
this.UncheckedString = uncheckedString;
}
public event EventHandler Toggled
{
add
{
this.Events.AddHandler(__evToggled, value);
}
remove
{
this.Events.RemoveHandler(__evToggled, value);
}
add => _events.AddHandler(EvToggled, value);
remove => _events.RemoveHandler(EvToggled, value);
}
public void OnToggled(EventArgs e)
{
(this.Events[__evToggled] as EventHandler)?.Invoke(this, e);
(_events[EvToggled] as EventHandler)?.Invoke(this, e);
}
public override async Task Action(MessageResult result, String value = null)
public override async Task Action(MessageResult result, string value = null)
{
if (result.Handled)
return;
await result.ConfirmAction(this.ChangedString);
await result.ConfirmAction(ChangedString);
switch (value ?? "unknown")
{
case "on":
if (this.Checked)
if (Checked)
return;
RenderNecessary = true;
_renderNecessary = true;
this.Checked = true;
Checked = true;
OnToggled(new EventArgs());
OnToggled(EventArgs.Empty);
break;
case "off":
if (!this.Checked)
if (!Checked)
return;
RenderNecessary = true;
_renderNecessary = true;
this.Checked = false;
Checked = false;
OnToggled(new EventArgs());
OnToggled(EventArgs.Empty);
break;
default:
RenderNecessary = false;
_renderNecessary = false;
break;
@@ -114,31 +106,31 @@ namespace TelegramBotBase.Controls.Inline
public override async Task Render(MessageResult result)
{
if (!RenderNecessary)
if (!_renderNecessary)
return;
var bf = new ButtonForm(this);
ButtonBase bOn = new ButtonBase((this.Checked ? CheckedIcon : UncheckedIcon) + " " + CheckedString, "on");
var bOn = new ButtonBase((Checked ? CheckedIcon : UncheckedIcon) + " " + CheckedString, "on");
ButtonBase bOff = new ButtonBase((!this.Checked ? CheckedIcon : UncheckedIcon) + " " + UncheckedString, "off");
var bOff = new ButtonBase((!Checked ? CheckedIcon : UncheckedIcon) + " " + UncheckedString, "off");
bf.AddButtonRow(bOn, bOff);
if (this.MessageId != null)
if (MessageId != null)
{
var m = await this.Device.Edit(this.MessageId.Value, this.Title, bf);
var m = await Device.Edit(MessageId.Value, Title, bf);
}
else
{
var m = await this.Device.Send(this.Title, bf, disableNotification: true);
var m = await Device.Send(Title, bf, disableNotification: true);
if (m != null)
{
this.MessageId = m.MessageId;
MessageId = m.MessageId;
}
}
this.RenderNecessary = false;
_renderNecessary = false;
}
+22 -23
View File
@@ -1,10 +1,9 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
using TelegramBotBase.Localizations;
namespace TelegramBotBase.Controls.Inline
{
@@ -16,20 +15,20 @@ namespace TelegramBotBase.Controls.Inline
public TreeViewNode VisibleNode { get; set; }
public String Title { get; set; }
public string Title { get; set; }
private int? MessageId { get; set; }
public String MoveUpIcon { get; set; } = Localizations.Default.Language["TreeView_LevelUp"];
public string MoveUpIcon { get; set; } = Default.Language["TreeView_LevelUp"];
public TreeView()
{
this.Nodes = new List<TreeViewNode>();
this.Title = Localizations.Default.Language["TreeView_Title"];
Nodes = new List<TreeViewNode>();
Title = Default.Language["TreeView_Title"];
}
public override async Task Action(MessageResult result, String value = null)
public override async Task Action(MessageResult result, string value = null)
{
await result.ConfirmAction();
@@ -43,14 +42,14 @@ namespace TelegramBotBase.Controls.Inline
case "up":
case "parent":
this.VisibleNode = (this.VisibleNode?.ParentNode);
VisibleNode = (VisibleNode?.ParentNode);
result.Handled = true;
break;
default:
var n = (this.VisibleNode != null ? this.VisibleNode.FindNodeByValue(val) : this.Nodes.FirstOrDefault(a => a.Value == val));
var n = (VisibleNode != null ? VisibleNode.FindNodeByValue(val) : Nodes.FirstOrDefault(a => a.Value == val));
if (n == null)
return;
@@ -58,11 +57,11 @@ namespace TelegramBotBase.Controls.Inline
if (n.ChildNodes.Count > 0)
{
this.VisibleNode = n;
VisibleNode = n;
}
else
{
this.SelectedNode = (this.SelectedNode != n ? n : null);
SelectedNode = (SelectedNode != n ? n : null);
}
result.Handled = true;
@@ -77,21 +76,21 @@ namespace TelegramBotBase.Controls.Inline
public override async Task Render(MessageResult result)
{
var startnode = this.VisibleNode;
var startnode = VisibleNode;
var nodes = (startnode?.ChildNodes ?? this.Nodes);
var nodes = (startnode?.ChildNodes ?? Nodes);
ButtonForm bf = new ButtonForm();
var bf = new ButtonForm();
if (startnode != null)
{
bf.AddButtonRow(new ButtonBase(this.MoveUpIcon, "up"), new ButtonBase(startnode.Text, "parent"));
bf.AddButtonRow(new ButtonBase(MoveUpIcon, "up"), new ButtonBase(startnode.Text, "parent"));
}
foreach (var n in nodes)
{
var s = n.Text;
if (this.SelectedNode == n)
if (SelectedNode == n)
{
s = "[ " + s + " ]";
}
@@ -101,20 +100,20 @@ namespace TelegramBotBase.Controls.Inline
if (this.MessageId != null)
if (MessageId != null)
{
var m = await this.Device.Edit(this.MessageId.Value, this.Title, bf);
var m = await Device.Edit(MessageId.Value, Title, bf);
}
else
{
var m = await this.Device.Send(this.Title, bf);
this.MessageId = m.MessageId;
var m = await Device.Send(Title, bf);
MessageId = m.MessageId;
}
}
public String GetPath()
public string GetPath()
{
return (this.VisibleNode?.GetPath() ?? "\\");
return (VisibleNode?.GetPath() ?? "\\");
}
+14 -17
View File
@@ -1,35 +1,32 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TelegramBotBase.Controls.Inline
{
public class TreeViewNode
{
public String Text { get; set; }
public string Text { get; set; }
public String Value { get; set; }
public string Value { get; set; }
public String Url { get; set; }
public string Url { get; set; }
public List<TreeViewNode> ChildNodes { get; set; } = new List<TreeViewNode>();
public TreeViewNode ParentNode { get; set; }
public TreeViewNode(String Text, String Value)
public TreeViewNode(string text, string value)
{
this.Text = Text;
this.Value = Value;
this.Text = text;
this.Value = value;
}
public TreeViewNode(String Text, String Value, String Url) : this(Text, Value)
public TreeViewNode(string text, string value, string url) : this(text, value)
{
this.Url = Url;
this.Url = url;
}
public TreeViewNode(String Text, String Value, params TreeViewNode[] childnodes) : this(Text, Value)
public TreeViewNode(string text, string value, params TreeViewNode[] childnodes) : this(text, value)
{
foreach(var c in childnodes)
{
@@ -44,14 +41,14 @@ namespace TelegramBotBase.Controls.Inline
ChildNodes.Add(node);
}
public TreeViewNode FindNodeByValue(String Value)
public TreeViewNode FindNodeByValue(string value)
{
return this.ChildNodes.FirstOrDefault(a => a.Value == Value);
return ChildNodes.FirstOrDefault(a => a.Value == value);
}
public String GetPath()
public string GetPath()
{
String s = "\\" + this.Value;
var s = "\\" + Value;
var p = this;
while (p.ParentNode != null)
{
@@ -1,36 +1,29 @@
using System;
using System.Collections.Generic;
using System.Text;
using TelegramBotBase.Controls.Hybrid;
using TelegramBotBase.Form;
using TelegramBotBase.Interfaces;
namespace TelegramBotBase.Datasources
namespace TelegramBotBase.DataSources
{
public class ButtonFormDataSource : Interfaces.IDataSource<ButtonRow>
public class ButtonFormDataSource : IDataSource<ButtonRow>
{
public virtual ButtonForm ButtonForm
{
get
{
return __buttonform;
}
set
{
__buttonform = value;
}
get => _buttonform;
set => _buttonform = value;
}
private ButtonForm __buttonform = null;
private ButtonForm _buttonform;
public ButtonFormDataSource()
{
__buttonform = new ButtonForm();
_buttonform = new ButtonForm();
}
public ButtonFormDataSource(ButtonForm bf)
{
__buttonform = bf;
_buttonform = bf;
}
@@ -71,9 +64,9 @@ namespace TelegramBotBase.Datasources
return ButtonForm.ToArray();
}
public virtual ButtonForm PickItems(int start, int count, String filter = null)
public virtual ButtonForm PickItems(int start, int count, string filter = null)
{
ButtonForm bf = new ButtonForm();
var bf = new ButtonForm();
ButtonForm dataForm = null;
if (filter == null)
@@ -85,9 +78,9 @@ namespace TelegramBotBase.Datasources
dataForm = ButtonForm.FilterDuplicate(filter, true);
}
for (int i = 0; i < count; i++)
for (var i = 0; i < count; i++)
{
int it = start + i;
var it = start + i;
if (it > dataForm.Rows - 1)
break;
@@ -98,7 +91,7 @@ namespace TelegramBotBase.Datasources
return bf;
}
public virtual ButtonForm PickAllItems(String filter = null)
public virtual ButtonForm PickAllItems(string filter = null)
{
if (filter == null)
return ButtonForm.Duplicate();
@@ -107,7 +100,7 @@ namespace TelegramBotBase.Datasources
return ButtonForm.FilterDuplicate(filter, true);
}
public virtual Tuple<ButtonRow, int> FindRow(String text, bool useText = true)
public virtual Tuple<ButtonRow, int> FindRow(string text, bool useText = true)
{
return ButtonForm.FindRow(text, useText);
}
@@ -117,7 +110,7 @@ namespace TelegramBotBase.Datasources
/// </summary>
/// <param name="filter"></param>
/// <returns></returns>
public virtual int CalculateMax(String filter = null)
public virtual int CalculateMax(string filter = null)
{
return PickAllItems(filter).Rows;
}
@@ -1,13 +1,12 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TelegramBotBase.Interfaces;
namespace TelegramBotBase.Datasources
namespace TelegramBotBase.DataSources
{
public class StaticDataSource<T> : Interfaces.IDataSource<T>
public class StaticDataSource<T> : IDataSource<T>
{
List<T> Data { get; set; }
private List<T> Data { get; set; }
public StaticDataSource()
{
@@ -16,17 +15,11 @@ namespace TelegramBotBase.Datasources
public StaticDataSource(List<T> data)
{
this.Data = data;
Data = data;
}
public int Count
{
get
{
return Data.Count;
}
}
public int Count => Data.Count;
public T ItemAt(int index)
{
+2 -8
View File
@@ -1,12 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TelegramBotBase.Enums
namespace TelegramBotBase.Enums
{
public enum eDeleteMode
public enum EDeleteMode
{
/// <summary>
/// Don't delete any message.
+2 -8
View File
@@ -1,12 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TelegramBotBase.Enums
namespace TelegramBotBase.Enums
{
public enum eDeleteSide
public enum EDeleteSide
{
/// <summary>
/// Delete only messages from this bot.
+2 -8
View File
@@ -1,12 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TelegramBotBase.Enums
namespace TelegramBotBase.Enums
{
public enum eKeyboardType
public enum EKeyboardType
{
/// <summary>
/// Uses a ReplyKeyboardMarkup
+2 -8
View File
@@ -1,12 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TelegramBotBase.Enums
namespace TelegramBotBase.Enums
{
public enum eMonthPickerMode
public enum EMonthPickerMode
{
/// <summary>
/// Shows the calendar with day picker mode
@@ -1,10 +1,6 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace TelegramBotBase.Enums
namespace TelegramBotBase.Enums
{
public enum eNavigationBarVisibility
public enum ENavigationBarVisibility
{
/// <summary>
/// Shows it depending on the amount of items.
+2 -6
View File
@@ -1,10 +1,6 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace TelegramBotBase.Enums
namespace TelegramBotBase.Enums
{
public enum eSettings
public enum ESettings
{
/// <summary>
/// How often could a form navigate to another (within one user action/call/message)
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TelegramBotBase.Exceptions
{
@@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace TelegramBotBase.Exceptions
{
@@ -11,12 +9,6 @@ namespace TelegramBotBase.Exceptions
public int Maximum { get; set; }
public override string Message
{
get
{
return $"You have exceeded the maximum of columns by {Value.ToString()} / {Maximum.ToString()}";
}
}
public override string Message => $"You have exceeded the maximum of columns by {Value.ToString()} / {Maximum.ToString()}";
}
}
@@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace TelegramBotBase.Exceptions
{
@@ -11,12 +9,6 @@ namespace TelegramBotBase.Exceptions
public int Maximum { get; set; }
public override string Message
{
get
{
return $"You have exceeded the maximum of rows by {Value.ToString()} / {Maximum.ToString()}";
}
}
public override string Message => $"You have exceeded the maximum of rows by {Value.ToString()} / {Maximum.ToString()}";
}
}
@@ -1,11 +1,10 @@
using System;
using System.Collections.Generic;
using System.Text;
using TelegramBotBase.Form;
using TelegramBotBase.Interfaces;
namespace TelegramBotBase.Factories
{
public class DefaultStartFormFactory : Interfaces.IStartFormFactory
public class DefaultStartFormFactory : IStartFormFactory
{
private readonly Type _startFormClass;
@@ -1,11 +1,9 @@
using System;
using System.Collections.Generic;
using System.Text;
using TelegramBotBase.Form;
using TelegramBotBase.Form;
using TelegramBotBase.Interfaces;
namespace TelegramBotBase.Factories
{
public class LambdaStartFormFactory : Interfaces.IStartFormFactory
public class LambdaStartFormFactory : IStartFormFactory
{
public delegate FormBase CreateFormDelegate();
+5 -12
View File
@@ -1,11 +1,4 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Attributes;
using TelegramBotBase.Base;
using TelegramBotBase.Attributes;
namespace TelegramBotBase.Form
{
@@ -15,12 +8,12 @@ namespace TelegramBotBase.Form
[IgnoreState]
public class AlertDialog : ConfirmDialog
{
public String ButtonText { get; set; }
public string ButtonText { get; set; }
public AlertDialog(String Message, String ButtonText) : base(Message)
public AlertDialog(string message, string buttonText) : base(message)
{
this.Buttons.Add(new ButtonBase(ButtonText, "ok"));
this.ButtonText = ButtonText;
Buttons.Add(new ButtonBase(buttonText, "ok"));
this.ButtonText = buttonText;
}
+19 -28
View File
@@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Attributes;
@@ -19,7 +18,7 @@ namespace TelegramBotBase.Form
/// <summary>
/// The message the users sees.
/// </summary>
public String Message { get; set; }
public string Message { get; set; }
/// <summary>
/// An additional optional value.
@@ -29,26 +28,24 @@ namespace TelegramBotBase.Form
public ButtonBase[][] Buttons { get; set; }
[Obsolete]
public Dictionary<String, FormBase> ButtonForms { get; set; } = new Dictionary<string, FormBase>();
public Dictionary<string, FormBase> ButtonForms { get; set; } = new Dictionary<string, FormBase>();
private EventHandlerList __Events { get; set; } = new EventHandlerList();
private static object __evButtonClicked { get; } = new object();
private static object EvButtonClicked { get; } = new object();
public ArrayPromptDialog()
{
}
public ArrayPromptDialog(String Message)
public ArrayPromptDialog(string message)
{
this.Message = Message;
this.Message = message;
}
public ArrayPromptDialog(String Message, params ButtonBase[][] Buttons)
public ArrayPromptDialog(string message, params ButtonBase[][] buttons)
{
this.Message = Message;
this.Buttons = Buttons;
this.Message = message;
this.Buttons = buttons;
}
public override async Task Action(MessageResult message)
@@ -64,59 +61,53 @@ namespace TelegramBotBase.Form
await message.DeleteMessage();
var buttons = this.Buttons.Aggregate((a, b) => a.Union(b).ToArray()).ToList();
var buttons = Buttons.Aggregate((a, b) => a.Union(b).ToArray()).ToList();
if(call==null)
{
return;
}
ButtonBase button = buttons.FirstOrDefault(a => a.Value == call.Value);
var button = buttons.FirstOrDefault(a => a.Value == call.Value);
if (button == null)
{
return;
}
OnButtonClicked(new ButtonClickedEventArgs(button) { Tag = this.Tag });
OnButtonClicked(new ButtonClickedEventArgs(button) { Tag = Tag });
FormBase fb = ButtonForms.ContainsKey(call.Value) ? ButtonForms[call.Value] : null;
var fb = ButtonForms.ContainsKey(call.Value) ? ButtonForms[call.Value] : null;
if (fb != null)
{
await this.NavigateTo(fb);
await NavigateTo(fb);
}
}
public override async Task Render(MessageResult message)
{
ButtonForm btn = new ButtonForm();
var btn = new ButtonForm();
foreach(var bl in this.Buttons)
foreach(var bl in Buttons)
{
btn.AddButtonRow(bl.Select(a => new ButtonBase(a.Text, CallbackData.Create("action", a.Value))).ToList());
}
await this.Device.Send(this.Message, btn);
await Device.Send(Message, btn);
}
public event EventHandler<ButtonClickedEventArgs> ButtonClicked
{
add
{
this.__Events.AddHandler(__evButtonClicked, value);
}
remove
{
this.__Events.RemoveHandler(__evButtonClicked, value);
}
add => Events.AddHandler(EvButtonClicked, value);
remove => Events.RemoveHandler(EvButtonClicked, value);
}
public void OnButtonClicked(ButtonClickedEventArgs e)
{
(this.__Events[__evButtonClicked] as EventHandler<ButtonClickedEventArgs>)?.Invoke(this, e);
(Events[EvButtonClicked] as EventHandler<ButtonClickedEventArgs>)?.Invoke(this, e);
}
}
}
+35 -32
View File
@@ -22,35 +22,36 @@ namespace TelegramBotBase.Form
public List<int> OldMessages { get; set; }
[SaveState]
public eDeleteMode DeleteMode { get; set; }
public EDeleteMode DeleteMode { get; set; }
[SaveState]
public eDeleteSide DeleteSide { get; set; }
public EDeleteSide DeleteSide { get; set; }
public AutoCleanForm()
{
this.OldMessages = new List<int>();
this.DeleteMode = eDeleteMode.OnEveryCall;
this.DeleteSide = eDeleteSide.BotOnly;
OldMessages = new List<int>();
DeleteMode = EDeleteMode.OnEveryCall;
DeleteSide = EDeleteSide.BotOnly;
this.Init += AutoCleanForm_Init;
Init += AutoCleanForm_Init;
this.Closed += AutoCleanForm_Closed;
Closed += AutoCleanForm_Closed;
}
private async Task AutoCleanForm_Init(object sender, InitEventArgs e)
private Task AutoCleanForm_Init(object sender, InitEventArgs e)
{
if (this.Device == null)
return;
if (Device == null)
return Task.CompletedTask;
this.Device.MessageSent += Device_MessageSent;
Device.MessageSent += Device_MessageSent;
this.Device.MessageReceived += Device_MessageReceived;
Device.MessageReceived += Device_MessageReceived;
this.Device.MessageDeleted += Device_MessageDeleted;
Device.MessageDeleted += Device_MessageDeleted;
return Task.CompletedTask;
}
private void Device_MessageDeleted(object sender, MessageDeletedEventArgs e)
@@ -61,23 +62,24 @@ namespace TelegramBotBase.Form
private void Device_MessageReceived(object sender, MessageReceivedEventArgs e)
{
if (this.DeleteSide == eDeleteSide.BotOnly)
if (DeleteSide == EDeleteSide.BotOnly)
return;
this.OldMessages.Add(e.Message.MessageId);
OldMessages.Add(e.Message.MessageId);
}
private async Task Device_MessageSent(object sender, MessageSentEventArgs e)
private Task Device_MessageSent(object sender, MessageSentEventArgs e)
{
if (this.DeleteSide == eDeleteSide.UserOnly)
return;
if (DeleteSide == EDeleteSide.UserOnly)
return Task.CompletedTask;
this.OldMessages.Add(e.Message.MessageId);
OldMessages.Add(e.Message.MessageId);
return Task.CompletedTask;
}
public override async Task PreLoad(MessageResult message)
{
if (this.DeleteMode != eDeleteMode.OnEveryCall)
if (DeleteMode != EDeleteMode.OnEveryCall)
return;
await MessageCleanup();
@@ -89,7 +91,7 @@ namespace TelegramBotBase.Form
/// <param name="Id"></param>
public void AddMessage(Message m)
{
this.OldMessages.Add(m.MessageId);
OldMessages.Add(m.MessageId);
}
@@ -99,16 +101,16 @@ namespace TelegramBotBase.Form
/// <param name="Id"></param>
public void AddMessage(int messageId)
{
this.OldMessages.Add(messageId);
OldMessages.Add(messageId);
}
/// <summary>
/// Keeps the message by removing it from the list
/// </summary>
/// <param name="Id"></param>
public void LeaveMessage(int Id)
/// <param name="id"></param>
public void LeaveMessage(int id)
{
this.OldMessages.Remove(Id);
OldMessages.Remove(id);
}
/// <summary>
@@ -116,18 +118,19 @@ namespace TelegramBotBase.Form
/// </summary>
public void LeaveLastMessage()
{
if (this.OldMessages.Count == 0)
if (OldMessages.Count == 0)
return;
this.OldMessages.RemoveAt(this.OldMessages.Count - 1);
OldMessages.RemoveAt(OldMessages.Count - 1);
}
private async Task AutoCleanForm_Closed(object sender, EventArgs e)
private Task AutoCleanForm_Closed(object sender, EventArgs e)
{
if (this.DeleteMode != eDeleteMode.OnLeavingForm)
return;
if (DeleteMode != EDeleteMode.OnLeavingForm)
return Task.CompletedTask;
MessageCleanup().Wait();
return Task.CompletedTask;
}
/// <summary>
@@ -167,7 +170,7 @@ namespace TelegramBotBase.Form
var retryAfterSeconds = ex.InnerExceptions
.Where(e => e is ApiRequestException apiEx && apiEx.ErrorCode == 429)
.Max(e => (int?)((ApiRequestException)e).Parameters.RetryAfter) ?? 0;
.Max(e => ((ApiRequestException)e).Parameters.RetryAfter) ?? 0;
retryAfterTask = Task.Delay(retryAfterSeconds * 1000);
}
@@ -207,7 +210,7 @@ namespace TelegramBotBase.Form
var retryAfterSeconds = ex.InnerExceptions
.Where(e => e is ApiRequestException apiEx && apiEx.ErrorCode == 429)
.Max(e => (int?)((ApiRequestException)e).Parameters.RetryAfter) ?? 0;
.Max(e => ((ApiRequestException)e).Parameters.RetryAfter) ?? 0;
retryAfterTask = Task.Delay(retryAfterSeconds * 1000);
}
+17 -21
View File
@@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using Telegram.Bot.Types.ReplyMarkups;
namespace TelegramBotBase.Form
@@ -14,22 +9,22 @@ namespace TelegramBotBase.Form
/// </summary>
public class ButtonBase
{
public virtual String Text { get; set; }
public virtual string Text { get; set; }
public String Value { get; set; }
public string Value { get; set; }
public String Url { get; set; }
public string Url { get; set; }
public ButtonBase()
{
}
public ButtonBase(String Text, String Value, String Url = null)
public ButtonBase(string text, string value, string url = null)
{
this.Text = Text;
this.Value = Value;
this.Url = Url;
this.Text = text;
this.Value = value;
this.Url = url;
}
@@ -40,16 +35,17 @@ namespace TelegramBotBase.Form
/// <returns></returns>
public virtual InlineKeyboardButton ToInlineButton(ButtonForm form)
{
String id = (form.DependencyControl != null ? form.DependencyControl.ControlID + "_" : "");
if (this.Url == null)
var id = (form.DependencyControl != null ? form.DependencyControl.ControlId + "_" : "");
if (Url == null)
{
return InlineKeyboardButton.WithCallbackData(this.Text, id + this.Value);
return InlineKeyboardButton.WithCallbackData(Text, id + Value);
}
var ikb = new InlineKeyboardButton(this.Text);
//ikb.Text = this.Text;
ikb.Url = this.Url;
var ikb = new InlineKeyboardButton(Text)
{
//ikb.Text = this.Text;
Url = Url
};
return ikb;
@@ -63,7 +59,7 @@ namespace TelegramBotBase.Form
/// <returns></returns>
public virtual KeyboardButton ToKeyboardButton(ButtonForm form)
{
return new KeyboardButton(this.Text);
return new KeyboardButton(Text);
}
}
+52 -70
View File
@@ -1,8 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types.ReplyMarkups;
using TelegramBotBase.Base;
using TelegramBotBase.Controls.Hybrid;
@@ -14,7 +12,7 @@ namespace TelegramBotBase.Form
/// </summary>
public class ButtonForm
{
List<ButtonRow> Buttons = new List<ButtonRow>();
private List<ButtonRow> _buttons = new List<ButtonRow>();
public IReplyMarkup Markup { get; set; }
@@ -24,13 +22,7 @@ namespace TelegramBotBase.Form
/// <summary>
/// Contains the number of rows.
/// </summary>
public int Rows
{
get
{
return Buttons.Count;
}
}
public int Rows => _buttons.Count;
/// <summary>
/// Contains the highest number of columns in an row.
@@ -39,18 +31,12 @@ namespace TelegramBotBase.Form
{
get
{
return Buttons.Select(a => a.Count).OrderByDescending(a => a).FirstOrDefault();
return _buttons.Select(a => a.Count).OrderByDescending(a => a).FirstOrDefault();
}
}
public ButtonRow this[int row]
{
get
{
return Buttons[row];
}
}
public ButtonRow this[int row] => _buttons[row];
public ButtonForm()
{
@@ -59,12 +45,12 @@ namespace TelegramBotBase.Form
public ButtonForm(ControlBase control)
{
this.DependencyControl = control;
DependencyControl = control;
}
public void AddButtonRow(String Text, String Value, String Url = null)
public void AddButtonRow(string text, string value, string url = null)
{
Buttons.Add(new List<ButtonBase>() { new ButtonBase(Text, Value, Url) });
_buttons.Add(new List<ButtonBase> { new ButtonBase(text, value, url) });
}
//public void AddButtonRow(ButtonRow row)
@@ -74,7 +60,7 @@ namespace TelegramBotBase.Form
public void AddButtonRow(ButtonRow row)
{
Buttons.Add(row);
_buttons.Add(row);
}
public void AddButtonRow(params ButtonBase[] row)
@@ -84,17 +70,17 @@ namespace TelegramBotBase.Form
public void AddButtonRows(IEnumerable<ButtonRow> rows)
{
Buttons.AddRange(rows);
_buttons.AddRange(rows);
}
public void InsertButtonRow(int index, IEnumerable<ButtonBase> row)
{
Buttons.Insert(index, row.ToList());
_buttons.Insert(index, row.ToList());
}
public void InsertButtonRow(int index, ButtonRow row)
{
Buttons.Insert(index, row);
_buttons.Insert(index, row);
}
//public void InsertButtonRow(int index, params ButtonBase[] row)
@@ -104,7 +90,7 @@ namespace TelegramBotBase.Form
public static T[][] SplitTo<T>(IEnumerable<T> items, int itemsPerRow = 2)
{
T[][] splitted = default(T[][]);
var splitted = default(T[][]);
try
{
@@ -126,10 +112,10 @@ namespace TelegramBotBase.Form
{
get
{
if (this.Buttons.Count == 0)
if (_buttons.Count == 0)
return 0;
return this.Buttons.Select(a => a.ToArray()).ToList().Aggregate((a, b) => a.Union(b).ToArray()).Length;
return _buttons.Select(a => a.ToArray()).ToList().Aggregate((a, b) => a.Union(b).ToArray()).Length;
}
}
@@ -140,7 +126,7 @@ namespace TelegramBotBase.Form
/// <param name="buttonsPerRow"></param>
public void AddSplitted(IEnumerable<ButtonBase> buttons, int buttonsPerRow = 2)
{
var sp = SplitTo<ButtonBase>(buttons, buttonsPerRow);
var sp = SplitTo(buttons, buttonsPerRow);
foreach (var bl in sp)
{
@@ -156,50 +142,50 @@ namespace TelegramBotBase.Form
/// <returns></returns>
public List<ButtonRow> GetRange(int start, int count)
{
return Buttons.Skip(start).Take(count).ToList();
return _buttons.Skip(start).Take(count).ToList();
}
public List<ButtonBase> ToList()
{
return this.Buttons.DefaultIfEmpty(new List<ButtonBase>()).Select(a => a.ToList()).Aggregate((a, b) => a.Union(b).ToList());
return _buttons.DefaultIfEmpty(new List<ButtonBase>()).Select(a => a.ToList()).Aggregate((a, b) => a.Union(b).ToList());
}
public InlineKeyboardButton[][] ToInlineButtonArray()
{
var ikb = this.Buttons.Select(a => a.ToArray().Select(b => b.ToInlineButton(this)).ToArray()).ToArray();
var ikb = _buttons.Select(a => a.ToArray().Select(b => b.ToInlineButton(this)).ToArray()).ToArray();
return ikb;
}
public KeyboardButton[][] ToReplyButtonArray()
{
var ikb = this.Buttons.Select(a => a.ToArray().Select(b => b.ToKeyboardButton(this)).ToArray()).ToArray();
var ikb = _buttons.Select(a => a.ToArray().Select(b => b.ToKeyboardButton(this)).ToArray()).ToArray();
return ikb;
}
public List<ButtonRow> ToArray()
{
return Buttons;
return _buttons;
}
public int FindRowByButton(ButtonBase button)
{
var row = this.Buttons.FirstOrDefault(a => a.ToArray().Count(b => b == button) > 0);
var row = _buttons.FirstOrDefault(a => a.ToArray().Count(b => b == button) > 0);
if (row == null)
return -1;
return this.Buttons.IndexOf(row);
return _buttons.IndexOf(row);
}
public Tuple<ButtonRow, int> FindRow(String text, bool useText = true)
public Tuple<ButtonRow, int> FindRow(string text, bool useText = true)
{
var r = this.Buttons.FirstOrDefault(a => a.Matches(text, useText));
var r = _buttons.FirstOrDefault(a => a.Matches(text, useText));
if (r == null)
return null;
var i = this.Buttons.IndexOf(r);
var i = _buttons.IndexOf(r);
return new Tuple<ButtonRow, int>(r, i);
}
@@ -209,9 +195,9 @@ namespace TelegramBotBase.Form
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public ButtonBase GetButtonByValue(String value)
public ButtonBase GetButtonByValue(string value)
{
return this.ToList().Where(a => a.Value == value).FirstOrDefault();
return ToList().Where(a => a.Value == value).FirstOrDefault();
}
public static implicit operator InlineKeyboardMarkup(ButtonForm form)
@@ -219,7 +205,7 @@ namespace TelegramBotBase.Form
if (form == null)
return null;
InlineKeyboardMarkup ikm = new InlineKeyboardMarkup(form.ToInlineButtonArray());
var ikm = new InlineKeyboardMarkup(form.ToInlineButtonArray());
return ikm;
}
@@ -229,7 +215,7 @@ namespace TelegramBotBase.Form
if (form == null)
return null;
ReplyKeyboardMarkup ikm = new ReplyKeyboardMarkup(form.ToReplyButtonArray());
var ikm = new ReplyKeyboardMarkup(form.ToReplyButtonArray());
return ikm;
}
@@ -240,20 +226,20 @@ namespace TelegramBotBase.Form
/// <returns></returns>
public ButtonForm Duplicate()
{
var bf = new ButtonForm()
var bf = new ButtonForm
{
Markup = this.Markup,
DependencyControl = this.DependencyControl
Markup = Markup,
DependencyControl = DependencyControl
};
foreach (var b in Buttons)
foreach (var b in _buttons)
{
var lst = new ButtonRow();
foreach (var b2 in b)
{
lst.Add(b2);
}
bf.Buttons.Add(lst);
bf._buttons.Add(lst);
}
return bf;
@@ -263,15 +249,15 @@ namespace TelegramBotBase.Form
/// Creates a copy of this form and filters by the parameter.
/// </summary>
/// <returns></returns>
public ButtonForm FilterDuplicate(String filter, bool ByRow = false)
public ButtonForm FilterDuplicate(string filter, bool byRow = false)
{
var bf = new ButtonForm()
var bf = new ButtonForm
{
Markup = this.Markup,
DependencyControl = this.DependencyControl
Markup = Markup,
DependencyControl = DependencyControl
};
foreach (var b in Buttons)
foreach (var b in _buttons)
{
var lst = new ButtonRow();
foreach (var b2 in b)
@@ -280,19 +266,17 @@ namespace TelegramBotBase.Form
continue;
//Copy full row, when at least one match has found.
if (ByRow)
if (byRow)
{
lst = b;
break;
}
else
{
lst.Add(b2);
}
lst.Add(b2);
}
if (lst.Count > 0)
bf.Buttons.Add(lst);
bf._buttons.Add(lst);
}
return bf;
@@ -302,15 +286,15 @@ namespace TelegramBotBase.Form
/// Creates a copy of this form and filters by the parameter.
/// </summary>
/// <returns></returns>
public ButtonForm TagDuplicate(List<String> tags, bool ByRow = false)
public ButtonForm TagDuplicate(List<string> tags, bool byRow = false)
{
var bf = new ButtonForm()
var bf = new ButtonForm
{
Markup = this.Markup,
DependencyControl = this.DependencyControl
Markup = Markup,
DependencyControl = DependencyControl
};
foreach (var b in Buttons)
foreach (var b in _buttons)
{
var lst = new ButtonRow();
foreach (var b2 in b)
@@ -322,19 +306,17 @@ namespace TelegramBotBase.Form
continue;
//Copy full row, when at least one match has found.
if (ByRow)
if (byRow)
{
lst = b;
break;
}
else
{
lst.Add(b2);
}
lst.Add(b2);
}
if (lst.Count > 0)
bf.Buttons.Add(lst);
bf._buttons.Add(lst);
}
return bf;
+12 -18
View File
@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
namespace TelegramBotBase.Form
{
@@ -14,10 +8,10 @@ namespace TelegramBotBase.Form
public class CallbackData
{
[JsonProperty("m")]
public String Method { get; set; }
public string Method { get; set; }
[JsonProperty("v")]
public String Value { get; set; }
public string Value { get; set; }
public CallbackData()
@@ -25,13 +19,13 @@ namespace TelegramBotBase.Form
}
public CallbackData(String method, String value)
public CallbackData(string method, string value)
{
this.Method = method;
this.Value = value;
Method = method;
Value = value;
}
public static String Create(String method, String value)
public static string Create(string method, string value)
{
return new CallbackData(method, value).Serialize();
}
@@ -40,13 +34,13 @@ namespace TelegramBotBase.Form
/// Serializes data to json string
/// </summary>
/// <returns></returns>
public String Serialize()
public string Serialize()
{
String s = "";
var s = "";
try
{
s = Newtonsoft.Json.JsonConvert.SerializeObject(this);
s = JsonConvert.SerializeObject(this);
}
catch
{
@@ -61,12 +55,12 @@ namespace TelegramBotBase.Form
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static CallbackData Deserialize(String data)
public static CallbackData Deserialize(string data)
{
CallbackData cd = null;
try
{
cd = Newtonsoft.Json.JsonConvert.DeserializeObject<CallbackData>(data);
cd = JsonConvert.DeserializeObject<CallbackData>(data);
return cd;
}
+17 -26
View File
@@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Attributes;
@@ -16,7 +15,7 @@ namespace TelegramBotBase.Form
/// <summary>
/// The message the users sees.
/// </summary>
public String Message { get; set; }
public string Message { get; set; }
/// <summary>
/// An additional optional value.
@@ -30,25 +29,23 @@ namespace TelegramBotBase.Form
public List<ButtonBase> Buttons { get; set; }
private EventHandlerList __Events { get; set; } = new EventHandlerList();
private static object __evButtonClicked { get; } = new object();
private static object EvButtonClicked { get; } = new object();
public ConfirmDialog()
{
}
public ConfirmDialog(String Message)
public ConfirmDialog(string message)
{
this.Message = Message;
this.Buttons = new List<Form.ButtonBase>();
this.Message = message;
Buttons = new List<ButtonBase>();
}
public ConfirmDialog(String Message, params ButtonBase[] Buttons)
public ConfirmDialog(string message, params ButtonBase[] buttons)
{
this.Message = Message;
this.Buttons = Buttons.ToList();
this.Message = message;
this.Buttons = buttons.ToList();
}
/// <summary>
@@ -57,7 +54,7 @@ namespace TelegramBotBase.Form
/// <param name="button"></param>
public void AddButton(ButtonBase button)
{
this.Buttons.Add(button);
Buttons.Add(button);
}
public override async Task Action(MessageResult message)
@@ -78,14 +75,14 @@ namespace TelegramBotBase.Form
await message.DeleteMessage();
ButtonBase button = this.Buttons.FirstOrDefault(a => a.Value == call.Value);
var button = Buttons.FirstOrDefault(a => a.Value == call.Value);
if (button == null)
{
return;
}
OnButtonClicked(new ButtonClickedEventArgs(button) { Tag = this.Tag });
OnButtonClicked(new ButtonClickedEventArgs(button) { Tag = Tag });
if (AutoCloseOnClick)
await CloseForm();
@@ -94,30 +91,24 @@ namespace TelegramBotBase.Form
public override async Task Render(MessageResult message)
{
ButtonForm btn = new ButtonForm();
var btn = new ButtonForm();
var buttons = this.Buttons.Select(a => new ButtonBase(a.Text, CallbackData.Create("action", a.Value))).ToList();
var buttons = Buttons.Select(a => new ButtonBase(a.Text, CallbackData.Create("action", a.Value))).ToList();
btn.AddButtonRow(buttons);
await this.Device.Send(this.Message, btn);
await Device.Send(Message, btn);
}
public event EventHandler<ButtonClickedEventArgs> ButtonClicked
{
add
{
this.__Events.AddHandler(__evButtonClicked, value);
}
remove
{
this.__Events.RemoveHandler(__evButtonClicked, value);
}
add => Events.AddHandler(EvButtonClicked, value);
remove => Events.RemoveHandler(EvButtonClicked, value);
}
public void OnButtonClicked(ButtonClickedEventArgs e)
{
(this.__Events[__evButtonClicked] as EventHandler<ButtonClickedEventArgs>)?.Invoke(this, e);
(Events[EvButtonClicked] as EventHandler<ButtonClickedEventArgs>)?.Invoke(this, e);
}
}
+12 -20
View File
@@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace TelegramBotBase.Form
{
@@ -8,32 +6,26 @@ namespace TelegramBotBase.Form
{
public override string Text
{
get
{
return GetText?.Invoke() ?? m_text;
}
set
{
m_text = value;
}
get => _getText?.Invoke() ?? _mText;
set => _mText = value;
}
private String m_text = "";
private string _mText = "";
private Func<String> GetText;
private Func<string> _getText;
public DynamicButton(String Text, String Value, String Url = null)
public DynamicButton(string text, string value, string url = null)
{
this.Text = Text;
this.Value = Value;
this.Url = Url;
this.Text = text;
this.Value = value;
this.Url = url;
}
public DynamicButton(Func<String> GetText, String Value, String Url = null)
public DynamicButton(Func<string> getText, string value, string url = null)
{
this.GetText = GetText;
this.Value = Value;
this.Url = Url;
this._getText = getText;
this.Value = value;
this.Url = url;
}
+23 -34
View File
@@ -1,8 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using Telegram.Bot.Types.Enums;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
@@ -10,38 +7,30 @@ namespace TelegramBotBase.Form
{
public class GroupForm : FormBase
{
public GroupForm()
{
}
public override async Task Load(MessageResult message)
{
switch (message.MessageType)
{
case Telegram.Bot.Types.Enums.MessageType.ChatMembersAdded:
case MessageType.ChatMembersAdded:
await OnMemberChanges(new MemberChangeEventArgs(Telegram.Bot.Types.Enums.MessageType.ChatMembersAdded, message, message.Message.NewChatMembers));
await OnMemberChanges(new MemberChangeEventArgs(MessageType.ChatMembersAdded, message, message.Message.NewChatMembers));
break;
case Telegram.Bot.Types.Enums.MessageType.ChatMemberLeft:
case MessageType.ChatMemberLeft:
await OnMemberChanges(new MemberChangeEventArgs(Telegram.Bot.Types.Enums.MessageType.ChatMemberLeft, message, message.Message.LeftChatMember));
await OnMemberChanges(new MemberChangeEventArgs(MessageType.ChatMemberLeft, message, message.Message.LeftChatMember));
break;
case Telegram.Bot.Types.Enums.MessageType.ChatPhotoChanged:
case Telegram.Bot.Types.Enums.MessageType.ChatPhotoDeleted:
case Telegram.Bot.Types.Enums.MessageType.ChatTitleChanged:
case Telegram.Bot.Types.Enums.MessageType.MigratedFromGroup:
case Telegram.Bot.Types.Enums.MessageType.MigratedToSupergroup:
case Telegram.Bot.Types.Enums.MessageType.MessagePinned:
case Telegram.Bot.Types.Enums.MessageType.GroupCreated:
case Telegram.Bot.Types.Enums.MessageType.SupergroupCreated:
case Telegram.Bot.Types.Enums.MessageType.ChannelCreated:
case MessageType.ChatPhotoChanged:
case MessageType.ChatPhotoDeleted:
case MessageType.ChatTitleChanged:
case MessageType.MigratedFromGroup:
case MessageType.MigratedToSupergroup:
case MessageType.MessagePinned:
case MessageType.GroupCreated:
case MessageType.SupergroupCreated:
case MessageType.ChannelCreated:
await OnGroupChanged(new GroupChangedEventArgs(message.MessageType, message));
@@ -61,26 +50,26 @@ namespace TelegramBotBase.Form
await OnMessageEdit(message);
}
public virtual async Task OnMemberChanges(MemberChangeEventArgs e)
public virtual Task OnMemberChanges(MemberChangeEventArgs e)
{
return Task.CompletedTask;
}
public virtual async Task OnGroupChanged(GroupChangedEventArgs e)
public virtual Task OnGroupChanged(GroupChangedEventArgs e)
{
return Task.CompletedTask;
}
public virtual async Task OnMessage(MessageResult e)
public virtual Task OnMessage(MessageResult e)
{
return Task.CompletedTask;
}
public virtual async Task OnMessageEdit(MessageResult e)
public virtual Task OnMessageEdit(MessageResult e)
{
return Task.CompletedTask;
}
}
}
+3 -5
View File
@@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace TelegramBotBase.Form
@@ -17,12 +15,12 @@ namespace TelegramBotBase.Form
/// </summary>
public async Task CloseForm()
{
await this.CloseControls();
await CloseControls();
await this.OnClosed(new EventArgs());
await OnClosed(EventArgs.Empty);
await this.ParentForm?.ReturnFromModal(this);
await ParentForm?.ReturnFromModal(this);
}
}
}
@@ -2,12 +2,13 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Attributes;
using TelegramBotBase.Base;
using TelegramBotBase.Interfaces;
using TelegramBotBase.Tools;
namespace TelegramBotBase.Form.Navigation
{
@@ -33,15 +34,15 @@ namespace TelegramBotBase.Form.Navigation
Index = -1;
ForceCleanupOnLastPop = true;
this.Init += NavigationController_Init;
this.Opened += NavigationController_Opened;
this.Closed += NavigationController_Closed;
Init += NavigationController_Init;
Opened += NavigationController_Opened;
Closed += NavigationController_Closed;
}
public NavigationController(FormBase startForm, params FormBase[] forms) : this()
{
this.Client = startForm.Client;
this.Device = startForm.Device;
Client = startForm.Client;
Device = startForm.Device;
startForm.NavigationController = this;
History.Add(startForm);
@@ -54,7 +55,7 @@ namespace TelegramBotBase.Form.Navigation
}
}
private async Task NavigationController_Init(object sender, Args.InitEventArgs e)
private async Task NavigationController_Init(object sender, InitEventArgs e)
{
if (CurrentForm == null)
return;
@@ -97,21 +98,21 @@ namespace TelegramBotBase.Form.Navigation
Device.FormSwitched = true;
await form.OnClosed(new EventArgs());
await form.OnClosed(EventArgs.Empty);
//Leave NavigationController and move to the last one
if (ForceCleanupOnLastPop && History.Count == 1)
{
var last_form = History[0];
last_form.NavigationController = null;
await this.NavigateTo(last_form);
var lastForm = History[0];
lastForm.NavigationController = null;
await NavigateTo(lastForm);
return;
}
if (History.Count > 0)
{
form = History[Index];
await form.OnOpened(new EventArgs());
await form.OnOpened(EventArgs.Empty);
}
}
@@ -134,11 +135,11 @@ namespace TelegramBotBase.Form.Navigation
/// <returns></returns>
public virtual async Task PushAsync(FormBase form, params object[] args)
{
form.Client = this.Client;
form.Device = this.Device;
form.Client = Client;
form.Device = Device;
form.NavigationController = this;
this.History.Add(form);
History.Add(form);
Index++;
Device.FormSwitched = true;
@@ -148,7 +149,7 @@ namespace TelegramBotBase.Form.Navigation
await form.OnInit(new InitEventArgs(args));
await form.OnOpened(new EventArgs());
await form.OnOpened(EventArgs.Empty);
}
/// <summary>
@@ -172,10 +173,10 @@ namespace TelegramBotBase.Form.Navigation
{
get
{
if (this.History.Count == 0)
if (History.Count == 0)
return null;
return this.History[Index];
return History[Index];
}
}
@@ -191,12 +192,12 @@ namespace TelegramBotBase.Form.Navigation
return;
int historyCount = e.GetInt("$controller.history.count");
var historyCount = e.GetInt("$controller.history.count");
for (int i = 0; i < historyCount; i++)
for (var i = 0; i < historyCount; i++)
{
var c = e.GetObject($"$controller.history[{i}]") as Dictionary<String, object>;
var c = e.GetObject($"$controller.history[{i}]") as Dictionary<string, object>;
@@ -205,23 +206,21 @@ namespace TelegramBotBase.Form.Navigation
if (qname == null)
continue;
Type t = Type.GetType(qname.ToString());
var t = Type.GetType(qname);
if (t == null || !t.IsSubclassOf(typeof(FormBase)))
{
continue;
}
var form = t.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as FormBase;
//No default constructor, fallback
if (form == null)
if (t.GetConstructor(new Type[] { })?.Invoke(new object[] { }) is not FormBase form)
{
continue;
}
var properties = c.Where(a => a.Key.StartsWith("$"));
var fields = form.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList();
var fields = form.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList();
foreach (var p in properties)
{
@@ -243,10 +242,10 @@ namespace TelegramBotBase.Form.Navigation
f.SetValue(form, p.Value);
}
catch (ArgumentException ex)
catch (ArgumentException)
{
Tools.Conversion.CustomConversionChecks(form, p, f);
Conversion.CustomConversionChecks(form, p, f);
}
catch
@@ -255,13 +254,13 @@ namespace TelegramBotBase.Form.Navigation
}
}
form.Device = this.Device;
form.Client = this.Client;
form.Device = Device;
form.Client = Client;
form.NavigationController = this;
form.OnInit(new InitEventArgs());
this.History.Add(form);
History.Add(form);
}
}
@@ -270,12 +269,12 @@ namespace TelegramBotBase.Form.Navigation
{
e.Set("$controller.history.count", History.Count.ToString());
int i = 0;
var i = 0;
foreach (var form in History)
{
var fields = form.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList();
var fields = form.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList();
var dt = new Dictionary<String, object>();
var dt = new Dictionary<string, object>();
foreach (var f in fields)
{
var val = f.GetValue(form);
+22 -32
View File
@@ -1,14 +1,12 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using Telegram.Bot.Types.ReplyMarkups;
using TelegramBotBase.Args;
using TelegramBotBase.Attributes;
using TelegramBotBase.Base;
using TelegramBotBase.Localizations;
namespace TelegramBotBase.Form
{
@@ -18,25 +16,23 @@ namespace TelegramBotBase.Form
/// <summary>
/// The message the users sees.
/// </summary>
public String Message { get; set; }
public string Message { get; set; }
/// <summary>
/// The returned text value by the user.
/// </summary>
public String Value { get; set; }
public string Value { get; set; }
/// <summary>
/// An additional optional value.
/// </summary>
public object Tag { get; set; }
private EventHandlerList __Events { get; set; } = new EventHandlerList();
private static object __evCompleted { get; } = new object();
private static object EvCompleted { get; } = new object();
public bool ShowBackButton { get; set; } = false;
public String BackLabel { get; set; } = Localizations.Default.Language["PromptDialog_Back"];
public string BackLabel { get; set; } = Default.Language["PromptDialog_Back"];
/// <summary>
/// Contains the RAW received message.
@@ -48,12 +44,12 @@ namespace TelegramBotBase.Form
}
public PromptDialog(String Message)
public PromptDialog(string message)
{
this.Message = Message;
this.Message = message;
}
public async override Task Load(MessageResult message)
public override async Task Load(MessageResult message)
{
if (message.Handled)
return;
@@ -61,16 +57,16 @@ namespace TelegramBotBase.Form
if (!message.IsFirstHandler)
return;
if (this.ShowBackButton && message.MessageText == BackLabel)
if (ShowBackButton && message.MessageText == BackLabel)
{
await this.CloseForm();
await CloseForm();
return;
}
if (this.Value == null)
if (Value == null)
{
this.Value = message.MessageText;
Value = message.MessageText;
ReceivedMessage = message.Message;
}
@@ -81,44 +77,38 @@ namespace TelegramBotBase.Form
public override async Task Render(MessageResult message)
{
if (this.Value == null)
if (Value == null)
{
if (this.ShowBackButton)
if (ShowBackButton)
{
ButtonForm bf = new ButtonForm();
var bf = new ButtonForm();
bf.AddButtonRow(new ButtonBase(BackLabel, "back"));
await this.Device.Send(this.Message, (ReplyMarkupBase)bf);
await Device.Send(Message, (ReplyMarkupBase)bf);
return;
}
await this.Device.Send(this.Message);
await Device.Send(Message);
return;
}
message.Handled = true;
OnCompleted(new PromptDialogCompletedEventArgs() { Tag = this.Tag, Value = this.Value });
OnCompleted(new PromptDialogCompletedEventArgs { Tag = Tag, Value = Value });
await this.CloseForm();
await CloseForm();
}
public event EventHandler<PromptDialogCompletedEventArgs> Completed
{
add
{
this.__Events.AddHandler(__evCompleted, value);
}
remove
{
this.__Events.RemoveHandler(__evCompleted, value);
}
add => Events.AddHandler(EvCompleted, value);
remove => Events.RemoveHandler(EvCompleted, value);
}
public void OnCompleted(PromptDialogCompletedEventArgs e)
{
(this.__Events[__evCompleted] as EventHandler<PromptDialogCompletedEventArgs>)?.Invoke(this, e);
(Events[EvCompleted] as EventHandler<PromptDialogCompletedEventArgs>)?.Invoke(this, e);
}
}
+13 -17
View File
@@ -1,11 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading.Tasks;
using Telegram.Bot.Types.Enums;
using TelegramBotBase.Base;
namespace TelegramBotBase.Form
{
/// <summary>
@@ -23,14 +19,14 @@ namespace TelegramBotBase.Form
public override async Task Load(MessageResult message)
{
if (message.Message.Chat.Type == Telegram.Bot.Types.Enums.ChatType.Channel)
if (message.Message.Chat.Type == ChatType.Channel)
{
if (await OpenChannel(message))
{
return;
}
}
if (message.Message.Chat.Type == Telegram.Bot.Types.Enums.ChatType.Supergroup)
if (message.Message.Chat.Type == ChatType.Supergroup)
{
if (await OpenSupergroup(message))
{
@@ -41,7 +37,7 @@ namespace TelegramBotBase.Form
return;
}
}
if (message.Message.Chat.Type == Telegram.Bot.Types.Enums.ChatType.Group)
if (message.Message.Chat.Type == ChatType.Group)
{
if (await OpenGroup(message))
{
@@ -53,24 +49,24 @@ namespace TelegramBotBase.Form
}
public virtual async Task<bool> OpenSupergroup(MessageResult e)
public virtual Task<bool> OpenSupergroup(MessageResult e)
{
return false;
return Task.FromResult(false);
}
public virtual async Task<bool> OpenChannel(MessageResult e)
public virtual Task<bool> OpenChannel(MessageResult e)
{
return false;
return Task.FromResult(false);
}
public virtual async Task<bool> Open(MessageResult e)
public virtual Task<bool> Open(MessageResult e)
{
return false;
return Task.FromResult(false);
}
public virtual async Task<bool> OpenGroup(MessageResult e)
public virtual Task<bool> OpenGroup(MessageResult e)
{
return false;
return Task.FromResult(false);
}
+9 -14
View File
@@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types.ReplyMarkups;
using Telegram.Bot.Types.ReplyMarkups;
namespace TelegramBotBase.Form
{
@@ -12,18 +7,18 @@ namespace TelegramBotBase.Form
/// </summary>
public class TagButtonBase : ButtonBase
{
public String Tag { get; set; }
public string Tag { get; set; }
public TagButtonBase()
{
}
public TagButtonBase(String Text, String Value, String Tag)
public TagButtonBase(string text, string value, string tag)
{
this.Text = Text;
this.Value = Value;
this.Tag = Tag;
this.Text = text;
this.Value = value;
this.Tag = tag;
}
@@ -34,9 +29,9 @@ namespace TelegramBotBase.Form
/// <returns></returns>
public override InlineKeyboardButton ToInlineButton(ButtonForm form)
{
String id = (form.DependencyControl != null ? form.DependencyControl.ControlID + "_" : "");
var id = (form.DependencyControl != null ? form.DependencyControl.ControlId + "_" : "");
return InlineKeyboardButton.WithCallbackData(this.Text, id + this.Value);
return InlineKeyboardButton.WithCallbackData(Text, id + Value);
}
@@ -48,7 +43,7 @@ namespace TelegramBotBase.Form
/// <returns></returns>
public override KeyboardButton ToKeyboardButton(ButtonForm form)
{
return new KeyboardButton(this.Text);
return new KeyboardButton(Text);
}
}
+1 -4
View File
@@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
using TelegramBotBase.Controls.Hybrid;
using System.Collections.Generic;
namespace TelegramBotBase.Interfaces
{
+2 -4
View File
@@ -1,11 +1,9 @@
using System;
using System.Collections.Generic;
using System.Text;
using TelegramBotBase.Form;
namespace TelegramBotBase.Interfaces
{
interface IDeviceSession
internal interface IDeviceSession
{
/// <summary>
/// Device or chat id
@@ -15,7 +13,7 @@ namespace TelegramBotBase.Interfaces
/// <summary>
/// Username of user or group
/// </summary>
String ChatTitle { get; set; }
string ChatTitle { get; set; }
/// <summary>
@@ -1,8 +1,5 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Sessions;
@@ -12,7 +9,7 @@ namespace TelegramBotBase.Interfaces
public interface IMessageLoopFactory
{
Task MessageLoop(BotBase Bot, DeviceSession session, UpdateResult ur, MessageResult e);
Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult e);
event EventHandler<UnhandledCallEventArgs> UnhandledCall;
@@ -1,7 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
using TelegramBotBase.Form;
using TelegramBotBase.Form;
namespace TelegramBotBase.Interfaces
{
+1 -5
View File
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Args;
namespace TelegramBotBase.Interfaces
{
@@ -1,9 +1,6 @@
using System;
using System.Collections.Generic;
using System.Text;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
namespace TelegramBotBase.Interfaces
{
+1 -5
View File
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace TelegramBotBase.Localizations
namespace TelegramBotBase.Localizations
{
public static class Default
{
+2 -6
View File
@@ -1,12 +1,8 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace TelegramBotBase.Localizations
namespace TelegramBotBase.Localizations
{
public class English : Localization
{
public English() : base()
public English()
{
Values["Language"] = "English";
Values["ButtonGrid_Title"] = "Menu";
+2 -6
View File
@@ -1,12 +1,8 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace TelegramBotBase.Localizations
namespace TelegramBotBase.Localizations
{
public class German : Localization
{
public German() : base()
public German()
{
Values["Language"] = "Deutsch (German)";
Values["ButtonGrid_Title"] = "Menü";
+3 -18
View File
@@ -1,27 +1,12 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Generic;
namespace TelegramBotBase.Localizations
{
public abstract class Localization
{
public Dictionary<String, String> Values = new Dictionary<string, string>();
public String this[String key]
{
get
{
return Values[key];
}
}
public Localization()
{
}
public Dictionary<string, string> Values = new Dictionary<string, string>();
public string this[string key] => Values[key];
}
}
+49 -68
View File
@@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Linq;
using Telegram.Bot.Types.Enums;
namespace TelegramBotBase.Markdown
@@ -22,16 +17,14 @@ namespace TelegramBotBase.Markdown
/// <param name="title"></param>
/// <param name="tooltip"></param>
/// <returns></returns>
public static String Link(this String url, String title = null, String tooltip = null)
public static string Link(this string url, string title = null, string tooltip = null)
{
switch (OutputMode)
return OutputMode switch
{
case ParseMode.Markdown:
return "[" + (title ?? url) + "](" + url + " " + (tooltip ?? "") + ")";
case ParseMode.Html:
return $"<a href=\"{url}\" title=\"{tooltip ?? ""}\">{title ?? ""}</b>";
}
return url;
ParseMode.Markdown => "[" + (title ?? url) + "](" + url + " " + (tooltip ?? "") + ")",
ParseMode.Html => $"<a href=\"{url}\" title=\"{tooltip ?? ""}\">{title ?? ""}</b>",
_ => url
};
}
/// <summary>
@@ -40,9 +33,9 @@ namespace TelegramBotBase.Markdown
/// <param name="userId"></param>
/// <param name="title"></param>
/// <returns></returns>
public static String MentionUser(this int userId, String title = null)
public static string MentionUser(this int userId, string title = null)
{
return Link("tg://user?id=" + userId.ToString(), title);
return Link("tg://user?id=" + userId, title);
}
/// <summary>
@@ -51,7 +44,7 @@ namespace TelegramBotBase.Markdown
/// <param name="userId"></param>
/// <param name="title"></param>
/// <returns></returns>
public static String MentionUser(this String username, String title = null)
public static string MentionUser(this string username, string title = null)
{
return Link("tg://user?id=" + username, title);
}
@@ -61,16 +54,14 @@ namespace TelegramBotBase.Markdown
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static String Bold(this String text)
public static string Bold(this string text)
{
switch (OutputMode)
return OutputMode switch
{
case ParseMode.Markdown:
return "*" + text + "*";
case ParseMode.Html:
return "<b>" + text + "</b>";
}
return text;
ParseMode.Markdown => "*" + text + "*",
ParseMode.Html => "<b>" + text + "</b>",
_ => text
};
}
/// <summary>
@@ -78,16 +69,14 @@ namespace TelegramBotBase.Markdown
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static String Strikesthrough(this String text)
public static string Strikesthrough(this string text)
{
switch (OutputMode)
return OutputMode switch
{
case ParseMode.Markdown:
return "~" + text + "~";
case ParseMode.Html:
return "<s>" + text + "</s>";
}
return text;
ParseMode.Markdown => "~" + text + "~",
ParseMode.Html => "<s>" + text + "</s>",
_ => text
};
}
/// <summary>
@@ -95,16 +84,14 @@ namespace TelegramBotBase.Markdown
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static String Italic(this String text)
public static string Italic(this string text)
{
switch (OutputMode)
return OutputMode switch
{
case ParseMode.Markdown:
return "_" + text + "_";
case ParseMode.Html:
return "<i>" + text + "</i>";
}
return text;
ParseMode.Markdown => "_" + text + "_",
ParseMode.Html => "<i>" + text + "</i>",
_ => text
};
}
/// <summary>
@@ -112,16 +99,14 @@ namespace TelegramBotBase.Markdown
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static String Underline(this String text)
public static string Underline(this string text)
{
switch (OutputMode)
return OutputMode switch
{
case ParseMode.Markdown:
return "__" + text + "__";
case ParseMode.Html:
return "<u>" + text + "</u>";
}
return text;
ParseMode.Markdown => "__" + text + "__",
ParseMode.Html => "<u>" + text + "</u>",
_ => text
};
}
/// <summary>
@@ -129,16 +114,14 @@ namespace TelegramBotBase.Markdown
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static String Monospace(this String text)
public static string Monospace(this string text)
{
switch (OutputMode)
return OutputMode switch
{
case ParseMode.Markdown:
return "`" + text + "`";
case ParseMode.Html:
return "<code>" + text + "</code>";
}
return text;
ParseMode.Markdown => "`" + text + "`",
ParseMode.Html => "<code>" + text + "</code>",
_ => text
};
}
/// <summary>
@@ -146,16 +129,14 @@ namespace TelegramBotBase.Markdown
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static String MultiMonospace(this String text)
public static string MultiMonospace(this string text)
{
switch (OutputMode)
return OutputMode switch
{
case ParseMode.Markdown:
return "```" + text + "```";
case ParseMode.Html:
return "<pre>" + text + "</pre>";
}
return text;
ParseMode.Markdown => "```" + text + "```",
ParseMode.Html => "<pre>" + text + "</pre>",
_ => text
};
}
/// <summary>
@@ -163,14 +144,14 @@ namespace TelegramBotBase.Markdown
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static String MarkdownV2Escape(this String text, params char[] toKeep)
public static string MarkdownV2Escape(this string text, params char[] toKeep)
{
char[] toEscape = new char[] { '_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!' };
var toEscape = new[] { '_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!' };
return text.EscapeAll(toEscape.Where(a => !toKeep.Contains(a)).Select(a => a.ToString()).ToArray());
}
public static string EscapeAll(this string seed, String[] chars, char escapeCharacter = '\\')
public static string EscapeAll(this string seed, string[] chars, char escapeCharacter = '\\')
{
return chars.Aggregate(seed, (str, cItem) => str.Replace(cItem, escapeCharacter + cItem));
}
@@ -1,13 +1,9 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Enums;
using TelegramBotBase.Interfaces;
using TelegramBotBase.Sessions;
@@ -18,32 +14,27 @@ namespace TelegramBotBase.MessageLoops
/// </summary>
public class FormBaseMessageLoop : IMessageLoopFactory
{
private static object __evUnhandledCall = new object();
private static readonly object EvUnhandledCall = new object();
private EventHandlerList __Events = new EventHandlerList();
private readonly EventHandlerList _events = new EventHandlerList();
public FormBaseMessageLoop()
{
}
public async Task MessageLoop(BotBase Bot, DeviceSession session, UpdateResult ur, MessageResult mr)
public async Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult mr)
{
var update = ur.RawData;
if (update.Type != Telegram.Bot.Types.Enums.UpdateType.Message
&& update.Type != Telegram.Bot.Types.Enums.UpdateType.EditedMessage
&& update.Type != Telegram.Bot.Types.Enums.UpdateType.CallbackQuery)
if (update.Type != UpdateType.Message
&& update.Type != UpdateType.EditedMessage
&& update.Type != UpdateType.CallbackQuery)
{
return;
}
//Is this a bot command ?
if (mr.IsFirstHandler && mr.IsBotCommand && Bot.IsKnownBotCommand(mr.BotCommand))
if (mr.IsFirstHandler && mr.IsBotCommand && bot.IsKnownBotCommand(mr.BotCommand))
{
var sce = new BotCommandEventArgs(mr.BotCommand, mr.BotCommandParameters, mr.Message, session.DeviceId, session);
await Bot.OnBotCommand(sce);
await bot.OnBotCommand(sce);
if (sce.Handled)
return;
@@ -64,14 +55,14 @@ namespace TelegramBotBase.MessageLoops
//Is Attachment ? (Photo, Audio, Video, Contact, Location, Document) (Ignore Callback Queries)
if (update.Type == Telegram.Bot.Types.Enums.UpdateType.Message)
if (update.Type == UpdateType.Message)
{
if (mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Contact
| mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Document
| mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Location
| mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Photo
| mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Video
| mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Audio)
if (mr.MessageType == MessageType.Contact
| mr.MessageType == MessageType.Document
| mr.MessageType == MessageType.Location
| mr.MessageType == MessageType.Photo
| mr.MessageType == MessageType.Video
| mr.MessageType == MessageType.Audio)
{
await activeForm.SentData(new DataResult(ur));
}
@@ -118,19 +109,13 @@ namespace TelegramBotBase.MessageLoops
/// </summary>
public event EventHandler<UnhandledCallEventArgs> UnhandledCall
{
add
{
this.__Events.AddHandler(__evUnhandledCall, value);
}
remove
{
this.__Events.RemoveHandler(__evUnhandledCall, value);
}
add => _events.AddHandler(EvUnhandledCall, value);
remove => _events.RemoveHandler(EvUnhandledCall, value);
}
public void OnUnhandledCall(UnhandledCallEventArgs e)
{
(this.__Events[__evUnhandledCall] as EventHandler<UnhandledCallEventArgs>)?.Invoke(this, e);
(_events[EvUnhandledCall] as EventHandler<UnhandledCallEventArgs>)?.Invoke(this, e);
}
}
+16 -31
View File
@@ -1,13 +1,9 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Enums;
using TelegramBotBase.Interfaces;
using TelegramBotBase.Sessions;
@@ -18,25 +14,20 @@ namespace TelegramBotBase.MessageLoops
/// </summary>
public class FullMessageLoop : IMessageLoopFactory
{
private static object __evUnhandledCall = new object();
private static readonly object EvUnhandledCall = new object();
private EventHandlerList __Events = new EventHandlerList();
private readonly EventHandlerList _events = new EventHandlerList();
public FullMessageLoop()
{
}
public async Task MessageLoop(BotBase Bot, DeviceSession session, UpdateResult ur, MessageResult mr)
public async Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult mr)
{
var update = ur.RawData;
//Is this a bot command ?
if (mr.IsFirstHandler && mr.IsBotCommand && Bot.IsKnownBotCommand(mr.BotCommand))
if (mr.IsFirstHandler && mr.IsBotCommand && bot.IsKnownBotCommand(mr.BotCommand))
{
var sce = new BotCommandEventArgs(mr.BotCommand, mr.BotCommandParameters, mr.Message, session.DeviceId, session);
await Bot.OnBotCommand(sce);
await bot.OnBotCommand(sce);
if (sce.Handled)
return;
@@ -57,14 +48,14 @@ namespace TelegramBotBase.MessageLoops
//Is Attachment ? (Photo, Audio, Video, Contact, Location, Document) (Ignore Callback Queries)
if (update.Type == Telegram.Bot.Types.Enums.UpdateType.Message)
if (update.Type == UpdateType.Message)
{
if (mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Contact
| mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Document
| mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Location
| mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Photo
| mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Video
| mr.MessageType == Telegram.Bot.Types.Enums.MessageType.Audio)
if (mr.MessageType == MessageType.Contact
| mr.MessageType == MessageType.Document
| mr.MessageType == MessageType.Location
| mr.MessageType == MessageType.Photo
| mr.MessageType == MessageType.Video
| mr.MessageType == MessageType.Audio)
{
await activeForm.SentData(new DataResult(ur));
}
@@ -111,19 +102,13 @@ namespace TelegramBotBase.MessageLoops
/// </summary>
public event EventHandler<UnhandledCallEventArgs> UnhandledCall
{
add
{
this.__Events.AddHandler(__evUnhandledCall, value);
}
remove
{
this.__Events.RemoveHandler(__evUnhandledCall, value);
}
add => _events.AddHandler(EvUnhandledCall, value);
remove => _events.RemoveHandler(EvUnhandledCall, value);
}
public void OnUnhandledCall(UnhandledCallEventArgs e)
{
(this.__Events[__evUnhandledCall] as EventHandler<UnhandledCallEventArgs>)?.Invoke(this, e);
(_events[EvUnhandledCall] as EventHandler<UnhandledCallEventArgs>)?.Invoke(this, e);
}
}
@@ -1,13 +1,8 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot.Types;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Enums;
using TelegramBotBase.Interfaces;
using TelegramBotBase.Sessions;
@@ -18,16 +13,11 @@ namespace TelegramBotBase.MessageLoops
/// </summary>
public class MinimalMessageLoop : IMessageLoopFactory
{
private static object __evUnhandledCall = new object();
private static readonly object EvUnhandledCall = new object();
private EventHandlerList __Events = new EventHandlerList();
private readonly EventHandlerList _events = new EventHandlerList();
public MinimalMessageLoop()
{
}
public async Task MessageLoop(BotBase Bot, DeviceSession session, UpdateResult ur, MessageResult mr)
public async Task MessageLoop(BotBase bot, DeviceSession session, UpdateResult ur, MessageResult mr)
{
var update = ur.RawData;
@@ -46,19 +36,13 @@ namespace TelegramBotBase.MessageLoops
/// </summary>
public event EventHandler<UnhandledCallEventArgs> UnhandledCall
{
add
{
this.__Events.AddHandler(__evUnhandledCall, value);
}
remove
{
this.__Events.RemoveHandler(__evUnhandledCall, value);
}
add => _events.AddHandler(EvUnhandledCall, value);
remove => _events.RemoveHandler(EvUnhandledCall, value);
}
public void OnUnhandledCall(UnhandledCallEventArgs e)
{
(this.__Events[__evUnhandledCall] as EventHandler<UnhandledCallEventArgs>)?.Invoke(this, e);
(_events[EvUnhandledCall] as EventHandler<UnhandledCallEventArgs>)?.Invoke(this, e);
}
}
@@ -1,5 +1,4 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
+48 -53
View File
@@ -1,9 +1,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Reflection;
using System.Threading.Tasks;
using TelegramBotBase.Args;
using TelegramBotBase.Attributes;
@@ -11,6 +9,8 @@ using TelegramBotBase.Base;
using TelegramBotBase.Form;
using TelegramBotBase.Interfaces;
using TelegramBotBase.Sessions;
using TelegramBotBase.Tools;
namespace TelegramBotBase
{
/// <summary>
@@ -37,7 +37,7 @@ namespace TelegramBotBase
public SessionBase()
{
this.SessionList = new Dictionary<long, DeviceSession>();
SessionList = new Dictionary<long, DeviceSession>();
}
/// <summary>
@@ -47,14 +47,8 @@ namespace TelegramBotBase
/// <returns></returns>
public DeviceSession this[long key]
{
get
{
return this.SessionList[key];
}
set
{
this.SessionList[key] = value;
}
get => SessionList[key];
set => SessionList[key] = value;
}
/// <summary>
@@ -64,7 +58,7 @@ namespace TelegramBotBase
/// <returns></returns>
public DeviceSession GetSession(long deviceId)
{
DeviceSession ds = this.SessionList.FirstOrDefault(a => a.Key == deviceId).Value ?? null;
var ds = SessionList.FirstOrDefault(a => a.Key == deviceId).Value ?? null;
return ds;
}
@@ -77,16 +71,15 @@ namespace TelegramBotBase
public async Task<DeviceSession> StartSession(long deviceId)
{
var start = BotBase.StartFormFactory.CreateForm();
//T start = typeof(T).GetConstructor(new Type[] { }).Invoke(new object[] { }) as T;
start.Client = this.Client;
start.Client = Client;
DeviceSession ds = new Sessions.DeviceSession(deviceId, start);
var ds = new DeviceSession(deviceId, start);
start.Device = ds;
await start.OnInit(new InitEventArgs());
await start.OnOpened(new EventArgs());
await start.OnOpened(EventArgs.Empty);
this[deviceId] = ds;
return ds;
@@ -101,7 +94,7 @@ namespace TelegramBotBase
var d = this[deviceId];
if (d != null)
{
this.SessionList.Remove(deviceId);
SessionList.Remove(deviceId);
}
}
@@ -112,7 +105,7 @@ namespace TelegramBotBase
/// <returns></returns>
public List<DeviceSession> GetUserSessions()
{
return this.SessionList.Where(a => a.Key > 0).Select(a => a.Value).ToList();
return SessionList.Where(a => a.Key > 0).Select(a => a.Value).ToList();
}
/// <summary>
@@ -121,7 +114,7 @@ namespace TelegramBotBase
/// <returns></returns>
public List<DeviceSession> GetGroupSessions()
{
return this.SessionList.Where(a => a.Key < 0).Select(a => a.Value).ToList();
return SessionList.Where(a => a.Key < 0).Select(a => a.Value).ToList();
}
/// <summary>
@@ -152,20 +145,18 @@ namespace TelegramBotBase
foreach (var s in container.States)
{
Type t = Type.GetType(s.QualifiedName);
var t = Type.GetType(s.QualifiedName);
if (t == null || !t.IsSubclassOf(typeof(FormBase)))
{
continue;
}
//Key already existing
if (this.SessionList.ContainsKey(s.DeviceId))
if (SessionList.ContainsKey(s.DeviceId))
continue;
var form = t.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as FormBase;
//No default constructor, fallback
if (form == null)
if (!(t.GetConstructor(new Type[] { })?.Invoke(new object[] { }) is FormBase form))
{
if (!statemachine.FallbackStateForm.IsSubclassOf(typeof(FormBase)))
continue;
@@ -182,7 +173,7 @@ namespace TelegramBotBase
if (s.Values != null && s.Values.Count > 0)
{
var properties = s.Values.Where(a => a.Key.StartsWith("$"));
var fields = form.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList();
var fields = form.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList();
foreach (var p in properties)
{
@@ -204,10 +195,10 @@ namespace TelegramBotBase
f.SetValue(form, p.Value);
}
catch (ArgumentException ex)
catch (ArgumentException)
{
Tools.Conversion.CustomConversionChecks(form, p, f);
Conversion.CustomConversionChecks(form, p, f);
}
catch
@@ -218,18 +209,20 @@ namespace TelegramBotBase
}
form.Client = Client;
var device = new DeviceSession(s.DeviceId, form);
var device = new DeviceSession(s.DeviceId, form)
{
ChatTitle = s.ChatTitle
};
device.ChatTitle = s.ChatTitle;
this.SessionList.Add(s.DeviceId, device);
SessionList.Add(s.DeviceId, device);
//Is Subclass of IStateForm
var iform = form as IStateForm;
if (iform != null)
if (form is IStateForm iform)
{
var ls = new LoadStateEventArgs();
ls.Values = s.Values;
var ls = new LoadStateEventArgs
{
Values = s.Values
};
iform.LoadState(ls);
}
@@ -237,12 +230,12 @@ namespace TelegramBotBase
{
await form.OnInit(new InitEventArgs());
await form.OnOpened(new EventArgs());
await form.OnOpened(EventArgs.Empty);
}
catch
{
//Skip on exception
this.SessionList.Remove(s.DeviceId);
SessionList.Remove(s.DeviceId);
}
}
@@ -263,7 +256,7 @@ namespace TelegramBotBase
var states = new List<StateEntry>();
foreach (var s in this.SessionList)
foreach (var s in SessionList)
{
if (s.Value == null)
{
@@ -274,11 +267,13 @@ namespace TelegramBotBase
try
{
var se = new StateEntry();
se.DeviceId = s.Key;
se.ChatTitle = s.Value.GetChatTitle();
se.FormUri = form.GetType().FullName;
se.QualifiedName = form.GetType().AssemblyQualifiedName;
var se = new StateEntry
{
DeviceId = s.Key,
ChatTitle = s.Value.GetChatTitle(),
FormUri = form.GetType().FullName,
QualifiedName = form.GetType().AssemblyQualifiedName
};
//Skip classes where IgnoreState attribute is existing
if (form.GetType().GetCustomAttributes(typeof(IgnoreState), true).Length != 0)
@@ -295,18 +290,17 @@ namespace TelegramBotBase
}
//Is Subclass of IStateForm
var iform = form as IStateForm;
if (iform != null)
if (form is IStateForm iform)
{
//Loading Session states
SaveStateEventArgs ssea = new SaveStateEventArgs();
var ssea = new SaveStateEventArgs();
iform.SaveState(ssea);
se.Values = ssea.Values;
}
//Search for public properties with SaveState attribute
var fields = form.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList();
var fields = form.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.GetCustomAttributes(typeof(SaveState), true).Length != 0).ToList();
foreach (var f in fields)
{
@@ -320,12 +314,13 @@ namespace TelegramBotBase
catch
{
//Continue on error (skip this form)
continue;
}
}
var sc = new StateContainer();
sc.States = states;
var sc = new StateContainer
{
States = states
};
statemachine.SaveFormStates(new SaveStatesEventArgs(sc));
}
@@ -335,11 +330,11 @@ namespace TelegramBotBase
/// </summary>
public void SaveSessionStates()
{
if (this.BotBase.StateMachine == null)
if (BotBase.StateMachine == null)
return;
this.SaveSessionStates(this.BotBase.StateMachine);
SaveSessionStates(BotBase.StateMachine);
}
}
}
+109 -148
View File
@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
@@ -34,13 +33,13 @@ namespace TelegramBotBase.Sessions
/// <summary>
/// Username of user or group
/// </summary>
public String ChatTitle { get; set; }
public string ChatTitle { get; set; }
/// <summary>
/// Returns the ChatTitle depending on groups/channels or users
/// </summary>
/// <returns></returns>
public String GetChatTitle()
public string GetChatTitle()
{
return LastMessage?.Chat.Title
?? LastMessage?.Chat.Username
@@ -71,70 +70,46 @@ namespace TelegramBotBase.Sessions
/// <summary>
/// Returns the ID of the last received message.
/// </summary>
public int LastMessageId
{
get
{
return this.LastMessage?.MessageId ?? -1;
}
}
public int LastMessageId => LastMessage?.MessageId ?? -1;
/// <summary>
/// Returns the last received message.
/// </summary>
public Message LastMessage { get; set; }
public MessageClient Client
{
get
{
return this.ActiveForm.Client;
}
}
public MessageClient Client => ActiveForm.Client;
/// <summary>
/// Returns if the messages is posted within a group.
/// </summary>
public bool IsGroup
{
get
{
return this.LastMessage != null && (this.LastMessage.Chat.Type == ChatType.Group | this.LastMessage.Chat.Type == ChatType.Supergroup);
}
}
public bool IsGroup => LastMessage != null && (LastMessage.Chat.Type == ChatType.Group | LastMessage.Chat.Type == ChatType.Supergroup);
/// <summary>
/// Returns if the messages is posted within a channel.
/// </summary>
public bool IsChannel
{
get
{
return this.LastMessage != null && this.LastMessage.Chat.Type == ChatType.Channel;
}
}
public bool IsChannel => LastMessage != null && LastMessage.Chat.Type == ChatType.Channel;
private EventHandlerList __Events = new EventHandlerList();
private readonly EventHandlerList _events = new EventHandlerList();
private static object __evMessageSent = new object();
private static object __evMessageReceived = new object();
private static object __evMessageDeleted = new object();
private static readonly object EvMessageSent = new object();
private static readonly object EvMessageReceived = new object();
private static readonly object EvMessageDeleted = new object();
public DeviceSession()
{
}
public DeviceSession(long DeviceId)
public DeviceSession(long deviceId)
{
this.DeviceId = DeviceId;
this.DeviceId = deviceId;
}
public DeviceSession(long DeviceId, FormBase StartForm)
public DeviceSession(long deviceId, FormBase startForm)
{
this.DeviceId = DeviceId;
this.ActiveForm = StartForm;
this.ActiveForm.Device = this;
this.DeviceId = deviceId;
ActiveForm = startForm;
ActiveForm.Device = this;
}
@@ -143,11 +118,11 @@ namespace TelegramBotBase.Sessions
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public async Task ConfirmAction(String CallbackQueryId, String message = "", bool showAlert = false, String urlToOpen = null)
public async Task ConfirmAction(string callbackQueryId, string message = "", bool showAlert = false, string urlToOpen = null)
{
try
{
await this.Client.TelegramClient.AnswerCallbackQueryAsync(CallbackQueryId, message, showAlert, urlToOpen);
await Client.TelegramClient.AnswerCallbackQueryAsync(callbackQueryId, message, showAlert, urlToOpen);
}
catch
{
@@ -162,7 +137,7 @@ namespace TelegramBotBase.Sessions
/// <param name="text"></param>
/// <param name="buttons"></param>
/// <returns></returns>
public async Task<Message> Edit(int messageId, String text, ButtonForm buttons = null, ParseMode parseMode = ParseMode.Markdown)
public async Task<Message> Edit(int messageId, string text, ButtonForm buttons = null, ParseMode parseMode = ParseMode.Markdown)
{
InlineKeyboardMarkup markup = buttons;
@@ -173,7 +148,7 @@ namespace TelegramBotBase.Sessions
try
{
return await API(a => a.EditMessageTextAsync(this.DeviceId, messageId, text, parseMode, replyMarkup: markup));
return await Api(a => a.EditMessageTextAsync(DeviceId, messageId, text, parseMode, replyMarkup: markup));
}
catch
{
@@ -191,7 +166,7 @@ namespace TelegramBotBase.Sessions
/// <param name="text"></param>
/// <param name="buttons"></param>
/// <returns></returns>
public async Task<Message> Edit(int messageId, String text, InlineKeyboardMarkup markup, ParseMode parseMode = ParseMode.Markdown)
public async Task<Message> Edit(int messageId, string text, InlineKeyboardMarkup markup, ParseMode parseMode = ParseMode.Markdown)
{
if (text.Length > Constants.Telegram.MaxMessageLength)
{
@@ -200,7 +175,7 @@ namespace TelegramBotBase.Sessions
try
{
return await API(a => a.EditMessageTextAsync(this.DeviceId, messageId, text, parseMode, replyMarkup: markup));
return await Api(a => a.EditMessageTextAsync(DeviceId, messageId, text, parseMode, replyMarkup: markup));
}
catch
{
@@ -229,7 +204,7 @@ namespace TelegramBotBase.Sessions
try
{
return await API(a => a.EditMessageTextAsync(this.DeviceId, message.MessageId, message.Text, parseMode, replyMarkup: markup));
return await Api(a => a.EditMessageTextAsync(DeviceId, message.MessageId, message.Text, parseMode, replyMarkup: markup));
}
catch
{
@@ -251,7 +226,7 @@ namespace TelegramBotBase.Sessions
try
{
return await API(a => a.EditMessageReplyMarkupAsync(this.DeviceId, messageId, bf));
return await Api(a => a.EditMessageReplyMarkupAsync(DeviceId, messageId, bf));
}
catch
{
@@ -269,9 +244,9 @@ namespace TelegramBotBase.Sessions
/// <param name="replyTo"></param>
/// <param name="disableNotification"></param>
/// <returns></returns>
public async Task<Message> Send(long deviceId, String text, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool MarkdownV2AutoEscape = true)
public async Task<Message> Send(long deviceId, string text, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool markdownV2AutoEscape = true)
{
if (this.ActiveForm == null)
if (ActiveForm == null)
return null;
InlineKeyboardMarkup markup = buttons;
@@ -281,17 +256,17 @@ namespace TelegramBotBase.Sessions
throw new MaxLengthException(text.Length);
}
if (parseMode == ParseMode.MarkdownV2 && MarkdownV2AutoEscape)
if (parseMode == ParseMode.MarkdownV2 && markdownV2AutoEscape)
{
text = text.MarkdownV2Escape();
}
try
{
var t = API(a => a.SendTextMessageAsync(deviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var t = Api(a => a.SendTextMessageAsync(deviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var o = GetOrigin(new StackTrace());
await OnMessageSent(new MessageSentEventArgs(await t, o));
return await t;
@@ -310,9 +285,9 @@ namespace TelegramBotBase.Sessions
/// <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.Markdown, bool MarkdownV2AutoEscape = true)
public async Task<Message> Send(string text, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool markdownV2AutoEscape = true)
{
return await Send(this.DeviceId, text, buttons, replyTo, disableNotification, parseMode, MarkdownV2AutoEscape);
return await Send(DeviceId, text, buttons, replyTo, disableNotification, parseMode, markdownV2AutoEscape);
}
/// <summary>
@@ -323,9 +298,9 @@ namespace TelegramBotBase.Sessions
/// <param name="replyTo"></param>
/// <param name="disableNotification"></param>
/// <returns></returns>
public async Task<Message> Send(String text, InlineKeyboardMarkup markup, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool MarkdownV2AutoEscape = true)
public async Task<Message> Send(string text, InlineKeyboardMarkup markup, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool markdownV2AutoEscape = true)
{
if (this.ActiveForm == null)
if (ActiveForm == null)
return null;
if (text.Length > Constants.Telegram.MaxMessageLength)
@@ -333,14 +308,14 @@ namespace TelegramBotBase.Sessions
throw new MaxLengthException(text.Length);
}
if (parseMode == ParseMode.MarkdownV2 && MarkdownV2AutoEscape)
if (parseMode == ParseMode.MarkdownV2 && markdownV2AutoEscape)
{
text = text.MarkdownV2Escape();
}
try
{
var t = API(a => a.SendTextMessageAsync(this.DeviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var t = Api(a => a.SendTextMessageAsync(DeviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var o = GetOrigin(new StackTrace());
await OnMessageSent(new MessageSentEventArgs(await t, o));
@@ -361,9 +336,9 @@ namespace TelegramBotBase.Sessions
/// <param name="replyTo"></param>
/// <param name="disableNotification"></param>
/// <returns></returns>
public async Task<Message> Send(String text, ReplyMarkupBase markup, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool MarkdownV2AutoEscape = true)
public async Task<Message> Send(string text, ReplyMarkupBase markup, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown, bool markdownV2AutoEscape = true)
{
if (this.ActiveForm == null)
if (ActiveForm == null)
return null;
if (text.Length > Constants.Telegram.MaxMessageLength)
@@ -371,14 +346,14 @@ namespace TelegramBotBase.Sessions
throw new MaxLengthException(text.Length);
}
if (parseMode == ParseMode.MarkdownV2 && MarkdownV2AutoEscape)
if (parseMode == ParseMode.MarkdownV2 && markdownV2AutoEscape)
{
text = text.MarkdownV2Escape();
}
try
{
var t = API(a => a.SendTextMessageAsync(this.DeviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var t = Api(a => a.SendTextMessageAsync(DeviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var o = GetOrigin(new StackTrace());
await OnMessageSent(new MessageSentEventArgs(await t, o));
@@ -399,16 +374,16 @@ namespace TelegramBotBase.Sessions
/// <param name="replyTo"></param>
/// <param name="disableNotification"></param>
/// <returns></returns>
public async Task<Message> SendPhoto(InputOnlineFile file, String caption = null, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown)
public async Task<Message> SendPhoto(InputOnlineFile file, string caption = null, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown)
{
if (this.ActiveForm == null)
if (ActiveForm == null)
return null;
InlineKeyboardMarkup markup = buttons;
try
{
var t = API(a => a.SendPhotoAsync(this.DeviceId, file, caption: caption, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var t = Api(a => a.SendPhotoAsync(DeviceId, file, caption: caption, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var o = GetOrigin(new StackTrace());
await OnMessageSent(new MessageSentEventArgs(await t, o));
@@ -429,16 +404,16 @@ namespace TelegramBotBase.Sessions
/// <param name="replyTo"></param>
/// <param name="disableNotification"></param>
/// <returns></returns>
public async Task<Message> SendVideo(InputOnlineFile file, String caption = null, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown)
public async Task<Message> SendVideo(InputOnlineFile file, string caption = null, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown)
{
if (this.ActiveForm == null)
if (ActiveForm == null)
return null;
InlineKeyboardMarkup markup = buttons;
try
{
var t = API(a => a.SendVideoAsync(this.DeviceId, file, caption: caption, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var t = Api(a => a.SendVideoAsync(DeviceId, file, caption: caption, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var o = GetOrigin(new StackTrace());
await OnMessageSent(new MessageSentEventArgs(await t, o));
@@ -459,16 +434,16 @@ namespace TelegramBotBase.Sessions
/// <param name="replyTo"></param>
/// <param name="disableNotification"></param>
/// <returns></returns>
public async Task<Message> SendVideo(String url, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown)
public async Task<Message> SendVideo(string url, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown)
{
if (this.ActiveForm == null)
if (ActiveForm == null)
return null;
InlineKeyboardMarkup markup = buttons;
try
{
var t = API(a => a.SendVideoAsync(this.DeviceId, new InputOnlineFile(url), parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var t = Api(a => a.SendVideoAsync(DeviceId, new InputOnlineFile(url), parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var o = GetOrigin(new StackTrace());
await OnMessageSent(new MessageSentEventArgs(await t, o));
@@ -490,20 +465,20 @@ namespace TelegramBotBase.Sessions
/// <param name="replyTo"></param>
/// <param name="disableNotification"></param>
/// <returns></returns>
public async Task<Message> SendVideo(String filename, byte[] video, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown)
public async Task<Message> SendVideo(string filename, byte[] video, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown)
{
if (this.ActiveForm == null)
if (ActiveForm == null)
return null;
InlineKeyboardMarkup markup = buttons;
try
{
MemoryStream ms = new MemoryStream(video);
var ms = new MemoryStream(video);
InputOnlineFile fts = new InputOnlineFile(ms, filename);
var fts = new InputOnlineFile(ms, filename);
var t = API(a => a.SendVideoAsync(this.DeviceId, fts, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var t = Api(a => a.SendVideoAsync(DeviceId, fts, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var o = GetOrigin(new StackTrace());
await OnMessageSent(new MessageSentEventArgs(await t, o));
@@ -525,22 +500,22 @@ namespace TelegramBotBase.Sessions
/// <param name="replyTo"></param>
/// <param name="disableNotification"></param>
/// <returns></returns>
public async Task<Message> SendLocalVideo(String filepath, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown)
public async Task<Message> SendLocalVideo(string filepath, ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false, ParseMode parseMode = ParseMode.Markdown)
{
if (this.ActiveForm == null)
if (ActiveForm == null)
return null;
InlineKeyboardMarkup markup = buttons;
try
{
FileStream fs = new FileStream(filepath, FileMode.Open);
var fs = new FileStream(filepath, FileMode.Open);
var filename = Path.GetFileName(filepath);
InputOnlineFile fts = new InputOnlineFile(fs, filename);
var fts = new InputOnlineFile(fs, filename);
var t = API(a => a.SendVideoAsync(this.DeviceId, fts, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var t = Api(a => a.SendVideoAsync(DeviceId, fts, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var o = GetOrigin(new StackTrace());
await OnMessageSent(new MessageSentEventArgs(await t, o));
@@ -563,11 +538,11 @@ namespace TelegramBotBase.Sessions
/// <param name="replyTo"></param>
/// <param name="disableNotification"></param>
/// <returns></returns>
public async Task<Message> SendDocument(String filename, byte[] document, String caption = "", ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false)
public async Task<Message> SendDocument(string filename, byte[] document, string caption = "", ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false)
{
MemoryStream ms = new MemoryStream(document);
var ms = new MemoryStream(document);
InputOnlineFile fts = new InputOnlineFile(ms, filename);
var fts = new InputOnlineFile(ms, filename);
return await SendDocument(fts, caption, buttons, replyTo, disableNotification);
}
@@ -583,7 +558,7 @@ namespace TelegramBotBase.Sessions
/// <param name="replyTo"></param>
/// <param name="disableNotification"></param>
/// <returns></returns>
public async Task<Message> SendTextFile(String filename, String textcontent, Encoding encoding = null, String caption = "", ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false)
public async Task<Message> SendTextFile(string filename, string textcontent, Encoding encoding = null, string caption = "", ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false)
{
encoding = encoding ?? Encoding.UTF8;
@@ -607,7 +582,7 @@ namespace TelegramBotBase.Sessions
/// <param name="replyTo"></param>
/// <param name="disableNotification"></param>
/// <returns></returns>
public async Task<Message> SendDocument(InputOnlineFile document, String caption = "", ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false)
public async Task<Message> SendDocument(InputOnlineFile document, string caption = "", ButtonForm buttons = null, int replyTo = 0, bool disableNotification = false)
{
InlineKeyboardMarkup markup = null;
if (buttons != null)
@@ -617,7 +592,7 @@ namespace TelegramBotBase.Sessions
try
{
var t = API(a => a.SendDocumentAsync(this.DeviceId, document, caption, replyMarkup: markup, disableNotification: disableNotification, replyToMessageId: replyTo));
var t = Api(a => a.SendDocumentAsync(DeviceId, document, caption, replyMarkup: markup, disableNotification: disableNotification, replyToMessageId: replyTo));
var o = GetOrigin(new StackTrace());
await OnMessageSent(new MessageSentEventArgs(await t, o));
@@ -637,7 +612,7 @@ namespace TelegramBotBase.Sessions
/// <returns></returns>
public async Task SetAction(ChatAction action)
{
await API(a => a.SendChatActionAsync(this.DeviceId, action));
await Api(a => a.SendChatActionAsync(DeviceId, action));
}
/// <summary>
@@ -645,13 +620,15 @@ namespace TelegramBotBase.Sessions
/// </summary>
/// <param name="buttonText"></param>
/// <param name="requestMessage"></param>
/// <param name="OneTimeOnly"></param>
/// <param name="oneTimeOnly"></param>
/// <returns></returns>
public async Task<Message> RequestContact(String buttonText = "Send your contact", String requestMessage = "Give me your phone number!", bool OneTimeOnly = true)
public async Task<Message> RequestContact(string buttonText = "Send your contact", string requestMessage = "Give me your phone number!", bool oneTimeOnly = true)
{
var rck = new ReplyKeyboardMarkup(KeyboardButton.WithRequestContact(buttonText));
rck.OneTimeKeyboard = OneTimeOnly;
return await API(a => a.SendTextMessageAsync(this.DeviceId, requestMessage, replyMarkup: rck));
var rck = new ReplyKeyboardMarkup(KeyboardButton.WithRequestContact(buttonText))
{
OneTimeKeyboard = oneTimeOnly
};
return await Api(a => a.SendTextMessageAsync(DeviceId, requestMessage, replyMarkup: rck));
}
/// <summary>
@@ -659,24 +636,26 @@ namespace TelegramBotBase.Sessions
/// </summary>
/// <param name="buttonText"></param>
/// <param name="requestMessage"></param>
/// <param name="OneTimeOnly"></param>
/// <param name="oneTimeOnly"></param>
/// <returns></returns>
public async Task<Message> RequestLocation(String buttonText = "Send your location", String requestMessage = "Give me your location!", bool OneTimeOnly = true)
public async Task<Message> RequestLocation(string buttonText = "Send your location", string requestMessage = "Give me your location!", bool oneTimeOnly = true)
{
var rcl = new ReplyKeyboardMarkup(KeyboardButton.WithRequestLocation(buttonText));
rcl.OneTimeKeyboard = OneTimeOnly;
return await API(a => a.SendTextMessageAsync(this.DeviceId, requestMessage, replyMarkup: rcl));
var rcl = new ReplyKeyboardMarkup(KeyboardButton.WithRequestLocation(buttonText))
{
OneTimeKeyboard = oneTimeOnly
};
return await Api(a => a.SendTextMessageAsync(DeviceId, requestMessage, replyMarkup: rcl));
}
public async Task<Message> HideReplyKeyboard(String closedMsg = "Closed", bool autoDeleteResponse = true)
public async Task<Message> HideReplyKeyboard(string closedMsg = "Closed", bool autoDeleteResponse = true)
{
try
{
var m = await this.Send(closedMsg, new ReplyKeyboardRemove());
var m = await Send(closedMsg, new ReplyKeyboardRemove());
if (autoDeleteResponse && m != null)
{
await this.DeleteMessage(m);
await DeleteMessage(m);
}
return m;
@@ -696,7 +675,7 @@ namespace TelegramBotBase.Sessions
public virtual async Task<bool> DeleteMessage(int messageId = -1)
{
await RAW(a => a.DeleteMessageAsync(this.DeviceId, messageId));
await Raw(a => a.DeleteMessageAsync(DeviceId, messageId));
OnMessageDeleted(new MessageDeletedEventArgs(messageId));
@@ -718,7 +697,7 @@ namespace TelegramBotBase.Sessions
{
try
{
await API(a => a.SetChatPermissionsAsync(this.DeviceId, permissions));
await Api(a => a.SetChatPermissionsAsync(DeviceId, permissions));
}
catch
{
@@ -728,7 +707,7 @@ namespace TelegramBotBase.Sessions
private Type GetOrigin(StackTrace stackTrace)
{
for (int i = 0; i < stackTrace.FrameCount; i++)
for (var i = 0; i < stackTrace.FrameCount; i++)
{
var methodBase = stackTrace.GetFrame(i).GetMethod();
@@ -749,7 +728,7 @@ namespace TelegramBotBase.Sessions
{
try
{
await API(a => a.RestrictChatMemberAsync(this.DeviceId, userId, permissions, until));
await Api(a => a.RestrictChatMemberAsync(DeviceId, userId, permissions, until));
}
catch
{
@@ -761,7 +740,7 @@ namespace TelegramBotBase.Sessions
{
try
{
return await API(a => a.GetChatMemberAsync(this.DeviceId, userId));
return await Api(a => a.GetChatMemberAsync(DeviceId, userId));
}
catch
{
@@ -775,7 +754,7 @@ namespace TelegramBotBase.Sessions
{
try
{
await API(a => a.BanChatMemberAsync(this.DeviceId, userId, until));
await Api(a => a.BanChatMemberAsync(DeviceId, userId, until));
}
catch
{
@@ -787,7 +766,7 @@ namespace TelegramBotBase.Sessions
{
try
{
await API(a => a.BanChatMemberAsync(this.DeviceId, userId, until));
await Api(a => a.BanChatMemberAsync(DeviceId, userId, until));
}
catch
{
@@ -799,7 +778,7 @@ namespace TelegramBotBase.Sessions
{
try
{
await API(a => a.UnbanChatMemberAsync(this.DeviceId, userId));
await Api(a => a.UnbanChatMemberAsync(DeviceId, userId));
}
catch
{
@@ -815,9 +794,9 @@ namespace TelegramBotBase.Sessions
/// <typeparam name="T"></typeparam>
/// <param name="call"></param>
/// <returns></returns>
public T RAW<T>(Func<Telegram.Bot.ITelegramBotClient, T> call)
public T Raw<T>(Func<ITelegramBotClient, T> call)
{
return call(this.Client.TelegramClient);
return call(Client.TelegramClient);
}
/// <summary>
@@ -826,10 +805,10 @@ namespace TelegramBotBase.Sessions
/// <typeparam name="T"></typeparam>
/// <param name="call"></param>
/// <returns></returns>
public async Task<T> API<T>(Func<Telegram.Bot.ITelegramBotClient, Task<T>> call)
public async Task<T> Api<T>(Func<ITelegramBotClient, Task<T>> call)
{
var numberOfTries = 0;
while (numberOfTries < DeviceSession.MaxNumberOfRetries)
while (numberOfTries < MaxNumberOfRetries)
{
try
{
@@ -854,10 +833,10 @@ namespace TelegramBotBase.Sessions
/// </summary>
/// <param name="call"></param>
/// <returns></returns>
public async Task API(Func<Telegram.Bot.ITelegramBotClient, Task> call)
public async Task Api(Func<ITelegramBotClient, Task> call)
{
var numberOfTries = 0;
while (numberOfTries < DeviceSession.MaxNumberOfRetries)
while (numberOfTries < MaxNumberOfRetries)
{
try
{
@@ -883,16 +862,10 @@ namespace TelegramBotBase.Sessions
/// <summary>
/// Eventhandler for sent messages
/// </summary>
public event Base.Async.AsyncEventHandler<MessageSentEventArgs> MessageSent
public event Async.AsyncEventHandler<MessageSentEventArgs> MessageSent
{
add
{
this.__Events.AddHandler(__evMessageSent, value);
}
remove
{
this.__Events.RemoveHandler(__evMessageSent, value);
}
add => _events.AddHandler(EvMessageSent, value);
remove => _events.RemoveHandler(EvMessageSent, value);
}
@@ -900,14 +873,14 @@ namespace TelegramBotBase.Sessions
{
if (e.Message == null)
return;
var handler = this.__Events[__evMessageSent]?.GetInvocationList().Cast<Base.Async.AsyncEventHandler<MessageSentEventArgs>>();
var handler = _events[EvMessageSent]?.GetInvocationList().Cast<Async.AsyncEventHandler<MessageSentEventArgs>>();
if (handler == null)
return;
foreach (var h in handler)
{
await Base.Async.InvokeAllAsync<MessageSentEventArgs>(h, this, e);
await h.InvokeAllAsync(this, e);
}
//(this.__Events[__evMessageSent] as EventHandler<MessageSentEventArgs>)?.Invoke(this, e);
@@ -918,20 +891,14 @@ namespace TelegramBotBase.Sessions
/// </summary>
public event EventHandler<MessageReceivedEventArgs> MessageReceived
{
add
{
this.__Events.AddHandler(__evMessageReceived, value);
}
remove
{
this.__Events.RemoveHandler(__evMessageReceived, value);
}
add => _events.AddHandler(EvMessageReceived, value);
remove => _events.RemoveHandler(EvMessageReceived, value);
}
public void OnMessageReceived(MessageReceivedEventArgs e)
{
(this.__Events[__evMessageReceived] as EventHandler<MessageReceivedEventArgs>)?.Invoke(this, e);
(_events[EvMessageReceived] as EventHandler<MessageReceivedEventArgs>)?.Invoke(this, e);
}
/// <summary>
@@ -939,20 +906,14 @@ namespace TelegramBotBase.Sessions
/// </summary>
public event EventHandler<MessageDeletedEventArgs> MessageDeleted
{
add
{
this.__Events.AddHandler(__evMessageDeleted, value);
}
remove
{
this.__Events.RemoveHandler(__evMessageDeleted, value);
}
add => _events.AddHandler(EvMessageDeleted, value);
remove => _events.RemoveHandler(EvMessageDeleted, value);
}
public void OnMessageDeleted(MessageDeletedEventArgs e)
{
(this.__Events[__evMessageDeleted] as EventHandler<MessageDeletedEventArgs>)?.Invoke(this, e);
(_events[EvMessageDeleted] as EventHandler<MessageDeletedEventArgs>)?.Invoke(this, e);
}
#endregion
@@ -960,7 +921,7 @@ namespace TelegramBotBase.Sessions
#region "Static"
/// <summary>
/// Indicates the maximum number of times a request that received error
/// Indicates the maximum number of times a request that received error
/// 429 will be sent again after a timeout until it receives code 200 or an error code not equal to 429.
/// </summary>
public static uint MaxNumberOfRetries { get; set; }
+18 -25
View File
@@ -1,8 +1,6 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System;
using System.IO;
using Newtonsoft.Json;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
@@ -13,9 +11,9 @@ namespace TelegramBotBase.States
/// <summary>
/// Is used for all complex data types. Use if other default machines are not working.
/// </summary>
public class JSONStateMachine : IStateMachine
public class JsonStateMachine : IStateMachine
{
public String FilePath { get; set; }
public string FilePath { get; set; }
public bool Overwrite { get; set; }
@@ -27,35 +25,30 @@ namespace TelegramBotBase.States
/// <param name="file">Path of the file and name where to save the session details.</param>
/// <param name="fallbackStateForm">Type of Form which will be saved instead of Form which has <seealso cref="Attributes.IgnoreState"/> attribute declared. Needs to be subclass of <seealso cref="Form.FormBase"/>.</param>
/// <param name="overwrite">Declares of the file could be overwritten.</param>
public JSONStateMachine(String file, Type fallbackStateForm = null, bool overwrite = true)
public JsonStateMachine(string file, Type fallbackStateForm = null, bool overwrite = true)
{
if (file is null)
{
throw new ArgumentNullException(nameof(file));
}
FallbackStateForm = fallbackStateForm;
this.FallbackStateForm = fallbackStateForm;
if (this.FallbackStateForm != null && !this.FallbackStateForm.IsSubclassOf(typeof(FormBase)))
if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase)))
{
throw new ArgumentException("FallbackStateForm is not a subclass of FormBase");
}
this.FilePath = file;
this.Overwrite = overwrite;
FilePath = file ?? throw new ArgumentNullException(nameof(file));
Overwrite = overwrite;
}
public StateContainer LoadFormStates()
{
try
{
var content = System.IO.File.ReadAllText(FilePath);
var content = File.ReadAllText(FilePath);
var sc = Newtonsoft.Json.JsonConvert.DeserializeObject<StateContainer>(content, new JsonSerializerSettings
var sc = JsonConvert.DeserializeObject<StateContainer>(content, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple
}) as StateContainer;
});
return sc;
}
@@ -69,25 +62,25 @@ namespace TelegramBotBase.States
public void SaveFormStates(SaveStatesEventArgs e)
{
if (System.IO.File.Exists(FilePath))
if (File.Exists(FilePath))
{
if (!this.Overwrite)
if (!Overwrite)
{
throw new Exception("File exists already.");
}
System.IO.File.Delete(FilePath);
File.Delete(FilePath);
}
try
{
var content = Newtonsoft.Json.JsonConvert.SerializeObject(e.States, Formatting.Indented, new JsonSerializerSettings
var content = JsonConvert.SerializeObject(e.States, Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple
});
System.IO.File.WriteAllText(FilePath, content);
File.WriteAllText(FilePath, content);
}
catch
{
@@ -1,8 +1,6 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System;
using System.IO;
using Newtonsoft.Json;
using TelegramBotBase.Args;
using TelegramBotBase.Base;
using TelegramBotBase.Form;
@@ -13,9 +11,9 @@ namespace TelegramBotBase.States
/// <summary>
/// Is used for simple object structures like classes, lists or basic datatypes without generics and other compiler based data types.
/// </summary>
public class SimpleJSONStateMachine : IStateMachine
public class SimpleJsonStateMachine : IStateMachine
{
public String FilePath { get; set; }
public string FilePath { get; set; }
public bool Overwrite { get; set; }
@@ -27,31 +25,26 @@ namespace TelegramBotBase.States
/// <param name="file">Path of the file and name where to save the session details.</param>
/// <param name="fallbackStateForm">Type of Form which will be saved instead of Form which has <seealso cref="Attributes.IgnoreState"/> attribute declared. Needs to be subclass of <seealso cref="Form.FormBase"/>.</param>
/// <param name="overwrite">Declares of the file could be overwritten.</param>
public SimpleJSONStateMachine(String file, Type fallbackStateForm = null, bool overwrite = true)
public SimpleJsonStateMachine(string file, Type fallbackStateForm = null, bool overwrite = true)
{
if (file is null)
{
throw new ArgumentNullException(nameof(file));
}
FallbackStateForm = fallbackStateForm;
this.FallbackStateForm = fallbackStateForm;
if (this.FallbackStateForm != null && !this.FallbackStateForm.IsSubclassOf(typeof(FormBase)))
if (FallbackStateForm != null && !FallbackStateForm.IsSubclassOf(typeof(FormBase)))
{
throw new ArgumentException("FallbackStateForm is not a subclass of FormBase");
}
this.FilePath = file;
this.Overwrite = overwrite;
FilePath = file ?? throw new ArgumentNullException(nameof(file));
Overwrite = overwrite;
}
public StateContainer LoadFormStates()
{
try
{
var content = System.IO.File.ReadAllText(FilePath);
var content = File.ReadAllText(FilePath);
var sc = Newtonsoft.Json.JsonConvert.DeserializeObject<StateContainer>(content) as StateContainer;
var sc = JsonConvert.DeserializeObject<StateContainer>(content);
return sc;
}
@@ -65,21 +58,21 @@ namespace TelegramBotBase.States
public void SaveFormStates(SaveStatesEventArgs e)
{
if (System.IO.File.Exists(FilePath))
if (File.Exists(FilePath))
{
if (!this.Overwrite)
if (!Overwrite)
{
throw new Exception("File exists already.");
}
System.IO.File.Delete(FilePath);
File.Delete(FilePath);
}
try
{
var content = Newtonsoft.Json.JsonConvert.SerializeObject(e.States, Formatting.Indented);
var content = JsonConvert.SerializeObject(e.States, Formatting.Indented);
System.IO.File.WriteAllText(FilePath, content);
File.WriteAllText(FilePath, content);
}
catch
{

Some files were not shown because too many files have changed in this diff Show More