Skip to content

Commit

Permalink
🔁 Add startup retry
Browse files Browse the repository at this point in the history
Make sure the service won't abort if the Telegram servers are down.
  • Loading branch information
database64128 committed Nov 5, 2024
1 parent 7455285 commit 55d0b02
Showing 1 changed file with 40 additions and 17 deletions.
57 changes: 40 additions & 17 deletions CubicBot.Telegram/BotService.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Telegram.Bot;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Polling;
using Telegram.Bot.Types;

namespace CubicBot.Telegram;

Expand Down Expand Up @@ -42,30 +44,51 @@ private async Task RunBotAsync(CancellationToken cancellationToken = default)

var saveDataTask = SaveDataHourlyAsync(data, cancellationToken);

try
TelegramBotClientOptions options = new(botToken)
{
using var httpClient = new HttpClient();
var bot = new TelegramBotClient(botToken, httpClient);
var me = await bot.GetMe(cancellationToken);
RetryCount = 7,
};
using HttpClient httpClient = new();
TelegramBotClient bot = new(options, httpClient);
User me;

if (string.IsNullOrEmpty(me.Username))
throw new Exception("Bot username is null or empty.");
while (true)
{
try
{
me = await bot.GetMe(cancellationToken);
break;
}
catch (RequestException ex)
{
logger.LogWarning(ex, "Failed to get bot info, retrying in 30 seconds");
await Task.Delay(30000, cancellationToken);
}
}

var updateHandler = new UpdateHandler(me.Username, config, data, logger);
await updateHandler.RegisterCommandsAsync(bot, cancellationToken);
if (string.IsNullOrEmpty(me.Username))
throw new Exception("Bot username is null or empty.");

logger.LogInformation("Started Telegram bot: @{BotUsername} ({BotId})", me.Username, me.Id);
var updateHandler = new UpdateHandler(me.Username, config, data, logger);

var updateReceiver = new QueuedUpdateReceiver(bot, null, updateHandler.HandleErrorAsync);
await updateHandler.HandleUpdateStreamAsync(bot, updateReceiver, cancellationToken);
}
catch (OperationCanceledException)
while (true)
{
try
{
await updateHandler.RegisterCommandsAsync(bot, cancellationToken);
break;
}
catch (RequestException ex)
{
logger.LogWarning(ex, "Failed to register commands, retrying in 30 seconds");
await Task.Delay(30000, cancellationToken);
}
}
catch (Exception ex)
{
throw new Exception("Failed to start Telegram bot", ex);
}

logger.LogInformation("Started Telegram bot: @{BotUsername} ({BotId})", me.Username, me.Id);

var updateReceiver = new QueuedUpdateReceiver(bot, null, updateHandler.HandleErrorAsync);
await updateHandler.HandleUpdateStreamAsync(bot, updateReceiver, cancellationToken);

await saveDataTask;
}
Expand Down

0 comments on commit 55d0b02

Please sign in to comment.