Skip to content

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

Revert "fixed telegram rate limiter"

Alishahryar15e44e13048ba
diff --git a/messaging/handler.py b/messaging/handler.py
index f4cbcf25..9815a43b 100644
--- a/messaging/handler.py
+++ b/messaging/handler.py
@@ -96,9 +96,7 @@ class ClaudeMessageHandler:
status_msg_id = await self.platform.send_message(
incoming.chat_id,
status_text,
- reply_to=incoming.message_id
- if incoming.message_id != incoming.message_id
- else None,
+ reply_to=incoming.message_id if incoming.message_id != incoming.message_id else None,
)
# Create or extend tree
@@ -184,26 +182,37 @@ class ClaudeMessageHandler:
nonlocal last_ui_update
now = time.time()
- # Match UI debounce with platform rate limits to prevent queue bloat
- # Default to 1.0s if rate_window is not available
- debounce = getattr(self.platform, "rate_window", 1.0)
- if not force and now - last_ui_update < debounce:
+ # Small 1s debounce for UI sanity (not a hard rate limit)
+ if not force and now - last_ui_update < 1.0:
return
- try:
- display = self._build_message(components, status)
- if display:
- # The platform is wrapped in RateLimitedPlatform, so it will wait
- # if globally rate limited or paused.
- await self.platform.edit_message(
- chat_id, status_msg_id, display, parse_mode="markdown"
- )
- last_ui_update = now
- except Exception as e:
- # Log error but don't crash the handler
- logger.error(f"UI update failed: {e}")
- # Don't immediate retry, wait for next scheduled update
- last_ui_update = now
+ # Retry logic for flood wait errors
+ max_retries = 3 if not force else 5
+ for attempt in range(max_retries):
+ try:
+ display = self._build_message(components, status)
+ if display:
+ await self.platform.edit_message(
+ chat_id, status_msg_id, display, parse_mode="markdown"
+ )
+ last_ui_update = now
+ return # Success, exit retry loop
+ except Exception as e:
+ error_msg = str(e).lower()
+ is_flood_error = "flood" in error_msg or "wait" in error_msg
+
+ if is_flood_error and attempt < max_retries - 1:
+ # Wait before retry on flood error
+ wait_time = 2 ** attempt # Exponential backoff: 2s, 4s, 8s
+ logger.warning(f"Flood wait on edit (attempt {attempt + 1}/{max_retries}), retrying in {wait_time}s...")
+ await asyncio.sleep(wait_time)
+ continue
+ else:
+ # Log and give up after retries or if not a flood error
+ if is_flood_error:
+ last_ui_update = now + 10 # Skip for 10s on persistent flood error
+ logger.error(f"UI update failed after {attempt + 1} attempts: {e}")
+ return
try:
# Get or create CLI session
@@ -235,9 +244,7 @@ class ClaudeMessageHandler:
incoming.text, session_id=captured_session_id
):
if not isinstance(event_data, dict):
- logger.warning(
- f"HANDLER: Non-dict event received: {type(event_data)}"
- )
+ logger.warning(f"HANDLER: Non-dict event received: {type(event_data)}")
continue
event_count += 1
if event_count % 10 == 0:
@@ -295,9 +302,7 @@ class ClaudeMessageHandler:
elif parsed["type"] == "error":
error_msg = parsed.get("message", "Unknown error")
- logger.error(
- f"HANDLER: Error event received: {error_msg[:200]}"
- )
+ logger.error(f"HANDLER: Error event received: {error_msg[:200]}")
components["errors"].append(error_msg)
logger.info(f"HANDLER: Updating UI with error status")
# Always force error status to bypass flood wait
@@ -341,9 +346,7 @@ class ClaudeMessageHandler:
except Exception as e:
logger.error(f"Failed to update child status: {e}")
except Exception as e:
- logger.error(
- f"HANDLER: Task failed with exception: {type(e).__name__}: {e}"
- )
+ logger.error(f"HANDLER: Task failed with exception: {type(e).__name__}: {e}")
error_msg = str(e)[:200]
components["errors"].append(error_msg)
# Always force error status to bypass flood wait
@@ -365,9 +368,7 @@ class ClaudeMessageHandler:
except Exception as e:
logger.error(f"Failed to update child status: {e}")
finally:
- logger.info(
- f"HANDLER: _process_node completed for node {node_id}, errors={len(components['errors'])}"
- )
+ logger.info(f"HANDLER: _process_node completed for node {node_id}, errors={len(components['errors'])}")
def _build_message(
self,
diff --git a/messaging/rate_limited_platform.py b/messaging/rate_limited_platform.py
index 2c44fa59..48c70972 100644
--- a/messaging/rate_limited_platform.py
+++ b/messaging/rate_limited_platform.py
@@ -27,11 +27,6 @@ class RateLimitedPlatform(MessagingPlatform):
f"RateLimitedPlatform initialized with {rate_limit} calls per {rate_window}s"
)
- @property
- def rate_window(self) -> float:
- """Return the rate limit window (period)."""
- return self._limiter.period
-
@property
def name(self) -> str:
return f"rate_limited_{self._platform.name}"
diff --git a/messaging/rate_limiter.py b/messaging/rate_limiter.py
index 450c9530..c6b4284b 100644
--- a/messaging/rate_limiter.py
+++ b/messaging/rate_limiter.py
@@ -1,7 +1,6 @@
import asyncio
import logging
import threading
-import time
from typing import Callable, Any, TypeVar, Coroutine
from ratelimitqueue import RateLimitQueue
@@ -20,20 +19,12 @@ class GlobalRateLimiter:
"""
def __init__(self, calls: int = 1, period: float = 1.0):
- self._period = period
self.queue = RateLimitQueue(calls=calls, per=period)
self._stop_event = threading.Event()
- self._pause_until = 0.0
- self._lock = threading.Lock()
self._worker_thread = threading.Thread(target=self._worker, daemon=True)
self._worker_thread.start()
logger.info(f"GlobalRateLimiter started with {calls} calls per {period}s")
- @property
- def period(self) -> float:
- """Return the rate limit period."""
- return self._period
-
async def execute(self, func: Callable[[], Coroutine[Any, Any, T]]) -> T:
"""
Schedule a function to be executed within the rate limit.
@@ -46,60 +37,23 @@ class GlobalRateLimiter:
def _worker(self):
"""Worker thread that pulls from the RateLimitQueue and executes tasks."""
- import concurrent.futures
-
while not self._stop_event.is_set():
try:
- # Check if paused
- with self._lock:
- pause_wait = self._pause_until - time.time()
-
- if pause_wait > 0:
- logger.warning(
- f"GlobalRateLimiter paused, waiting {pause_wait:.1f}s..."
- )
- # Sleep in small increments to remain responsive to stop event
- time.sleep(min(pause_wait, 1.0))
- continue
-
# get() blocks based on rate limit
+ # We don't use timeout here to avoid the skip issue
+ # instead we depend on the queue blocking
item = self.queue.get(block=True)
task_fn, future, loop = item
- if future.done():
- self.queue.task_done()
- continue
-
- # Execute the task and WAIT for it to complete
- # This ensures we don't pull the next item until this one is done,
- # which is critical for detecting and honoring flood waits.
- async def run_task(f=task_fn):
- return await f()
-
- task_future = asyncio.run_coroutine_threadsafe(run_task(), loop)
- try:
- result = task_future.result()
- if not future.done():
- loop.call_soon_threadsafe(future.set_result, result)
- except (concurrent.futures.CancelledError, asyncio.CancelledError):
- if not future.done():
- loop.call_soon_threadsafe(future.cancel)
- except Exception as e:
- # Detect flood wait (e.g. from Telethon)
- wait_seconds = getattr(e, "seconds", None)
- if wait_seconds:
- logger.error(
- f"GlobalRateLimiter detected flood wait: pausing for {wait_seconds}s"
- )
- with self._lock:
- # Set pause if it's further in the future than current pause
- self._pause_until = max(
- self._pause_until, time.time() + wait_seconds
- )
-
- if not future.done():
- loop.call_soon_threadsafe(future.set_exception, e)
+ # Execute the task
+ async def run_task(f=task_fn, fut=future, l=loop):
+ try:
+ result = await f()
+ l.call_soon_threadsafe(fut.set_result, result)
+ except Exception as e:
+ l.call_soon_threadsafe(fut.set_exception, e)
+ asyncio.run_coroutine_threadsafe(run_task(), loop)
self.queue.task_done()
except Exception as e:
logger.error(f"Error in GlobalRateLimiter worker: {e}")