Enhance Telegram bot configuration and error handling
- Updated `.env.example` to include a new `Telegram__ProxyUrl` setting for proxy configuration when accessing the Bot API, improving connectivity options. - Modified `Program.cs` to support proxy settings for the Telegram bot client, allowing for better handling of network restrictions. - Improved error handling in `TelegramBotHostedService` to ensure the bot can recover from network errors without crashing the application, implementing a retry mechanism with a delay. - Added `ProxyUrl` property to `TelegramOptions` for better configuration management.
This commit is contained in:
@@ -17,6 +17,8 @@ public sealed class TelegramBotHostedService(
|
||||
ILogger<TelegramBotHostedService> logger)
|
||||
: BackgroundService
|
||||
{
|
||||
private static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(30);
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(options.Value.BotToken))
|
||||
@@ -33,13 +35,32 @@ public sealed class TelegramBotHostedService(
|
||||
|
||||
logger.LogInformation("Telegram bot starting (long polling)...");
|
||||
|
||||
try
|
||||
// ReceiveAsync может упасть с сетевой ошибкой (Telegram API недоступен/заблокирован) —
|
||||
// это НЕ должно ронять весь хост (BackgroundServiceExceptionBehavior.StopHost по умолчанию
|
||||
// убивает всё приложение при необработанном исключении в BackgroundService). Панель обязана
|
||||
// работать без бота, поэтому ловим, логируем и переподключаемся с паузой (см. CLAUDE.md).
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
await botClient.ReceiveAsync(updateHandler, receiverOptions, stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
// Штатная остановка вместе с приложением.
|
||||
try
|
||||
{
|
||||
await botClient.ReceiveAsync(updateHandler, receiverOptions, stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
// Штатная остановка вместе с приложением.
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Telegram bot polling failed, retrying in {Delay}", RetryDelay);
|
||||
try
|
||||
{
|
||||
await Task.Delay(RetryDelay, stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Остановка приложения во время паузы перед повтором.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user