Spaces:
Running on Zero
Running on Zero
File size: 8,738 Bytes
8ce9e44 34b6c2c 8ce9e44 75b7d18 8ce9e44 011d740 8ce9e44 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 | import asyncio
import os
import sys
import time
import logging
import subprocess
from aiohttp import web
from pyrogram import Client, filters, idle
from pyrogram.types import (
InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery, Message
)
from pyrogram.errors import MessageNotModified
# Configuraciones y DB
from config import API_ID, API_HASH, BOT_TOKEN, DOWNLOAD_DIR
from database import get_config
from firebase_service import save_user_config_fb
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# --- WEB SERVER (Página Fantasma - Minimalista) ---
async def handle_health(request):
html = """
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MP3 Extractor | Stealth</title>
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;900&display=swap" rel="stylesheet">
<style>
body { margin: 0; padding: 0; background: #000; color: #fff; font-family: 'Outfit', sans-serif; height: 100vh; display: flex; align-items: center; justify-content: center; overflow: hidden; }
.glow { position: absolute; width: 400px; height: 400px; background: radial-gradient(circle, rgba(255,255,255,0.05) 0%, transparent 70%); animation: pulse 4s infinite alternate; }
@keyframes pulse { from { transform: scale(1); opacity: 0.3; } to { transform: scale(1.5); opacity: 0.1; } }
.content { text-align: center; z-index: 10; cursor: pointer; }
h1 { font-size: 3rem; font-weight: 900; letter-spacing: -0.05em; margin-bottom: 0.5rem; }
p { font-size: 0.9rem; letter-spacing: 0.4em; text-transform: uppercase; opacity: 0.4; }
</style>
</head>
<body onclick="location.href='https://t.me/SmartVideoSplitterBot'">
<div class="glow"></div>
<div class="content">
<h1>MP3 EXTRACTOR</h1>
<p>System Status: Active</p>
</div>
</body>
</html>
"""
return web.Response(text=html, content_type='text/html')
async def start_web_server():
try:
app_web = web.Application()
app_web.router.add_get('/', handle_health)
runner = web.AppRunner(app_web)
await runner.setup()
port = int(os.environ.get("WEB_PORT", 8080))
site = web.TCPSite(runner, '0.0.0.0', port)
await site.start()
logger.info(f"Web server running on port {port}")
except Exception as e:
logger.warning(f"Web server exception ignored: {e}")
# --- PYROGRAM CLIENT ---
WORKDIR = "sessions"
if not os.path.exists(WORKDIR): os.makedirs(WORKDIR)
# WORKDIR = "sessions"
app = Client("brody_base_bot_v2", api_id=int(API_ID), api_hash=API_HASH, bot_token=BOT_TOKEN, workers=100, in_memory=True)
# --- LÓGICA DE EXTRACCIÓN MP3 ---
SEM_EXTRACT = asyncio.Semaphore(1) # Máximo 1 proceso FFmpeg (Mejor estabilidad en CPU limitada)
USER_PROCESSING_LOCKS = {}
async def extract_audio_task(client, message, msg_status):
chat_id = message.chat.id
if chat_id not in USER_PROCESSING_LOCKS:
USER_PROCESSING_LOCKS[chat_id] = asyncio.Lock()
async with USER_PROCESSING_LOCKS[chat_id]:
async with SEM_EXTRACT:
try:
await msg_status.edit("⬇️ **Descargando...**")
from tools_media import fast_download, get_meta, get_thumb
job_dir = os.path.join(DOWNLOAD_DIR, f"mp3_{chat_id}_{int(time.time())}")
os.makedirs(job_dir, exist_ok=True)
media = message.document or message.video
orig_name = getattr(media, "file_name", None)
if not orig_name:
orig_name = f"vid_{int(time.time())}.mp4"
logger.info(f"[DEBUG] Media details: type={type(media)}, file_name={getattr(media, 'file_name', None)}")
logger.info(f"[DEBUG] Resolved orig_name: {orig_name}")
logger.info(f"[DEBUG] job_dir: {job_dir}")
input_path = os.path.join(job_dir, orig_name)
path = await fast_download(client, message, input_path, msg_status, "Descargando")
if not path:
await msg_status.edit("❌ Error al descargar."); return
# Mejorado: Detectar info y extraer carátula
await msg_status.edit("🔍 **Analizando...**")
w, h, dur = await get_meta(path)
thumb_path = await get_thumb(path, chat_id, int(time.time()), duration=dur)
output_mp3 = os.path.join(job_dir, os.path.splitext(orig_name)[0] + ".mp3")
await msg_status.edit("⚡ **Extrayendo Audio (Turbo)...**")
# Comando optimizado
cmd = [
"ffmpeg", "-i", path, "-vn",
"-acodec", "libmp3lame", "-q:a", "2",
"-map_metadata", "0",
"-threads", "0",
"-y", output_mp3
]
proc = await asyncio.create_subprocess_exec(
*cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await proc.communicate()
if not os.path.exists(output_mp3) or os.path.getsize(output_mp3) < 1000:
err_msg = stderr.decode()[-200:] if stderr else "Error desconocido"
logger.error(f"FFmpeg Error: {err_msg}")
await msg_status.edit(f"❌ Fallo en la extracción.\n`{err_msg}`")
return
# Enviar con CARÁTULA y METADATOS
await msg_status.edit("📤 **Enviando MP3 Premium...**")
from tools_media import progreso
await client.send_audio(
chat_id, output_mp3,
thumb=thumb_path,
duration=dur,
performer="Brody Extractor",
title=os.path.splitext(orig_name)[0],
caption=f"🎵 **Audio Extraído**\n🎬 `{orig_name}`",
progress=progreso, progress_args=(msg_status, [time.time(), 0], "Subiendo")
)
await msg_status.delete()
# Limpieza
if thumb_path and os.path.exists(thumb_path): os.remove(thumb_path)
import shutil; shutil.rmtree(job_dir, ignore_errors=True)
except Exception as e:
await msg_status.edit(f"❌ Error: {e}")
# --- MENÚS ---
async def send_panel(client, chat_id, message_id=None):
kb = InlineKeyboardMarkup([[InlineKeyboardButton("🎯 Sistema de Extracción Activo", callback_data="none")]])
txt = "🎧 **Extractor MP3 PRO**\n\nEnvía cualquier video o archivo y extraeré su audio al instante.\n\n✅ **Estado**: En línea y procesando."
if message_id: await client.edit_message_text(chat_id, message_id, txt, reply_markup=kb)
else: await client.send_message(chat_id, txt, reply_markup=kb)
@app.on_message(filters.command("start") & filters.private)
async def start_cmd(c, m): await send_panel(c, m.chat.id)
@app.on_message((filters.video | filters.document) & filters.private)
async def media_handler(c, m):
if m.document and not m.document.mime_type.startswith("video"): return
msg_status = await m.reply("⏳ **En cola...** Esperando turno.")
asyncio.create_task(extract_audio_task(c, m, msg_status))
@app.on_message(filters.command("help") & filters.private)
async def help_cmd(c, m):
await m.reply(
"🎧 **Twisted Audio Help**\n\n"
"Este bot extrae el audio de tus videos automáticamente.\n\n"
"✅ **Cómo usar**: Solo envíame un video o un archivo de video.\n"
"✅ **Calidad**: MP3 Premium con carátula y metadatos.\n"
"✅ **Cola**: Si envías varios, los procesaré uno por uno en orden."
)
async def main():
await start_web_server(); await app.start()
try:
from pyrogram.types import BotCommand
await app.set_bot_commands([
BotCommand("start", "⚙️ Panel Principal"),
BotCommand("help", "❓ Ayuda e Instrucciones")
])
except: pass
await idle(); await app.stop()
if __name__ == "__main__": app.run(main()) |