feat: поддержка голосовых сообщений в TG боте (Whisper STT)
Voice → скачать .ogg → OpenAI Whisper API → текст → Claude Code. Показывает распознанный текст перед ответом. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -11,12 +11,14 @@ Commands:
|
||||
/sp <query> — 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()
|
||||
|
||||
Reference in New Issue
Block a user