2026-06-03 18:39:05 +00:00
|
|
|
|
import asyncio
|
2026-10-22 10:51:39 +00:00
|
|
|
|
import html
|
2026-06-03 18:39:05 +00:00
|
|
|
|
import json
|
|
|
|
|
|
import logging
|
|
|
|
|
|
import os
|
2026-06-20 08:07:24 +00:00
|
|
|
|
import re
|
2026-06-03 18:39:05 +00:00
|
|
|
|
import tempfile
|
|
|
|
|
|
from datetime import datetime
|
|
|
|
|
|
|
2026-10-21 18:33:31 +00:00
|
|
|
|
import aiohttp
|
2026-06-03 18:39:05 +00:00
|
|
|
|
import edge_tts
|
2026-10-21 18:33:31 +00:00
|
|
|
|
import edge_tts.exceptions
|
2026-06-20 08:07:24 +00:00
|
|
|
|
import emoji
|
2026-06-03 18:39:05 +00:00
|
|
|
|
from mutagen.mp3 import MP3
|
|
|
|
|
|
from telegram import Bot, Update
|
|
|
|
|
|
from telegram.ext import Application, CommandHandler, MessageHandler, filters
|
|
|
|
|
|
|
|
|
|
|
|
logging.basicConfig(
|
|
|
|
|
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
|
|
|
|
|
level=logging.INFO
|
|
|
|
|
|
)
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
USER_TOKEN = os.environ['USER_BOT_TOKEN']
|
|
|
|
|
|
ADMIN_TOKEN = os.environ['ADMIN_BOT_TOKEN']
|
|
|
|
|
|
TTS_VOICE = os.environ.get('TTS_VOICE', 'ru-RU-DmitryNeural')
|
2026-10-22 10:51:39 +00:00
|
|
|
|
# Max silence between audio chunks. From RU IPs Microsoft streams audio at
|
|
|
|
|
|
# roughly real-time speed, so a total timeout would kill long texts.
|
2026-08-27 20:07:32 +00:00
|
|
|
|
TTS_TIMEOUT = int(os.environ.get('TTS_TIMEOUT', '30'))
|
2026-10-22 10:51:39 +00:00
|
|
|
|
# Hard cap for the whole synthesis of one attempt.
|
|
|
|
|
|
TTS_TOTAL_TIMEOUT = int(os.environ.get('TTS_TOTAL_TIMEOUT', '900'))
|
2026-10-21 18:33:31 +00:00
|
|
|
|
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)
|
2026-06-03 18:39:05 +00:00
|
|
|
|
DATA_DIR = os.environ.get('DATA_DIR', '/app/data')
|
|
|
|
|
|
os.makedirs(DATA_DIR, exist_ok=True)
|
|
|
|
|
|
|
|
|
|
|
|
ADMIN_CHAT_ID_FILE = os.path.join(DATA_DIR, 'admin_chat_id.txt')
|
|
|
|
|
|
STATS_FILE = os.path.join(DATA_DIR, 'stats.json')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def load_admin_chat_id():
|
|
|
|
|
|
try:
|
|
|
|
|
|
with open(ADMIN_CHAT_ID_FILE) as f:
|
|
|
|
|
|
return int(f.read().strip())
|
|
|
|
|
|
except (FileNotFoundError, ValueError):
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def save_admin_chat_id(chat_id):
|
|
|
|
|
|
with open(ADMIN_CHAT_ID_FILE, 'w') as f:
|
|
|
|
|
|
f.write(str(chat_id))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def load_stats():
|
|
|
|
|
|
try:
|
|
|
|
|
|
with open(STATS_FILE) as f:
|
|
|
|
|
|
return json.load(f)
|
|
|
|
|
|
except (FileNotFoundError, json.JSONDecodeError):
|
|
|
|
|
|
return {"users": [], "total_messages": 0}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def save_stats(stats):
|
|
|
|
|
|
with open(STATS_FILE, 'w') as f:
|
|
|
|
|
|
json.dump(stats, f)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_ogg_duration(path: str) -> int:
|
|
|
|
|
|
"""Read audio duration in seconds (MP3 from edge-tts v7)."""
|
|
|
|
|
|
try:
|
|
|
|
|
|
audio = MP3(path)
|
|
|
|
|
|
return int(audio.info.length)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
logger.warning(f"Could not read duration from {path}")
|
|
|
|
|
|
return 0
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-06-20 08:07:24 +00:00
|
|
|
|
def clean_text(text: str) -> str:
|
|
|
|
|
|
text = emoji.replace_emoji(text, '')
|
2026-06-20 08:20:57 +00:00
|
|
|
|
text = re.sub(r'@\S+\s*', '', text)
|
2026-06-20 08:07:24 +00:00
|
|
|
|
text = re.sub(r'[ \t]+', ' ', text)
|
|
|
|
|
|
text = re.sub(r'\n{2,}', '\n', text)
|
2026-06-20 08:26:28 +00:00
|
|
|
|
text = re.sub(r'\n', ' ', text)
|
2026-06-20 08:07:24 +00:00
|
|
|
|
text = text.strip()
|
2026-06-20 08:26:28 +00:00
|
|
|
|
|
|
|
|
|
|
parts = re.split(r'(?<=[.!?])\s+', text)
|
2026-06-20 08:32:33 +00:00
|
|
|
|
if parts and re.search(r'макс|max', parts[-1], re.IGNORECASE):
|
2026-06-20 08:26:28 +00:00
|
|
|
|
text = ' '.join(p.strip() for p in parts[:-1] if p.strip())
|
|
|
|
|
|
|
2026-06-20 08:07:24 +00:00
|
|
|
|
if text:
|
2026-06-20 13:25:40 +00:00
|
|
|
|
text += '\nКонец.'
|
2026-06-20 08:07:24 +00:00
|
|
|
|
return text
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-10-22 10:51:39 +00:00
|
|
|
|
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()
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-10-21 18:33:31 +00:00
|
|
|
|
async def synthesize(text: str, path: str) -> None:
|
|
|
|
|
|
"""Run edge-tts with retries: Microsoft intermittently answers 403 /
|
|
|
|
|
|
NoAudioReceived (especially from RU IPs), so one attempt is not enough."""
|
|
|
|
|
|
last_exc: Exception | None = None
|
|
|
|
|
|
for attempt in range(1, TTS_RETRIES + 1):
|
2026-10-22 10:51:39 +00:00
|
|
|
|
started = asyncio.get_running_loop().time()
|
2026-10-21 18:33:31 +00:00
|
|
|
|
try:
|
2026-10-22 10:51:39 +00:00
|
|
|
|
await _synthesize_once(text, path)
|
|
|
|
|
|
elapsed = asyncio.get_running_loop().time() - started
|
|
|
|
|
|
logger.info(f"TTS ok on attempt {attempt} in {elapsed:.1f}s ({len(text)} chars)")
|
2026-10-21 18:33:31 +00:00
|
|
|
|
return
|
|
|
|
|
|
except asyncio.TimeoutError as e:
|
|
|
|
|
|
last_exc = e
|
2026-10-22 10:51:39 +00:00
|
|
|
|
logger.warning(f"TTS attempt {attempt}/{TTS_RETRIES}: timeout ({e or f'no audio for {TTS_TIMEOUT}s'})")
|
2026-10-21 18:33:31 +00:00
|
|
|
|
except (edge_tts.exceptions.EdgeTTSException, aiohttp.ClientError) as e:
|
|
|
|
|
|
last_exc = e
|
|
|
|
|
|
logger.warning(f"TTS attempt {attempt}/{TTS_RETRIES}: {type(e).__name__}: {str(e)[:120]}")
|
|
|
|
|
|
await asyncio.sleep(1)
|
|
|
|
|
|
raise last_exc # type: ignore[misc]
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-10-22 10:51:39 +00:00
|
|
|
|
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}")
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-06-03 18:39:05 +00:00
|
|
|
|
admin_chat_id = load_admin_chat_id()
|
|
|
|
|
|
|
|
|
|
|
|
# Separate Bot instance for sending admin notifications
|
|
|
|
|
|
admin_bot = Bot(token=ADMIN_TOKEN)
|
|
|
|
|
|
|
|
|
|
|
|
# ────────────────────────── ADMIN BOT ──────────────────────────
|
|
|
|
|
|
|
|
|
|
|
|
async def admin_start(update: Update, context):
|
|
|
|
|
|
"""Capture admin chat ID on /start and persist."""
|
|
|
|
|
|
global admin_chat_id
|
|
|
|
|
|
admin_chat_id = update.effective_chat.id
|
|
|
|
|
|
save_admin_chat_id(admin_chat_id)
|
|
|
|
|
|
await update.message.reply_text(
|
|
|
|
|
|
f'✅ Админ-панель готова.\n'
|
|
|
|
|
|
f'Твой chat_id: <code>{admin_chat_id}</code>\n\n'
|
|
|
|
|
|
f'Сюда будут приходить все озвучки пользователей.\n'
|
|
|
|
|
|
f'Используй /stat для статистики.',
|
|
|
|
|
|
parse_mode='HTML'
|
|
|
|
|
|
)
|
|
|
|
|
|
logger.info(f"Admin registered: chat_id={admin_chat_id}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def admin_stat(update: Update, context):
|
|
|
|
|
|
"""Show bot usage statistics."""
|
|
|
|
|
|
s = load_stats()
|
|
|
|
|
|
unique = len(s['users'])
|
|
|
|
|
|
total = s['total_messages']
|
|
|
|
|
|
await update.message.reply_text(
|
|
|
|
|
|
f'📊 <b>Статистика бота</b>\n\n'
|
|
|
|
|
|
f'👥 Уникальных пользователей: <b>{unique}</b>\n'
|
|
|
|
|
|
f'🎤 Озвучено сообщений: <b>{total}</b>',
|
|
|
|
|
|
parse_mode='HTML'
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ────────────────────────── USER BOT ───────────────────────────
|
|
|
|
|
|
|
|
|
|
|
|
async def user_start(update: Update, context):
|
|
|
|
|
|
await update.message.reply_text(
|
|
|
|
|
|
'👋 Привет! Отправь мне текст, и я озвучу его '
|
|
|
|
|
|
'голосом <b>Дмитрия</b> (ru-RU).\n\n'
|
|
|
|
|
|
'Просто пришли любое текстовое сообщение.',
|
|
|
|
|
|
parse_mode='HTML'
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def handle_user_message(update: Update, context):
|
2026-06-03 18:43:02 +00:00
|
|
|
|
"""Receive text/caption → TTS → reply voice → forward to admin."""
|
2026-06-03 18:39:05 +00:00
|
|
|
|
global admin_chat_id
|
|
|
|
|
|
user = update.effective_user
|
2026-06-20 08:07:24 +00:00
|
|
|
|
raw_text = update.message.text or update.message.caption
|
2026-06-03 18:43:02 +00:00
|
|
|
|
|
2026-06-20 08:07:24 +00:00
|
|
|
|
if not raw_text:
|
2026-06-03 18:43:02 +00:00
|
|
|
|
# Media without caption — silently ignore
|
|
|
|
|
|
return
|
2026-06-03 18:39:05 +00:00
|
|
|
|
|
2026-06-20 08:07:24 +00:00
|
|
|
|
text = clean_text(raw_text)
|
|
|
|
|
|
if not text:
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
logger.info(f"User {user.full_name} (id={user.id}): {raw_text[:80]}")
|
2026-06-03 18:39:05 +00:00
|
|
|
|
|
|
|
|
|
|
# Track stats
|
|
|
|
|
|
stats = load_stats()
|
|
|
|
|
|
if user.id not in stats['users']:
|
|
|
|
|
|
stats['users'].append(user.id)
|
|
|
|
|
|
stats['total_messages'] = stats.get('total_messages', 0) + 1
|
|
|
|
|
|
save_stats(stats)
|
|
|
|
|
|
|
2026-10-22 10:51:39 +00:00
|
|
|
|
# Show "recording voice" for the whole synthesis (it can take minutes)
|
|
|
|
|
|
action_task = asyncio.create_task(keep_recording_action(update.message.chat))
|
2026-06-03 18:39:05 +00:00
|
|
|
|
|
|
|
|
|
|
# Generate TTS with edge-tts (Microsoft, free, offline-capable)
|
|
|
|
|
|
tmp = tempfile.NamedTemporaryFile(suffix='.ogg', delete=False)
|
|
|
|
|
|
tmp_path = tmp.name
|
|
|
|
|
|
tmp.close()
|
|
|
|
|
|
|
|
|
|
|
|
try:
|
2026-08-27 20:07:32 +00:00
|
|
|
|
try:
|
2026-10-21 18:33:31 +00:00
|
|
|
|
await synthesize(text, tmp_path)
|
|
|
|
|
|
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}")
|
2026-10-22 10:51:39 +00:00
|
|
|
|
action_task.cancel()
|
2026-08-27 20:07:32 +00:00
|
|
|
|
await update.message.reply_text(
|
|
|
|
|
|
'⚠️ Сервис озвучки не отвечает. Попробуй ещё раз через минуту.'
|
|
|
|
|
|
)
|
2026-10-22 10:51:39 +00:00
|
|
|
|
await notify_admin(user, raw_text, f'❌ Озвучка не удалась: {html.escape(type(e).__name__)}')
|
2026-08-27 20:07:32 +00:00
|
|
|
|
return
|
2026-06-03 18:39:05 +00:00
|
|
|
|
|
|
|
|
|
|
# ── 1. Send voice back to user ──
|
2026-10-22 10:51:39 +00:00
|
|
|
|
action_task.cancel()
|
2026-06-03 18:39:05 +00:00
|
|
|
|
duration = get_ogg_duration(tmp_path)
|
|
|
|
|
|
with open(tmp_path, 'rb') as f:
|
|
|
|
|
|
await update.message.reply_voice(voice=f, duration=duration)
|
|
|
|
|
|
|
|
|
|
|
|
# ── 2. Forward to admin ──
|
2026-10-22 10:51:39 +00:00
|
|
|
|
await notify_admin(user, raw_text, f'🔊 Длительность: {duration // 60}:{duration % 60:02d}',
|
|
|
|
|
|
voice_path=tmp_path, duration=duration)
|
2026-06-03 18:39:05 +00:00
|
|
|
|
|
|
|
|
|
|
finally:
|
2026-10-22 10:51:39 +00:00
|
|
|
|
action_task.cancel()
|
2026-06-03 18:39:05 +00:00
|
|
|
|
try:
|
|
|
|
|
|
os.unlink(tmp_path)
|
|
|
|
|
|
except OSError:
|
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# ────────────────────────── SETUP ──────────────────────────────
|
|
|
|
|
|
|
|
|
|
|
|
def build_admin_app() -> Application:
|
|
|
|
|
|
app = Application.builder().token(ADMIN_TOKEN).build()
|
|
|
|
|
|
app.add_handler(CommandHandler('start', admin_start))
|
|
|
|
|
|
app.add_handler(CommandHandler('stat', admin_stat))
|
|
|
|
|
|
return app
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def build_user_app() -> Application:
|
2026-10-22 10:51:39 +00:00
|
|
|
|
app = Application.builder().token(USER_TOKEN).concurrent_updates(True).build()
|
2026-06-03 18:39:05 +00:00
|
|
|
|
app.add_handler(CommandHandler('start', user_start))
|
2026-06-03 18:43:02 +00:00
|
|
|
|
app.add_handler(MessageHandler((filters.TEXT | filters.CAPTION) & ~filters.COMMAND, handle_user_message))
|
2026-06-03 18:39:05 +00:00
|
|
|
|
return app
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def main():
|
|
|
|
|
|
admin_app = build_admin_app()
|
|
|
|
|
|
user_app = build_user_app()
|
|
|
|
|
|
|
|
|
|
|
|
# Run both bots concurrently
|
|
|
|
|
|
async with admin_app:
|
|
|
|
|
|
await admin_app.initialize()
|
|
|
|
|
|
await admin_app.start()
|
|
|
|
|
|
await admin_app.updater.start_polling()
|
|
|
|
|
|
logger.info("Admin bot polling started")
|
|
|
|
|
|
|
|
|
|
|
|
async with user_app:
|
|
|
|
|
|
await user_app.initialize()
|
|
|
|
|
|
await user_app.start()
|
|
|
|
|
|
await user_app.updater.start_polling()
|
|
|
|
|
|
logger.info("User bot polling started")
|
|
|
|
|
|
|
|
|
|
|
|
# Keep alive
|
|
|
|
|
|
while True:
|
|
|
|
|
|
await asyncio.sleep(3600)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
|
|
try:
|
|
|
|
|
|
asyncio.run(main())
|
|
|
|
|
|
except (KeyboardInterrupt, SystemExit):
|
|
|
|
|
|
logger.info("Shutting down gracefully...")
|