Added common 403 exception handling. At least two reason of not sending message to user. 1. Bot blocked, 2. User deleted.

This commit is contained in:
Ruberoid 2025-07-22 10:52:43 +03:00
parent 89fa1c845d
commit 2692797dbc

View File

@ -36,31 +36,28 @@ public sealed class MessageDispatcherHandler : IMessageDispatcherHandler
{
await _bot.SendMessageAsync(tm, cancellationToken);
}
catch (Exception ex) when (ex is ApiRequestException &&
ex.Message.Equals("Forbidden: bot was blocked by the user",
StringComparison.OrdinalIgnoreCase))
catch (ApiRequestException ex) when (ex.ErrorCode == 403)
{
_logger.LogWarning("Bot was blocked by user {ChatId}, marking user as blocked.", tm.ChatId);
_logger.LogWarning("Bot can't interract with user {ChatId}.", tm.ChatId);
_logger.LogDebug(ex.ToString());
try
{
var user = await _usersService.GetByIdentity(tm.ChatId.Identifier ?? 0, cancellationToken);
if (user != null)
{
// Атомарно (лол. Клод считает, что две инструкции ниже это "атомарно") блокируем пользователя и деактивируем все его подписки
await _usersService.BlockBot(user.Id, cancellationToken);
await _textMatcherService.DeactivateAllUserSubscriptions(user.Id, cancellationToken);
_logger.LogInformation("Successfully blocked user {UserId} (ChatId: {ChatId}) and deactivated all subscriptions.", user.Id, tm.ChatId);
_logger.LogInformation("Successfully deactivated user {UserId} subscriptions. ", tm.ChatId);
}
else
{
_logger.LogWarning("Could not find user with ChatId {ChatId} to mark as blocked.", tm.ChatId);
_logger.LogWarning("Could not find user with TelegramId {ChatId} to mark as blocked.", tm.ChatId);
}
}
catch (Exception blockEx)
{
_logger.LogError(blockEx, "Failed to process user blocking for ChatId {ChatId}.", tm.ChatId);
_logger.LogError(blockEx, "Failed to process user blocking for TelegramId {ChatId}.", tm.ChatId);
}
}
break;