Merge pull request #32 from MajMcCloud/development

Updating to 5.2
This commit is contained in:
Florian Zevedei
2022-11-23 13:15:35 +01:00
committed by GitHub
68 changed files with 1605 additions and 264 deletions
+1 -1
View File
@@ -7,7 +7,7 @@ using Telegram.Bot.Types;
namespace TelegramBotBase.Args
{
public class MessageSentEventArgs
public class MessageSentEventArgs : EventArgs
{
public int MessageId
{
+22 -18
View File
@@ -108,8 +108,9 @@ namespace TelegramBotBase.Base
public async Task<InputOnlineFile> DownloadDocument()
{
var encryptedContent = new System.IO.MemoryStream(this.Document.FileSize.Value);
var file = await this.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Document.FileId, encryptedContent);
var encryptedContent = new System.IO.MemoryStream();
encryptedContent.SetLength(this.Document.FileSize.Value);
var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Document.FileId, encryptedContent);
return new InputOnlineFile(encryptedContent, this.Document.FileName);
}
@@ -122,9 +123,9 @@ namespace TelegramBotBase.Base
/// <returns></returns>
public async Task DownloadDocument(String path)
{
var file = await this.Client.TelegramClient.GetFileAsync(this.Document.FileId);
var file = await Device.Client.TelegramClient.GetFileAsync(this.Document.FileId);
FileStream fs = new FileStream(path, FileMode.Create);
await this.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
fs.Close();
fs.Dispose();
}
@@ -136,7 +137,7 @@ namespace TelegramBotBase.Base
public async Task<byte[]> DownloadRawDocument()
{
MemoryStream ms = new MemoryStream();
await this.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Document.FileId, ms);
await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Document.FileId, ms);
return ms.ToArray();
}
@@ -156,7 +157,7 @@ namespace TelegramBotBase.Base
public async Task<String> DownloadRawTextDocument(Encoding encoding)
{
MemoryStream ms = new MemoryStream();
await this.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Document.FileId, ms);
await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Document.FileId, ms);
ms.Position = 0;
@@ -167,34 +168,36 @@ namespace TelegramBotBase.Base
public async Task<InputOnlineFile> DownloadVideo()
{
var encryptedContent = new System.IO.MemoryStream(this.Video.FileSize.Value);
var file = await this.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Video.FileId, encryptedContent);
var encryptedContent = new System.IO.MemoryStream();
encryptedContent.SetLength(this.Video.FileSize.Value);
var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Video.FileId, encryptedContent);
return new InputOnlineFile(encryptedContent, "");
}
public async Task DownloadVideo(String path)
{
var file = await this.Client.TelegramClient.GetFileAsync(this.Video.FileId);
var file = await Device.Client.TelegramClient.GetFileAsync(this.Video.FileId);
FileStream fs = new FileStream(path, FileMode.Create);
await this.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
fs.Close();
fs.Dispose();
}
public async Task<InputOnlineFile> DownloadAudio()
{
var encryptedContent = new System.IO.MemoryStream(this.Audio.FileSize.Value);
var file = await this.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Audio.FileId, encryptedContent);
var encryptedContent = new System.IO.MemoryStream();
encryptedContent.SetLength(this.Audio.FileSize.Value);
var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Audio.FileId, encryptedContent);
return new InputOnlineFile(encryptedContent, "");
}
public async Task DownloadAudio(String path)
{
var file = await this.Client.TelegramClient.GetFileAsync(this.Audio.FileId);
var file = await Device.Client.TelegramClient.GetFileAsync(this.Audio.FileId);
FileStream fs = new FileStream(path, FileMode.Create);
await this.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
fs.Close();
fs.Dispose();
}
@@ -202,8 +205,9 @@ namespace TelegramBotBase.Base
public async Task<InputOnlineFile> DownloadPhoto(int index)
{
var photo = this.Photos[index];
var encryptedContent = new System.IO.MemoryStream(photo.FileSize.Value);
var file = await this.Client.TelegramClient.GetInfoAndDownloadFileAsync(photo.FileId, encryptedContent);
var encryptedContent = new System.IO.MemoryStream();
encryptedContent.SetLength(photo.FileSize.Value);
var file = await Device.Client.TelegramClient.GetInfoAndDownloadFileAsync(photo.FileId, encryptedContent);
return new InputOnlineFile(encryptedContent, "");
}
@@ -211,9 +215,9 @@ namespace TelegramBotBase.Base
public async Task DownloadPhoto(int index, String path)
{
var photo = this.Photos[index];
var file = await this.Client.TelegramClient.GetFileAsync(photo.FileId);
var file = await Device.Client.TelegramClient.GetFileAsync(photo.FileId);
FileStream fs = new FileStream(path, FileMode.Create);
await this.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
await Device.Client.TelegramClient.DownloadFileAsync(file.FilePath, fs);
fs.Close();
fs.Dispose();
}
-9
View File
@@ -55,9 +55,6 @@ namespace TelegramBotBase.Form
public async Task OnInit(InitEventArgs e)
{
if (this.Events[__evInit] == null)
return;
var handler = this.Events[__evInit]?.GetInvocationList().Cast<AsyncEventHandler<InitEventArgs>>();
if (handler == null)
return;
@@ -87,9 +84,6 @@ namespace TelegramBotBase.Form
public async Task OnOpened(EventArgs e)
{
if (this.Events[__evOpened] == null)
return;
var handler = this.Events[__evOpened]?.GetInvocationList().Cast<AsyncEventHandler<EventArgs>>();
if (handler == null)
return;
@@ -120,9 +114,6 @@ namespace TelegramBotBase.Form
public async Task OnClosed(EventArgs e)
{
if (this.Events[__evClosed] == null)
return;
var handler = this.Events[__evClosed]?.GetInvocationList().Cast<AsyncEventHandler<EventArgs>>();
if (handler == null)
return;
+14 -6
View File
@@ -159,27 +159,35 @@ namespace TelegramBotBase.Base
/// This will return the current list of bot commands.
/// </summary>
/// <returns></returns>
public async Task<BotCommand[]> GetBotCommands()
public async Task<BotCommand[]> GetBotCommands(BotCommandScope scope = null, String languageCode = null)
{
return await this.TelegramClient.GetMyCommandsAsync();
return await this.TelegramClient.GetMyCommandsAsync(scope, languageCode);
}
/// <summary>
/// This will set your bot commands to the given list.
/// </summary>
/// <param name="botcommands"></param>
/// <returns></returns>
public async Task SetBotCommands(List<BotCommand> botcommands)
public async Task SetBotCommands(List<BotCommand> botcommands, BotCommandScope scope = null, String languageCode = null)
{
await this.TelegramClient.SetMyCommandsAsync(botcommands);
await this.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)
{
await this.TelegramClient.DeleteMyCommandsAsync(scope, languageCode);
}
#region "Events"
public event Async.AsyncEventHandler<UpdateResult> MessageLoop
{
+1 -7
View File
@@ -29,12 +29,6 @@ namespace TelegramBotBase.Base
}
}
public DeviceSession Device
{
get;
set;
}
/// <summary>
/// The message id
/// </summary>
@@ -170,7 +164,7 @@ namespace TelegramBotBase.Base
}
/// <summary>
/// Confirm incomming action (i.e. Button click)
/// Confirm incoming action (i.e. Button click)
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
+7 -2
View File
@@ -4,12 +4,17 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot;
using TelegramBotBase.Sessions;
namespace TelegramBotBase.Base
{
public class ResultBase : EventArgs
{
public MessageClient Client { get; set; }
public DeviceSession Device
{
get;
set;
}
public virtual long DeviceId { get; set; }
@@ -42,7 +47,7 @@ namespace TelegramBotBase.Base
{
try
{
await this.Client.TelegramClient.DeleteMessageAsync(this.DeviceId, (messageId == -1 ? this.MessageId : messageId));
await Device.Client.TelegramClient.DeleteMessageAsync(this.DeviceId, (messageId == -1 ? this.MessageId : messageId));
}
catch
{
+80 -58
View File
@@ -13,7 +13,7 @@ using TelegramBotBase.Args;
using TelegramBotBase.Attributes;
using TelegramBotBase.Base;
using TelegramBotBase.Enums;
using TelegramBotBase.Factories.MessageLoops;
using TelegramBotBase.MessageLoops;
using TelegramBotBase.Form;
using TelegramBotBase.Interfaces;
using TelegramBotBase.Sessions;
@@ -24,7 +24,7 @@ namespace TelegramBotBase
/// Bot base class for full Device/Context and Messagehandling
/// </summary>
/// <typeparam name="T"></typeparam>
public class BotBase
public sealed class BotBase
{
public MessageClient Client { get; set; }
@@ -36,17 +36,17 @@ namespace TelegramBotBase
/// <summary>
/// List of all running/active sessions
/// </summary>
public SessionBase Sessions { get; set; }
public SessionManager Sessions { get; set; }
/// <summary>
/// Contains System commands which will be available at everytime and didnt get passed to forms, i.e. /start
/// </summary>
public List<BotCommand> BotCommands { get; set; }
public Dictionary<BotCommandScope, List<BotCommand>> BotCommandScopes { get; set; } = new Dictionary<BotCommandScope, List<BotCommand>>();
#region "Events"
private EventHandlerList __Events = new EventHandlerList();
private EventHandlerList __events = new EventHandlerList();
private static object __evSessionBegins = new object();
@@ -83,9 +83,9 @@ namespace TelegramBotBase
/// </summary>
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.NavigationMaximum, 10);
@@ -93,10 +93,9 @@ namespace TelegramBotBase
SetSetting(eSettings.SkipAllMessages, false);
SetSetting(eSettings.SaveSessionsOnConsoleExit, false);
this.BotCommands = new List<BotCommand>();
BotCommandScopes = new Dictionary<BotCommandScope, List<BotCommand>>();
this.Sessions = new SessionBase();
this.Sessions.BotBase = this;
Sessions = new SessionManager(this);
}
@@ -104,31 +103,22 @@ namespace TelegramBotBase
/// <summary>
/// Start your Bot
/// </summary>
public void Start()
public async Task Start()
{
if (this.Client == null)
return;
this.Client.MessageLoop += Client_MessageLoop;
Client.MessageLoop += Client_MessageLoop;
if (this.StateMachine != null)
{
this.Sessions.LoadSessionStates(this.StateMachine);
}
if (StateMachine != null) await Sessions.LoadSessionStates(StateMachine);
//Enable auto session saving
if (this.GetSetting(eSettings.SaveSessionsOnConsoleExit, false))
{
TelegramBotBase.Tools.Console.SetHandler(() =>
{
this.Sessions.SaveSessionStates();
});
}
if (GetSetting(eSettings.SaveSessionsOnConsoleExit, false))
TelegramBotBase.Tools.Console.SetHandler(() => { Task.Run(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);
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;
@@ -160,24 +150,24 @@ namespace TelegramBotBase
mr.IsFirstHandler = false;
} while (ds.FormSwitched && i < this.GetSetting(eSettings.NavigationMaximum, 10));
} while (ds.FormSwitched && i < GetSetting(eSettings.NavigationMaximum, 10));
}
/// <summary>
/// Stop your Bot
/// </summary>
public void Stop()
public async Task 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();
await Sessions.SaveSessionStates();
}
/// <summary>
@@ -187,12 +177,12 @@ namespace TelegramBotBase
/// <returns></returns>
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);
}
}
@@ -206,6 +196,11 @@ namespace TelegramBotBase
{
var mr = new MessageResult();
mr.UpdateData = new Update()
{
Message = new Message()
};
await InvokeMessageLoop(DeviceId, mr);
}
@@ -247,7 +242,34 @@ namespace TelegramBotBase
/// </summary>
public async Task UploadBotCommands()
{
await this.Client.SetBotCommands(this.BotCommands);
foreach (var bs in BotCommandScopes)
{
if (bs.Value != null)
{
await Client.SetBotCommands(bs.Value, bs.Key);
}
else
{
await Client.DeleteBotCommands(bs.Key);
}
}
}
/// <summary>
/// Searching if parameter is a known command in all configured BotCommandScopes.
/// </summary>
/// <param name="command"></param>
/// <returns></returns>
public bool IsKnownBotCommand(String command)
{
foreach (var scope in BotCommandScopes)
{
if (scope.Value.Any(a => "/" + a.Command == command))
return true;
}
return false;
}
/// <summary>
@@ -257,7 +279,7 @@ namespace TelegramBotBase
/// <param name="Value"></param>
public void SetSetting(eSettings set, uint Value)
{
this.SystemSettings[set] = Value;
SystemSettings[set] = Value;
}
/// <summary>
@@ -267,7 +289,7 @@ namespace TelegramBotBase
/// <param name="Value"></param>
public void SetSetting(eSettings set, bool Value)
{
this.SystemSettings[set] = (Value ? 1u : 0u);
SystemSettings[set] = (Value ? 1u : 0u);
}
/// <summary>
@@ -278,10 +300,10 @@ namespace TelegramBotBase
/// <returns></returns>
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>
@@ -292,10 +314,10 @@ namespace TelegramBotBase
/// <returns></returns>
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"
@@ -308,17 +330,17 @@ namespace TelegramBotBase
{
add
{
this.__Events.AddHandler(__evSessionBegins, value);
__events.AddHandler(__evSessionBegins, value);
}
remove
{
this.__Events.RemoveHandler(__evSessionBegins, value);
__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);
}
@@ -329,17 +351,17 @@ namespace TelegramBotBase
{
add
{
this.__Events.AddHandler(__evMessage, value);
__events.AddHandler(__evMessage, value);
}
remove
{
this.__Events.RemoveHandler(__evMessage, value);
__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);
}
@@ -351,7 +373,7 @@ namespace TelegramBotBase
public async Task OnBotCommand(BotCommandEventArgs e)
{
if (this.BotCommand != null)
if (BotCommand != null)
await BotCommand(this, e);
}
@@ -362,17 +384,17 @@ namespace TelegramBotBase
{
add
{
this.__Events.AddHandler(__evException, value);
__events.AddHandler(__evException, value);
}
remove
{
this.__Events.RemoveHandler(__evException, value);
__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);
}
@@ -383,17 +405,17 @@ namespace TelegramBotBase
{
add
{
this.__Events.AddHandler(__evUnhandledCall, value);
__events.AddHandler(__evUnhandledCall, value);
}
remove
{
this.__Events.RemoveHandler(__evUnhandledCall, value);
__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);
}
+38 -12
View File
@@ -7,6 +7,7 @@ using Telegram.Bot.Types;
using TelegramBotBase.Base;
using TelegramBotBase.Builder.Interfaces;
using TelegramBotBase.Commands;
using TelegramBotBase.Factories;
using TelegramBotBase.Form;
using TelegramBotBase.Interfaces;
using TelegramBotBase.Localizations;
@@ -23,7 +24,12 @@ namespace TelegramBotBase.Builder
MessageClient _client = null;
List<BotCommand> _botcommands = new List<BotCommand>();
/// <summary>
/// Contains different Botcommands for different areas.
/// </summary>
Dictionary<BotCommandScope, List<BotCommand>> _BotCommandScopes { get; set; } = new Dictionary<BotCommandScope, List<BotCommand>>();
//List<BotCommand> _botcommands = new List<BotCommand>();
IStateMachine _statemachine = null;
@@ -111,11 +117,20 @@ namespace TelegramBotBase.Builder
public IStartFormSelectionStage DefaultMessageLoop()
{
_messageloopfactory = new Factories.MessageLoops.FormBaseMessageLoop();
_messageloopfactory = new MessageLoops.FormBaseMessageLoop();
return this;
}
public IStartFormSelectionStage MinimalMessageLoop()
{
_messageloopfactory = new MessageLoops.MinimalMessageLoop();
return this;
}
public IStartFormSelectionStage CustomMessageLoop(IMessageLoopFactory messageLoopClass)
{
_messageloopfactory = messageLoopClass;
@@ -134,7 +149,7 @@ namespace TelegramBotBase.Builder
#endregion
#region "Step 3 (Start Form/Factory)"
#region "Step 3 (Start Form/Factory)"
public INetworkingSelectionStage WithStartForm(Type startFormClass)
{
@@ -149,6 +164,19 @@ namespace TelegramBotBase.Builder
return this;
}
public INetworkingSelectionStage WithServiceProvider(Type startFormClass, IServiceProvider serviceProvider)
{
this._factory = new ServiceProviderStartFormFactory(startFormClass, serviceProvider);
return this;
}
public INetworkingSelectionStage WithServiceProvider<T>(IServiceProvider serviceProvider)
where T : FormBase
{
this._factory = new ServiceProviderStartFormFactory<T>(serviceProvider);
return this;
}
public INetworkingSelectionStage WithStartFormFactory(IStartFormFactory factory)
{
this._factory = factory;
@@ -212,7 +240,7 @@ namespace TelegramBotBase.Builder
public ISessionSerializationStage OnlyStart()
{
_botcommands.Start("Starts the bot");
_BotCommandScopes.Start("Starts the bot");
return this;
@@ -220,15 +248,15 @@ namespace TelegramBotBase.Builder
public ISessionSerializationStage DefaultCommands()
{
_botcommands.Start("Starts the bot");
_botcommands.Help("Should show you some help");
_botcommands.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<List<BotCommand>> action)
public ISessionSerializationStage CustomCommands(Action<Dictionary<BotCommandScope, List<BotCommand>>> action)
{
action?.Invoke(_botcommands);
action?.Invoke(_BotCommandScopes);
return this;
}
@@ -307,9 +335,7 @@ namespace TelegramBotBase.Builder
bb.Client = _client;
bb.Sessions.Client = bb.Client;
bb.BotCommands = _botcommands;
bb.BotCommandScopes = _BotCommandScopes;
bb.StateMachine = _statemachine;
@@ -33,7 +33,9 @@ namespace TelegramBotBase.Builder.Interfaces
/// </summary>
/// <param name="action"></param>
/// <returns></returns>
ISessionSerializationStage CustomCommands(Action<List<BotCommand>> action);
ISessionSerializationStage CustomCommands(Action<Dictionary<BotCommandScope, List<BotCommand>>> action);
}
}
@@ -16,6 +16,14 @@ namespace TelegramBotBase.Builder.Interfaces
/// <returns></returns>
IStartFormSelectionStage DefaultMessageLoop();
/// <summary>
/// Chooses a minimalistic message loop, which catches all update types and only calls the Load function.
/// </summary>
/// <returns></returns>
IStartFormSelectionStage MinimalMessageLoop();
/// <summary>
/// Chooses a custom message loop.
/// </summary>
@@ -23,6 +23,22 @@ namespace TelegramBotBase.Builder.Interfaces
/// <returns></returns>
INetworkingSelectionStage WithStartForm<T>() where T : FormBase, new();
/// <summary>
/// Chooses a StartFormFactory which will be use for new sessions.
/// </summary>
/// <param name="startFormClass"></param>
/// <param name="serviceProvider"></param>
/// <returns></returns>
INetworkingSelectionStage WithServiceProvider(Type startFormClass, IServiceProvider serviceProvider);
/// <summary>
/// Chooses a StartFormFactory which will be use for new sessions.
/// </summary>
/// <param name="serviceProvider"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
INetworkingSelectionStage WithServiceProvider<T>(IServiceProvider serviceProvider) where T : FormBase;
/// <summary>
/// Chooses a StartFormFactory which will be use for new sessions.
/// </summary>
+117 -23
View File
@@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Telegram.Bot.Types;
@@ -8,33 +10,28 @@ namespace TelegramBotBase.Commands
public static class Extensions
{
/// <summary>
/// Adding the default /start command with a description.
/// Adding the command with a description.
/// </summary>
/// <param name="cmds"></param>
/// <param name="command"></param>
/// <param name="description"></param>
public static void Start(this List<BotCommand> cmds, String description)
public static void Add(this Dictionary<BotCommandScope, List<BotCommand>> cmds, String command, String description, BotCommandScope scope = null)
{
cmds.Add(new BotCommand() { Command = "start", Description = description });
}
if (scope == null)
{
scope = BotCommandScope.Default();
}
/// <summary>
/// Adding the default /help command with a description.
/// </summary>
/// <param name="cmds"></param>
/// <param name="description"></param>
public static void Help(this List<BotCommand> cmds, String description)
{
cmds.Add(new BotCommand() { Command = "help", Description = description });
}
var item = cmds.FirstOrDefault(a => a.Key.Type == scope.Type);
/// <summary>
/// Adding the default /settings command with a description.
/// </summary>
/// <param name="cmds"></param>
/// <param name="description"></param>
public static void Settings(this List<BotCommand> cmds, String description)
{
cmds.Add(new BotCommand() { Command = "settings", Description = description });
if (item.Value != null)
{
item.Value.Add(new BotCommand() { Command = command, Description = description });
}
else
{
cmds.Add(scope, new List<BotCommand> { new BotCommand() { Command = command, Description = description } });
}
}
/// <summary>
@@ -43,9 +40,106 @@ namespace TelegramBotBase.Commands
/// <param name="cmds"></param>
/// <param name="command"></param>
/// <param name="description"></param>
public static void Add(this List<BotCommand> cmds, String command, String description)
public static void Clear(this Dictionary<BotCommandScope, List<BotCommand>> cmds, BotCommandScope scope = null)
{
cmds.Add(new BotCommand() { Command = command, Description = description });
if (scope == null)
{
scope = BotCommandScope.Default();
}
var item = cmds.FirstOrDefault(a => a.Key.Type == scope.Type);
if (item.Key != null)
{
cmds[item.Key] = null;
}
else
{
cmds[scope] = null;
}
}
/// <summary>
/// Adding the default /start command with a description.
/// </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);
/// <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);
/// <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);
/// <summary>
/// Clears all default commands.
/// </summary>
/// <param name="cmds"></param>
public static void ClearDefaultCommands(this Dictionary<BotCommandScope, List<BotCommand>> cmds) => Clear(cmds, null);
/// <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 });
/// <summary>
/// Adding a chat command with a description.
/// </summary>
/// <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 });
/// <summary>
/// Adding a group command with a description.
/// </summary>
/// <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());
/// <summary>
/// Clears all group commands.
/// </summary>
/// <param name="cmds"></param>
public static void ClearGroupCommands(this Dictionary<BotCommandScope, List<BotCommand>> cmds) => Clear(cmds, new BotCommandScopeAllGroupChats());
/// <summary>
/// Adding group admin command with a description.
/// </summary>
/// <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());
/// <summary>
/// Clears all group admin commands.
/// </summary>
/// <param name="cmds"></param>
public static void ClearGroupAdminCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds) => Clear(cmds, new BotCommandScopeAllChatAdministrators());
/// <summary>
/// Adding a privat command with a description.
/// </summary>
/// <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());
/// <summary>
/// Clears all private commands.
/// </summary>
/// <param name="cmds"></param>
public static void ClearPrivateChatCommand(this Dictionary<BotCommandScope, List<BotCommand>> cmds) => Clear(cmds, new BotCommandScopeAllPrivateChats());
}
}
+1 -1
View File
@@ -50,7 +50,7 @@ namespace TelegramBotBase.Controls.Hybrid
}
private void Device_MessageSent(object sender, MessageSentEventArgs e)
private async Task Device_MessageSent(object sender, MessageSentEventArgs e)
{
if (e.Origin == null || !e.Origin.IsSubclassOf(typeof(MultiView)))
return;
@@ -35,7 +35,7 @@ namespace TelegramBotBase.Datasources
/// <summary>
/// Returns the amount of rows exisiting.
/// Returns the amount of rows existing.
/// </summary>
/// <returns></returns>
public virtual int Count => ButtonForm.Count;
@@ -0,0 +1,35 @@
using System;
using Microsoft.Extensions.DependencyInjection;
using TelegramBotBase.Form;
using TelegramBotBase.Interfaces;
namespace TelegramBotBase.Factories
{
public class ServiceProviderStartFormFactory : IStartFormFactory
{
private readonly Type _startFormClass;
private readonly IServiceProvider _serviceProvider;
public ServiceProviderStartFormFactory(Type startFormClass, IServiceProvider serviceProvider)
{
if (!typeof(FormBase).IsAssignableFrom(startFormClass))
throw new ArgumentException("startFormClass argument must be a FormBase type");
_startFormClass = startFormClass;
_serviceProvider = serviceProvider;
}
public FormBase CreateForm()
{
return (FormBase)ActivatorUtilities.CreateInstance(_serviceProvider, _startFormClass);
}
}
public class ServiceProviderStartFormFactory<T> : ServiceProviderStartFormFactory
where T : FormBase
{
public ServiceProviderStartFormFactory(IServiceProvider serviceProvider) : base(typeof(T), serviceProvider)
{
}
}
}
+1 -1
View File
@@ -67,7 +67,7 @@ namespace TelegramBotBase.Form
this.OldMessages.Add(e.Message.MessageId);
}
private void Device_MessageSent(object sender, MessageSentEventArgs e)
private async Task Device_MessageSent(object sender, MessageSentEventArgs e)
{
if (this.DeleteSide == eDeleteSide.UserOnly)
return;
+2 -2
View File
@@ -28,10 +28,10 @@ namespace TelegramBotBase.Localizations
Values["ToggleButton_OnIcon"] = "⚫";
Values["ToggleButton_OffIcon"] = "⚪";
Values["ToggleButton_Title"] = "Toggle";
Values["ToggleButton_Changed"] = "Choosen";
Values["ToggleButton_Changed"] = "Chosen";
Values["MultiToggleButton_SelectedIcon"] = "✅";
Values["MultiToggleButton_Title"] = "Multi-Toggle";
Values["MultiToggleButton_Changed"] = "Choosen";
Values["MultiToggleButton_Changed"] = "Chosen";
Values["PromptDialog_Back"] = "Back";
Values["ToggleButton_Changed"] = "Setting changed";
}
@@ -11,8 +11,11 @@ using TelegramBotBase.Enums;
using TelegramBotBase.Interfaces;
using TelegramBotBase.Sessions;
namespace TelegramBotBase.Factories.MessageLoops
namespace TelegramBotBase.MessageLoops
{
/// <summary>
/// Thats the default message loop which reacts to Message, EditMessage and CallbackQuery.
/// </summary>
public class FormBaseMessageLoop : IMessageLoopFactory
{
private static object __evUnhandledCall = new object();
@@ -37,7 +40,7 @@ namespace TelegramBotBase.Factories.MessageLoops
}
//Is this a bot command ?
if (mr.IsFirstHandler && mr.IsBotCommand && Bot.BotCommands.Count(a => "/" + a.Command == mr.BotCommand) > 0)
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);
@@ -0,0 +1,130 @@
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;
namespace TelegramBotBase.MessageLoops
{
/// <summary>
/// This message loop reacts to all update types.
/// </summary>
public class FullMessageLoop : IMessageLoopFactory
{
private static object __evUnhandledCall = new object();
private EventHandlerList __Events = new EventHandlerList();
public FullMessageLoop()
{
}
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))
{
var sce = new BotCommandEventArgs(mr.BotCommand, mr.BotCommandParameters, mr.Message, session.DeviceId, session);
await Bot.OnBotCommand(sce);
if (sce.Handled)
return;
}
mr.Device = session;
var activeForm = session.ActiveForm;
//Pre Loading Event
await activeForm.PreLoad(mr);
//Send Load event to controls
await activeForm.LoadControls(mr);
//Loading Event
await activeForm.Load(mr);
//Is Attachment ? (Photo, Audio, Video, Contact, Location, Document) (Ignore Callback Queries)
if (update.Type == Telegram.Bot.Types.Enums.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)
{
await activeForm.SentData(new DataResult(ur));
}
}
//Action Event
if (!session.FormSwitched && mr.IsAction)
{
//Send Action event to controls
await activeForm.ActionControls(mr);
//Send Action event to form itself
await activeForm.Action(mr);
if (!mr.Handled)
{
var uhc = new UnhandledCallEventArgs(ur.Message.Text, mr.RawData, session.DeviceId, mr.MessageId, ur.Message, session);
OnUnhandledCall(uhc);
if (uhc.Handled)
{
mr.Handled = true;
if (!session.FormSwitched)
{
return;
}
}
}
}
if (!session.FormSwitched)
{
//Render Event
await activeForm.RenderControls(mr);
await activeForm.Render(mr);
}
}
/// <summary>
/// Will be called if no form handeled this call
/// </summary>
public event EventHandler<UnhandledCallEventArgs> UnhandledCall
{
add
{
this.__Events.AddHandler(__evUnhandledCall, value);
}
remove
{
this.__Events.RemoveHandler(__evUnhandledCall, value);
}
}
public void OnUnhandledCall(UnhandledCallEventArgs e)
{
(this.__Events[__evUnhandledCall] as EventHandler<UnhandledCallEventArgs>)?.Invoke(this, e);
}
}
}
@@ -0,0 +1,65 @@
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;
namespace TelegramBotBase.MessageLoops
{
/// <summary>
/// This is a minimal message loop which will react to all update types and just calling the Load method.
/// </summary>
public class MinimalMessageLoop : IMessageLoopFactory
{
private static object __evUnhandledCall = new object();
private EventHandlerList __Events = new EventHandlerList();
public MinimalMessageLoop()
{
}
public async Task MessageLoop(BotBase Bot, DeviceSession session, UpdateResult ur, MessageResult mr)
{
var update = ur.RawData;
mr.Device = session;
var activeForm = session.ActiveForm;
//Loading Event
await activeForm.Load(mr);
}
/// <summary>
/// Will be called if no form handeled this call
/// </summary>
public event EventHandler<UnhandledCallEventArgs> UnhandledCall
{
add
{
this.__Events.AddHandler(__evUnhandledCall, value);
}
remove
{
this.__Events.RemoveHandler(__evUnhandledCall, value);
}
}
public void OnUnhandledCall(UnhandledCallEventArgs e)
{
(this.__Events[__evUnhandledCall] as EventHandler<UnhandledCallEventArgs>)?.Invoke(this, e);
}
}
}
@@ -14,14 +14,14 @@ using TelegramBotBase.Sessions;
namespace TelegramBotBase
{
/// <summary>
/// Base class for managing all active sessions
/// Class for managing all active sessions
/// </summary>
public class SessionBase
public sealed class SessionManager
{
/// <summary>
/// The Basic message client.
/// </summary>
public MessageClient Client { get; set; }
public MessageClient Client => BotBase.Client;
/// <summary>
/// A list of all active sessions.
@@ -32,29 +32,13 @@ namespace TelegramBotBase
/// <summary>
/// Reference to the Main BotBase instance for later use.
/// </summary>
public BotBase BotBase { get; set; }
public BotBase BotBase { get; }
public SessionBase()
public SessionManager(BotBase botBase)
{
this.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;
}
BotBase = botBase;
SessionList = new Dictionary<long, DeviceSession>();
}
/// <summary>
@@ -64,7 +48,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,7 +61,6 @@ 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;
@@ -88,7 +71,7 @@ namespace TelegramBotBase
await start.OnOpened(new EventArgs());
this[deviceId] = ds;
SessionList[deviceId] = ds;
return ds;
}
@@ -98,12 +81,8 @@ namespace TelegramBotBase
/// <param name="deviceId"></param>
public void EndSession(long deviceId)
{
var d = this[deviceId];
if (d != null)
{
this.SessionList.Remove(deviceId);
}
var d = SessionList[deviceId];
if (d != null) SessionList.Remove(deviceId);
}
/// <summary>
@@ -112,7 +91,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,27 +100,27 @@ 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>
/// Loads the previously saved states from the machine.
/// </summary>
public async void LoadSessionStates()
public async Task LoadSessionStates()
{
if (BotBase.StateMachine == null)
{
return;
}
LoadSessionStates(BotBase.StateMachine);
await LoadSessionStates(BotBase.StateMachine);
}
/// <summary>
/// Loads the previously saved states from the machine.
/// </summary>
public async void LoadSessionStates(IStateMachine statemachine)
public async Task LoadSessionStates(IStateMachine statemachine)
{
if (statemachine == null)
{
@@ -159,7 +138,7 @@ namespace TelegramBotBase
}
//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;
@@ -222,7 +201,7 @@ namespace TelegramBotBase
device.ChatTitle = s.ChatTitle;
this.SessionList.Add(s.DeviceId, device);
SessionList.Add(s.DeviceId, device);
//Is Subclass of IStateForm
var iform = form as IStateForm;
@@ -242,7 +221,7 @@ namespace TelegramBotBase
catch
{
//Skip on exception
this.SessionList.Remove(s.DeviceId);
SessionList.Remove(s.DeviceId);
}
}
@@ -254,7 +233,7 @@ namespace TelegramBotBase
/// <summary>
/// Saves all open states into the machine.
/// </summary>
public void SaveSessionStates(IStateMachine statemachine)
public async Task SaveSessionStates(IStateMachine statemachine)
{
if (statemachine == null)
{
@@ -263,7 +242,7 @@ namespace TelegramBotBase
var states = new List<StateEntry>();
foreach (var s in this.SessionList)
foreach (var s in SessionList)
{
if (s.Value == null)
{
@@ -333,13 +312,13 @@ namespace TelegramBotBase
/// <summary>
/// Saves all open states into the machine.
/// </summary>
public void SaveSessionStates()
public async Task SaveSessionStates()
{
if (this.BotBase.StateMachine == null)
if (BotBase.StateMachine == null)
return;
this.SaveSessionStates(this.BotBase.StateMachine);
await SaveSessionStates(BotBase.StateMachine);
}
}
}
+97 -12
View File
@@ -84,7 +84,7 @@ namespace TelegramBotBase.Sessions
/// </summary>
public Message LastMessage { get; set; }
private MessageClient Client
public MessageClient Client
{
get
{
@@ -291,7 +291,8 @@ namespace TelegramBotBase.Sessions
var t = API(a => a.SendTextMessageAsync(deviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var o = GetOrigin(new StackTrace());
OnMessageSent(new MessageSentEventArgs(await t, o));
await OnMessageSent(new MessageSentEventArgs(await t, o));
return await t;
}
@@ -342,7 +343,7 @@ namespace TelegramBotBase.Sessions
var t = API(a => a.SendTextMessageAsync(this.DeviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var o = GetOrigin(new StackTrace());
OnMessageSent(new MessageSentEventArgs(await t, o));
await OnMessageSent(new MessageSentEventArgs(await t, o));
return await t;
}
@@ -380,7 +381,7 @@ namespace TelegramBotBase.Sessions
var t = API(a => a.SendTextMessageAsync(this.DeviceId, text, parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var o = GetOrigin(new StackTrace());
OnMessageSent(new MessageSentEventArgs(await t, o));
await OnMessageSent(new MessageSentEventArgs(await t, o));
return await t;
}
@@ -410,7 +411,7 @@ namespace TelegramBotBase.Sessions
var t = API(a => a.SendPhotoAsync(this.DeviceId, file, caption: caption, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var o = GetOrigin(new StackTrace());
OnMessageSent(new MessageSentEventArgs(await t, o));
await OnMessageSent(new MessageSentEventArgs(await t, o));
return await t;
}
@@ -440,7 +441,7 @@ namespace TelegramBotBase.Sessions
var t = API(a => a.SendVideoAsync(this.DeviceId, file, caption: caption, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var o = GetOrigin(new StackTrace());
OnMessageSent(new MessageSentEventArgs(await t, o));
await OnMessageSent(new MessageSentEventArgs(await t, o));
return await t;
}
@@ -453,7 +454,7 @@ namespace TelegramBotBase.Sessions
/// <summary>
/// Sends an video
/// </summary>
/// <param name="file"></param>
/// <param name="url"></param>
/// <param name="buttons"></param>
/// <param name="replyTo"></param>
/// <param name="disableNotification"></param>
@@ -470,7 +471,79 @@ namespace TelegramBotBase.Sessions
var t = API(a => a.SendVideoAsync(this.DeviceId, new InputOnlineFile(url), parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var o = GetOrigin(new StackTrace());
OnMessageSent(new MessageSentEventArgs(await t, o));
await OnMessageSent(new MessageSentEventArgs(await t, o));
return await t;
}
catch
{
return null;
}
}
/// <summary>
/// Sends an video
/// </summary>
/// <param name="filename"></param>
/// <param name="video"></param>
/// <param name="buttons"></param>
/// <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)
{
if (this.ActiveForm == null)
return null;
InlineKeyboardMarkup markup = buttons;
try
{
MemoryStream ms = new MemoryStream(video);
InputOnlineFile fts = new InputOnlineFile(ms, filename);
var t = API(a => a.SendVideoAsync(this.DeviceId, fts, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var o = GetOrigin(new StackTrace());
await OnMessageSent(new MessageSentEventArgs(await t, o));
return await t;
}
catch
{
return null;
}
}
/// <summary>
/// Sends an local file as video
/// </summary>
/// <param name="filename"></param>
/// <param name="video"></param>
/// <param name="buttons"></param>
/// <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)
{
if (this.ActiveForm == null)
return null;
InlineKeyboardMarkup markup = buttons;
try
{
FileStream fs = new FileStream(filepath, FileMode.Open);
var filename = Path.GetFileName(filepath);
InputOnlineFile fts = new InputOnlineFile(fs, filename);
var t = API(a => a.SendVideoAsync(this.DeviceId, fts, parseMode: parseMode, replyToMessageId: replyTo, replyMarkup: markup, disableNotification: disableNotification));
var o = GetOrigin(new StackTrace());
await OnMessageSent(new MessageSentEventArgs(await t, o));
return await t;
}
@@ -547,7 +620,7 @@ namespace TelegramBotBase.Sessions
var t = API(a => a.SendDocumentAsync(this.DeviceId, document, caption, replyMarkup: markup, disableNotification: disableNotification, replyToMessageId: replyTo));
var o = GetOrigin(new StackTrace());
OnMessageSent(new MessageSentEventArgs(await t, o));
await OnMessageSent(new MessageSentEventArgs(await t, o));
return await t;
}
@@ -810,7 +883,7 @@ namespace TelegramBotBase.Sessions
/// <summary>
/// Eventhandler for sent messages
/// </summary>
public event EventHandler<MessageSentEventArgs> MessageSent
public event Base.Async.AsyncEventHandler<MessageSentEventArgs> MessageSent
{
add
{
@@ -823,9 +896,21 @@ namespace TelegramBotBase.Sessions
}
public void OnMessageSent(MessageSentEventArgs e)
public async Task OnMessageSent(MessageSentEventArgs e)
{
(this.__Events[__evMessageSent] as EventHandler<MessageSentEventArgs>)?.Invoke(this, e);
if (e.Message == null)
return;
var handler = this.__Events[__evMessageSent]?.GetInvocationList().Cast<Base.Async.AsyncEventHandler<MessageSentEventArgs>>();
if (handler == null)
return;
foreach (var h in handler)
{
await Base.Async.InvokeAllAsync<MessageSentEventArgs>(h, this, e);
}
//(this.__Events[__evMessageSent] as EventHandler<MessageSentEventArgs>)?.Invoke(this, e);
}
/// <summary>
+3 -2
View File
@@ -23,6 +23,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="6.0.0" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" />
</ItemGroup>
@@ -57,8 +58,8 @@
<ItemGroup>
<PackageReference Include="Telegram.Bot" Version="17.0.0" />
<PackageReference Include="Telegram.Bot.Extensions.Polling" Version="1.0.1" />
<PackageReference Include="Telegram.Bot" Version="18.0.0" />
<PackageReference Include="Telegram.Bot.Extensions.Polling" Version="1.0.2" />
</ItemGroup>
<ItemGroup>