fix: длинные тексты падали по таймауту, админ не получал уведомления
All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 29s
All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 29s
- с RU-IP Microsoft отдаёт аудио почти в реальном времени: 650 символов ~48с, поэтому общий таймаут 30с обрывал любой длинный текст на всех попытках. Теперь TTS_TIMEOUT считается как пауза между кусками аудио, плюс общий предел TTS_TOTAL_TIMEOUT (900с) - админ получает уведомление и при неудачной озвучке - подпись к голосовому в админ-боте больше не превышает лимит Telegram 1024 символа: длинный текст уходит отдельными сообщениями; HTML экранируется - статус «записывает голосовое» обновляется всё время синтеза - concurrent_updates: долгая озвучка одного пользователя не блокирует других Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
f745ccddac
commit
2fa260c2e6
4 changed files with 96 additions and 32 deletions
|
|
@ -2,6 +2,7 @@ USER_BOT_TOKEN=8876513915:AAHA6VPGpbKSkn6Fdhwv2PfkRB7ojfgd6_U
|
||||||
ADMIN_BOT_TOKEN=8865704844:AAF2wmXiAZtfTlgdpMUwuj5S8lsjVS0lwQM
|
ADMIN_BOT_TOKEN=8865704844:AAF2wmXiAZtfTlgdpMUwuj5S8lsjVS0lwQM
|
||||||
TTS_VOICE=ru-RU-DmitryNeural
|
TTS_VOICE=ru-RU-DmitryNeural
|
||||||
TTS_TIMEOUT=30
|
TTS_TIMEOUT=30
|
||||||
|
TTS_TOTAL_TIMEOUT=900
|
||||||
TTS_RETRIES=5
|
TTS_RETRIES=5
|
||||||
# HTTP-прокси для запросов к Microsoft TTS (например v2rayA: http://192.168.8.1:20171). Пусто = напрямую.
|
# HTTP-прокси для запросов к Microsoft TTS (например v2rayA: http://192.168.8.1:20171). Пусто = напрямую.
|
||||||
TTS_PROXY=
|
TTS_PROXY=
|
||||||
|
|
|
||||||
|
|
@ -128,7 +128,8 @@ Container ──443/tcp──▶ speech.microsoft.com (edge-tts)
|
||||||
USER_BOT_TOKEN=*** # Токен пользовательского бота (Telegram BotFather)
|
USER_BOT_TOKEN=*** # Токен пользовательского бота (Telegram BotFather)
|
||||||
ADMIN_BOT_TOKEN=*** # Токен админского бота
|
ADMIN_BOT_TOKEN=*** # Токен админского бота
|
||||||
TTS_VOICE=ru-RU-DmitryNeural # Голос edge-tts (опционально)
|
TTS_VOICE=ru-RU-DmitryNeural # Голос edge-tts (опционально)
|
||||||
TTS_TIMEOUT=30 # Таймаут одной попытки, сек (опционально)
|
TTS_TIMEOUT=30 # Макс. пауза между кусками аудио, сек (опционально)
|
||||||
|
TTS_TOTAL_TIMEOUT=900 # Предел на всю попытку, сек (опционально)
|
||||||
TTS_RETRIES=5 # Попыток озвучки при 403 / NoAudioReceived (опционально)
|
TTS_RETRIES=5 # Попыток озвучки при 403 / NoAudioReceived (опционально)
|
||||||
TTS_PROXY= # HTTP-прокси до speech.platform.bing.com, напр. v2rayA http://host:20171 (опционально)
|
TTS_PROXY= # HTTP-прокси до speech.platform.bing.com, напр. v2rayA http://host:20171 (опционально)
|
||||||
```
|
```
|
||||||
|
|
|
||||||
|
|
@ -58,7 +58,8 @@ graph LR
|
||||||
| `USER_BOT_TOKEN` | Токен пользовательского бота | `856708...` |
|
| `USER_BOT_TOKEN` | Токен пользовательского бота | `856708...` |
|
||||||
| `ADMIN_BOT_TOKEN` | Токен админского бота | `880853...` |
|
| `ADMIN_BOT_TOKEN` | Токен админского бота | `880853...` |
|
||||||
| `TTS_VOICE` | Голос edge-tts (опционально) | `ru-RU-DmitryNeural` |
|
| `TTS_VOICE` | Голос edge-tts (опционально) | `ru-RU-DmitryNeural` |
|
||||||
| `TTS_TIMEOUT` | Таймаут одной попытки озвучки, сек (опционально) | `30` |
|
| `TTS_TIMEOUT` | Сколько секунд ждать следующего куска аудио, прежде чем считать попытку зависшей (опционально) | `30` |
|
||||||
|
| `TTS_TOTAL_TIMEOUT` | Предел на всю попытку озвучки, сек (опционально) | `900` |
|
||||||
| `TTS_RETRIES` | Число попыток: Microsoft периодически отвечает 403 / пустым аудио (опционально) | `5` |
|
| `TTS_RETRIES` | Число попыток: Microsoft периодически отвечает 403 / пустым аудио (опционально) | `5` |
|
||||||
| `TTS_PROXY` | HTTP-прокси для запросов к `speech.platform.bing.com`, например порт v2rayA (опционально) | `http://192.168.8.1:20171` |
|
| `TTS_PROXY` | HTTP-прокси для запросов к `speech.platform.bing.com`, например порт v2rayA (опционально) | `http://192.168.8.1:20171` |
|
||||||
|
|
||||||
|
|
|
||||||
121
app/bot.py
121
app/bot.py
|
|
@ -1,4 +1,5 @@
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import html
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
|
@ -23,7 +24,11 @@ logger = logging.getLogger(__name__)
|
||||||
USER_TOKEN = os.environ['USER_BOT_TOKEN']
|
USER_TOKEN = os.environ['USER_BOT_TOKEN']
|
||||||
ADMIN_TOKEN = os.environ['ADMIN_BOT_TOKEN']
|
ADMIN_TOKEN = os.environ['ADMIN_BOT_TOKEN']
|
||||||
TTS_VOICE = os.environ.get('TTS_VOICE', 'ru-RU-DmitryNeural')
|
TTS_VOICE = os.environ.get('TTS_VOICE', 'ru-RU-DmitryNeural')
|
||||||
|
# Max silence between audio chunks. From RU IPs Microsoft streams audio at
|
||||||
|
# roughly real-time speed, so a total timeout would kill long texts.
|
||||||
TTS_TIMEOUT = int(os.environ.get('TTS_TIMEOUT', '30'))
|
TTS_TIMEOUT = int(os.environ.get('TTS_TIMEOUT', '30'))
|
||||||
|
# Hard cap for the whole synthesis of one attempt.
|
||||||
|
TTS_TOTAL_TIMEOUT = int(os.environ.get('TTS_TOTAL_TIMEOUT', '900'))
|
||||||
TTS_RETRIES = int(os.environ.get('TTS_RETRIES', '5'))
|
TTS_RETRIES = int(os.environ.get('TTS_RETRIES', '5'))
|
||||||
TTS_PROXY = os.environ.get('TTS_PROXY') or None # e.g. http://192.168.8.1:20171 (v2rayA)
|
TTS_PROXY = os.environ.get('TTS_PROXY') or None # e.g. http://192.168.8.1:20171 (v2rayA)
|
||||||
DATA_DIR = os.environ.get('DATA_DIR', '/app/data')
|
DATA_DIR = os.environ.get('DATA_DIR', '/app/data')
|
||||||
|
|
@ -86,20 +91,43 @@ def clean_text(text: str) -> str:
|
||||||
return text
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
async def _synthesize_once(text: str, path: str) -> None:
|
||||||
|
"""One edge-tts attempt. Fails if no audio chunk arrives for TTS_TIMEOUT
|
||||||
|
seconds, or if the whole attempt exceeds TTS_TOTAL_TIMEOUT."""
|
||||||
|
communicate = edge_tts.Communicate(text, voice=TTS_VOICE, proxy=TTS_PROXY)
|
||||||
|
stream = communicate.stream()
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
deadline = loop.time() + TTS_TOTAL_TIMEOUT
|
||||||
|
try:
|
||||||
|
with open(path, 'wb') as f:
|
||||||
|
while True:
|
||||||
|
left = deadline - loop.time()
|
||||||
|
if left <= 0:
|
||||||
|
raise asyncio.TimeoutError(f'total {TTS_TOTAL_TIMEOUT}s exceeded')
|
||||||
|
try:
|
||||||
|
chunk = await asyncio.wait_for(anext(stream), timeout=min(TTS_TIMEOUT, left))
|
||||||
|
except StopAsyncIteration:
|
||||||
|
break
|
||||||
|
if chunk['type'] == 'audio':
|
||||||
|
f.write(chunk['data'])
|
||||||
|
finally:
|
||||||
|
await stream.aclose()
|
||||||
|
|
||||||
|
|
||||||
async def synthesize(text: str, path: str) -> None:
|
async def synthesize(text: str, path: str) -> None:
|
||||||
"""Run edge-tts with retries: Microsoft intermittently answers 403 /
|
"""Run edge-tts with retries: Microsoft intermittently answers 403 /
|
||||||
NoAudioReceived (especially from RU IPs), so one attempt is not enough."""
|
NoAudioReceived (especially from RU IPs), so one attempt is not enough."""
|
||||||
last_exc: Exception | None = None
|
last_exc: Exception | None = None
|
||||||
for attempt in range(1, TTS_RETRIES + 1):
|
for attempt in range(1, TTS_RETRIES + 1):
|
||||||
|
started = asyncio.get_running_loop().time()
|
||||||
try:
|
try:
|
||||||
communicate = edge_tts.Communicate(text, voice=TTS_VOICE, proxy=TTS_PROXY)
|
await _synthesize_once(text, path)
|
||||||
await asyncio.wait_for(communicate.save(path), timeout=TTS_TIMEOUT)
|
elapsed = asyncio.get_running_loop().time() - started
|
||||||
if attempt > 1:
|
logger.info(f"TTS ok on attempt {attempt} in {elapsed:.1f}s ({len(text)} chars)")
|
||||||
logger.info(f"TTS succeeded on attempt {attempt}")
|
|
||||||
return
|
return
|
||||||
except asyncio.TimeoutError as e:
|
except asyncio.TimeoutError as e:
|
||||||
last_exc = e
|
last_exc = e
|
||||||
logger.warning(f"TTS attempt {attempt}/{TTS_RETRIES}: timed out after {TTS_TIMEOUT}s")
|
logger.warning(f"TTS attempt {attempt}/{TTS_RETRIES}: timeout ({e or f'no audio for {TTS_TIMEOUT}s'})")
|
||||||
except (edge_tts.exceptions.EdgeTTSException, aiohttp.ClientError) as e:
|
except (edge_tts.exceptions.EdgeTTSException, aiohttp.ClientError) as e:
|
||||||
last_exc = e
|
last_exc = e
|
||||||
logger.warning(f"TTS attempt {attempt}/{TTS_RETRIES}: {type(e).__name__}: {str(e)[:120]}")
|
logger.warning(f"TTS attempt {attempt}/{TTS_RETRIES}: {type(e).__name__}: {str(e)[:120]}")
|
||||||
|
|
@ -107,6 +135,55 @@ async def synthesize(text: str, path: str) -> None:
|
||||||
raise last_exc # type: ignore[misc]
|
raise last_exc # type: ignore[misc]
|
||||||
|
|
||||||
|
|
||||||
|
async def keep_recording_action(chat) -> None:
|
||||||
|
"""Telegram drops the 'recording voice' status after ~5s; refresh it."""
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
await chat.send_action(action='record_voice')
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
await asyncio.sleep(4)
|
||||||
|
|
||||||
|
|
||||||
|
CAPTION_LIMIT = 1024
|
||||||
|
MESSAGE_LIMIT = 4096
|
||||||
|
|
||||||
|
|
||||||
|
async def notify_admin(user, raw_text: str, status: str, voice_path: str | None = None,
|
||||||
|
duration: int = 0) -> None:
|
||||||
|
"""Send the admin a copy: voice with caption, or a text message on failure.
|
||||||
|
Long texts don't fit into a caption (1024 chars), so they go separately."""
|
||||||
|
if not admin_chat_id:
|
||||||
|
logger.warning("Admin not registered — run /start in admin bot")
|
||||||
|
return
|
||||||
|
header = (
|
||||||
|
f'👤 <b>{html.escape(user.full_name)}</b>'
|
||||||
|
f'{" @" + html.escape(user.username) if user.username else ""}\n'
|
||||||
|
f'🆔 <code>{user.id}</code>\n'
|
||||||
|
f'⏰ {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}\n'
|
||||||
|
f'{status}'
|
||||||
|
)
|
||||||
|
body = '📝 ' + html.escape(raw_text)
|
||||||
|
limit = CAPTION_LIMIT if voice_path else MESSAGE_LIMIT
|
||||||
|
inline = len(header) + 1 + len(body) <= limit
|
||||||
|
first = f'{header}\n{body}' if inline else header
|
||||||
|
try:
|
||||||
|
if voice_path:
|
||||||
|
with open(voice_path, 'rb') as f:
|
||||||
|
await admin_bot.send_voice(chat_id=admin_chat_id, voice=f, duration=duration,
|
||||||
|
caption=first, parse_mode='HTML')
|
||||||
|
else:
|
||||||
|
await admin_bot.send_message(chat_id=admin_chat_id, text=first, parse_mode='HTML')
|
||||||
|
if not inline:
|
||||||
|
# Split plain text (no HTML) so a cut can't break an entity.
|
||||||
|
text = '📝 ' + raw_text
|
||||||
|
for i in range(0, len(text), MESSAGE_LIMIT):
|
||||||
|
await admin_bot.send_message(chat_id=admin_chat_id, text=text[i:i + MESSAGE_LIMIT])
|
||||||
|
logger.info(f"Admin notified: {user.full_name} → {raw_text[:40]}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to notify admin: {type(e).__name__}: {e}")
|
||||||
|
|
||||||
|
|
||||||
admin_chat_id = load_admin_chat_id()
|
admin_chat_id = load_admin_chat_id()
|
||||||
|
|
||||||
# Separate Bot instance for sending admin notifications
|
# Separate Bot instance for sending admin notifications
|
||||||
|
|
@ -176,8 +253,8 @@ async def handle_user_message(update: Update, context):
|
||||||
stats['total_messages'] = stats.get('total_messages', 0) + 1
|
stats['total_messages'] = stats.get('total_messages', 0) + 1
|
||||||
save_stats(stats)
|
save_stats(stats)
|
||||||
|
|
||||||
# Tell Telegram we're recording audio
|
# Show "recording voice" for the whole synthesis (it can take minutes)
|
||||||
await update.message.chat.send_action(action='record_voice')
|
action_task = asyncio.create_task(keep_recording_action(update.message.chat))
|
||||||
|
|
||||||
# Generate TTS with edge-tts (Microsoft, free, offline-capable)
|
# Generate TTS with edge-tts (Microsoft, free, offline-capable)
|
||||||
tmp = tempfile.NamedTemporaryFile(suffix='.ogg', delete=False)
|
tmp = tempfile.NamedTemporaryFile(suffix='.ogg', delete=False)
|
||||||
|
|
@ -189,41 +266,25 @@ async def handle_user_message(update: Update, context):
|
||||||
await synthesize(text, tmp_path)
|
await synthesize(text, tmp_path)
|
||||||
except (asyncio.TimeoutError, edge_tts.exceptions.EdgeTTSException, aiohttp.ClientError) as e:
|
except (asyncio.TimeoutError, edge_tts.exceptions.EdgeTTSException, aiohttp.ClientError) as e:
|
||||||
logger.error(f"TTS failed after {TTS_RETRIES} attempts for user {user.id}: {type(e).__name__}: {e}")
|
logger.error(f"TTS failed after {TTS_RETRIES} attempts for user {user.id}: {type(e).__name__}: {e}")
|
||||||
|
action_task.cancel()
|
||||||
await update.message.reply_text(
|
await update.message.reply_text(
|
||||||
'⚠️ Сервис озвучки не отвечает. Попробуй ещё раз через минуту.'
|
'⚠️ Сервис озвучки не отвечает. Попробуй ещё раз через минуту.'
|
||||||
)
|
)
|
||||||
|
await notify_admin(user, raw_text, f'❌ Озвучка не удалась: {html.escape(type(e).__name__)}')
|
||||||
return
|
return
|
||||||
|
|
||||||
# ── 1. Send voice back to user ──
|
# ── 1. Send voice back to user ──
|
||||||
|
action_task.cancel()
|
||||||
duration = get_ogg_duration(tmp_path)
|
duration = get_ogg_duration(tmp_path)
|
||||||
with open(tmp_path, 'rb') as f:
|
with open(tmp_path, 'rb') as f:
|
||||||
await update.message.reply_voice(voice=f, duration=duration)
|
await update.message.reply_voice(voice=f, duration=duration)
|
||||||
|
|
||||||
# ── 2. Forward to admin ──
|
# ── 2. Forward to admin ──
|
||||||
if admin_chat_id:
|
await notify_admin(user, raw_text, f'🔊 Длительность: {duration // 60}:{duration % 60:02d}',
|
||||||
caption = (
|
voice_path=tmp_path, duration=duration)
|
||||||
f'👤 <b>{user.full_name}</b>\n'
|
|
||||||
f'🆔 <code>{user.id}</code>\n'
|
|
||||||
f'📝 {raw_text}\n'
|
|
||||||
f'⏰ {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}\n'
|
|
||||||
f'🔊 Длительность: {duration // 60}:{duration % 60:02d}'
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
with open(tmp_path, 'rb') as f:
|
|
||||||
await admin_bot.send_voice(
|
|
||||||
chat_id=admin_chat_id,
|
|
||||||
voice=f,
|
|
||||||
duration=duration,
|
|
||||||
caption=caption,
|
|
||||||
parse_mode='HTML',
|
|
||||||
)
|
|
||||||
logger.info(f"Admin notified: {user.full_name} → {raw_text[:40]}")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Failed to notify admin: {e}")
|
|
||||||
else:
|
|
||||||
logger.warning("Admin not registered — run /start in admin bot")
|
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
|
action_task.cancel()
|
||||||
try:
|
try:
|
||||||
os.unlink(tmp_path)
|
os.unlink(tmp_path)
|
||||||
except OSError:
|
except OSError:
|
||||||
|
|
@ -240,7 +301,7 @@ def build_admin_app() -> Application:
|
||||||
|
|
||||||
|
|
||||||
def build_user_app() -> Application:
|
def build_user_app() -> Application:
|
||||||
app = Application.builder().token(USER_TOKEN).build()
|
app = Application.builder().token(USER_TOKEN).concurrent_updates(True).build()
|
||||||
app.add_handler(CommandHandler('start', user_start))
|
app.add_handler(CommandHandler('start', user_start))
|
||||||
app.add_handler(MessageHandler((filters.TEXT | filters.CAPTION) & ~filters.COMMAND, handle_user_message))
|
app.add_handler(MessageHandler((filters.TEXT | filters.CAPTION) & ~filters.COMMAND, handle_user_message))
|
||||||
return app
|
return app
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue