Command exited with code 0. Command output: + log(f"User {target} has blocked the bot.") + return None else: res_body = await resp.text() - log(f"HTTP Bot API fallback status {resp.status}: {res_body}") + log(f"HTTP Bot API send status {resp.status} to {target}: {res_body}") except Exception as http_err: - log(f"HTTP Bot API fallback failed: {http_err}") + log(f"HTTP Bot API send to {target} failed: {http_err}") return None async def _http_pin_message(self, chat_id: int | str, message_id: int) -> bool: @@ -608,29 +541,106 @@ async def send(self, chat_id: str | int, text: str, keyboard: Optional[Any] = None): target = int(chat_id) if str(chat_id).lstrip("-").isdigit() else chat_id + return await self._send_http(target, text, keyboard) - # Skip Pyrogram if bot is offline or currently reconnecting - if not self.bot or not getattr(self.bot, "is_connected", False) or self._bot_restarting: - return await self._send_http_fallback(target, text, keyboard) + async def _bot_http_polling_loop(self) -> None: + log("[bot poller] Starting Telegram HTTP Bot API long-polling loop...") + offset = -1 + first_call = True - try: - return await asyncio.wait_for( - self.bot.send_message(target, text, reply_markup=keyboard), - timeout=5.0, - ) - except UserIsBlocked: - log(f"User {target} has blocked the bot. Skipping.") - return None - except Exception as exc: - err_str = str(exc).lower() - if any(k in err_str for k in ("handler is closed", "tcptransport closed", "connection lost", "auth_key_unregistered")): - log(f"Pyrogram transport failure detected ({exc}). Triggering bot recovery...") - asyncio.create_task(self._restart_bot_client()) - elif "timed out" in err_str or "timeout" in err_str or "connection" in err_str or "socket" in err_str: - log(f"Pyrogram send_message to {target} timed out/network error ({exc}). Trying HTTP Bot API fallback...") - else: - log(f"Pyrogram send_message to {target} failed: {exc}. Trying HTTP Bot API fallback...") - return await self._send_http_fallback(target, text, keyboard) + while True: + try: + if not self.http or not self.bot_token: + await asyncio.sleep(2) + continue + + url = f"https://api.telegram.org/bot{self.bot_token}/getUpdates" + params: dict[str, Any] = { + "offset": offset, + "timeout": 20, + "allowed_updates": json.dumps(["message"]), + } + + async with self.http.get(url, params=params, timeout=aiohttp.ClientTimeout(total=30)) as resp: + if resp.status == 200: + data = await resp.json() + updates = data.get("result", []) + + if first_call: + if updates: + highest_id = max(u.get("update_id", 0) for u in updates) + offset = highest_id + 1 + log(f"[bot poller] Cleared {len(updates)} stale pending updates. Starting fresh at offset {offset}") + else: + offset = 0 + first_call = False + continue + + for u in updates: + u_id = u.get("update_id", 0) + if u_id >= offset: + offset = u_id + 1 + + raw_msg = u.get("message") + if not raw_msg: + continue + + chat_info = raw_msg.get("chat", {}) + c_type = chat_info.get("type", "") + from_info = raw_msg.get("from", {}) + if not from_info or from_info.get("is_bot"): + continue + + msg = SimpleNamespace( + id=raw_msg.get("message_id"), + text=(raw_msg.get("text", "") or raw_msg.get("caption", "")).strip(), + chat=SimpleNamespace( + id=chat_info.get("id"), + type=ChatType.PRIVATE if c_type == "private" else (ChatType.CHANNEL if c_type == "channel" else ChatType.SUPERGROUP), + ), + from_user=SimpleNamespace( + id=from_info.get("id"), + is_bot=from_info.get("is_bot", False), + first_name=from_info.get("first_name", ""), + username=from_info.get("username", ""), + ), + ) + asyncio.create_task(self._handle_bot_message(None, msg)) + + elif resp.status in (409, 429): + log(f"[bot poller] Telegram API status {resp.status}. Backing off 5s...") + await asyncio.sleep(5) + else: + await asyncio.sleep(2) + + except asyncio.CancelledError: + break + except Exception as exc: + await asyncio.sleep(2) + + async def _watchdog_loop(self) -> None: + while True: + try: + await asyncio.sleep(20) + # 1. Check bot poller task + if hasattr(self, "bot_polling_task") and self.bot_polling_task: