V17 - Big Update

- Adding a message loop interface to build custom message loops
- extracting default message loop from BotBase into seperate class
- updates to BotBaseBuilder for integration of custom message loops
- updating all result classes for using the new Update object of V17
- improving MessageResult and UpdateResult classes
- BotBase has been prepared for cleanup (a lot of comments)
- Comment cleanup at the next build
- updating Readme
This commit is contained in:
FlorianDahn 2021-11-26 17:57:49 +01:00
parent e9c25ea9e4
commit 31e52887ba
16 changed files with 824 additions and 330 deletions

View File

@ -147,6 +147,7 @@ It needs to be a subclass of "FormBase" you will find in Namespace TelegramBotBa
var bb = BotBaseBuilder var bb = BotBaseBuilder
.Create() .Create()
.WithAPIKey("{YOUR API KEY}") .WithAPIKey("{YOUR API KEY}")
.DefaultMessageLoop()
.WithStartForm<StartForm>() .WithStartForm<StartForm>()
.NoProxy() .NoProxy()
.CustomCommands(a => .CustomCommands(a =>
@ -263,6 +264,7 @@ Below we have 4 options.
var bb = BotBaseBuilder var bb = BotBaseBuilder
.Create() .Create()
.WithAPIKey("{YOUR API KEY}") .WithAPIKey("{YOUR API KEY}")
.DefaultMessageLoop()
.WithStartForm<Start>() .WithStartForm<Start>()
.NoProxy() .NoProxy()
.CustomCommands(a => .CustomCommands(a =>
@ -984,6 +986,7 @@ In general you didn't need to do more then, to keep the actual form:
var bb = BotBaseBuilder var bb = BotBaseBuilder
.Create() .Create()
.WithAPIKey("{YOUR API KEY}") .WithAPIKey("{YOUR API KEY}")
.DefaultMessageLoop()
.WithStartForm<StartForm>() .WithStartForm<StartForm>()
.NoProxy() .NoProxy()
.CustomCommands(a => .CustomCommands(a =>
@ -1007,6 +1010,7 @@ In general you didn't need to do more then, to keep the actual form:
var bb = BotBaseBuilder var bb = BotBaseBuilder
.Create() .Create()
.WithAPIKey("{YOUR API KEY}") .WithAPIKey("{YOUR API KEY}")
.DefaultMessageLoop()
.WithStartForm<StartForm>() .WithStartForm<StartForm>()
.NoProxy() .NoProxy()
.CustomCommands(a => .CustomCommands(a =>
@ -1031,6 +1035,7 @@ In general you didn't need to do more then, to keep the actual form:
var bb = BotBaseBuilder var bb = BotBaseBuilder
.Create() .Create()
.WithAPIKey("{YOUR API KEY}") .WithAPIKey("{YOUR API KEY}")
.DefaultMessageLoop()
.WithStartForm<StartForm>() .WithStartForm<StartForm>()
.NoProxy() .NoProxy()
.CustomCommands(a => .CustomCommands(a =>

View File

@ -4,6 +4,7 @@ using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using Telegram.Bot.Types.InputFiles; using Telegram.Bot.Types.InputFiles;
@ -14,7 +15,11 @@ namespace TelegramBotBase.Base
/// </summary> /// </summary>
public class DataResult : ResultBase public class DataResult : ResultBase
{ {
public Telegram.Bot.Args.MessageEventArgs RawMessageData { get; set; }
//public Telegram.Bot.Args.MessageEventArgs RawMessageData { get; set; }
public UpdateResult Update { get; set; }
public Contact Contact public Contact Contact
{ {
@ -64,11 +69,21 @@ namespace TelegramBotBase.Base
} }
} }
//public Telegram.Bot.Types.Enums.MessageType Type
//{
// get
// {
// return this.RawMessageData?.Message?.Type ?? Telegram.Bot.Types.Enums.MessageType.Unknown;
// }
//}
public Telegram.Bot.Types.Enums.MessageType Type public Telegram.Bot.Types.Enums.MessageType Type
{ {
get get
{ {
return this.RawMessageData?.Message?.Type ?? Telegram.Bot.Types.Enums.MessageType.Unknown; return this.Message?.Type ?? Telegram.Bot.Types.Enums.MessageType.Unknown;
} }
} }
@ -87,23 +102,30 @@ namespace TelegramBotBase.Base
} }
public DataResult(Telegram.Bot.Args.MessageEventArgs rawdata) //public DataResult(Telegram.Bot.Args.MessageEventArgs rawdata)
//{
// this.RawMessageData = rawdata;
// this.Message = rawdata.Message;
//}
//public DataResult(MessageResult message)
//{
// this.RawMessageData = message.RawMessageData;
// this.Message = message.Message;
// this.Client = message.Client;
//}
public DataResult(UpdateResult update)
{ {
this.RawMessageData = rawdata; this.Update = update;
this.Message = rawdata.Message;
} }
public DataResult(MessageResult message)
{
this.RawMessageData = message.RawMessageData;
this.Message = message.Message;
this.Client = message.Client;
}
public async Task<InputOnlineFile> DownloadDocument() public async Task<InputOnlineFile> DownloadDocument()
{ {
var encryptedContent = new System.IO.MemoryStream(this.Document.FileSize); var encryptedContent = new System.IO.MemoryStream(this.Document.FileSize.Value);
var file = await this.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Document.FileId, encryptedContent); var file = await this.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Document.FileId, encryptedContent);
return new InputOnlineFile(encryptedContent, this.Document.FileName); return new InputOnlineFile(encryptedContent, this.Document.FileName);
@ -162,7 +184,7 @@ namespace TelegramBotBase.Base
public async Task<InputOnlineFile> DownloadVideo() public async Task<InputOnlineFile> DownloadVideo()
{ {
var encryptedContent = new System.IO.MemoryStream(this.Video.FileSize); var encryptedContent = new System.IO.MemoryStream(this.Video.FileSize.Value);
var file = await this.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Video.FileId, encryptedContent); var file = await this.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Video.FileId, encryptedContent);
return new InputOnlineFile(encryptedContent, ""); return new InputOnlineFile(encryptedContent, "");
@ -179,7 +201,7 @@ namespace TelegramBotBase.Base
public async Task<InputOnlineFile> DownloadAudio() public async Task<InputOnlineFile> DownloadAudio()
{ {
var encryptedContent = new System.IO.MemoryStream(this.Audio.FileSize); var encryptedContent = new System.IO.MemoryStream(this.Audio.FileSize.Value);
var file = await this.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Audio.FileId, encryptedContent); var file = await this.Client.TelegramClient.GetInfoAndDownloadFileAsync(this.Audio.FileId, encryptedContent);
return new InputOnlineFile(encryptedContent, ""); return new InputOnlineFile(encryptedContent, "");
@ -197,7 +219,7 @@ namespace TelegramBotBase.Base
public async Task<InputOnlineFile> DownloadPhoto(int index) public async Task<InputOnlineFile> DownloadPhoto(int index)
{ {
var photo = this.Photos[index]; var photo = this.Photos[index];
var encryptedContent = new System.IO.MemoryStream(photo.FileSize); var encryptedContent = new System.IO.MemoryStream(photo.FileSize.Value);
var file = await this.Client.TelegramClient.GetInfoAndDownloadFileAsync(photo.FileId, encryptedContent); var file = await this.Client.TelegramClient.GetInfoAndDownloadFileAsync(photo.FileId, encryptedContent);
return new InputOnlineFile(encryptedContent, ""); return new InputOnlineFile(encryptedContent, "");

View File

@ -5,8 +5,13 @@ using System.Linq;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Text; using System.Text;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot.Exceptions;
using Telegram.Bot;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Extensions.Polling;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base
{ {
@ -19,16 +24,20 @@ namespace TelegramBotBase.Base
public String APIKey { get; set; } public String APIKey { get; set; }
public Telegram.Bot.TelegramBotClient TelegramClient { 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 object __evOnMessage = new object(); private static object __evOnMessage = new object();
private static object __evOnMessageEdit = new object(); private static object __evOnMessageEdit = new object();
private static object __evCallbackQuery = new object(); private static object __evCallbackQuery = new object();
CancellationTokenSource __cancellationTokenSource;
public MessageClient(String APIKey) public MessageClient(String APIKey)
{ {
@ -47,13 +56,22 @@ namespace TelegramBotBase.Base
Prepare(); Prepare();
} }
public MessageClient(String APIKey, Uri proxyUrl)
public MessageClient(String APIKey, Uri proxyUrl, NetworkCredential credential = null)
{ {
this.APIKey = APIKey; this.APIKey = APIKey;
var proxy = new WebProxy(proxyUrl); var proxy = new WebProxy(proxyUrl)
{
Credentials = credential
};
this.TelegramClient = new Telegram.Bot.TelegramBotClient(APIKey, proxy); var httpClient = new HttpClient(
new HttpClientHandler { Proxy = proxy, UseProxy = true }
);
this.TelegramClient = new Telegram.Bot.TelegramBotClient(APIKey, httpClient);
Prepare(); Prepare();
} }
@ -70,11 +88,17 @@ namespace TelegramBotBase.Base
var proxy = new WebProxy(proxyHost, proxyPort); var proxy = new WebProxy(proxyHost, proxyPort);
this.TelegramClient = new Telegram.Bot.TelegramBotClient(APIKey, proxy); var httpClient = new HttpClient(
new HttpClientHandler { Proxy = proxy, UseProxy = true }
);
this.TelegramClient = new Telegram.Bot.TelegramBotClient(APIKey, httpClient);
Prepare(); Prepare();
} }
public MessageClient(String APIKey, Telegram.Bot.TelegramBotClient Client) public MessageClient(String APIKey, Telegram.Bot.TelegramBotClient Client)
{ {
this.APIKey = APIKey; this.APIKey = APIKey;
@ -88,61 +112,105 @@ namespace TelegramBotBase.Base
{ {
this.TelegramClient.Timeout = new TimeSpan(0, 0, 30); this.TelegramClient.Timeout = new TimeSpan(0, 0, 30);
this.TelegramClient.OnMessage += TelegramClient_OnMessage;
this.TelegramClient.OnMessageEdited += TelegramClient_OnMessageEdited;
this.TelegramClient.OnCallbackQuery += TelegramClient_OnCallbackQuery;
}
private async void TelegramClient_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e) //this.TelegramClient.OnMessage += TelegramClient_OnMessage;
{ //this.TelegramClient.OnMessageEdited += TelegramClient_OnMessageEdited;
//Skip empty messages by default //this.TelegramClient.OnCallbackQuery += TelegramClient_OnCallbackQuery;
if (e.Message == null)
return;
try
{
var mr = new MessageResult(e);
mr.Client = this;
OnMessage(mr);
}
catch
{
}
} }
private async void TelegramClient_OnMessageEdited(object sender, Telegram.Bot.Args.MessageEventArgs e)
{
//Skip empty messages by default
if (e.Message == null)
return;
try public void StartReceiving()
{
var mr = new MessageResult(e);
mr.Client = this;
OnMessageEdit(mr);
}
catch
{ {
__cancellationTokenSource = new CancellationTokenSource();
} var receiverOptions = new ReceiverOptions
{
AllowedUpdates = { } // receive all update types
};
this.TelegramClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, receiverOptions, __cancellationTokenSource.Token);
} }
private async void TelegramClient_OnCallbackQuery(object sender, Telegram.Bot.Args.CallbackQueryEventArgs e) public void StopReceiving()
{ {
try __cancellationTokenSource.Cancel();
{
var ar = new MessageResult(e);
ar.Client = this;
OnAction(ar);
} }
catch
{
//private async void TelegramClient_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e)
//{
// //Skip empty messages by default
// if (e.Message == null)
// return;
// try
// {
// var mr = new MessageResult(e);
// mr.Client = this;
// OnMessage(mr);
// }
// catch
// {
// }
//}
//private async void TelegramClient_OnMessageEdited(object sender, Telegram.Bot.Args.MessageEventArgs e)
//{
// //Skip empty messages by default
// if (e.Message == null)
// return;
// try
// {
// var mr = new MessageResult(e);
// mr.Client = this;
// OnMessageEdit(mr);
// }
// catch
// {
// }
//}
//private async void TelegramClient_OnCallbackQuery(object sender, Telegram.Bot.Args.CallbackQueryEventArgs e)
//{
// try
// {
// var ar = new MessageResult(e);
// ar.Client = this;
// OnAction(ar);
// }
// catch
// {
// }
//}
public Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{
OnMessageLoop(new UpdateResult(update, null));
return Task.CompletedTask;
} }
public Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
{
if (exception is ApiRequestException exAPI)
{
Console.WriteLine($"Telegram API Error:\n[{exAPI.ErrorCode}]\n{exAPI.Message}");
} }
else
{
Console.WriteLine(exception.ToString());
}
return Task.CompletedTask;
}
/// <summary> /// <summary>
/// This will return the current list of bot commands. /// This will return the current list of bot commands.
@ -168,56 +236,78 @@ namespace TelegramBotBase.Base
#region "Events" #region "Events"
public event EventHandler<MessageResult> Message
public event Async.AsyncEventHandler<UpdateResult> MessageLoop
{ {
add add
{ {
this.__Events.AddHandler(__evOnMessage, value); this.__Events.AddHandler(__evOnMessageLoop, value);
} }
remove remove
{ {
this.__Events.RemoveHandler(__evOnMessage, value); this.__Events.RemoveHandler(__evOnMessageLoop, value);
} }
} }
public void OnMessage(MessageResult result) public void OnMessageLoop(UpdateResult update)
{ {
(this.__Events[__evOnMessage] as EventHandler<MessageResult>)?.Invoke(this, result); (this.__Events[__evOnMessageLoop] as Async.AsyncEventHandler<UpdateResult>)?.Invoke(this, update);
} }
public event EventHandler<MessageResult> MessageEdit
{
add
{
this.__Events.AddHandler(__evOnMessageEdit, value);
}
remove
{
this.__Events.RemoveHandler(__evOnMessageEdit, value);
}
}
public void OnMessageEdit(MessageResult result) //public event EventHandler<MessageResult> Message
{ //{
(this.__Events[__evOnMessageEdit] as EventHandler<MessageResult>)?.Invoke(this, result); // add
} // {
// this.__Events.AddHandler(__evOnMessage, value);
// }
// remove
// {
// this.__Events.RemoveHandler(__evOnMessage, value);
// }
//}
public event EventHandler<MessageResult> Action //public void OnMessage(MessageResult result)
{ //{
add // (this.__Events[__evOnMessage] as EventHandler<MessageResult>)?.Invoke(this, result);
{ //}
this.__Events.AddHandler(__evCallbackQuery, value);
}
remove
{
this.__Events.RemoveHandler(__evCallbackQuery, value);
}
}
public void OnAction(MessageResult result)
{
(this.__Events[__evCallbackQuery] as EventHandler<MessageResult>)?.Invoke(this, result); //public event EventHandler<MessageResult> MessageEdit
} //{
// add
// {
// this.__Events.AddHandler(__evOnMessageEdit, value);
// }
// remove
// {
// this.__Events.RemoveHandler(__evOnMessageEdit, value);
// }
//}
//public void OnMessageEdit(MessageResult result)
//{
// (this.__Events[__evOnMessageEdit] as EventHandler<MessageResult>)?.Invoke(this, result);
//}
//public event EventHandler<MessageResult> Action
//{
// add
// {
// this.__Events.AddHandler(__evCallbackQuery, value);
// }
// remove
// {
// this.__Events.RemoveHandler(__evCallbackQuery, value);
// }
//}
//public void OnAction(MessageResult result)
//{
// (this.__Events[__evCallbackQuery] as EventHandler<MessageResult>)?.Invoke(this, result);
//}
#endregion #endregion

View File

@ -3,15 +3,21 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot;
using Telegram.Bot.Types;
using TelegramBotBase.Sessions; using TelegramBotBase.Sessions;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base
{ {
public class MessageResult : ResultBase public class MessageResult : ResultBase
{ {
public Telegram.Bot.Args.MessageEventArgs RawMessageData { get; set; }
public Telegram.Bot.Args.CallbackQueryEventArgs RawCallbackData { get; set; } //public Telegram.Bot.Args.MessageEventArgs RawMessageData { get; set; }
//public Telegram.Bot.Args.CallbackQueryEventArgs RawCallbackData { get; set; }
public Telegram.Bot.Types.Update UpdateData { get; set; }
/// <summary> /// <summary>
/// Returns the Device/ChatId /// Returns the Device/ChatId
@ -20,8 +26,9 @@ namespace TelegramBotBase.Base
{ {
get get
{ {
return this.RawMessageData?.Message?.Chat.Id return this.UpdateData?.Message?.Chat?.Id
?? this.RawCallbackData?.CallbackQuery.Message?.Chat.Id ?? this.UpdateData?.EditedMessage?.Chat.Id
?? this.UpdateData?.CallbackQuery.Message?.Chat.Id
?? Device?.DeviceId ?? Device?.DeviceId
?? 0; ?? 0;
} }
@ -40,8 +47,9 @@ namespace TelegramBotBase.Base
{ {
get get
{ {
return this.Message?.MessageId return this.UpdateData?.Message?.MessageId
?? this.RawCallbackData?.CallbackQuery?.Message?.MessageId ?? this.Message?.MessageId
?? this.UpdateData?.CallbackQuery?.Message?.MessageId
?? 0; ?? 0;
} }
} }
@ -50,7 +58,7 @@ namespace TelegramBotBase.Base
{ {
get get
{ {
return this.RawMessageData?.Message?.Text ?? ""; return this.UpdateData?.Message?.Text ?? "";
} }
} }
@ -58,7 +66,7 @@ namespace TelegramBotBase.Base
{ {
get get
{ {
return this.RawMessageData?.Message?.Text ?? ""; return this.UpdateData?.Message?.Text ?? "";
} }
} }
@ -66,8 +74,19 @@ namespace TelegramBotBase.Base
{ {
get get
{ {
return this.RawMessageData?.Message?.Type return Message?.Type ?? Telegram.Bot.Types.Enums.MessageType.Unknown;
?? 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;
} }
} }
@ -78,7 +97,7 @@ namespace TelegramBotBase.Base
{ {
get get
{ {
return (this.RawCallbackData != null); return (this.UpdateData.CallbackQuery != null);
} }
} }
@ -133,7 +152,7 @@ namespace TelegramBotBase.Base
{ {
get get
{ {
return this.RawCallbackData?.CallbackQuery?.Data; return this.UpdateData?.CallbackQuery?.Data;
} }
} }
@ -162,14 +181,7 @@ namespace TelegramBotBase.Base
/// <returns></returns> /// <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)
{ {
try await this.Device.ConfirmAction(this.UpdateData.CallbackQuery.Id, message, showAlert, urlToOpen);
{
await this.Client.TelegramClient.AnswerCallbackQueryAsync(this.RawCallbackData.CallbackQuery.Id, message, showAlert, urlToOpen);
}
catch
{
}
} }
public override async Task DeleteMessage() public override async Task DeleteMessage()
@ -189,17 +201,24 @@ namespace TelegramBotBase.Base
} }
public MessageResult(Telegram.Bot.Args.MessageEventArgs rawdata) public MessageResult(Telegram.Bot.Types.Update update)
{ {
this.RawMessageData = rawdata; this.UpdateData = update;
this.Message = rawdata.Message;
} }
public MessageResult(Telegram.Bot.Args.CallbackQueryEventArgs callback)
{ //public MessageResult(Telegram.Bot.Args.MessageEventArgs rawdata)
this.RawCallbackData = callback; //{
this.Message = callback.CallbackQuery.Message; // this.RawMessageData = rawdata;
} // this.Message = rawdata.Message;
//}
//public MessageResult(Telegram.Bot.Args.CallbackQueryEventArgs callback)
//{
// this.RawCallbackData = callback;
// this.Message = callback.CallbackQuery.Message;
//}
} }
} }

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot;
namespace TelegramBotBase.Base namespace TelegramBotBase.Base
{ {
@ -20,7 +21,7 @@ namespace TelegramBotBase.Base
} }
} }
public Telegram.Bot.Types.Message Message { get; set; } public virtual Telegram.Bot.Types.Message Message { get; set; }
/// <summary> /// <summary>
/// Deletes the current message /// Deletes the current message

View File

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Telegram.Bot.Types;
using TelegramBotBase.Sessions;
namespace TelegramBotBase.Base
{
public class UpdateResult : ResultBase
{
public UpdateResult(Update rawData, DeviceSession device)
{
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 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;
}
}
}

View File

@ -3,13 +3,17 @@ using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Telegram.Bot; using Telegram.Bot;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Types; using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using TelegramBotBase.Args; using TelegramBotBase.Args;
using TelegramBotBase.Attributes; using TelegramBotBase.Attributes;
using TelegramBotBase.Base; using TelegramBotBase.Base;
using TelegramBotBase.Enums; using TelegramBotBase.Enums;
using TelegramBotBase.Factories.MessageLoops;
using TelegramBotBase.Form; using TelegramBotBase.Form;
using TelegramBotBase.Interfaces; using TelegramBotBase.Interfaces;
using TelegramBotBase.Sessions; using TelegramBotBase.Sessions;
@ -69,6 +73,8 @@ namespace TelegramBotBase
/// </summary> /// </summary>
public IStartFormFactory StartFormFactory { get; set; } public IStartFormFactory StartFormFactory { get; set; }
public IMessageLoopFactory MessageLoopFactory { get; set; }
public Dictionary<eSettings, uint> SystemSettings { get; private set; } public Dictionary<eSettings, uint> SystemSettings { get; private set; }
@ -88,6 +94,8 @@ namespace TelegramBotBase
this.Sessions.BotBase = this; this.Sessions.BotBase = this;
} }
/// <summary> /// <summary>
/// Start your Bot /// Start your Bot
/// </summary> /// </summary>
@ -96,9 +104,12 @@ namespace TelegramBotBase
if (this.Client == null) if (this.Client == null)
return; return;
this.Client.Message += Client_Message; this.Client.MessageLoop += Client_MessageLoop;
this.Client.MessageEdit += Client_MessageEdit;
this.Client.Action += Client_Action; //this.Client.Message += Client_Message;
//this.Client.MessageEdit += Client_MessageEdit;
//this.Client.Action += Client_Action;
if (this.StateMachine != null) if (this.StateMachine != null)
{ {
@ -116,7 +127,39 @@ namespace TelegramBotBase
DeviceSession.MaxNumberOfRetries = this.GetSetting(eSettings.MaxNumberOfRetries, 5); DeviceSession.MaxNumberOfRetries = this.GetSetting(eSettings.MaxNumberOfRetries, 5);
this.Client.TelegramClient.StartReceiving(); this.Client.StartReceiving();
}
private async Task Client_MessageLoop(object sender, UpdateResult e)
{
DeviceSession ds = this.Sessions.GetSession(e.DeviceId);
if (ds == null)
{
ds = this.Sessions.StartSession(e.DeviceId).GetAwaiter().GetResult();
e.Device = ds;
ds.LastMessage = e.RawData.Message;
OnSessionBegins(new SessionBeginEventArgs(e.DeviceId, ds));
}
var mr = new MessageResult(e.RawData);
int i = 0;
//Should formulars get navigated (allow maximum of 10, to dont get loops)
do
{
i++;
//Reset navigation
ds.FormSwitched = false;
await MessageLoopFactory.MessageLoop(this, ds, e, mr);
mr.IsFirstHandler = false;
} while (ds.FormSwitched && i < this.GetSetting(eSettings.NavigationMaximum, 10));
} }
@ -128,10 +171,14 @@ namespace TelegramBotBase
if (this.Client == null) if (this.Client == null)
return; return;
this.Client.Message -= Client_Message; this.Client.MessageLoop -= Client_MessageLoop;
this.Client.Action -= Client_Action;
this.Client.TelegramClient.StopReceiving(); //this.Client.Message -= Client_Message;
//this.Client.MessageEdit -= Client_MessageEdit;
//this.Client.Action -= Client_Action;
this.Client.StopReceiving();
this.Sessions.SaveSessionStates(); this.Sessions.SaveSessionStates();
} }
@ -152,35 +199,37 @@ namespace TelegramBotBase
} }
} }
private async void Client_Message(object sender, MessageResult e)
{
if (this.GetSetting(eSettings.SkipAllMessages, false))
return;
try
{
DeviceSession ds = this.Sessions.GetSession(e.DeviceId);
e.Device = ds;
if (this.GetSetting(eSettings.LogAllMessages, false)) //private async void Client_Message(object sender, MessageResult e)
{ //{
OnMessage(new MessageIncomeEventArgs(e.DeviceId, ds, e)); // if (this.GetSetting(eSettings.SkipAllMessages, false))
} // return;
ds?.OnMessageReceived(new MessageReceivedEventArgs(e.Message)); // try
// {
// DeviceSession ds = this.Sessions.GetSession(e.DeviceId);
// e.Device = ds;
await Client_Loop(sender, e); // if (this.GetSetting(eSettings.LogAllMessages, false))
} // {
catch (Telegram.Bot.Exceptions.ApiRequestException ex) // OnMessage(new MessageIncomeEventArgs(e.DeviceId, ds, e));
{ // }
} // ds?.OnMessageReceived(new MessageReceivedEventArgs(e.Message));
catch (Exception ex)
{ // await Client_Loop(sender, e);
DeviceSession ds = this.Sessions.GetSession(e.DeviceId); // }
OnException(new SystemExceptionEventArgs(e.Message.Text, ds?.DeviceId ?? -1, ds, ex)); // catch (Telegram.Bot.Exceptions.ApiRequestException ex)
} // {
}
// }
// catch (Exception ex)
// {
// DeviceSession ds = this.Sessions.GetSession(e.DeviceId);
// OnException(new SystemExceptionEventArgs(e.Message.Text, ds?.DeviceId ?? -1, ds, ex));
// }
//}
@ -255,101 +304,107 @@ namespace TelegramBotBase
//} //}
private async Task Client_Loop(object sender, MessageResult e)
{
DeviceSession ds = e.Device;
if (ds == null)
{
ds = await this.Sessions.StartSession(e.DeviceId);
e.Device = ds;
ds.LastMessage = e.Message;
OnSessionBegins(new SessionBeginEventArgs(e.DeviceId, ds)); //private async Task Client_Loop(object sender, MessageResult e)
} //{
// DeviceSession ds = e.Device;
// if (ds == null)
// {
// ds = await this.Sessions.StartSession(e.DeviceId);
// e.Device = ds;
// ds.LastMessage = e.Message;
ds.LastAction = DateTime.Now; // OnSessionBegins(new SessionBeginEventArgs(e.DeviceId, ds));
ds.LastMessage = e.Message; // }
//Is this a bot command ? // ds.LastAction = DateTime.Now;
if (e.IsBotCommand && this.BotCommands.Count(a => "/" + a.Command == e.BotCommand) > 0) // ds.LastMessage = e.Message;
{
var sce = new BotCommandEventArgs(e.BotCommand, e.BotCommandParameters, e.Message, ds.DeviceId, ds);
await OnBotCommand(sce);
if (sce.Handled) // //Is this a bot command ?
return; // if (e.IsBotCommand && this.BotCommands.Count(a => "/" + a.Command == e.BotCommand) > 0)
} // {
// var sce = new BotCommandEventArgs(e.BotCommand, e.BotCommandParameters, e.Message, ds.DeviceId, ds);
// await OnBotCommand(sce);
FormBase activeForm = null; // if (sce.Handled)
// return;
// }
int i = 0; // FormBase activeForm = null;
//Should formulars get navigated (allow maximum of 10, to dont get loops) // int i = 0;
do
{
i++;
//Reset navigation // //Should formulars get navigated (allow maximum of 10, to dont get loops)
ds.FormSwitched = false; // do
// {
activeForm = ds.ActiveForm; // i++;
//Pre Loading Event
await activeForm.PreLoad(e);
//Send Load event to controls
await activeForm.LoadControls(e);
//Loading Event
await activeForm.Load(e);
//Is Attachment ? (Photo, Audio, Video, Contact, Location, Document)
if (e.MessageType == Telegram.Bot.Types.Enums.MessageType.Contact | e.MessageType == Telegram.Bot.Types.Enums.MessageType.Document | e.MessageType == Telegram.Bot.Types.Enums.MessageType.Location |
e.MessageType == Telegram.Bot.Types.Enums.MessageType.Photo | e.MessageType == Telegram.Bot.Types.Enums.MessageType.Video | e.MessageType == Telegram.Bot.Types.Enums.MessageType.Audio)
{
await activeForm.SentData(new DataResult(e));
}
//Action Event
if (!ds.FormSwitched && e.IsAction)
{
//Send Action event to controls
await activeForm.ActionControls(e);
//Send Action event to form itself
await activeForm.Action(e);
if (!e.Handled)
{
var uhc = new UnhandledCallEventArgs(e.Message.Text, e.RawData, ds.DeviceId, e.MessageId, e.Message, ds);
OnUnhandledCall(uhc);
if (uhc.Handled)
{
e.Handled = true;
if (!ds.FormSwitched)
{
break;
}
}
}
}
if (!ds.FormSwitched)
{
//Render Event
await activeForm.RenderControls(e);
await activeForm.Render(e);
}
e.IsFirstHandler = false;
} while (ds.FormSwitched && i < this.GetSetting(eSettings.NavigationMaximum, 10));
}
// //Reset navigation
// ds.FormSwitched = false;
// activeForm = ds.ActiveForm;
// //Pre Loading Event
// await activeForm.PreLoad(e);
// //Send Load event to controls
// await activeForm.LoadControls(e);
// //Loading Event
// await activeForm.Load(e);
// //Is Attachment ? (Photo, Audio, Video, Contact, Location, Document)
// if (e.MessageType == Telegram.Bot.Types.Enums.MessageType.Contact | e.MessageType == Telegram.Bot.Types.Enums.MessageType.Document | e.MessageType == Telegram.Bot.Types.Enums.MessageType.Location |
// e.MessageType == Telegram.Bot.Types.Enums.MessageType.Photo | e.MessageType == Telegram.Bot.Types.Enums.MessageType.Video | e.MessageType == Telegram.Bot.Types.Enums.MessageType.Audio)
// {
// await activeForm.SentData(new DataResult(e));
// }
// //Action Event
// if (!ds.FormSwitched && e.IsAction)
// {
// //Send Action event to controls
// await activeForm.ActionControls(e);
// //Send Action event to form itself
// await activeForm.Action(e);
// if (!e.Handled)
// {
// var uhc = new UnhandledCallEventArgs(e.Message.Text, e.RawData, ds.DeviceId, e.MessageId, e.Message, ds);
// OnUnhandledCall(uhc);
// if (uhc.Handled)
// {
// e.Handled = true;
// if (!ds.FormSwitched)
// {
// break;
// }
// }
// }
// }
// if (!ds.FormSwitched)
// {
// //Render Event
// await activeForm.RenderControls(e);
// await activeForm.Render(e);
// }
// e.IsFirstHandler = false;
// } while (ds.FormSwitched && i < this.GetSetting(eSettings.NavigationMaximum, 10));
//}
/// <summary> /// <summary>
/// This will invoke the full message loop for the device even when no "userevent" like message or action has been raised. /// This will invoke the full message loop for the device even when no "userevent" like message or action has been raised.
@ -374,7 +429,8 @@ namespace TelegramBotBase
DeviceSession ds = this.Sessions.GetSession(DeviceId); DeviceSession ds = this.Sessions.GetSession(DeviceId);
e.Device = ds; e.Device = ds;
await Client_Loop(this, e); await MessageLoopFactory.MessageLoop(this, ds, new UpdateResult(e.UpdateData, ds), e);
//await Client_Loop(this, e);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -383,79 +439,85 @@ namespace TelegramBotBase
} }
} }
private async void Client_MessageEdit(object sender, MessageResult e)
//private async void Client_MessageEdit(object sender, MessageResult e)
//{
// if (this.GetSetting(eSettings.SkipAllMessages, false))
// return;
// try
// {
// DeviceSession ds = this.Sessions.GetSession(e.DeviceId);
// e.Device = ds;
// if (this.GetSetting(eSettings.LogAllMessages, false))
// {
// OnMessage(new MessageIncomeEventArgs(e.DeviceId, ds, e));
// }
// //Call same, to handle received liked edited
// ds?.OnMessageReceived(new MessageReceivedEventArgs(e.Message));
// await Client_TryMessageEdit(sender, e);
// }
// catch (Telegram.Bot.Exceptions.ApiRequestException ex)
// {
// }
// catch (Exception ex)
// {
// DeviceSession ds = this.Sessions.GetSession(e.DeviceId);
// OnException(new SystemExceptionEventArgs(e.Message.Text, ds?.DeviceId ?? -1, ds, ex));
// }
//}
//private async Task Client_TryMessageEdit(object sender, MessageResult e)
//{
// DeviceSession ds = e.Device;
// if (ds == null)
// {
// ds = await this.Sessions.StartSession(e.DeviceId);
// e.Device = ds;
// }
// ds.LastAction = DateTime.Now;
// ds.LastMessage = e.Message;
// //Pre Loading Event
// await ds.ActiveForm.Edited(e);
// //When form has been switched due navigation within the edit method, reopen Client_Message
// if (ds.FormSwitched)
// {
// await Client_Loop(sender, e);
// }
//}
//private async void Client_Action(object sender, MessageResult e)
//{
// try
// {
// DeviceSession ds = this.Sessions.GetSession(e.DeviceId);
// e.Device = ds;
// if (this.GetSetting(eSettings.LogAllMessages, false))
// {
// OnMessage(new MessageIncomeEventArgs(e.DeviceId, ds, e));
// }
// await Client_Loop(sender, e);
// }
// catch (Exception ex)
// {
// DeviceSession ds = this.Sessions.GetSession(e.DeviceId);
// OnException(new SystemExceptionEventArgs(e.Message.Text, ds?.DeviceId ?? -1, ds, ex));
// }
//}
public void MessageLoopFactory_UnhandledCall(object sender, UnhandledCallEventArgs e)
{ {
if (this.GetSetting(eSettings.SkipAllMessages, false)) OnUnhandledCall(e);
return;
try
{
DeviceSession ds = this.Sessions.GetSession(e.DeviceId);
e.Device = ds;
if (this.GetSetting(eSettings.LogAllMessages, false))
{
OnMessage(new MessageIncomeEventArgs(e.DeviceId, ds, e));
}
//Call same, to handle received liked edited
ds?.OnMessageReceived(new MessageReceivedEventArgs(e.Message));
await Client_TryMessageEdit(sender, e);
}
catch (Telegram.Bot.Exceptions.ApiRequestException ex)
{
}
catch (Exception ex)
{
DeviceSession ds = this.Sessions.GetSession(e.DeviceId);
OnException(new SystemExceptionEventArgs(e.Message.Text, ds?.DeviceId ?? -1, ds, ex));
}
}
private async Task Client_TryMessageEdit(object sender, MessageResult e)
{
DeviceSession ds = e.Device;
if (ds == null)
{
ds = await this.Sessions.StartSession(e.DeviceId);
e.Device = ds;
}
ds.LastAction = DateTime.Now;
ds.LastMessage = e.Message;
//Pre Loading Event
await ds.ActiveForm.Edited(e);
//When form has been switched due navigation within the edit method, reopen Client_Message
if (ds.FormSwitched)
{
await Client_Loop(sender, e);
}
}
private async void Client_Action(object sender, MessageResult e)
{
try
{
DeviceSession ds = this.Sessions.GetSession(e.DeviceId);
e.Device = ds;
if (this.GetSetting(eSettings.LogAllMessages, false))
{
OnMessage(new MessageIncomeEventArgs(e.DeviceId, ds, e));
}
await Client_Loop(sender, e);
}
catch (Exception ex)
{
DeviceSession ds = this.Sessions.GetSession(e.DeviceId);
OnException(new SystemExceptionEventArgs(e.Message.Text, ds?.DeviceId ?? -1, ds, ex));
}
} }
//private async void Client_TryAction(object sender, MessageResult e) //private async void Client_TryAction(object sender, MessageResult e)

View File

@ -12,7 +12,7 @@ using TelegramBotBase.Interfaces;
namespace TelegramBotBase.Builder namespace TelegramBotBase.Builder
{ {
public class BotBaseBuilder : IAPIKeySelectionStage, IStartFormSelectionStage, IBuildingStage, INetworkingSelectionStage, IBotCommandsStage, ISessionSerializationStage public class BotBaseBuilder : IAPIKeySelectionStage, IMessageLoopSelectionStage, IStartFormSelectionStage, IBuildingStage, INetworkingSelectionStage, IBotCommandsStage, ISessionSerializationStage
{ {
String _apiKey = null; String _apiKey = null;
@ -25,17 +25,55 @@ namespace TelegramBotBase.Builder
IStateMachine _statemachine = null; IStateMachine _statemachine = null;
IMessageLoopFactory _messageloopfactory = null;
public static IAPIKeySelectionStage Create() public static IAPIKeySelectionStage Create()
{ {
return new BotBaseBuilder(); return new BotBaseBuilder();
} }
public IStartFormSelectionStage WithAPIKey(string apiKey) #region "Step 1"
public IMessageLoopSelectionStage WithAPIKey(string apiKey)
{ {
this._apiKey = apiKey; this._apiKey = apiKey;
return this; return this;
} }
#endregion
#region "Step 2"
public IStartFormSelectionStage DefaultMessageLoop()
{
_messageloopfactory = new Factories.MessageLoops.FormBaseMessageLoop();
return this;
}
public IStartFormSelectionStage CustomMessageLoop(Type messageLoopClass)
{
if (messageLoopClass.IsSubclassOf(typeof(IMessageLoopFactory)))
throw new ArgumentException($"Not a subclass of {nameof(IMessageLoopFactory)}");
_messageloopfactory = messageLoopClass.GetConstructor(new Type[] { })?.Invoke(new object[] { }) as IMessageLoopFactory;
return this;
}
public IStartFormSelectionStage CustomMessageLoop<T>()
where T : class, new()
{
_messageloopfactory = typeof(T).GetConstructor(new Type[] { })?.Invoke(new object[] { }) as IMessageLoopFactory;
return this;
}
#endregion
#region "Step 3"
public INetworkingSelectionStage WithStartForm(Type startFormClass) public INetworkingSelectionStage WithStartForm(Type startFormClass)
{ {
this._factory = new Factories.DefaultStartFormFactory(startFormClass); this._factory = new Factories.DefaultStartFormFactory(startFormClass);
@ -55,6 +93,8 @@ namespace TelegramBotBase.Builder
return this; return this;
} }
#endregion
public IBotCommandsStage WithProxy(string proxyAddress) public IBotCommandsStage WithProxy(string proxyAddress)
{ {
@ -64,6 +104,7 @@ namespace TelegramBotBase.Builder
return this; return this;
} }
public IBotCommandsStage NoProxy() public IBotCommandsStage NoProxy()
{ {
_client = new MessageClient(_apiKey); _client = new MessageClient(_apiKey);
@ -79,6 +120,7 @@ namespace TelegramBotBase.Builder
return this; return this;
} }
public IBotCommandsStage WithHostAndPort(string proxyHost, int proxyPort) public IBotCommandsStage WithHostAndPort(string proxyHost, int proxyPort)
{ {
_client = new MessageClient(_apiKey, proxyHost, proxyPort); _client = new MessageClient(_apiKey, proxyHost, proxyPort);
@ -139,6 +181,10 @@ namespace TelegramBotBase.Builder
bb.StateMachine = _statemachine; bb.StateMachine = _statemachine;
bb.MessageLoopFactory = _messageloopfactory;
bb.MessageLoopFactory.UnhandledCall += bb.MessageLoopFactory_UnhandledCall;
return bb; return bb;
} }

View File

@ -11,7 +11,7 @@ namespace TelegramBotBase.Builder.Interfaces
/// </summary> /// </summary>
/// <param name="apiKey"></param> /// <param name="apiKey"></param>
/// <returns></returns> /// <returns></returns>
IStartFormSelectionStage WithAPIKey(String apiKey); IMessageLoopSelectionStage WithAPIKey(String apiKey);
} }
} }

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Text;
using TelegramBotBase.Form;
using TelegramBotBase.Interfaces;
namespace TelegramBotBase.Builder.Interfaces
{
public interface IMessageLoopSelectionStage
{
/// <summary>
/// Chooses a default message loop.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
IStartFormSelectionStage DefaultMessageLoop();
/// <summary>
/// Chooses a custom message loop.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
IStartFormSelectionStage CustomMessageLoop(Type startFormClass);
/// <summary>
/// Chooses a custom message loop.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
IStartFormSelectionStage CustomMessageLoop<T>() where T : class, new();
}
}

View File

@ -8,6 +8,7 @@ namespace TelegramBotBase.Builder.Interfaces
{ {
public interface INetworkingSelectionStage public interface INetworkingSelectionStage
{ {
/// <summary> /// <summary>
/// Chooses a proxy as network configuration. /// Chooses a proxy as network configuration.
/// </summary> /// </summary>
@ -29,6 +30,7 @@ namespace TelegramBotBase.Builder.Interfaces
/// <returns></returns> /// <returns></returns>
IBotCommandsStage WithBotClient(TelegramBotClient client); IBotCommandsStage WithBotClient(TelegramBotClient client);
/// <summary> /// <summary>
/// Sets the custom proxy host and port. /// Sets the custom proxy host and port.
/// </summary> /// </summary>

View File

@ -0,0 +1,131 @@
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.Factories.MessageLoops
{
public class FormBaseMessageLoop : IMessageLoopFactory
{
private static object __evUnhandledCall = new object();
private EventHandlerList __Events = new EventHandlerList();
public FormBaseMessageLoop()
{
}
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)
{
return;
}
//Is this a bot command ?
if (mr.IsFirstHandler && mr.IsBotCommand && Bot.BotCommands.Count(a => "/" + a.Command == mr.BotCommand) > 0)
{
var sce = new BotCommandEventArgs(mr.BotCommand, mr.BotCommandParameters, mr.Message, session.DeviceId, session);
await Bot.OnBotCommand(sce);
if (sce.Handled)
return;
}
//var mr = new MessageResult(update);
mr.Device = session;
//var message = update.Message ?? update.EditedMessage;
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)
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);
}
}
}

View File

@ -46,9 +46,9 @@ namespace TelegramBotBase.Form
return InlineKeyboardButton.WithCallbackData(this.Text, id + this.Value); return InlineKeyboardButton.WithCallbackData(this.Text, id + this.Value);
} }
var ikb = new InlineKeyboardButton(); var ikb = new InlineKeyboardButton(this.Text);
ikb.Text = this.Text; //ikb.Text = this.Text;
ikb.Url = this.Url; ikb.Url = this.Url;
return ikb; return ikb;

View File

@ -24,12 +24,12 @@ namespace TelegramBotBase.Form
{ {
case Telegram.Bot.Types.Enums.MessageType.ChatMembersAdded: case Telegram.Bot.Types.Enums.MessageType.ChatMembersAdded:
await OnMemberChanges(new MemberChangeEventArgs(Telegram.Bot.Types.Enums.MessageType.ChatMembersAdded, message, message.RawMessageData.Message.NewChatMembers)); await OnMemberChanges(new MemberChangeEventArgs(Telegram.Bot.Types.Enums.MessageType.ChatMembersAdded, message, message.Message.NewChatMembers));
break; break;
case Telegram.Bot.Types.Enums.MessageType.ChatMemberLeft: case Telegram.Bot.Types.Enums.MessageType.ChatMemberLeft:
await OnMemberChanges(new MemberChangeEventArgs(Telegram.Bot.Types.Enums.MessageType.ChatMemberLeft, message, message.RawMessageData.Message.LeftChatMember)); await OnMemberChanges(new MemberChangeEventArgs(Telegram.Bot.Types.Enums.MessageType.ChatMemberLeft, message, message.Message.LeftChatMember));
break; break;

View File

@ -0,0 +1,21 @@
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;
namespace TelegramBotBase.Interfaces
{
public interface IMessageLoopFactory
{
Task MessageLoop(BotBase Bot, DeviceSession session, UpdateResult ur, MessageResult e);
event EventHandler<UnhandledCallEventArgs> UnhandledCall;
}
}

View File

@ -769,7 +769,7 @@ namespace TelegramBotBase.Sessions
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <param name="call"></param> /// <param name="call"></param>
/// <returns></returns> /// <returns></returns>
public T RAW<T>(Func<Telegram.Bot.TelegramBotClient, T> call) public T RAW<T>(Func<Telegram.Bot.ITelegramBotClient, T> call)
{ {
return call(this.Client.TelegramClient); return call(this.Client.TelegramClient);
} }
@ -780,7 +780,7 @@ namespace TelegramBotBase.Sessions
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <param name="call"></param> /// <param name="call"></param>
/// <returns></returns> /// <returns></returns>
public async Task<T> API<T>(Func<Telegram.Bot.TelegramBotClient, Task<T>> call) public async Task<T> API<T>(Func<Telegram.Bot.ITelegramBotClient, Task<T>> call)
{ {
var numberOfTries = 0; var numberOfTries = 0;
while (numberOfTries < DeviceSession.MaxNumberOfRetries) while (numberOfTries < DeviceSession.MaxNumberOfRetries)
@ -794,8 +794,8 @@ namespace TelegramBotBase.Sessions
if (ex.ErrorCode != 429) if (ex.ErrorCode != 429)
throw; throw;
if (ex.Parameters != null) if (ex.Parameters != null && ex.Parameters.RetryAfter != null)
await Task.Delay(ex.Parameters.RetryAfter * 1000); await Task.Delay(ex.Parameters.RetryAfter.Value * 1000);
numberOfTries++; numberOfTries++;
} }
@ -808,7 +808,7 @@ namespace TelegramBotBase.Sessions
/// </summary> /// </summary>
/// <param name="call"></param> /// <param name="call"></param>
/// <returns></returns> /// <returns></returns>
public async Task API(Func<Telegram.Bot.TelegramBotClient, Task> call) public async Task API(Func<Telegram.Bot.ITelegramBotClient, Task> call)
{ {
var numberOfTries = 0; var numberOfTries = 0;
while (numberOfTries < DeviceSession.MaxNumberOfRetries) while (numberOfTries < DeviceSession.MaxNumberOfRetries)
@ -823,8 +823,8 @@ namespace TelegramBotBase.Sessions
if (ex.ErrorCode != 429) if (ex.ErrorCode != 429)
throw; throw;
if (ex.Parameters != null) if (ex.Parameters != null && ex.Parameters.RetryAfter != null)
await Task.Delay(ex.Parameters.RetryAfter * 1000); await Task.Delay(ex.Parameters.RetryAfter.Value * 1000);
numberOfTries++; numberOfTries++;
} }