Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)
Python
add retry for telegram message edits with tests and updated rate telegram limit
Alishahryar17045e0ed4481
diff --git a/.env.example b/.env.exampleindex dad446ba..ec482ef6 100644--- a/.env.example+++ b/.env.example@@ -18,7 +18,7 @@ ALLOWED_TELEGRAM_USER_ID=""# Messaging Rate Limiting-MESSAGING_RATE_LIMIT=10+MESSAGING_RATE_LIMIT=1MESSAGING_RATE_WINDOW=1diff --git a/api/app.py b/api/app.pyindex 69868edc..aa2d59e2 100644--- a/api/app.py+++ b/api/app.py@@ -1,6 +1,10 @@"""FastAPI application factory and configuration."""import os++# Opt-in to future behavior for python-telegram-bot+os.environ["PTB_TIMEDELTA"] = "1"+import loggingfrom contextlib import asynccontextmanagerfrom fastapi import FastAPI, Requestdiff --git a/messaging/handler.py b/messaging/handler.pyindex e36c7183..674002ae 100644--- a/messaging/handler.py+++ b/messaging/handler.py@@ -412,27 +412,30 @@ class ClaudeMessageHandler:for err in components["errors"]:lines.append(f"⚠️ **Error:** `{err}`")- # 6. Status (Bottom)- if status:- lines.append("")- lines.append(status)+ if not any(lines) and not status:+ return "⏳ **Claude is working...**"# Telegram character limit is 4096. We leave buffer for status updates.LIMIT = 3900+ # Filter out empty lines first for a clean join+ lines = [l for l in lines if l]++ # The main content is everything EXCEPT the status if provided+ # We handle status separately to ensure it's always included+ main_text = "\n".join(lines)status_text = f"\n\n{status}" if status else ""- main_text = "\n".join(lines[:-2] if status else lines)if len(main_text) + len(status_text) <= LIMIT:return (- "\n".join([l for l in lines if l])- if not status- else "\n".join([l for l in lines[:-2] if l]) + status_text+ main_text + status_text+ if main_text + status_text+ else "⏳ **Claude is working...**")# If too long, truncate the main content but keep the status and close code blocksavailable_limit = LIMIT - len(status_text) - 20 # 20 for truncation marker- truncated_main = main_text[:available_limit] + "\n... (truncated)"+ truncated_main = main_text[:available_limit].rstrip() + "\n... (truncated)"# Close any open code blocksif truncated_main.count("```") % 2 != 0:diff --git a/messaging/limiter.py b/messaging/limiter.pyindex 18aa45ba..727b4b67 100644--- a/messaging/limiter.py+++ b/messaging/limiter.py@@ -104,6 +104,11 @@ class GlobalRateLimiter:try:if hasattr(e, "seconds"):seconds = e.seconds+ elif "after " in error_msg:+ # Try to parse "retry after X"+ parts = error_msg.split("after ")+ if len(parts) > 1:+ seconds = int(parts[1].split()[0])except:pass@@ -115,12 +120,14 @@ class GlobalRateLimiter:)else:logger.error(- f"Error in limiter worker for key {dedup_key}: {e}"+ f"Error in limiter worker for key {dedup_key}: {type(e).__name__}: {e}")except asyncio.CancelledError:breakexcept Exception as e:- logger.error(f"Error in limiter worker: {e}", exc_info=True)+ logger.error(+ f"GlobalRateLimiter worker critical error: {e}", exc_info=True+ )await asyncio.sleep(1)async def _enqueue_internal(self, func, future, dedup_key, front=False):@@ -173,11 +180,29 @@ class GlobalRateLimiter:future = asyncio.get_event_loop().create_future()async def _wrapped():- try:- return await self._enqueue_internal(func, future, dedup_key)- except Exception as e:- logger.error(f"Error in fire_and_forget for key {dedup_key}: {e}")- if not future.done():- future.set_exception(e)+ max_retries = 2+ for attempt in range(max_retries + 1):+ try:+ return await self.enqueue(func, dedup_key)+ except Exception as e:+ error_msg = str(e).lower()+ # Only retry transient connectivity issues that might have slipped through+ # or occurred between platform checks.+ if attempt < max_retries and any(+ x in error_msg for x in ["connect", "timeout", "broken"]+ ):+ wait = 2**attempt+ logger.warning(+ f"Limiter fire_and_forget transient error (attempt {attempt + 1}): {e}. Retrying in {wait}s..."+ )+ await asyncio.sleep(wait)+ continue++ logger.error(+ f"Final error in fire_and_forget for key {dedup_key}: {type(e).__name__}: {e}"+ )+ if not future.done():+ future.set_exception(e)+ breakasyncio.create_task(_wrapped())diff --git a/messaging/telegram.py b/messaging/telegram.pyindex b983c999..45524a82 100644--- a/messaging/telegram.py+++ b/messaging/telegram.py@@ -7,6 +7,11 @@ Implements MessagingPlatform for Telegram using python-telegram-bot.import asyncioimport loggingimport os++# Opt-in to future behavior for python-telegram-bot (retry_after as timedelta)+# This must be set BEFORE importing telegram.error+os.environ["PTB_TIMEDELTA"] = "1"+from typing import Callable, Awaitable, Optional, Any, Dictfrom .base import MessagingPlatform@@ -144,6 +149,48 @@ class TelegramPlatform(MessagingPlatform):self._connected = Falselogger.info("Telegram platform stopped")+ async def _with_retry(+ self, func: Callable[..., Awaitable[Any]], *args, **kwargs+ ) -> Any:+ """Helper to execute a function with exponential backoff on network errors."""+ max_retries = 3+ last_error = None+ for attempt in range(max_retries):+ try:+ return await func(*args, **kwargs)+ except (NetworkError, asyncio.TimeoutError) as e:+ last_error = e+ if attempt < max_retries - 1:+ wait_time = 2**attempt # 1s, 2s, 4s+ logger.warning(+ f"Telegram API network error (attempt {attempt + 1}/{max_retries}): {e}. Retrying in {wait_time}s..."+ )+ await asyncio.sleep(wait_time)+ else:+ logger.error(+ f"Telegram API failed after {max_retries} attempts: {e}"+ )+ raise+ except RetryAfter as e:+ # Telegram explicitly tells us to wait+ wait_secs = e.retry_after+ if hasattr(wait_secs, "total_seconds"):+ wait_secs = wait_secs.total_seconds()++ logger.warning(f"Rate limited by Telegram, waiting {wait_secs}s...")+ await asyncio.sleep(wait_secs)+ # We don't increment attempt here, as this is a specific instruction+ return await func(*args, **kwargs)+ except TelegramError as e:+ # Non-network Telegram errors+ if "Message is not modified" in str(e):+ return None+ if "Can't parse entities" in str(e) and kwargs.get("parse_mode"):+ logger.warning("Markdown failed, retrying without parse_mode")+ kwargs["parse_mode"] = None+ return await func(*args, **kwargs)+ raise+async def send_message(self,chat_id: str,@@ -155,33 +202,16 @@ class TelegramPlatform(MessagingPlatform):if not self._application:raise RuntimeError("Telegram application not initialized")- try:+ async def _do_send(mode=parse_mode):msg = await self._application.bot.send_message(chat_id=chat_id,text=text,reply_to_message_id=int(reply_to) if reply_to else None,- parse_mode=parse_mode,+ parse_mode=mode,)return str(msg.message_id)- except RetryAfter as e:- logger.warning(f"Rate limited by Telegram, retry in {e.retry_after}s")- # In a real system, we might sleep, but for now we propagate or let the caller handle- raise- except TelegramError as e:- if "Can't parse entities" in str(e):- logger.warning(- f"Markdown failed for message, falling back to plain text: {e}"- )- # Retry as plain text (no parse_mode)- msg = await self._application.bot.send_message(- chat_id=chat_id,- text=text,- reply_to_message_id=int(reply_to) if reply_to else None,- parse_mode=None,- )- return str(msg.message_id)- logger.error(f"Telegram API Error: {e}")- raise++ return await self._with_retry(_do_send)async def edit_message(self,@@ -194,33 +224,15 @@ class TelegramPlatform(MessagingPlatform):if not self._application:raise RuntimeError("Telegram application not initialized")- try:+ async def _do_edit(mode=parse_mode):await self._application.bot.edit_message_text(chat_id=chat_id,message_id=int(message_id),text=text,- parse_mode=parse_mode,+ parse_mode=mode,)- except RetryAfter as e:- logger.warning(f"Rate limited on edit, retry in {e.retry_after}s")- raise- except TelegramError as e:- if "Message is not modified" in str(e):- pass- elif "Can't parse entities" in str(e):- logger.warning(- f"Markdown failed for edit, falling back to plain text: {e}"- )- # Retry as plain text- await self._application.bot.edit_message_text(- chat_id=chat_id,- message_id=int(message_id),- text=text,- parse_mode=None,- )- else:- logger.error(f"Telegram Edit Error: {e}")- raise++ await self._with_retry(_do_edit)async def queue_send_message(self,diff --git a/tests/conftest.py b/tests/conftest.pyindex 0f9e71b1..f4ffb152 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -6,6 +6,7 @@ import sys# Set mock environment BEFORE any imports that use Settingsos.environ.setdefault("NVIDIA_NIM_API_KEY", "test_key")os.environ.setdefault("MODEL", "test-model")+os.environ["PTB_TIMEDELTA"] = "1"# Add project root to pathsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))diff --git a/tests/test_reliability.py b/tests/test_reliability.pynew file mode 100644index 00000000..e1d7d4b2--- /dev/null+++ b/tests/test_reliability.py@@ -0,0 +1,103 @@+import pytest+import asyncio+from unittest.mock import AsyncMock, MagicMock, patch+from messaging.telegram import TelegramPlatform+from telegram.error import NetworkError, RetryAfter, TelegramError+from messaging.handler import ClaudeMessageHandler+++def telegram_platform():+ with patch("messaging.telegram.TELEGRAM_AVAILABLE", True):+ platform = TelegramPlatform(bot_token="test_token", allowed_user_id="12345")+ return platform+++async def test_telegram_retry_on_network_error(telegram_platform):+ mock_bot = AsyncMock()+ mock_msg = MagicMock()+ mock_msg.message_id = 999++ # Fail twice, then succeed+ mock_bot.send_message.side_effect = [+ NetworkError("Connection failed"),+ NetworkError("Connection failed"),+ mock_msg,+ ]++ telegram_platform._application = MagicMock()+ telegram_platform._application.bot = mock_bot++ # We need to patch asyncio.sleep to speed up the test+ with patch("asyncio.sleep", AsyncMock()) as mock_sleep:+ msg_id = await telegram_platform.send_message("chat_1", "hello")++ assert msg_id == "999"+ assert mock_bot.send_message.call_count == 3+ assert mock_sleep.call_count == 2+++async def test_telegram_retry_on_retry_after(telegram_platform):+ mock_bot = AsyncMock()+ mock_msg = MagicMock()+ mock_msg.message_id = 1000++ # Fail with RetryAfter, then succeed+ mock_bot.send_message.side_effect = [RetryAfter(retry_after=5), mock_msg]++ telegram_platform._application = MagicMock()+ telegram_platform._application.bot = mock_bot++ with patch("asyncio.sleep", AsyncMock()) as mock_sleep:+ msg_id = await telegram_platform.send_message("chat_1", "hello")++ assert msg_id == "1000"+ assert mock_bot.send_message.call_count == 2+ mock_sleep.assert_called_with(5)+++async def test_telegram_no_retry_on_bad_request(telegram_platform):+ mock_bot = AsyncMock()++ # Fail with generic TelegramError (should not retry unless specific conditions met)+ mock_bot.send_message.side_effect = TelegramError("Bad Request: some error")++ telegram_platform._application = MagicMock()+ telegram_platform._application.bot = mock_bot++ with pytest.raises(TelegramError):+ await telegram_platform.send_message("chat_1", "hello")++ assert mock_bot.send_message.call_count == 1+++def test_handler_build_message_hardening():+ handler = ClaudeMessageHandler(AsyncMock(), AsyncMock(), AsyncMock())++ # Case 1: Empty components+ components = {+ "thinking": [],+ "tools": [],+ "subagents": [],+ "content": [],+ "errors": [],+ }+ msg = handler._build_message(components)+ assert msg == "⏳ **Claude is working...**"++ # Case 2: Truncation with code block closing+ long_thinking = "thought " * 200 # ~1400 chars+ components["thinking"] = [long_thinking]+ components["content"] = ["This is a very long message. " * 300] # ~ 8700 chars++ msg = handler._build_message(components, status="Finishing...")++ assert len(msg) <= 4096+ assert "truncated" in msg+ assert "Finishing..." in msg+ # If thinking contains backticks, they should be balanced+ if "```" in msg:+ assert msg.count("```") % 2 == 0