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:
@@ -59,11 +59,26 @@ builder.Services.AddSingleton<IRealtimeNotifier, SignalRRealtimeNotifier>();
|
||||
// реальный HTTP-вызов через неё никогда не происходит (все вызывающие места сами проверяют BotToken).
|
||||
builder.Services.AddSingleton<ITelegramBotClient>(sp =>
|
||||
{
|
||||
var options = sp.GetRequiredService<IOptions<TelegramOptions>>();
|
||||
var token = options.Value.BotToken;
|
||||
return new TelegramBotClient(string.IsNullOrWhiteSpace(token)
|
||||
var options = sp.GetRequiredService<IOptions<TelegramOptions>>().Value;
|
||||
var token = string.IsNullOrWhiteSpace(options.BotToken)
|
||||
? "0:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
|
||||
: token);
|
||||
: options.BotToken;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(options.ProxyUrl))
|
||||
return new TelegramBotClient(token);
|
||||
|
||||
// Прокси (обычно socks5://) для запросов к Bot API — на случай, если Telegram недоступен напрямую
|
||||
// с сети сервера. Пусто (по умолчанию) — без прокси, прямое подключение (см. .env.example).
|
||||
var proxyUri = new Uri(options.ProxyUrl);
|
||||
var proxy = new WebProxy(proxyUri);
|
||||
if (!string.IsNullOrEmpty(proxyUri.UserInfo))
|
||||
{
|
||||
var credentials = proxyUri.UserInfo.Split(':', 2);
|
||||
proxy.Credentials = new NetworkCredential(credentials[0], credentials.Length > 1 ? credentials[1] : string.Empty);
|
||||
}
|
||||
|
||||
var handler = new SocketsHttpHandler { Proxy = proxy, UseProxy = true };
|
||||
return new TelegramBotClient(token, new HttpClient(handler));
|
||||
});
|
||||
// Scoped — зависит от IIdentityService (scoped), не Singleton.
|
||||
builder.Services.AddScoped<ITelegramNotifier, TelegramNotifier>();
|
||||
|
||||
Reference in New Issue
Block a user