Merge pull request #3 from Xilosof/bug/ApiRequestException-handling

Fix handling ApiRequestException when sending a request.
This commit is contained in:
Florian Dahn 2021-03-14 20:34:07 +01:00 committed by GitHub
commit 8142b626b2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 46 additions and 18 deletions

View File

@ -72,6 +72,7 @@ namespace TelegramBotBase
{
this.SystemSettings = new Dictionary<eSettings, uint>();
SetSetting(eSettings.MaxNumberOfRetries, 5);
SetSetting(eSettings.NavigationMaximum, 10);
SetSetting(eSettings.LogAllMessages, false);
SetSetting(eSettings.SkipAllMessages, false);
@ -177,6 +178,8 @@ namespace TelegramBotBase
});
}
DeviceSession.MaxNumberOfRetries = this.GetSetting(eSettings.MaxNumberOfRetries, 5);
this.Client.TelegramClient.StartReceiving();
}

View File

@ -27,9 +27,14 @@ namespace TelegramBotBase.Enums
/// <summary>
/// Does stick to the console event handler and saves all sessions on exit.
/// </summary>
SaveSessionsOnConsoleExit = 4
SaveSessionsOnConsoleExit = 4,
/// <summary>
/// Indicates the maximum number of times a request that received error
/// 429 will be sent again after a timeout until it receives code 200 or an error code not equal to 429.
/// </summary>
MaxNumberOfRetries = 5,
}
}

View File

@ -769,21 +769,25 @@ namespace TelegramBotBase.Sessions
/// <param name="call"></param>
/// <returns></returns>
public async Task<T> API<T>(Func<Telegram.Bot.TelegramBotClient, Task<T>> call)
{
var numberOfTries = 0;
while (numberOfTries < DeviceSession.MaxNumberOfRetries)
{
try
{
return await call(this.Client.TelegramClient);
return await call(Client.TelegramClient);
}
catch (ApiRequestException ex)
{
if (ex.ErrorCode != 429)
throw;
if (ex.Parameters != null)
{
await Task.Delay(ex.Parameters.RetryAfter);
await Task.Delay(ex.Parameters.RetryAfter * 1000);
return await call(this.Client.TelegramClient);
numberOfTries++;
}
}
return default(T);
}
@ -793,18 +797,24 @@ namespace TelegramBotBase.Sessions
/// <param name="call"></param>
/// <returns></returns>
public async Task API(Func<Telegram.Bot.TelegramBotClient, Task> call)
{
var numberOfTries = 0;
while (numberOfTries < DeviceSession.MaxNumberOfRetries)
{
try
{
await call(this.Client.TelegramClient);
await call(Client.TelegramClient);
return;
}
catch (ApiRequestException ex)
{
if (ex.Parameters != null)
{
await Task.Delay(ex.Parameters.RetryAfter);
if (ex.ErrorCode != 429)
throw;
await call(this.Client.TelegramClient);
if (ex.Parameters != null)
await Task.Delay(ex.Parameters.RetryAfter * 1000);
numberOfTries++;
}
}
}
@ -876,5 +886,15 @@ namespace TelegramBotBase.Sessions
}
#endregion
#region "Static"
/// <summary>
/// Indicates the maximum number of times a request that received error
/// 429 will be sent again after a timeout until it receives code 200 or an error code not equal to 429.
/// </summary>
public static uint MaxNumberOfRetries { get; set; }
#endregion "Static"
}
}