From 52dce3647c6edc6e874fb5a22ebfc6c9ce4699b4 Mon Sep 17 00:00:00 2001 From: anor Date: Mon, 23 Mar 2026 02:33:52 +1000 Subject: [PATCH] =?UTF-8?q?fix:=20typing=20indicator=20=E2=80=94=20keep=5F?= =?UTF-8?q?typing=20=D0=BA=D0=B0=D0=B6=D0=B4=D1=8B=D0=B5=204=20=D1=81?= =?UTF-8?q?=D0=B5=D0=BA=20+=20run=5Fin=5Fexecutor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - keep_typing(): фоновая задача, отправляет typing каждые 4 сек - ask: run_in_executor чтобы не блокировать event loop - Typing видно всё время пока бот думает Co-Authored-By: Claude Opus 4.6 (1M context) --- src/smeta_railway/ai/telegram_bot.py | 39 +++++++++++++++++++++------- 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/src/smeta_railway/ai/telegram_bot.py b/src/smeta_railway/ai/telegram_bot.py index d167ffe..c94389f 100644 --- a/src/smeta_railway/ai/telegram_bot.py +++ b/src/smeta_railway/ai/telegram_bot.py @@ -11,6 +11,7 @@ Commands: Текстовое сообщение — автоматически определяет: поиск или вопрос """ +import asyncio import logging import os from pathlib import Path @@ -24,6 +25,19 @@ from telegram.ext import ( filters, ) + +async def keep_typing(bot, chat_id, stop_event: asyncio.Event): + """Send typing action every 4 seconds until stopped.""" + while not stop_event.is_set(): + try: + await bot.send_chat_action(chat_id=chat_id, action="typing") + except Exception: + pass + try: + await asyncio.wait_for(stop_event.wait(), timeout=4.0) + except asyncio.TimeoutError: + pass + logger = logging.getLogger(__name__) # Admin chat ID — will be set on first /start from admin @@ -144,28 +158,31 @@ async def ask_command(update: Update, context: ContextTypes.DEFAULT_TYPE): import time - # Classify to estimate wait time assistant = get_assistant() q_type = assistant._classify_question(question) - if q_type == "cag": - wait_msg = await update.message.reply_text("🤔 Ищу в таблицах... ~5 сек") - else: - wait_msg = await update.message.reply_text("🤔 Ищу в базе норм и документах... ~15-20 сек") + eta = "~5 сек" if q_type == "cag" else "~15-20 сек" + wait_msg = await update.message.reply_text(f"🤔 Думаю... {eta}") - # Show typing indicator - await context.bot.send_chat_action(chat_id=update.effective_chat.id, action="typing") + # Keep typing indicator active throughout + stop_typing = asyncio.Event() + typing_task = asyncio.create_task( + keep_typing(context.bot, update.effective_chat.id, stop_typing) + ) try: t0 = time.time() - answer = assistant.ask(question) + answer = await asyncio.get_event_loop().run_in_executor( + None, assistant.ask, question + ) elapsed = time.time() - t0 + stop_typing.set() + await typing_task + if len(answer) > 4000: answer = answer[:3900] + "\n\n... (ответ сокращён)" - answer += f"\n\n⏱ {elapsed:.1f}с" - # Delete "thinking" message and send answer try: await wait_msg.delete() except Exception: @@ -173,6 +190,8 @@ async def ask_command(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text(answer) except Exception as e: + stop_typing.set() + await typing_task logger.error(f"Ask error: {e}") try: await wait_msg.delete()