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
more robust error handling by telegram bot
Alishahryar1f7f5b985903c
diff --git a/messaging/handler.py b/messaging/handler.pyindex d85b5e45..d36d7beb 100644--- a/messaging/handler.py+++ b/messaging/handler.py@@ -372,33 +372,31 @@ class ClaudeMessageHandler:status: Optional[str] = None,) -> str:"""- Build unified message with specific order:- 1. Thinking- 2. Tools- 3. Subagents- 4. Content- 5. Errors- 6. Status (Bottom)+ Build unified message with specific order.+ Handles truncation while preserving markdown structure (closing code blocks)."""lines = []# 1. Thinkingif components["thinking"]:- full_thinking = "".join(components["thinking"])- display = full_thinking- if len(display) > 800:- display = display[:795] + "..."- lines.append(f"💭 **Thinking:**\n```\n{display}\n```")+ thinking_text = "".join(components["thinking"])+ # Truncate thinking if too long, it's usually less critical than final content+ if len(thinking_text) > 1000:+ thinking_text = thinking_text[:995] + "..."++ # Ensure it doesn't break a code block if we eventually support them inside thinking+ lines.append(f"💭 **Thinking:**\n```\n{thinking_text}\n```")# 2. Toolsif components["tools"]:unique_tools = []seen = set()for t in components["tools"]:- if t not in seen:- unique_tools.append(t)+ if t and t not in seen:+ unique_tools.append(str(t))seen.add(t)- lines.append(f"🛠 **Tools:** `{', '.join(unique_tools)}`")+ if unique_tools:+ lines.append(f"🛠 **Tools:** `{', '.join(unique_tools)}`")# 3. Subagentsif components["subagents"]:@@ -407,8 +405,7 @@ class ClaudeMessageHandler:# 4. Contentif components["content"]:- full_content = "".join(components["content"])- lines.append(full_content)+ lines.append("".join(components["content"]))# 5. Errorsif components["errors"]:@@ -420,13 +417,28 @@ class ClaudeMessageHandler:lines.append("")lines.append(status)- result = "\n".join(lines)+ # Telegram character limit is 4096. We leave buffer for status updates.+ LIMIT = 3900++ 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+ )++ # If too long, truncate the main content but keep the status and close code blocks+ available_limit = LIMIT - len(status_text) - 20 # 20 for truncation marker+ truncated_main = main_text[:available_limit] + "\n... (truncated)"- # Truncate if too long (Telegram limit ~4096)- if len(result) > 3800:- result = "..." + result[-3795:]+ # Close any open code blocks+ if truncated_main.count("```") % 2 != 0:+ truncated_main += "\n```"- return result+ return truncated_main + status_textdef _get_initial_status(self,diff --git a/messaging/limiter.py b/messaging/limiter.pyindex 55e72c97..18aa45ba 100644--- a/messaging/limiter.py+++ b/messaging/limiter.py@@ -93,7 +93,11 @@ class GlobalRateLimiter:if not f.done():f.set_result(result)except Exception as e:- # Handle Telegram FloodWaitError specifically+ # Report error to all futures and log it+ for f in futures:+ if not f.done():+ f.set_exception(e)+error_msg = str(e).lower()if "flood" in error_msg or "wait" in error_msg:seconds = 30@@ -103,20 +107,16 @@ class GlobalRateLimiter:except:pass- logger.error(f"FloodWait detected! Pausing for {seconds}s")+ logger.error(+ f"FloodWait detected! Pausing worker for {seconds}s"+ )self._paused_until = (asyncio.get_event_loop().time() + seconds)-- # Re-queue the tasks at the front (as a high priority update)- await self._enqueue_internal_multi(- func, futures, dedup_key, front=True- )- await asyncio.sleep(seconds)else:- for f in futures:- if not f.done():- f.set_exception(e)+ logger.error(+ f"Error in limiter worker for key {dedup_key}: {e}"+ )except asyncio.CancelledError:breakexcept Exception as e:@@ -171,4 +171,13 @@ class GlobalRateLimiter:dedup_key = f"task_{id(func)}_{asyncio.get_event_loop().time()}"future = asyncio.get_event_loop().create_future()- asyncio.create_task(self._enqueue_internal(func, future, dedup_key))++ 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)++ asyncio.create_task(_wrapped())diff --git a/messaging/telegram.py b/messaging/telegram.pyindex 80eba46b..cd7a8d04 100644--- a/messaging/telegram.py+++ b/messaging/telegram.py@@ -147,6 +147,18 @@ class TelegramPlatform(MessagingPlatform):# In a real system, we might sleep, but for now we propagate or let the caller handleraiseexcept 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@@ -174,6 +186,17 @@ class TelegramPlatform(MessagingPlatform):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}")raisediff --git a/tests/test_robust_formatting.py b/tests/test_robust_formatting.pynew file mode 100644index 00000000..4feb81bc--- /dev/null+++ b/tests/test_robust_formatting.py@@ -0,0 +1,64 @@+import pytest+from unittest.mock import MagicMock+from messaging.handler import ClaudeMessageHandler+++def handler():+ platform = MagicMock()+ cli = MagicMock()+ store = MagicMock()+ return ClaudeMessageHandler(platform, cli, store)+++def test_truncation_closes_code_blocks(handler):+ """Verify that truncation correctly closes open code blocks."""+ components = {+ "thinking": [+ "Starting some long thinking process that will definitely cause truncation later on..."+ ],+ "tools": [],+ "subagents": [],+ "content": [+ "```python\ndef very_long_function():\n # " + "A" * 4000+ ], # Long content+ "errors": [],+ }++ msg = handler._build_message(components, "✅ **Complete**")++ assert "... (truncated)" in msg+ # The limit is 3900. Our content + thinking is > 4000.+ # The backtick count must be even to be a valid block.+ assert msg.count("```") % 2 == 0+ assert msg.endswith("```") or "✅ **Complete**" in msg.split("```")[-1]+++def test_truncation_preserves_status(handler):+ """Verify that status is still appended after truncation."""+ components = {+ "thinking": ["Thinking..."],+ "tools": [],+ "subagents": [],+ "content": ["A" * 5000],+ "errors": [],+ }+ status = "READY_STATUS"+ msg = handler._build_message(components, status)++ assert status in msg+ assert "... (truncated)" in msg+++def test_empty_components_with_status(handler):+ """Verify message building with just a status."""+ components = {+ "thinking": [],+ "tools": [],+ "subagents": [],+ "content": [],+ "errors": [],+ }+ status = "Simple Status"+ msg = handler._build_message(components, status)+ assert msg == "\n\nSimple Status"