fix(tg): reviewer fixes — error handling, timeouts, db index

- commands.py: try/except TelegramBadRequest around all Bot API calls (#2);
  /new handles "topics limit" with user-friendly message (#4)
- start.py: isolate _check_and_prune_stale_topics with try/except Exception (#3)
- message.py: asyncio.timeout(30) around stream_message; handle TimeoutError (#6)
- db.py: add idx_chats_user_id index in init_db() (#7)
- settings.py: remove dead active_chat_id variable (#8)
- tests: add test_message.py (stream error/success); add 2 tests in test_commands.py
  (topics limit, /archive in General topic)
This commit is contained in:
Mikhail Putilovskij 2026-04-02 13:44:59 +03:00
parent c95360ce1f
commit 8901e60f6a
7 changed files with 161 additions and 25 deletions

View file

@ -1,5 +1,6 @@
from __future__ import annotations
import asyncio
import time
import structlog
@ -46,22 +47,26 @@ async def handle_topic_message(message: Message, dispatcher: EventDispatcher) ->
last_edit_len = 0
try:
async for chunk in dispatcher._platform.stream_message(
user_id=platform_user.user_id,
chat_id=str(thread_id),
text=incoming.text,
attachments=None,
):
accumulated += chunk.delta
now = time.monotonic()
delta = len(accumulated) - last_edit_len
if delta >= STREAM_MIN_DELTA and (now - last_edit_time) >= STREAM_EDIT_INTERVAL:
await _safe_edit(placeholder, accumulated)
last_edit_time = now
last_edit_len = len(accumulated)
async with asyncio.timeout(30):
async for chunk in dispatcher._platform.stream_message(
user_id=platform_user.user_id,
chat_id=str(thread_id),
text=incoming.text,
attachments=None,
):
accumulated += chunk.delta
now = time.monotonic()
delta = len(accumulated) - last_edit_len
if delta >= STREAM_MIN_DELTA and (now - last_edit_time) >= STREAM_EDIT_INTERVAL:
await _safe_edit(placeholder, accumulated)
last_edit_time = now
last_edit_len = len(accumulated)
await _safe_edit(placeholder, accumulated or "...")
await _safe_edit(placeholder, accumulated or "...")
except TimeoutError:
logger.warning("platform_timeout", user_id=user_id, thread_id=thread_id)
await _safe_edit(placeholder, "Сервис не отвечает, попробуй позже")
except TelegramBadRequest as e:
if "thread not found" in str(e).lower():
db.archive_chat(user_id=user_id, thread_id=thread_id)