Integration of changes

Integrate some changes and cleanups

Co-Authored-By: Alexey <110727638+ZavaruKitsu@users.noreply.github.com>
This commit is contained in:
FlorianDahn 2022-10-09 17:12:52 +02:00
parent 91002c8271
commit f39b1d11be
6 changed files with 79 additions and 112 deletions

View File

@ -164,7 +164,7 @@ namespace TelegramBotBase.Base
} }
/// <summary> /// <summary>
/// Confirm incomming action (i.e. Button click) /// Confirm incoming action (i.e. Button click)
/// </summary> /// </summary>
/// <param name="message"></param> /// <param name="message"></param>
/// <returns></returns> /// <returns></returns>

View File

@ -24,7 +24,7 @@ namespace TelegramBotBase
/// Bot base class for full Device/Context and Messagehandling /// Bot base class for full Device/Context and Messagehandling
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
public class BotBase public sealed class BotBase
{ {
public MessageClient Client { get; set; } public MessageClient Client { get; set; }
@ -36,7 +36,7 @@ namespace TelegramBotBase
/// <summary> /// <summary>
/// List of all running/active sessions /// List of all running/active sessions
/// </summary> /// </summary>
public SessionBase Sessions { get; set; } public SessionManager Sessions { get; set; }
/// <summary> /// <summary>
/// Contains System commands which will be available at everytime and didnt get passed to forms, i.e. /start /// Contains System commands which will be available at everytime and didnt get passed to forms, i.e. /start
@ -46,7 +46,7 @@ namespace TelegramBotBase
#region "Events" #region "Events"
private EventHandlerList __Events = new EventHandlerList(); private EventHandlerList __events = new EventHandlerList();
private static object __evSessionBegins = new object(); private static object __evSessionBegins = new object();
@ -83,9 +83,9 @@ namespace TelegramBotBase
/// </summary> /// </summary>
public Dictionary<eSettings, uint> SystemSettings { get; private set; } public Dictionary<eSettings, uint> SystemSettings { get; private set; }
public BotBase() internal BotBase()
{ {
this.SystemSettings = new Dictionary<eSettings, uint>(); SystemSettings = new Dictionary<eSettings, uint>();
SetSetting(eSettings.MaxNumberOfRetries, 5); SetSetting(eSettings.MaxNumberOfRetries, 5);
SetSetting(eSettings.NavigationMaximum, 10); SetSetting(eSettings.NavigationMaximum, 10);
@ -93,10 +93,9 @@ namespace TelegramBotBase
SetSetting(eSettings.SkipAllMessages, false); SetSetting(eSettings.SkipAllMessages, false);
SetSetting(eSettings.SaveSessionsOnConsoleExit, false); SetSetting(eSettings.SaveSessionsOnConsoleExit, false);
this.BotCommandScopes = new Dictionary<BotCommandScope, List<BotCommand>>(); BotCommandScopes = new Dictionary<BotCommandScope, List<BotCommand>>();
this.Sessions = new SessionBase(); Sessions = new SessionManager(this);
this.Sessions.BotBase = this;
} }
@ -104,31 +103,22 @@ namespace TelegramBotBase
/// <summary> /// <summary>
/// Start your Bot /// Start your Bot
/// </summary> /// </summary>
public void Start() public async Task Start()
{ {
if (this.Client == null) Client.MessageLoop += Client_MessageLoop;
return;
this.Client.MessageLoop += Client_MessageLoop;
if (this.StateMachine != null) if (StateMachine != null) await Sessions.LoadSessionStates(StateMachine);
{
this.Sessions.LoadSessionStates(this.StateMachine);
}
//Enable auto session saving //Enable auto session saving
if (this.GetSetting(eSettings.SaveSessionsOnConsoleExit, false)) if (GetSetting(eSettings.SaveSessionsOnConsoleExit, false))
{ TelegramBotBase.Tools.Console.SetHandler(() => { Task.Run(Sessions.SaveSessionStates); });
TelegramBotBase.Tools.Console.SetHandler(() =>
{
this.Sessions.SaveSessionStates();
});
}
DeviceSession.MaxNumberOfRetries = this.GetSetting(eSettings.MaxNumberOfRetries, 5); DeviceSession.MaxNumberOfRetries = GetSetting(eSettings.MaxNumberOfRetries, 5);
this.Client.StartReceiving(); Client.StartReceiving();
} }
@ -137,7 +127,7 @@ namespace TelegramBotBase
DeviceSession ds = this.Sessions.GetSession(e.DeviceId); DeviceSession ds = this.Sessions.GetSession(e.DeviceId);
if (ds == null) if (ds == null)
{ {
ds = this.Sessions.StartSession(e.DeviceId).GetAwaiter().GetResult(); ds = Sessions.StartSession(e.DeviceId).GetAwaiter().GetResult();
e.Device = ds; e.Device = ds;
ds.LastMessage = e.RawData.Message; ds.LastMessage = e.RawData.Message;
@ -160,24 +150,24 @@ namespace TelegramBotBase
mr.IsFirstHandler = false; mr.IsFirstHandler = false;
} while (ds.FormSwitched && i < this.GetSetting(eSettings.NavigationMaximum, 10)); } while (ds.FormSwitched && i < GetSetting(eSettings.NavigationMaximum, 10));
} }
/// <summary> /// <summary>
/// Stop your Bot /// Stop your Bot
/// </summary> /// </summary>
public void Stop() public async Task Stop()
{ {
if (this.Client == null) if (Client == null)
return; return;
this.Client.MessageLoop -= Client_MessageLoop; Client.MessageLoop -= Client_MessageLoop;
this.Client.StopReceiving(); Client.StopReceiving();
this.Sessions.SaveSessionStates(); await Sessions.SaveSessionStates();
} }
/// <summary> /// <summary>
@ -187,12 +177,12 @@ namespace TelegramBotBase
/// <returns></returns> /// <returns></returns>
public async Task SentToAll(String message) public async Task SentToAll(String message)
{ {
if (this.Client == null) if (Client == null)
return; 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);
} }
} }
@ -252,17 +242,17 @@ namespace TelegramBotBase
/// </summary> /// </summary>
public async Task UploadBotCommands() public async Task UploadBotCommands()
{ {
foreach (var bs in this.BotCommandScopes) foreach (var bs in BotCommandScopes)
{ {
if(bs.Value !=null) if (bs.Value != null)
{ {
await this.Client.SetBotCommands(bs.Value, bs.Key); await Client.SetBotCommands(bs.Value, bs.Key);
} }
else else
{ {
await this.Client.DeleteBotCommands(bs.Key); await Client.DeleteBotCommands(bs.Key);
} }
} }
} }
@ -273,7 +263,7 @@ namespace TelegramBotBase
/// <returns></returns> /// <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)) if (scope.Value.Any(a => "/" + a.Command == command))
return true; return true;
@ -289,7 +279,7 @@ namespace TelegramBotBase
/// <param name="Value"></param> /// <param name="Value"></param>
public void SetSetting(eSettings set, uint Value) public void SetSetting(eSettings set, uint Value)
{ {
this.SystemSettings[set] = Value; SystemSettings[set] = Value;
} }
/// <summary> /// <summary>
@ -299,7 +289,7 @@ namespace TelegramBotBase
/// <param name="Value"></param> /// <param name="Value"></param>
public void SetSetting(eSettings set, bool Value) public void SetSetting(eSettings set, bool Value)
{ {
this.SystemSettings[set] = (Value ? 1u : 0u); SystemSettings[set] = (Value ? 1u : 0u);
} }
/// <summary> /// <summary>
@ -310,10 +300,10 @@ namespace TelegramBotBase
/// <returns></returns> /// <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 defaultValue;
return this.SystemSettings[set]; return SystemSettings[set];
} }
/// <summary> /// <summary>
@ -324,10 +314,10 @@ namespace TelegramBotBase
/// <returns></returns> /// <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 defaultValue;
return this.SystemSettings[set] == 0u ? false : true; return SystemSettings[set] == 0u ? false : true;
} }
#region "Events" #region "Events"
@ -340,17 +330,17 @@ namespace TelegramBotBase
{ {
add add
{ {
this.__Events.AddHandler(__evSessionBegins, value); __events.AddHandler(__evSessionBegins, value);
} }
remove remove
{ {
this.__Events.RemoveHandler(__evSessionBegins, value); __events.RemoveHandler(__evSessionBegins, value);
} }
} }
public void OnSessionBegins(SessionBeginEventArgs e) public void OnSessionBegins(SessionBeginEventArgs e)
{ {
(this.__Events[__evSessionBegins] as EventHandler<SessionBeginEventArgs>)?.Invoke(this, e); (__events[__evSessionBegins] as EventHandler<SessionBeginEventArgs>)?.Invoke(this, e);
} }
@ -361,17 +351,17 @@ namespace TelegramBotBase
{ {
add add
{ {
this.__Events.AddHandler(__evMessage, value); __events.AddHandler(__evMessage, value);
} }
remove remove
{ {
this.__Events.RemoveHandler(__evMessage, value); __events.RemoveHandler(__evMessage, value);
} }
} }
public void OnMessage(MessageIncomeEventArgs e) public void OnMessage(MessageIncomeEventArgs e)
{ {
(this.__Events[__evMessage] as EventHandler<MessageIncomeEventArgs>)?.Invoke(this, e); (__events[__evMessage] as EventHandler<MessageIncomeEventArgs>)?.Invoke(this, e);
} }
@ -383,7 +373,7 @@ namespace TelegramBotBase
public async Task OnBotCommand(BotCommandEventArgs e) public async Task OnBotCommand(BotCommandEventArgs e)
{ {
if (this.BotCommand != null) if (BotCommand != null)
await BotCommand(this, e); await BotCommand(this, e);
} }
@ -394,17 +384,17 @@ namespace TelegramBotBase
{ {
add add
{ {
this.__Events.AddHandler(__evException, value); __events.AddHandler(__evException, value);
} }
remove remove
{ {
this.__Events.RemoveHandler(__evException, value); __events.RemoveHandler(__evException, value);
} }
} }
public void OnException(SystemExceptionEventArgs e) public void OnException(SystemExceptionEventArgs e)
{ {
(this.__Events[__evException] as EventHandler<SystemExceptionEventArgs>)?.Invoke(this, e); (__events[__evException] as EventHandler<SystemExceptionEventArgs>)?.Invoke(this, e);
} }
@ -415,17 +405,17 @@ namespace TelegramBotBase
{ {
add add
{ {
this.__Events.AddHandler(__evUnhandledCall, value); __events.AddHandler(__evUnhandledCall, value);
} }
remove remove
{ {
this.__Events.RemoveHandler(__evUnhandledCall, value); __events.RemoveHandler(__evUnhandledCall, value);
} }
} }
public void OnUnhandledCall(UnhandledCallEventArgs e) public void OnUnhandledCall(UnhandledCallEventArgs e)
{ {
(this.__Events[__evUnhandledCall] as EventHandler<UnhandledCallEventArgs>)?.Invoke(this, e); (__events[__evUnhandledCall] as EventHandler<UnhandledCallEventArgs>)?.Invoke(this, e);
} }

View File

@ -335,8 +335,6 @@ namespace TelegramBotBase.Builder
bb.Client = _client; bb.Client = _client;
bb.Sessions.Client = bb.Client;
bb.BotCommandScopes = _BotCommandScopes; bb.BotCommandScopes = _BotCommandScopes;
bb.StateMachine = _statemachine; bb.StateMachine = _statemachine;

View File

@ -35,7 +35,7 @@ namespace TelegramBotBase.Datasources
/// <summary> /// <summary>
/// Returns the amount of rows exisiting. /// Returns the amount of rows existing.
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public virtual int Count => ButtonForm.Count; public virtual int Count => ButtonForm.Count;

View File

@ -28,10 +28,10 @@ namespace TelegramBotBase.Localizations
Values["ToggleButton_OnIcon"] = "⚫"; Values["ToggleButton_OnIcon"] = "⚫";
Values["ToggleButton_OffIcon"] = "⚪"; Values["ToggleButton_OffIcon"] = "⚪";
Values["ToggleButton_Title"] = "Toggle"; Values["ToggleButton_Title"] = "Toggle";
Values["ToggleButton_Changed"] = "Choosen"; Values["ToggleButton_Changed"] = "Chosen";
Values["MultiToggleButton_SelectedIcon"] = "✅"; Values["MultiToggleButton_SelectedIcon"] = "✅";
Values["MultiToggleButton_Title"] = "Multi-Toggle"; Values["MultiToggleButton_Title"] = "Multi-Toggle";
Values["MultiToggleButton_Changed"] = "Choosen"; Values["MultiToggleButton_Changed"] = "Chosen";
Values["PromptDialog_Back"] = "Back"; Values["PromptDialog_Back"] = "Back";
Values["ToggleButton_Changed"] = "Setting changed"; Values["ToggleButton_Changed"] = "Setting changed";
} }

View File

@ -14,14 +14,14 @@ using TelegramBotBase.Sessions;
namespace TelegramBotBase namespace TelegramBotBase
{ {
/// <summary> /// <summary>
/// Base class for managing all active sessions /// Class for managing all active sessions
/// </summary> /// </summary>
public class SessionBase public sealed class SessionManager
{ {
/// <summary> /// <summary>
/// The Basic message client. /// The Basic message client.
/// </summary> /// </summary>
public MessageClient Client { get; set; } public MessageClient Client => BotBase.Client;
/// <summary> /// <summary>
/// A list of all active sessions. /// A list of all active sessions.
@ -32,29 +32,13 @@ namespace TelegramBotBase
/// <summary> /// <summary>
/// Reference to the Main BotBase instance for later use. /// Reference to the Main BotBase instance for later use.
/// </summary> /// </summary>
public BotBase BotBase { get; set; } public BotBase BotBase { get; }
public SessionBase() public SessionManager(BotBase botBase)
{ {
this.SessionList = new Dictionary<long, DeviceSession>(); BotBase = botBase;
} SessionList = new Dictionary<long, DeviceSession>();
/// <summary>
/// Get device session from Device/ChatId
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public DeviceSession this[long key]
{
get
{
return this.SessionList[key];
}
set
{
this.SessionList[key] = value;
}
} }
/// <summary> /// <summary>
@ -64,7 +48,7 @@ namespace TelegramBotBase
/// <returns></returns> /// <returns></returns>
public DeviceSession GetSession(long deviceId) 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; return ds;
} }
@ -77,7 +61,6 @@ namespace TelegramBotBase
public async Task<DeviceSession> StartSession(long deviceId) public async Task<DeviceSession> StartSession(long deviceId)
{ {
var start = BotBase.StartFormFactory.CreateForm(); var start = BotBase.StartFormFactory.CreateForm();
//T start = typeof(T).GetConstructor(new Type[] { }).Invoke(new object[] { }) as T;
start.Client = this.Client; start.Client = this.Client;
@ -88,7 +71,7 @@ namespace TelegramBotBase
await start.OnOpened(new EventArgs()); await start.OnOpened(new EventArgs());
this[deviceId] = ds; SessionList[deviceId] = ds;
return ds; return ds;
} }
@ -98,12 +81,8 @@ namespace TelegramBotBase
/// <param name="deviceId"></param> /// <param name="deviceId"></param>
public void EndSession(long deviceId) public void EndSession(long deviceId)
{ {
var d = this[deviceId]; var d = SessionList[deviceId];
if (d != null) if (d != null) SessionList.Remove(deviceId);
{
this.SessionList.Remove(deviceId);
}
} }
/// <summary> /// <summary>
@ -112,7 +91,7 @@ namespace TelegramBotBase
/// <returns></returns> /// <returns></returns>
public List<DeviceSession> GetUserSessions() 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> /// <summary>
@ -121,27 +100,27 @@ namespace TelegramBotBase
/// <returns></returns> /// <returns></returns>
public List<DeviceSession> GetGroupSessions() 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> /// <summary>
/// Loads the previously saved states from the machine. /// Loads the previously saved states from the machine.
/// </summary> /// </summary>
public async void LoadSessionStates() public async Task LoadSessionStates()
{ {
if (BotBase.StateMachine == null) if (BotBase.StateMachine == null)
{ {
return; return;
} }
LoadSessionStates(BotBase.StateMachine); await LoadSessionStates(BotBase.StateMachine);
} }
/// <summary> /// <summary>
/// Loads the previously saved states from the machine. /// Loads the previously saved states from the machine.
/// </summary> /// </summary>
public async void LoadSessionStates(IStateMachine statemachine) public async Task LoadSessionStates(IStateMachine statemachine)
{ {
if (statemachine == null) if (statemachine == null)
{ {
@ -159,7 +138,7 @@ namespace TelegramBotBase
} }
//Key already existing //Key already existing
if (this.SessionList.ContainsKey(s.DeviceId)) if (SessionList.ContainsKey(s.DeviceId))
continue; continue;
var form = t.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as FormBase; var form = t.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as FormBase;
@ -222,7 +201,7 @@ namespace TelegramBotBase
device.ChatTitle = s.ChatTitle; device.ChatTitle = s.ChatTitle;
this.SessionList.Add(s.DeviceId, device); SessionList.Add(s.DeviceId, device);
//Is Subclass of IStateForm //Is Subclass of IStateForm
var iform = form as IStateForm; var iform = form as IStateForm;
@ -242,7 +221,7 @@ namespace TelegramBotBase
catch catch
{ {
//Skip on exception //Skip on exception
this.SessionList.Remove(s.DeviceId); SessionList.Remove(s.DeviceId);
} }
} }
@ -254,7 +233,7 @@ namespace TelegramBotBase
/// <summary> /// <summary>
/// Saves all open states into the machine. /// Saves all open states into the machine.
/// </summary> /// </summary>
public void SaveSessionStates(IStateMachine statemachine) public async Task SaveSessionStates(IStateMachine statemachine)
{ {
if (statemachine == null) if (statemachine == null)
{ {
@ -263,7 +242,7 @@ namespace TelegramBotBase
var states = new List<StateEntry>(); var states = new List<StateEntry>();
foreach (var s in this.SessionList) foreach (var s in SessionList)
{ {
if (s.Value == null) if (s.Value == null)
{ {
@ -333,13 +312,13 @@ namespace TelegramBotBase
/// <summary> /// <summary>
/// Saves all open states into the machine. /// Saves all open states into the machine.
/// </summary> /// </summary>
public void SaveSessionStates() public async Task SaveSessionStates()
{ {
if (this.BotBase.StateMachine == null) if (BotBase.StateMachine == null)
return; return;
this.SaveSessionStates(this.BotBase.StateMachine); await SaveSessionStates(BotBase.StateMachine);
} }
} }
} }