From 8d3977c9e3b1871fe2a81d38758357975d4314cc Mon Sep 17 00:00:00 2001 From: anor Date: Mon, 30 Mar 2026 17:30:06 +1000 Subject: [PATCH] =?UTF-8?q?feat:=20=D0=BF=D0=BE=D0=B4=D0=B4=D0=B5=D1=80?= =?UTF-8?q?=D0=B6=D0=BA=D0=B0=20=D0=B3=D0=BE=D0=BB=D0=BE=D1=81=D0=BE=D0=B2?= =?UTF-8?q?=D1=8B=D1=85=20=D1=81=D0=BE=D0=BE=D0=B1=D1=89=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=B9=20=D0=B2=20TG=20=D0=B1=D0=BE=D1=82=D0=B5=20(Whisper=20ST?= =?UTF-8?q?T)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Voice → скачать .ogg → OpenAI Whisper API → текст → Claude Code. Показывает распознанный текст перед ответом. Co-Authored-By: Claude Opus 4.6 (1M context) --- src/smeta_railway/ai/telegram_bot.py | 85 ++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) diff --git a/src/smeta_railway/ai/telegram_bot.py b/src/smeta_railway/ai/telegram_bot.py index 28f88ba..120666d 100644 --- a/src/smeta_railway/ai/telegram_bot.py +++ b/src/smeta_railway/ai/telegram_bot.py @@ -11,12 +11,14 @@ Commands: /sp — profit margin (instant, no LLM) /new — reset conversation context Text — any text → Claude Code answers + Voice — voice message → Whisper STT → Claude Code answers """ import asyncio import json import logging import os +import tempfile import time from telegram import Update @@ -294,6 +296,88 @@ async def text_message(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text(answer) +# ── Voice message handling ──────────────────────────────────────────────── + +async def transcribe_voice(file_path: str) -> str: + """Transcribe voice message using OpenAI Whisper API.""" + import httpx + + api_key = os.environ.get("OPENAI_API_KEY", "") + if not api_key: + return "" + + async with httpx.AsyncClient(timeout=30) as client: + with open(file_path, "rb") as f: + resp = await client.post( + "https://api.openai.com/v1/audio/transcriptions", + headers={"Authorization": f"Bearer {api_key}"}, + files={"file": ("voice.ogg", f, "audio/ogg")}, + data={"model": "whisper-1", "language": "ru"}, + ) + resp.raise_for_status() + return resp.json().get("text", "") + + +async def voice_message(update: Update, context: ContextTypes.DEFAULT_TYPE): + """Voice message → Whisper STT → Claude Code.""" + user_id = update.effective_user.id + chat_id = update.effective_chat.id + + wait_msg = await update.message.reply_text("🎤 Распознаю голос...") + + # Download voice file + voice = update.message.voice or update.message.audio + if not voice: + await wait_msg.edit_text("Не удалось получить голосовое сообщение.") + return + + try: + tg_file = await context.bot.get_file(voice.file_id) + with tempfile.NamedTemporaryFile(suffix=".ogg", delete=False) as tmp: + tmp_path = tmp.name + await tg_file.download_to_drive(tmp_path) + + # Transcribe + text = await transcribe_voice(tmp_path) + os.unlink(tmp_path) + + if not text: + await wait_msg.edit_text("Не удалось распознать речь.") + return + + await wait_msg.edit_text(f"🤔 «{text[:100]}{'...' if len(text) > 100 else ''}»\nДумаю...") + + except Exception as e: + logger.error(f"Voice transcription error: {e}") + await wait_msg.edit_text(f"Ошибка распознавания: {e}") + return + + # Typing indicator + stop_typing = asyncio.Event() + typing_task = asyncio.create_task( + keep_typing(context.bot, chat_id, stop_typing) + ) + + try: + answer = await ask_claude(text, user_id) + except Exception as e: + logger.error(f"Claude error for user {user_id}: {e}") + answer = f"Ошибка: {e}" + finally: + stop_typing.set() + await typing_task + + try: + await wait_msg.delete() + except Exception: + pass + + if len(answer) > 4000: + answer = answer[:3900] + "\n\n... (ответ сокращён)" + + await update.message.reply_text(answer) + + # ── Entry point ─────────────────────────────────────────────────────────── def run_bot(): @@ -324,6 +408,7 @@ def run_bot(): app.add_handler(CommandHandler("nr", nr_command)) app.add_handler(CommandHandler("sp", sp_command)) app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, text_message)) + app.add_handler(MessageHandler(filters.VOICE | filters.AUDIO, voice_message)) logger.info("Bot started. Polling...") app.run_polling()