fix: typing indicator — keep_typing каждые 4 сек + run_in_executor
- keep_typing(): фоновая задача, отправляет typing каждые 4 сек - ask: run_in_executor чтобы не блокировать event loop - Typing видно всё время пока бот думает Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user