fix: typing — threading.Thread + asyncio.sleep polling

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-23 02:41:49 +10:00
co-authored by Claude Opus 4.6
parent 2b3ccc77d8
commit 40bf548390
+30 -33
View File
@@ -158,7 +158,7 @@ async def ask_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
import time
import concurrent.futures
import threading
assistant = get_assistant()
q_type = assistant._classify_question(question)
@@ -166,50 +166,47 @@ async def ask_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
wait_msg = await update.message.reply_text(f"🤔 Думаю... {eta}")
chat_id = update.effective_chat.id
# Start LLM in thread pool (non-blocking)
loop = asyncio.get_event_loop()
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
future = loop.run_in_executor(executor, assistant.ask, question)
t0 = time.time()
# Send typing every 4 sec while waiting
while not future.done():
# Run LLM in a thread
result_holder = {"answer": None, "error": None, "done": False}
def run_llm():
try:
result_holder["answer"] = assistant.ask(question)
except Exception as e:
result_holder["error"] = str(e)
result_holder["done"] = True
thread = threading.Thread(target=run_llm)
thread.start()
# Send typing every 3 sec while thread is running
while not result_holder["done"]:
try:
await context.bot.send_chat_action(chat_id=chat_id, action="typing")
except Exception:
pass
try:
await asyncio.wait_for(asyncio.shield(future), timeout=4.0)
break
except asyncio.TimeoutError:
continue
except Exception:
break
logger.info("Sent typing action")
except Exception as e:
logger.error(f"Typing error: {e}")
await asyncio.sleep(3)
thread.join()
elapsed = time.time() - t0
try:
answer = future.result()
elapsed = time.time() - t0
await wait_msg.delete()
except Exception:
pass
if result_holder["error"]:
await update.message.reply_text(f"Ошибка: {result_holder['error']}")
else:
answer = result_holder["answer"]
if len(answer) > 4000:
answer = answer[:3900] + "\n\n... (ответ сокращён)"
answer += f"\n\n⏱ {elapsed:.1f}с"
try:
await wait_msg.delete()
except Exception:
pass
await update.message.reply_text(answer)
except Exception as e:
logger.error(f"Ask error: {e}")
try:
await wait_msg.delete()
except Exception:
pass
await update.message.reply_text(f"Ошибка: {e}")
async def nr_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = " ".join(context.args) if context.args else ""