import asyncio import html import json import logging import os import re import tempfile from datetime import datetime import aiohttp import edge_tts import edge_tts.exceptions import emoji 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') # 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')) # 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_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') 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 def clean_text(text: str) -> str: text = emoji.replace_emoji(text, '') text = re.sub(r'@\S+\s*', '', text) text = re.sub(r'[ \t]+', ' ', text) text = re.sub(r'\n{2,}', '\n', text) text = re.sub(r'\n', ' ', text) text = text.strip() parts = re.split(r'(?<=[.!?])\s+', text) if parts and re.search(r'макс|max', parts[-1], re.IGNORECASE): text = ' '.join(p.strip() for p in parts[:-1] if p.strip()) if text: text += '\nКонец.' 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: """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): started = asyncio.get_running_loop().time() try: 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)") return except asyncio.TimeoutError as e: last_exc = e 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: 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] 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'👤 {html.escape(user.full_name)}' f'{" @" + html.escape(user.username) if user.username else ""}\n' f'🆔 {user.id}\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() # 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: {admin_chat_id}\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'📊 Статистика бота\n\n' f'👥 Уникальных пользователей: {unique}\n' f'🎤 Озвучено сообщений: {total}', parse_mode='HTML' ) # ────────────────────────── USER BOT ─────────────────────────── async def user_start(update: Update, context): await update.message.reply_text( '👋 Привет! Отправь мне текст, и я озвучу его ' 'голосом Дмитрия (ru-RU).\n\n' 'Просто пришли любое текстовое сообщение.', parse_mode='HTML' ) async def handle_user_message(update: Update, context): """Receive text/caption → TTS → reply voice → forward to admin.""" global admin_chat_id user = update.effective_user raw_text = update.message.text or update.message.caption if not raw_text: # Media without caption — silently ignore return text = clean_text(raw_text) if not text: return logger.info(f"User {user.full_name} (id={user.id}): {raw_text[:80]}") # 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) # Show "recording voice" for the whole synthesis (it can take minutes) action_task = asyncio.create_task(keep_recording_action(update.message.chat)) # Generate TTS with edge-tts (Microsoft, free, offline-capable) tmp = tempfile.NamedTemporaryFile(suffix='.ogg', delete=False) tmp_path = tmp.name tmp.close() try: try: 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}") action_task.cancel() await update.message.reply_text( '⚠️ Сервис озвучки не отвечает. Попробуй ещё раз через минуту.' ) await notify_admin(user, raw_text, f'❌ Озвучка не удалась: {html.escape(type(e).__name__)}') return # ── 1. Send voice back to user ── action_task.cancel() 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 ── await notify_admin(user, raw_text, f'🔊 Длительность: {duration // 60}:{duration % 60:02d}', voice_path=tmp_path, duration=duration) finally: action_task.cancel() 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: app = Application.builder().token(USER_TOKEN).concurrent_updates(True).build() app.add_handler(CommandHandler('start', user_start)) app.add_handler(MessageHandler((filters.TEXT | filters.CAPTION) & ~filters.COMMAND, handle_user_message)) 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...")