Spaces:
Paused
Paused
Download main.py from saske560/Compresas-2: direct link, hf CLI and curl.
- Browser
- Download file 206 kB
-
https://huggingface.co/spaces/saske560/Compresas-2/resolve/main/main.py
- Command line
-
hf download hf://spaces/saske560/Compresas-2/main.py
-
curl -L -o main.py https://huggingface.co/spaces/saske560/Compresas-2/resolve/main/main.py
206 kB
import os
import asyncio
import logging
import time
import random
import contextlib
import gc
from collections import deque
import re
import subprocess
import json
import shutil
import tempfile
import zipfile
from typing import Optional, Dict, Any, List
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from urllib.parse import quote_plus, urlparse
try:
from dotenv import load_dotenv
except Exception:
def load_dotenv(*args, **kwargs):
return False
import asyncpg
import psutil
from pyrogram import Client, filters
from pyrogram.types import (
Message, InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
)
# =====================
# CONFIGURACIÓN
# =====================
load_dotenv()
API_ID = os.environ.get("API_ID", "24288670")
API_HASH = os.environ.get("API_HASH", "81c58005802498656d6b689dae1edacc")
BOT_TOKEN = os.environ.get("BOT_TOKEN", "")
BOT_VERSION = "V.6 Ultra Supabase"
BOT_CREATOR = "@Sasuke286"
SUPABASE_URL = os.environ.get("SUPABASE_URL", "https://lkqihreksoitujnwanik.supabase.co")
SUPABASE_PUBLISHABLE_KEY = os.environ.get("SUPABASE_PUBLISHABLE_KEY", "")
SUPABASE_SERVICE_ROLE_KEY = os.environ.get("SUPABASE_SERVICE_ROLE_KEY", "")
SUPABASE_DB_PASSWORD = os.environ.get("SUPABASE_DB_PASSWORD", "")
SUPABASE_PROJECT_REF = os.environ.get("SUPABASE_PROJECT_REF") or (urlparse(SUPABASE_URL).hostname or "").split(".")[0]
DATABASE_URL = os.environ.get("DATABASE_URL", "").strip()
SUPABASE_DB_URL = os.environ.get("SUPABASE_DB_URL", "").strip() or DATABASE_URL
SUPABASE_POOLER_URL = os.environ.get("SUPABASE_POOLER_URL", "").strip()
SUPABASE_DIRECT_URL = os.environ.get("SUPABASE_DIRECT_URL", "").strip()
SUPABASE_POOL_MODE = os.environ.get("SUPABASE_POOL_MODE", "session").strip().lower() or "session"
SUPABASE_USE_TRANSACTION_POOLER = SUPABASE_POOL_MODE == "transaction"
DB_NAME = f"supabase:{SUPABASE_PROJECT_REF or 'unknown'}"
def _redact_db_url(url: str) -> str:
if not url:
return ""
return re.sub(r"://([^:]+):([^@]+)@", r"://\1:***@", url)
def _looks_like_direct_supabase_url(url: str) -> bool:
if not url:
return False
host = (urlparse(url).hostname or "").lower()
return host.startswith("db.") and host.endswith(".supabase.co")
def _build_default_supabase_db_url() -> str:
if SUPABASE_DB_URL:
return SUPABASE_DB_URL
if SUPABASE_POOLER_URL:
return SUPABASE_POOLER_URL
if SUPABASE_DIRECT_URL:
return SUPABASE_DIRECT_URL
if not SUPABASE_PROJECT_REF or not SUPABASE_DB_PASSWORD:
return ""
# Último recurso: conexión directa. Si tu hosting es IPv4-only, el error posterior te indicará que uses el pooler.
return f"postgresql://postgres:{quote_plus(SUPABASE_DB_PASSWORD)}@db.{SUPABASE_PROJECT_REF}.supabase.co:5432/postgres?sslmode=require"
SUPER_ADMINS_STATIC = [5702506445]
# =====================
# CALIDADES PREDEFINIDAS
# Siempre reducen el tamaño del archivo
# =====================
QUALITY_PRESETS = {
"144p": {"resolution": "256x144", "crf": "38", "audio_bitrate": "48k", "fps": "24", "preset": "ultrafast", "codec": "libx265", "label": "144p — Mínimo tamaño"},
"240p": {"resolution": "426x240", "crf": "36", "audio_bitrate": "56k", "fps": "24", "preset": "ultrafast", "codec": "libx265", "label": "240p — Muy ligero"},
"360p": {"resolution": "640x360", "crf": "33", "audio_bitrate": "64k", "fps": "25", "preset": "ultrafast", "codec": "libx265", "label": "360p — Ligero"},
"480p": {"resolution": "854x480", "crf": "30", "audio_bitrate": "80k", "fps": "28", "preset": "ultrafast", "codec": "libx265", "label": "480p — Equilibrado ⭐"},
"720p": {"resolution": "1280x720", "crf": "28", "audio_bitrate": "96k", "fps": "30", "preset": "ultrafast", "codec": "libx265", "label": "720p — HD"},
"1080p": {"resolution": "1920x1080","crf": "26", "audio_bitrate": "128k", "fps": "30", "preset": "ultrafast", "codec": "libx265", "label": "1080p — Full HD"},
}
DEFAULT_QUALITY = QUALITY_PRESETS["480p"].copy()
DEFAULT_QUALITY.pop("label", None)
DEFAULT_PLANS = {
"free": {
"name": "🆓 Free",
"max_file_size_mb": 200,
"daily_videos": 5,
"queue_priority": False,
"custom_quality": False,
"own_queue": False,
},
"basic": {
"name": "⭐ Basic",
"max_file_size_mb": 500,
"daily_videos": 20,
"queue_priority": False,
"custom_quality": True,
"own_queue": True,
},
"pro": {
"name": "💎 Pro",
"max_file_size_mb": 2000,
"daily_videos": 100,
"queue_priority": True,
"custom_quality": True,
"own_queue": True,
},
"premium": {
"name": "👑 Premium",
"max_file_size_mb": 4000,
"daily_videos": 500,
"queue_priority": True,
"custom_quality": True,
"own_queue": True,
},
"admin": {
"name": "🛡️ Admin",
"max_file_size_mb": 999999,
"daily_videos": 999999,
"queue_priority": True,
"custom_quality": True,
"own_queue": True,
},
"superadmin": {
"name": "⚡ SuperAdmin",
"max_file_size_mb": 999999,
"daily_videos": 999999,
"queue_priority": True,
"custom_quality": True,
"own_queue": True,
},
}
PLANS: Dict[str, dict] = {k: dict(v) for k, v in DEFAULT_PLANS.items()}
BOT_MODE: str = "private"
INDIVIDUAL_QUEUES_ENABLED: bool = True
VIDEO_EXTENSIONS = {
".mp4", ".mkv", ".mpg", ".mpeg", ".ts", ".m2ts", ".mts",
".mov", ".avi", ".wmv", ".flv", ".webm", ".m4v", ".3gp", ".vob", ".ogv",
}
PROGRESS_EDIT_EVERY = 5
TRANSFER_PROGRESS_MIN_INTERVAL = max(2.0, float(os.environ.get("TRANSFER_PROGRESS_MIN_INTERVAL", "3.0")))
TRANSFER_SPEED_WINDOW_SECONDS = max(1.0, float(os.environ.get("TRANSFER_SPEED_WINDOW_SECONDS", "3.0")))
MAX_CPU_PERCENT = max(50, min(95, int(os.environ.get("MAX_CPU_PERCENT", "85"))))
CPU_MONITOR_INTERVAL = max(0.5, float(os.environ.get("CPU_MONITOR_INTERVAL", "2.0")))
COMPRESS_STALL_SECONDS = max(120, int(os.environ.get("COMPRESS_STALL_SECONDS", "420")))
COMPRESS_START_GRACE_SECONDS = max(60, int(os.environ.get("COMPRESS_START_GRACE_SECONDS", "120")))
FFMPEG_OUTPUT_IDLE_SECONDS = max(45, int(os.environ.get("FFMPEG_OUTPUT_IDLE_SECONDS", "120")))
STALL_CPU_FLOOR_PERCENT = max(0.5, float(os.environ.get("STALL_CPU_FLOOR_PERCENT", "2.0")))
UPLOAD_STALL_SECONDS = max(300, int(os.environ.get("UPLOAD_STALL_SECONDS", "1800")))
UPLOAD_HEARTBEAT_EVERY = max(5.0, float(os.environ.get("UPLOAD_HEARTBEAT_EVERY", "15.0")))
UPLOAD_HARD_TIMEOUT_SECONDS = max(900, int(os.environ.get("UPLOAD_HARD_TIMEOUT_SECONDS", "7200")))
FINALIZE_GRACE_SECONDS = max(120, int(os.environ.get("FINALIZE_GRACE_SECONDS", "900")))
QUEUE_WATCHDOG_INTERVAL = max(2.0, float(os.environ.get("QUEUE_WATCHDOG_INTERVAL", "5.0")))
CPU_LIMIT_HEADROOM_PERCENT = max(1, min(15, int(os.environ.get("CPU_LIMIT_HEADROOM_PERCENT", "4"))))
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)
BASE_DIR = "/app"
DOWNLOADS_DIR = os.path.join(BASE_DIR, "downloads")
COMPRESSED_DIR = os.path.join(BASE_DIR, "compressed")
SESSION_DIR = os.path.join(BASE_DIR, "session")
BACKUPS_DIR = os.path.join(BASE_DIR, "backups")
os.makedirs(DOWNLOADS_DIR, exist_ok=True)
os.makedirs(COMPRESSED_DIR, exist_ok=True)
os.makedirs(SESSION_DIR, exist_ok=True)
os.makedirs(BACKUPS_DIR, exist_ok=True)
def _usable_cpu_ids() -> List[int]:
try:
proc = psutil.Process()
affinity = proc.cpu_affinity()
if affinity:
return sorted(int(cpu) for cpu in affinity)
except Exception:
pass
try:
affinity = os.sched_getaffinity(0)
if affinity:
return sorted(int(cpu) for cpu in affinity)
except Exception:
pass
cpu_count = psutil.cpu_count(logical=True) or (os.cpu_count() or 1)
return list(range(max(1, cpu_count)))
def _try_read_text(path: str) -> Optional[str]:
try:
with open(path, "r", encoding="utf-8", errors="replace") as f:
return f.read().strip()
except Exception:
return None
def _parse_cgroup_cpu_max(text: str) -> Optional[float]:
try:
parts = (text or "").strip().split()
if len(parts) < 2:
return None
quota_s, period_s = parts[0], parts[1]
if quota_s == "max":
return None
quota = int(quota_s)
period = int(period_s)
if quota <= 0 or period <= 0:
return None
return quota / period
except Exception:
return None
def _cgroup_paths() -> List[str]:
paths: List[str] = []
try:
with open("/proc/self/cgroup", "r", encoding="utf-8", errors="replace") as f:
for line in f:
line = line.strip()
if not line:
continue
parts = line.split(":")
if len(parts) != 3:
continue
_, controllers, cgrp_path = parts
if controllers == "":
paths.append(cgrp_path or "/")
else:
ctrls = set((controllers or "").split(","))
if "cpu" in ctrls:
paths.append(cgrp_path or "/")
except Exception:
pass
out: List[str] = []
for path in paths:
if path not in out:
out.append(path)
if "/" not in out:
out.append("/")
return out
def _cgroup_cpu_quota_cpus() -> Optional[float]:
candidates = ["/sys/fs/cgroup/cpu.max"]
for rel in _cgroup_paths():
if rel and rel != "/":
candidates.append(f"/sys/fs/cgroup{rel}/cpu.max")
for path in candidates:
txt = _try_read_text(path)
if not txt:
continue
if txt.split()[0] == "max":
return None
cpus = _parse_cgroup_cpu_max(txt)
if cpus is not None and cpus > 0:
return cpus
quota_pairs: List[tuple[str, str]] = []
for base in ("/sys/fs/cgroup/cpu", "/sys/fs/cgroup/cpu,cpuacct", "/sys/fs/cgroup"):
quota_pairs.append((f"{base}/cpu.cfs_quota_us", f"{base}/cpu.cfs_period_us"))
for rel in _cgroup_paths():
if rel and rel != "/":
for base in ("/sys/fs/cgroup/cpu", "/sys/fs/cgroup/cpu,cpuacct"):
quota_pairs.append((f"{base}{rel}/cpu.cfs_quota_us", f"{base}{rel}/cpu.cfs_period_us"))
for qpath, ppath in quota_pairs:
qtxt = _try_read_text(qpath)
ptxt = _try_read_text(ppath)
if not qtxt or not ptxt:
continue
try:
quota = int(qtxt)
period = int(ptxt)
if quota < 0:
return None
if quota == 0 or period <= 0:
continue
cpus = quota / period
if cpus > 0:
return cpus
except Exception:
continue
return None
def _effective_cpu_capacity() -> float:
usable = float(len(_usable_cpu_ids()) or 1)
quota = _cgroup_cpu_quota_cpus()
if quota is not None and quota > 0:
usable = min(usable, quota)
return max(1.0, usable)
def _max_parallel_cpu_slots() -> int:
usable_affinity = len(_usable_cpu_ids()) or 1
capacity = _effective_cpu_capacity()
limit = max(1, int(capacity * (MAX_CPU_PERCENT / 100.0)))
return max(1, min(usable_affinity, limit))
def _pick_cpu_subset(cpu_ids: List[int], slot_index: int, wanted: int) -> List[int]:
if not cpu_ids:
return []
wanted = max(1, min(len(cpu_ids), int(wanted)))
if wanted >= len(cpu_ids):
return list(cpu_ids)
start = (max(0, int(slot_index)) * wanted) % len(cpu_ids)
subset = [cpu_ids[(start + offset) % len(cpu_ids)] for offset in range(wanted)]
return sorted(set(subset))
def _allocate_cpu_subset(cpu_ids: List[int], job_index: int, active_jobs: int, total_slots: int) -> List[int]:
if not cpu_ids:
return []
active_jobs = max(1, int(active_jobs))
total_slots = max(1, min(len(cpu_ids), int(total_slots)))
pool = list(cpu_ids[:total_slots]) or list(cpu_ids)
j = int(job_index) % active_jobs
subset = pool[j::active_jobs]
if not subset:
subset = [pool[j % len(pool)]]
return sorted(set(subset))
FFMPEG_ACTIVE_JOBS: Dict[str, float] = {}
FFMPEG_ACTIVE_LOCK: asyncio.Lock = asyncio.Lock()
async def _register_active_ffmpeg(job_key: str) -> tuple[str, int, int]:
key = (job_key or "").strip() or f"anon:{time.time_ns()}"
async with FFMPEG_ACTIVE_LOCK:
FFMPEG_ACTIVE_JOBS[key] = time.time()
active_keys = list(FFMPEG_ACTIVE_JOBS.keys())
return key, len(active_keys), active_keys.index(key)
async def _unregister_active_ffmpeg(job_key: str):
if not job_key:
return
async with FFMPEG_ACTIVE_LOCK:
FFMPEG_ACTIVE_JOBS.pop(job_key, None)
async def _active_ffmpeg_count() -> int:
async with FFMPEG_ACTIVE_LOCK:
return len(FFMPEG_ACTIVE_JOBS)
# =====================
# SUPABASE / POSTGRES
# =====================
_pg_pool: Optional[asyncpg.Pool] = None
_COLLECTION_KEY_FIELDS = {
"users": "user_id",
"groups": "group_id",
"admins": "user_id",
"super_admins": "user_id",
"plans": "key",
"config": "key",
"reports": "id",
}
def _json_loads_if_needed(value):
if isinstance(value, str):
try:
return json.loads(value)
except Exception:
return value
return value
def _set_path(data: dict, path: str, value):
cur = data
parts = path.split(".")
for part in parts[:-1]:
if not isinstance(cur.get(part), dict):
cur[part] = {}
cur = cur[part]
cur[parts[-1]] = value
def _inc_path(data: dict, path: str, value):
cur = data
parts = path.split(".")
for part in parts[:-1]:
if not isinstance(cur.get(part), dict):
cur[part] = {}
cur = cur[part]
cur[parts[-1]] = cur.get(parts[-1], 0) + value
def _get_path(data: dict, path: str, default=None):
cur = data
for part in path.split("."):
if not isinstance(cur, dict) or part not in cur:
return default
cur = cur[part]
return cur
def _apply_update(doc: dict, update: dict) -> dict:
result = dict(doc)
for path, value in update.get("$set", {}).items():
_set_path(result, path, value)
for path, value in update.get("$inc", {}).items():
_inc_path(result, path, value)
return result
def _compare_value(actual, op: str, expected) -> bool:
if op == "$nin":
return actual not in expected
if op == "$in":
return actual in expected
if op == "$ne":
return actual != expected
if op == "$lt":
return actual is not None and actual < expected
if op == "$lte":
return actual is not None and actual <= expected
if op == "$gt":
return actual is not None and actual > expected
if op == "$gte":
return actual is not None and actual >= expected
if op == "$exists":
exists = actual is not None
return exists if expected else not exists
return actual == expected
def _matches_filter(doc: dict, flt: dict) -> bool:
if not flt:
return True
for key, cond in flt.items():
if key == "$or":
if not any(_matches_filter(doc, sub) for sub in cond):
return False
continue
actual = _get_path(doc, key, None)
if isinstance(cond, dict):
for op, expected in cond.items():
if op == "$exists":
exists = _get_path(doc, key, None) is not None or key in doc
if bool(expected) != bool(exists):
return False
elif not _compare_value(actual, op, expected):
return False
else:
if actual != cond:
return False
return True
class _AsyncCursor:
def __init__(self, docs: List[dict]):
self._docs = list(docs)
self._index = 0
def sort(self, field: str, direction: int = 1):
reverse = int(direction) < 0
self._docs.sort(key=lambda d: (_get_path(d, field, None) is None, _get_path(d, field, None)), reverse=reverse)
return self
def limit(self, n: int):
self._docs = self._docs[:n]
return self
async def to_list(self, length: Optional[int] = None):
return list(self._docs if length is None else self._docs[:length])
def __aiter__(self):
self._index = 0
return self
async def __anext__(self):
if self._index >= len(self._docs):
raise StopAsyncIteration
value = self._docs[self._index]
self._index += 1
return value
class _AsyncCollection:
def __init__(self, name: str):
self.name = name
self.key_field = _COLLECTION_KEY_FIELDS.get(name)
async def create_index(self, *args, **kwargs):
return None
async def _fetch_rows(self):
async with _pg_pool.acquire() as conn:
rows = await conn.fetch(
"SELECT doc_id, key, data FROM bot_store WHERE collection = $1 ORDER BY doc_id ASC",
self.name,
)
docs = []
for row in rows:
doc = _json_loads_if_needed(row["data"]) or {}
if not isinstance(doc, dict):
doc = {"value": doc}
doc = dict(doc)
if self.key_field and row["key"] is not None and self.key_field not in doc:
raw_key = row["key"]
try:
doc[self.key_field] = int(raw_key) if raw_key.isdigit() or (raw_key.startswith("-") and raw_key[1:].isdigit()) else raw_key
except Exception:
doc[self.key_field] = raw_key
doc["_doc_id"] = row["doc_id"]
docs.append(doc)
return docs
def _extract_key(self, data: dict):
if not self.key_field or not data:
return None
value = data.get(self.key_field)
return None if value is None else str(value)
async def find_one(self, flt: dict):
docs = await self.find(flt).to_list(1)
return docs[0] if docs else None
async def update_one(self, flt: dict, update: dict, upsert: bool = False):
current = await self.find_one(flt)
if current is None and not upsert:
return None
base = {k: v for k, v in (current or {}).items() if not k.startswith("_")}
new_doc = _apply_update(base, update)
key_value = self._extract_key(new_doc) or self._extract_key(flt)
async with _pg_pool.acquire() as conn:
if current is None:
await conn.execute(
"INSERT INTO bot_store(collection, key, data) VALUES($1, $2, $3::jsonb)",
self.name, key_value, json.dumps(new_doc),
)
else:
await conn.execute(
"UPDATE bot_store SET key=$1, data=$2::jsonb, updated_at=NOW() WHERE doc_id=$3",
key_value, json.dumps(new_doc), current.get("_doc_id"),
)
return new_doc
async def insert_one(self, doc: dict):
key_value = self._extract_key(doc)
async with _pg_pool.acquire() as conn:
await conn.execute(
"INSERT INTO bot_store(collection, key, data) VALUES($1, $2, $3::jsonb)",
self.name, key_value, json.dumps(doc),
)
return {"inserted": True}
async def delete_one(self, flt: dict):
doc = await self.find_one(flt)
if not doc:
return {"deleted_count": 0}
async with _pg_pool.acquire() as conn:
await conn.execute("DELETE FROM bot_store WHERE doc_id=$1", doc.get("_doc_id"))
return {"deleted_count": 1}
def find(self, flt: Optional[dict] = None):
async def _collect():
docs = await self._fetch_rows()
matched = [d for d in docs if _matches_filter(d, flt or {})]
return _AsyncCursor(matched)
return _AwaitableCursorFactory(_collect)
async def count_documents(self, flt: Optional[dict] = None):
docs = await self.find(flt or {}).to_list(None)
return len(docs)
def aggregate(self, pipeline: list):
async def _collect():
docs = await self.find({}).to_list(None)
if self.name == "stats" and pipeline:
orig = sum(float(d.get("original_mb", 0) or 0) for d in docs)
comp = sum(float(d.get("compressed_mb", 0) or 0) for d in docs)
return _AsyncCursor([{"_id": None, "o": orig, "c": comp}])
return _AsyncCursor([])
return _AwaitableCursorFactory(_collect)
class _AwaitableCursorFactory:
def __init__(self, builder):
self._builder = builder
self._cursor = None
async def _ensure(self):
if self._cursor is None:
self._cursor = await self._builder()
return self._cursor
def sort(self, *args, **kwargs):
async def _builder():
cursor = await self._ensure()
return cursor.sort(*args, **kwargs)
return _AwaitableCursorFactory(_builder)
def limit(self, *args, **kwargs):
async def _builder():
cursor = await self._ensure()
return cursor.limit(*args, **kwargs)
return _AwaitableCursorFactory(_builder)
async def to_list(self, length: Optional[int] = None):
cursor = await self._ensure()
return await cursor.to_list(length)
def __aiter__(self):
self._aiter = None
return self
async def __anext__(self):
if self._aiter is None:
cursor = await self._ensure()
self._aiter = cursor.__aiter__()
return await self._aiter.__anext__()
class _AsyncDB:
def __getitem__(self, name: str):
return _AsyncCollection(name)
async def list_collection_names(self):
docs = await db["config"].count_documents({}) # fuerza inicialización si hace falta
_ = docs
async with _pg_pool.acquire() as conn:
rows = await conn.fetch("SELECT DISTINCT collection FROM bot_store ORDER BY collection ASC")
return [r["collection"] for r in rows]
db = _AsyncDB()
col_users = db["users"]
col_groups = db["groups"]
col_admins = db["admins"]
col_super_admins = db["super_admins"]
col_stats = db["stats"]
col_plans = db["plans"]
col_config = db["config"]
async def _connect_pg():
global _pg_pool
if _pg_pool is not None:
return
db_url = _build_default_supabase_db_url()
if not db_url:
raise RuntimeError(
"Falta la cadena Postgres de Supabase. Usa una de estas variables: SUPABASE_DB_URL, DATABASE_URL, SUPABASE_POOLER_URL o SUPABASE_DIRECT_URL."
)
create_pool_kwargs = dict(min_size=1, max_size=4, command_timeout=60)
if ":6543/" in db_url or SUPABASE_USE_TRANSACTION_POOLER:
# Supavisor transaction mode no soporta prepared statements.
create_pool_kwargs["statement_cache_size"] = 0
try:
_pg_pool = await asyncpg.create_pool(db_url, **create_pool_kwargs)
except OSError as e:
_pg_pool = None
if getattr(e, "errno", None) == 101:
extra = ""
if _looks_like_direct_supabase_url(db_url):
extra = (
" Estás usando la URL directa de Supabase y ese host suele requerir IPv6. "
"Cambia a la URL del pooler en Supabase > Connect (Session mode para servidor normal o Transaction mode para serverless)."
)
raise RuntimeError(
"No se puede llegar a la base de datos de Supabase desde este hosting (Network is unreachable)."
+ extra
+ " URL actual: " + _redact_db_url(db_url)
) from e
raise
except Exception as e:
_pg_pool = None
msg = str(e)
if "prepared statement" in msg.lower() or "statement_cache_size" in msg.lower():
raise RuntimeError(
"La conexión parece estar usando Supabase Transaction mode. Usa el puerto 6543 y deja que el bot desactive statement_cache_size automáticamente."
) from e
raise
async with _pg_pool.acquire() as conn:
await conn.execute("""
CREATE TABLE IF NOT EXISTS bot_store (
doc_id BIGSERIAL PRIMARY KEY,
collection TEXT NOT NULL,
key TEXT NULL,
data JSONB NOT NULL DEFAULT '{}'::jsonb,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
""")
await conn.execute("CREATE INDEX IF NOT EXISTS bot_store_collection_idx ON bot_store(collection)")
await conn.execute("CREATE UNIQUE INDEX IF NOT EXISTS bot_store_collection_key_uidx ON bot_store(collection, key) WHERE key IS NOT NULL")
async def db_init():
await _connect_pg()
await col_users.create_index("user_id", unique=True)
await col_groups.create_index("group_id", unique=True)
await col_admins.create_index("user_id", unique=True)
await col_super_admins.create_index("user_id", unique=True)
await col_plans.create_index("key", unique=True)
await col_config.create_index("key", unique=True)
await _sync_plans_from_db()
await _load_config_from_db()
for uid in SUPER_ADMINS_STATIC:
await col_super_admins.update_one({"user_id": uid}, {"$set": {"user_id": uid}}, upsert=True)
await col_admins.update_one({"user_id": uid}, {"$set": {"user_id": uid}}, upsert=True)
await col_users.update_one({"user_id": uid}, {"$set": {"user_id": uid, "plan": "superadmin", "authorized": True}}, upsert=True)
logger.info("✅ Supabase/Postgres listo — %s", DB_NAME)
async def _sync_plans_from_db():
global PLANS
PLANS = {k: dict(v) for k, v in DEFAULT_PLANS.items()}
async for doc in col_plans.find({}):
key = doc.get("key")
if key and key in PLANS:
for f in ("max_file_size_mb", "daily_videos", "queue_priority", "custom_quality", "name", "own_queue"):
if f in doc:
PLANS[key][f] = doc[f]
async def _load_config_from_db():
global BOT_MODE, LOG_CHAT_ID, LOG_VIDEOS, INDIVIDUAL_QUEUES_ENABLED
doc = await col_config.find_one({"key": "bot_mode"})
if doc:
BOT_MODE = doc.get("value", "private")
doc2 = await col_config.find_one({"key": "log_chat_id"})
if doc2 and doc2.get("value") is not None:
LOG_CHAT_ID = int(doc2["value"])
doc3 = await col_config.find_one({"key": "log_videos"})
if doc3:
LOG_VIDEOS = bool(doc3.get("value", True))
doc4 = await col_config.find_one({"key": "individual_queues"})
if doc4:
INDIVIDUAL_QUEUES_ENABLED = bool(doc4.get("value", True))
logger.info("🔧 Modo: %s | Logs: %s | Cola individual: %s", BOT_MODE, LOG_CHAT_ID, INDIVIDUAL_QUEUES_ENABLED)
async def _save_config_to_db(key: str, value):
await col_config.update_one({"key": key}, {"$set": {"key": key, "value": value}}, upsert=True)
async def _save_plan_to_db(key: str):
data = dict(PLANS[key])
data["key"] = key
await col_plans.update_one({"key": key}, {"$set": data}, upsert=True)
# =====================
# DB HELPERS
# =====================
async def get_user(uid: int):
return await col_users.find_one({"user_id": uid})
async def upsert_user(uid: int, data: dict):
await col_users.update_one({"user_id": uid}, {"$set": data}, upsert=True)
async def is_super_admin(uid: int) -> bool:
if uid in SUPER_ADMINS_STATIC:
return True
return bool(await col_super_admins.find_one({"user_id": uid}))
async def is_admin(uid: int) -> bool:
if await is_super_admin(uid):
return True
return bool(await col_admins.find_one({"user_id": uid}))
async def is_authorized_user(uid: int) -> bool:
if await is_admin(uid):
return True
doc = await get_user(uid)
if doc and doc.get("authorized"):
return True
if BOT_MODE == "public":
if not doc:
await upsert_user(uid, {"user_id": uid, "authorized": True, "plan": "free"})
return True
return False
async def is_authorized_group(cid: int) -> bool:
if BOT_MODE == "public":
return True
return bool(await col_groups.find_one({"group_id": cid}))
PLAN_EXPIRY_DAYS: int = 30
async def _notify_plan_change(uid: int, old_plan: str, new_plan: str, reason: str = ""):
old_info = PLANS.get(old_plan, {}).get('name', old_plan)
new_info = PLANS.get(new_plan, {}).get('name', new_plan)
try:
text = (
f"📋 **Tu plan ha cambiado**\n\n"
f"📤 Plan anterior: **{old_info}**\n"
f"📥 Plan nuevo: **{new_info}**\n"
)
if reason:
text += f"\n📝 Motivo: {reason}"
if new_plan == "free":
text += "\n\n💡 Contacta al admin para renovar tu plan: /planes"
await bot.send_message(uid, text)
except Exception:
pass
async def _assign_plan(uid: int, plan_key: str, days: int = None, notify: bool = True, reason: str = ""):
old_doc = await get_user(uid)
old_plan = (old_doc or {}).get("plan", "free")
data = {"user_id": uid, "plan": plan_key, "authorized": True}
if plan_key == "free":
data["plan_expires"] = None
else:
expiry_days = days if days is not None else PLAN_EXPIRY_DAYS
data["plan_expires"] = (datetime.utcnow() + timedelta(days=expiry_days)).isoformat()
data["plan_days"] = expiry_days
await upsert_user(uid, data)
if notify and old_plan != plan_key:
await _notify_plan_change(uid, old_plan, plan_key, reason)
async def _check_plan_expiry(uid: int, doc: dict) -> str:
plan = doc.get("plan", "free")
if plan in ("free", "admin", "superadmin"):
return plan
expires_str = doc.get("plan_expires")
if not expires_str:
expiry = datetime.utcnow() + timedelta(days=PLAN_EXPIRY_DAYS)
await col_users.update_one(
{"user_id": uid},
{"$set": {"plan_expires": expiry.isoformat(), "plan_days": PLAN_EXPIRY_DAYS}}
)
return plan
try:
expires = datetime.fromisoformat(expires_str)
except Exception:
return plan
if datetime.utcnow() > expires:
await col_users.update_one(
{"user_id": uid},
{"$set": {"plan": "free", "plan_expires": None}}
)
await _notify_plan_change(uid, plan, "free",
"Tu plan ha expirado. Contacta al admin para renovarlo.")
asyncio.create_task(_log(f"⏰ Plan expirado: usuario `{uid}` — {plan} → free"))
return "free"
return plan
async def get_user_plan(uid: int) -> str:
if await is_super_admin(uid):
return "superadmin"
if await is_admin(uid):
return "admin"
doc = await get_user(uid)
if not doc:
return "free"
return await _check_plan_expiry(uid, doc)
async def get_plan_info(uid: int) -> dict:
return PLANS.get(await get_user_plan(uid), PLANS["free"])
async def check_daily_limit(uid: int, chat_id: int = None):
if chat_id and chat_id != uid and await is_authorized_group(chat_id):
return True, 0, 999999
plan = await get_plan_info(uid)
limit = plan["daily_videos"]
if limit >= 99999:
return True, 0, limit
today = datetime.utcnow().strftime("%Y-%m-%d")
doc = await get_user(uid)
used = (doc or {}).get("daily_usage", {}).get(today, 0)
return used < limit, used, limit
async def increment_daily_usage(uid: int):
today = datetime.utcnow().strftime("%Y-%m-%d")
await col_users.update_one({"user_id": uid}, {"$inc": {f"daily_usage.{today}": 1}}, upsert=True)
async def get_user_quality(uid: int) -> dict:
doc = await get_user(uid)
q = (doc or {}).get("quality", DEFAULT_QUALITY.copy())
# Limpiar campo label si existe
q.pop("label", None)
return q
async def set_user_quality(uid: int, quality: dict):
q = dict(quality)
q.pop("label", None)
await upsert_user(uid, {"quality": q})
async def log_stat(uid: int, orig_mb: float, comp_mb: float, dur_s: float):
await col_stats.insert_one({"user_id": uid, "original_mb": orig_mb, "compressed_mb": comp_mb, "duration_s": dur_s, "date": datetime.utcnow().isoformat()})
await col_users.update_one({"user_id": uid}, {"$inc": {"total_compressions": 1, "total_saved_mb": orig_mb - comp_mb}}, upsert=True)
# =====================
# BACKUP / IMPORT DB
# =====================
async def _next_numeric_id(collection_name: str, field: str = "id") -> int:
docs = await db[collection_name].find({}).to_list(None)
current = 0
for doc in docs:
try:
current = max(current, int(doc.get(field, 0) or 0))
except Exception:
pass
return current + 1
async def _export_database_zip() -> str:
export_dir = tempfile.mkdtemp(prefix="db_export_", dir=BACKUPS_DIR)
zip_path = os.path.join(BACKUPS_DIR, f"compresultra_supabase_backup_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.zip")
collections = ["users", "groups", "admins", "super_admins", "plans", "config", "stats", "reports"]
manifest = {
"bot": "CompresUltra Bot",
"version": BOT_VERSION,
"database": DB_NAME,
"exported_at_utc": datetime.utcnow().isoformat() + "Z",
"collections": collections,
}
with open(os.path.join(export_dir, "manifest.json"), "w", encoding="utf-8") as fh:
json.dump(manifest, fh, ensure_ascii=False, indent=2)
for name in collections:
docs = await db[name].find({}).to_list(None)
cleaned = [{k: v for k, v in doc.items() if not str(k).startswith("_")} for doc in docs]
with open(os.path.join(export_dir, f"{name}.json"), "w", encoding="utf-8") as fh:
json.dump(cleaned, fh, ensure_ascii=False, indent=2, default=str)
with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
for filename in sorted(os.listdir(export_dir)):
zf.write(os.path.join(export_dir, filename), arcname=filename)
shutil.rmtree(export_dir, ignore_errors=True)
return zip_path
async def _replace_collection_docs(collection_name: str, docs: list):
async with _pg_pool.acquire() as conn:
await conn.execute("DELETE FROM bot_store WHERE collection = $1", collection_name)
col = db[collection_name]
for doc in docs:
doc = {k: v for k, v in dict(doc).items() if not str(k).startswith("_")}
await col.insert_one(doc)
async def _import_database_export(path_to_file: str) -> dict:
workdir = tempfile.mkdtemp(prefix="db_import_", dir=BACKUPS_DIR)
extracted_dir = workdir
try:
lower = path_to_file.lower()
if lower.endswith(".zip"):
with zipfile.ZipFile(path_to_file, "r") as zf:
zf.extractall(extracted_dir)
elif lower.endswith(".json"):
shutil.copy2(path_to_file, os.path.join(extracted_dir, os.path.basename(path_to_file)))
else:
raise ValueError("Formato no soportado. Usa un .zip o .json exportado por el bot.")
imported = {}
for name in ["users", "groups", "admins", "super_admins", "plans", "config", "stats", "reports"]:
file_path = os.path.join(extracted_dir, f"{name}.json")
if not os.path.exists(file_path):
continue
with open(file_path, "r", encoding="utf-8") as fh:
docs = json.load(fh)
if not isinstance(docs, list):
raise ValueError(f"{name}.json no contiene una lista válida.")
await _replace_collection_docs(name, docs)
imported[name] = len(docs)
await _sync_plans_from_db()
await _load_config_from_db()
for uid in SUPER_ADMINS_STATIC:
await col_super_admins.update_one({"user_id": uid}, {"$set": {"user_id": uid}}, upsert=True)
await col_admins.update_one({"user_id": uid}, {"$set": {"user_id": uid}}, upsert=True)
await col_users.update_one({"user_id": uid}, {"$set": {"user_id": uid, "plan": "superadmin", "authorized": True}}, upsert=True)
return imported
finally:
shutil.rmtree(workdir, ignore_errors=True)
# =====================
# JOB SYSTEM
# =====================
@dataclass
class Job:
job_id: str
user_id: int
chat_id: int
status_msg_id: int
cancelled: bool = False # True cuando el USUARIO cancela
system_cancelled: bool = False # True cuando el SISTEMA/watchdog cancela (no el usuario)
task: Optional[asyncio.Task] = None
process: Optional[asyncio.subprocess.Process] = None
files: list = field(default_factory=list)
fname: str = ""
progress_pct: float = 0.0
progress_bar: str = ""
stage: str = ""
queue_name: str = ""
is_processing: bool = False
started_at: float = 0.0
last_activity_at: float = field(default_factory=time.time)
cpu_throttle_events: int = 0
cpu_usage_pct: float = 0.0
cpu_slots: int = 0
cpu_slots_max: int = 0
ffmpeg_last_progress_at: float = 0.0
ffmpeg_last_output_at: float = 0.0
ffmpeg_last_stderr: str = ""
upload_started_at: float = 0.0
upload_last_progress_at: float = 0.0
upload_completed_at: float = 0.0
upload_last_bytes: int = 0
upload_total_bytes: int = 0
ACTIVE_JOBS: Dict[str, Job] = {}
# ── Sistema de colas ─────────────────────────────────────────────────
# Cola GLOBAL reservada para usuarios Free
_global_queue_list: list = []
_global_queue_lock: asyncio.Lock = asyncio.Lock()
_global_queue_event: asyncio.Event = asyncio.Event()
_global_worker_task: Optional[asyncio.Task] = None
_global_currently_processing: Optional[str] = None
# Colas separadas por plan: basic / pro / premium / grupos
_user_queues: Dict[str, dict] = {} # queue_key -> {"list": [], "lock": Lock, "event": Event, "worker": Task|None, "processing": str|None}
PLAN_QUEUE_LABELS = {
"free": "🆓 Cola Free",
"basic": "⭐ Cola Basic",
"pro": "💎 Cola Pro",
"premium": "👑 Cola Premium",
"group": "🏘️ Cola de Grupos",
}
QUEUE_PLANS_WITH_PRIVATE_LANES = {"basic", "pro", "premium", "admin", "superadmin"}
PENDING_CONFIRM: Dict[str, tuple] = {}
REPORTS: list = []
LOG_CHAT_ID: Optional[int] = None
LOG_VIDEOS: bool = True
def _queue_base_key(queue_key: str) -> str:
if not queue_key:
return "free"
return queue_key.split(":", 1)[0]
def _plan_queue_key(plan_key: str, in_group: bool = False, uid: Optional[int] = None) -> str:
if in_group:
return "group"
if INDIVIDUAL_QUEUES_ENABLED and plan_key in QUEUE_PLANS_WITH_PRIVATE_LANES:
if uid is not None:
return f"{plan_key}:{uid}"
return plan_key
return "free"
def _plan_queue_label(queue_key: str) -> str:
base_key = _queue_base_key(queue_key)
base_label = PLAN_QUEUE_LABELS.get(base_key, f"🧵 Cola {base_key.title()}")
if ":" not in queue_key:
return base_label
_, owner_id = queue_key.split(":", 1)
if owner_id.isdigit():
return f"{base_label} · Usuario {owner_id}"
return base_label
def _queue_snapshot_counts() -> Dict[str, int]:
counts = {"free": len(_global_queue_list), "basic": 0, "pro": 0, "premium": 0, "group": 0}
for key, uq in _user_queues.items():
base_key = _queue_base_key(key)
counts[base_key] = counts.get(base_key, 0) + len(uq.get("list", [])) + (1 if uq.get("processing") else 0)
return counts
def _user_plan_queue_keys(plan_key: str, in_group: bool = False, uid: Optional[int] = None) -> List[str]:
queue_key = _plan_queue_key(plan_key, in_group, uid)
keys = [queue_key]
if uid is None and INDIVIDUAL_QUEUES_ENABLED and plan_key in QUEUE_PLANS_WITH_PRIVATE_LANES:
prefix = f"{plan_key}:"
keys.extend(sorted(k for k in _user_queues.keys() if k.startswith(prefix)))
return list(dict.fromkeys(keys))
# ─── BOTONES ────────────────────────────────────────────────────────
def _cancel_markup(job_id: str) -> InlineKeyboardMarkup:
"""Botón cancelar en rojo usando URL vacía trick — usa inline button con emoji rojo."""
return InlineKeyboardMarkup([[
InlineKeyboardButton("🔴 Cancelar", callback_data=f"cancel:{job_id}")
]])
def _queue_markup(job_id: str) -> InlineKeyboardMarkup:
return InlineKeyboardMarkup([
[InlineKeyboardButton("📋 Mi posición en cola", callback_data=f"vcola:{job_id}")],
[InlineKeyboardButton("🔴 Cancelar", callback_data=f"cancel:{job_id}")],
])
def _confirm_markup(key: str) -> InlineKeyboardMarkup:
return InlineKeyboardMarkup([[
InlineKeyboardButton("✅ Comprimir", callback_data=f"cyes:{key}"),
InlineKeyboardButton("🔴 No comprimir", callback_data=f"cno:{key}"),
]])
def _quality_menu_markup(uid: int = None) -> InlineKeyboardMarkup:
"""Menú de calidades con botones."""
buttons = []
row = []
for key, preset in QUALITY_PRESETS.items():
label = preset["label"]
row.append(InlineKeyboardButton(f"📺 {label}", callback_data=f"setq:{key}"))
if len(row) == 1:
buttons.append(row)
row = []
if row:
buttons.append(row)
buttons.append([InlineKeyboardButton("🔴 Cancelar", callback_data="qcancel")])
return InlineKeyboardMarkup(buttons)
async def _terminate_process(proc: Optional[asyncio.subprocess.Process], timeout: float = 5.0):
if not proc or proc.returncode is not None:
return
with contextlib.suppress(Exception):
proc.terminate()
try:
await asyncio.wait_for(proc.wait(), timeout=timeout)
return
except Exception:
pass
with contextlib.suppress(Exception):
proc.kill()
with contextlib.suppress(Exception):
await asyncio.wait_for(proc.wait(), timeout=timeout)
def _job_touch(job: Optional[Job], *, stage: Optional[str] = None, progress: Optional[float] = None):
if not job:
return
now = time.time()
job.last_activity_at = now
if stage is not None:
job.stage = stage
if not job.started_at:
job.started_at = now
if progress is not None:
progress = max(0.0, min(100.0, float(progress)))
job.progress_pct = progress
job.progress_bar = _bar(progress / 100.0)
async def _cleanup_job(job: Job):
await _terminate_process(job.process)
job.process = None
job.is_processing = False
job.task = None
for p in list(job.files):
try:
if p and os.path.exists(p):
os.remove(p)
except Exception:
pass
ACTIVE_JOBS.pop(job.job_id, None)
async def _remove_job_from_queues(job_id: str):
async with _global_queue_lock:
for i, item in enumerate(list(_global_queue_list)):
if item[3] == job_id:
return "free", _global_queue_list.pop(i)
for queue_key, uq in _user_queues.items():
async with uq["lock"]:
for i, item in enumerate(list(uq["list"])):
if item[3] == job_id:
return queue_key, uq["list"].pop(i)
return None, None
def _is_job_processing(job_id: str) -> bool:
if _global_currently_processing == job_id:
return True
return any(uq.get("processing") == job_id for uq in _user_queues.values())
def _job_queue_position(job_id: str) -> Optional[tuple[str, int, int]]:
if _global_currently_processing == job_id:
return ("free", 0, max(1, len(_global_queue_list) + 1))
for i, item in enumerate(_global_queue_list, 1):
if item[3] == job_id:
return ("free", i, len(_global_queue_list))
for queue_key, uq in _user_queues.items():
if uq.get("processing") == job_id:
total = len(uq.get("list", [])) + 1
return (queue_key, 0, max(1, total))
for i, item in enumerate(uq.get("list", []), 1):
if item[3] == job_id:
total = len(uq.get("list", [])) + (1 if uq.get("processing") else 0)
return (queue_key, i, max(1, total))
return None
async def _edit_job_status(job: Job, text: str, *, remove_markup: bool = True):
try:
await bot.edit_message_text(
chat_id=job.chat_id,
message_id=job.status_msg_id,
text=text,
reply_markup=None if remove_markup else _cancel_markup(job.job_id),
)
except Exception:
pass
async def _force_finish_job(job: Job, reason: str, *, notify_user: bool = True):
# Usa system_cancelled para que no se confunda con una cancelación del usuario
job.system_cancelled = True
job.is_processing = False
if notify_user:
await _edit_job_status(job, reason, remove_markup=True)
await _cleanup_job(job)
# =====================
# UTILS
# =====================
def _fmt_bytes(n: float) -> str:
for u in ("B", "KB", "MB", "GB", "TB"):
if n < 1024 or u == "TB":
return f"{n:.2f} {u}" if u != "B" else f"{int(n)} B"
n /= 1024
return f"{n:.2f} TB"
def _fmt_eta(s) -> str:
if s is None or s <= 0 or s == float("inf"):
return "—"
m, sec = divmod(int(s), 60)
h, m = divmod(m, 60)
return f"{h}h {m:02d}m {sec:02d}s" if h else (f"{m}m {sec:02d}s" if m else f"{sec}s")
def _bar(p: float, n: int = 14) -> str:
p = max(0.0, min(1.0, float(p)))
f = int(round(p * n))
return "█" * f + "░" * (n - f)
def _fmt_time(s):
return f"{int(s//3600):02}:{int((s%3600)//60):02}:{int(s%60):02}"
def _is_video_doc(doc) -> bool:
if not doc:
return False
mt = getattr(doc, "mime_type", "") or ""
if mt.startswith("video/"):
return True
ext = os.path.splitext((getattr(doc, "file_name", "") or "").lower())[1]
return ext in VIDEO_EXTENSIONS
def _unlim(n) -> str:
return "∞" if n >= 99999 else str(n)
class _Editor:
def __init__(self, msg: Message, job_id=None, every=PROGRESS_EDIT_EVERY):
self.msg = msg
self.job_id = job_id
self.every = max(1, int(every))
self._last = 0.0
self._lock = asyncio.Lock()
async def set(self, text: str, force=False, keep_cancel=None):
now = time.time()
if not force and (now - self._last) < self.every:
return
async with self._lock:
now = time.time()
if not force and (now - self._last) < self.every:
return
if keep_cancel is None:
keep_cancel = bool(self.job_id)
rm = _cancel_markup(self.job_id) if (keep_cancel and self.job_id) else None
try:
await self.msg.edit_text(text, reply_markup=rm)
self._last = now
except Exception:
pass
# =====================
# FFMPEG HELPERS
# =====================
async def _duration(path: str) -> float:
try:
p = await asyncio.create_subprocess_exec(
"ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", path,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
out, _ = await p.communicate()
if p.returncode == 0:
return float(out.decode().strip() or 0)
except Exception:
pass
return 0.0
async def _thumbnail(video: str, dest: str, sec: int = 3) -> bool:
try:
os.makedirs(os.path.dirname(dest) or ".", exist_ok=True)
p = await asyncio.create_subprocess_exec(
"ffmpeg", "-y", "-ss", str(max(0, sec)), "-i", video,
"-vframes", "1", "-vf", "scale=320:-1", "-q:v", "6", dest,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
await p.communicate()
return p.returncode == 0 and os.path.exists(dest) and os.path.getsize(dest) > 0
except Exception:
return False
async def _compress(in_f, out_f, uid, status_msg=None, job=None, title=""):
q = await get_user_quality(uid)
label = title or os.path.basename(in_f)
editor = _Editor(status_msg, job_id=(job.job_id if job else None)) if status_msg else None
dur = await _duration(in_f) if status_msg else 0.0
res = q.get("resolution", "854x480")
try:
rw, rh = res.split("x")
rw, rh = int(rw), int(rh)
except Exception:
rw, rh = 854, 480
usable_cpu_ids = _usable_cpu_ids()
usable_cpu_count = len(usable_cpu_ids) or 1
host_cpu_count = psutil.cpu_count(logical=True) or (os.cpu_count() or usable_cpu_count)
cpu_quota_cpus = _cgroup_cpu_quota_cpus()
cpu_capacity = _effective_cpu_capacity()
max_parallel_slots = _max_parallel_cpu_slots()
job_key, active_jobs, slot_index = await _register_active_ffmpeg(job.job_id if job else "")
cpu_subset = _allocate_cpu_subset(usable_cpu_ids, slot_index, active_jobs, max_parallel_slots)
current_cpu_slots = max(1, len(cpu_subset) or 1)
filter_threads = max(1, min(current_cpu_slots, usable_cpu_count))
frame_threads = max(2, min(6, current_cpu_slots))
# Usar flags=+ilme+ildct mejora velocidad en scale; añadir sws_flags para scale rápido
scale_filter = (
f"scale={rw}:{rh}:force_original_aspect_ratio=decrease:flags=fast_bilinear,"
f"scale=trunc(iw/2)*2:trunc(ih/2)*2,"
f"fps={q['fps']}"
)
codec_args = []
if str(q.get("codec", "")).lower() == "libx265":
# pools y frame-threads para máxima velocidad con ultrafast
codec_args = [
"-x265-params",
f"pools={filter_threads}:frame-threads={frame_threads}:wpp=1:pmode=1:pme=1:rd=2:me=hex:subme=2:b-adapt=0:rc-lookahead=5:no-open-gop=1",
"-tune", "fastdecode",
]
cmd = [
"ffmpeg", "-hide_banner", "-nostdin", "-loglevel", "warning", "-i", in_f,
"-vf", scale_filter,
"-filter_threads", str(filter_threads),
"-filter_complex_threads", str(max(1, min(4, filter_threads))),
"-c:v", q["codec"], "-crf", q["crf"], "-preset", q["preset"],
*codec_args,
"-thread_type", "frame+slice",
"-b:a", q["audio_bitrate"],
"-c:a", "aac",
"-ac", "2",
"-movflags", "+faststart",
"-threads", str(max(1, current_cpu_slots)),
"-max_muxing_queue_size", "4096",
"-progress", "pipe:1", "-nostats", "-y", out_f,
]
proc = await asyncio.create_subprocess_exec(*cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if job:
job.process = proc
job.cpu_slots = current_cpu_slots
job.cpu_slots_max = max_parallel_slots
job.cpu_usage_pct = 0.0
job.ffmpeg_last_progress_at = time.time()
job.ffmpeg_last_output_at = time.time()
job.ffmpeg_last_stderr = ""
_job_touch(job, stage="comprimiendo", progress=0)
out_time_ms = 0
now0 = time.time()
last_progress_at = now0
last_output_at = now0
last_stderr_at = now0
stderr_tail = deque(maxlen=80)
t0 = now0
ffmpeg_cpu_pct_total = 0.0
ffmpeg_cpu_pct_quota = 0.0
proc_cpu_raw = 0.0
input_size_mb = 0.0
with contextlib.suppress(Exception):
input_size_mb = max(0.0, os.path.getsize(in_f) / (1024 * 1024))
dynamic_start_grace = max(COMPRESS_START_GRACE_SECONDS, min(300, int(input_size_mb * 0.35) + int(dur * 0.02 if dur else 0)))
dynamic_stall_limit = max(COMPRESS_STALL_SECONDS, min(1200, int(dur * 0.12) if dur else 0))
async def _read_stdout():
nonlocal out_time_ms, last_progress_at, last_output_at
async for line in proc.stdout:
last_output_at = time.time()
if job:
job.ffmpeg_last_output_at = last_output_at
s = line.decode("utf-8", errors="replace").strip()
if "=" not in s:
continue
k, v = s.split("=", 1)
if k == "out_time_ms":
try:
new_out_time_ms = int(v)
if new_out_time_ms >= out_time_ms:
out_time_ms = new_out_time_ms
last_progress_at = time.time()
if job:
job.ffmpeg_last_progress_at = last_progress_at
except Exception:
pass
elif k == "progress" and v == "end":
last_progress_at = time.time()
if job:
job.ffmpeg_last_progress_at = last_progress_at
break
async def _read_stderr():
nonlocal last_output_at, last_stderr_at
while True:
line = await proc.stderr.readline()
if not line:
break
last_output_at = time.time()
last_stderr_at = last_output_at
decoded = line.decode("utf-8", errors="replace").strip()
stderr_tail.append(decoded)
if job:
job.ffmpeg_last_output_at = last_output_at
job.ffmpeg_last_stderr = decoded[:300]
async def _cpu_guard():
nonlocal ffmpeg_cpu_pct_total, ffmpeg_cpu_pct_quota, current_cpu_slots, cpu_subset, active_jobs, proc_cpu_raw
if proc.pid is None:
return
try:
ps_proc = psutil.Process(proc.pid)
except Exception:
return
def _apply_affinity(subset: List[int]):
nonlocal cpu_subset, current_cpu_slots
if not subset:
return
with contextlib.suppress(Exception):
ps_proc.cpu_affinity(subset)
cpu_subset = subset
current_cpu_slots = max(1, len(subset))
_apply_affinity(cpu_subset)
with contextlib.suppress(Exception):
ps_proc.cpu_percent(None)
await asyncio.sleep(0.5)
while proc.returncode is None:
try:
try:
active_now = await _active_ffmpeg_count()
except Exception:
active_now = active_jobs
active_now = max(1, int(active_now) or 1)
if active_now != active_jobs:
active_jobs = active_now
new_subset = _allocate_cpu_subset(usable_cpu_ids, slot_index, active_jobs, max_parallel_slots)
if new_subset and new_subset != cpu_subset:
_apply_affinity(new_subset)
proc_cpu_raw = ps_proc.cpu_percent(None)
ffmpeg_cpu_pct_total = max(0.0, min(100.0, proc_cpu_raw / max(1, host_cpu_count)))
ffmpeg_cpu_pct_quota = max(0.0, min(100.0, proc_cpu_raw / max(1.0, cpu_capacity)))
if job:
job.cpu_usage_pct = ffmpeg_cpu_pct_total
job.cpu_slots = current_cpu_slots
job.cpu_slots_max = max_parallel_slots
job.ffmpeg_last_output_at = max(job.ffmpeg_last_output_at or 0.0, last_output_at)
_job_touch(job, stage="comprimiendo", progress=(job.progress_pct if job else None))
except Exception:
pass
await asyncio.sleep(CPU_MONITOR_INTERVAL)
rt_out = asyncio.create_task(_read_stdout())
rt_err = asyncio.create_task(_read_stderr())
wt = asyncio.create_task(proc.wait())
cpu_guard_task = asyncio.create_task(_cpu_guard())
try:
while not wt.done():
if job and (job.cancelled or job.system_cancelled):
raise asyncio.CancelledError()
now = time.time()
elapsed = now - t0
progress_idle = now - last_progress_at
output_idle = now - max(last_output_at, last_stderr_at, last_progress_at)
no_progress_yet = out_time_ms <= 0
cpu_looks_idle = proc_cpu_raw < STALL_CPU_FLOOR_PERCENT
if no_progress_yet:
if elapsed > dynamic_start_grace and output_idle > FFMPEG_OUTPUT_IDLE_SECONDS and cpu_looks_idle:
raise RuntimeError("FFmpeg no arrancó bien la compresión y quedó sin actividad.")
else:
if progress_idle > dynamic_stall_limit and output_idle > FFMPEG_OUTPUT_IDLE_SECONDS and cpu_looks_idle:
raise RuntimeError("La compresión quedó atascada sin avance real durante demasiado tiempo.")
await asyncio.sleep(PROGRESS_EDIT_EVERY)
ds = out_time_ms / 1_000_000 if out_time_ms else 0.0
p = (ds / dur) if dur > 0 else 0.0
if job:
_job_touch(job, stage="comprimiendo", progress=(p * 100.0))
if editor:
el = time.time() - t0
sp = ds / el if el > 0 else 0.0
eta = (dur - ds) / sp if sp > 0 and dur > 0 else None
cpu_slots_txt = len(cpu_subset) if cpu_subset else current_cpu_slots
quota_txt = "sin límite" if cpu_quota_cpus is None else f"{cpu_quota_cpus:.2f}"
await editor.set(
(f"🎬 `{label}`\n" if label else "") +
f"🗜️ **Comprimiendo...**\n"
f"{_bar(p)} `{p*100:5.1f}%`\n"
f"⏱️ Procesado: `{_fmt_eta(ds)}` / `{_fmt_eta(dur)}`\n"
f"⚡ Velocidad: `{sp:.2f}x`\n"
f"🧠 CPU: `{cpu_slots_txt} cores` | FFmpeg: `{ffmpeg_cpu_pct_total:.1f}%` host / `{ffmpeg_cpu_pct_quota:.1f}%` cuota\n"
f"🛡️ Tope(host): `{MAX_CPU_PERCENT}%` | Pool: `{max_parallel_slots}` | Jobs: `{active_jobs}`\n"
f"🧩 Cuota cgroup: `{quota_txt}` CPU | Capacidad: `{cpu_capacity:.2f}`\n"
f"🧯 Stall: `{int(progress_idle)}s/{dynamic_stall_limit}s` | Salida: `{int(output_idle)}s/{FFMPEG_OUTPUT_IDLE_SECONDS}s`\n"
f"⏳ ETA: `{_fmt_eta(eta)}`"
)
await wt
except asyncio.CancelledError:
await _terminate_process(proc)
raise
except Exception:
await _terminate_process(proc)
raise
finally:
cpu_guard_task.cancel()
for task in (rt_out, rt_err, cpu_guard_task):
with contextlib.suppress(asyncio.CancelledError, Exception):
await task
await _unregister_active_ffmpeg(job_key)
if job:
job.cpu_usage_pct = 0.0
job.cpu_slots = 0
job.cpu_slots_max = 0
if proc.returncode != 0:
# Si el trabajo fue cancelado (usuario o sistema), ffmpeg termina con -15/143; no es un error real
if job and (job.cancelled or job.system_cancelled):
raise asyncio.CancelledError()
err = "\n".join([x for x in stderr_tail if x][-8:]) or "FFmpeg terminó con error."
if proc.returncode in (-9, 137):
err = "El proceso de compresión fue terminado por el sistema (memoria/recursos insuficientes)."
elif proc.returncode in (-15, 143):
err = "La compresión fue detenida antes de terminar. Revisa watchdog, reinicios del hosting o falta de recursos."
raise RuntimeError(err)
if not os.path.exists(out_f) or os.path.getsize(out_f) == 0:
raise RuntimeError("No se generó el archivo comprimido.")
return proc.returncode
async def _download(client, message, dst, editor, job=None, title=""):
t0 = time.time()
last_ui_at = 0.0
last_speed_at = t0
last_speed_bytes = 0
smoothed_speed = 0.0
async def _cb(cur, tot):
nonlocal last_ui_at, last_speed_at, last_speed_bytes, smoothed_speed
if job and (job.cancelled or job.system_cancelled):
raise asyncio.CancelledError()
now = time.time()
dt_speed = now - last_speed_at
if dt_speed >= TRANSFER_SPEED_WINDOW_SECONDS or (tot and cur >= tot):
delta_bytes = max(0, int(cur) - int(last_speed_bytes))
inst_speed = (delta_bytes / dt_speed) if dt_speed > 0 else 0.0
if inst_speed > 0:
smoothed_speed = inst_speed if smoothed_speed <= 0 else (smoothed_speed * 0.35) + (inst_speed * 0.65)
last_speed_at = now
last_speed_bytes = int(cur)
elapsed = max(0.001, now - t0)
sp = smoothed_speed if smoothed_speed > 0 else (cur / elapsed)
p = cur / tot if tot else 0
eta = (tot - cur) / sp if sp > 0 and tot else None
if job:
_job_touch(job, stage="descargando", progress=(p * 100.0))
if (now - last_ui_at) < TRANSFER_PROGRESS_MIN_INTERVAL and not (tot and cur >= tot):
return
last_ui_at = now
await editor.set(
(f"🎬 `{title}`\n" if title else "") +
f"📥 **Descargando...**\n"
f"{_bar(p)} `{p*100:5.1f}%`\n"
f"📦 {_fmt_bytes(cur)} / {_fmt_bytes(tot)}\n"
f"⚡ {_fmt_bytes(sp)}/s\n"
f"⏳ ETA: `{_fmt_eta(eta)}`",
force=bool(tot and cur >= tot),
)
await editor.set("📥 **Descargando...**\n" + _bar(0) + " `0.0%`", force=True)
await message.download(file_name=dst, progress=_cb)
await editor.set("✅ **Descarga completa.**\n" + _bar(1) + " `100%`", force=True)
# =====================
# COLA GLOBAL (para free)
# =====================
async def _ensure_global_worker():
global _global_worker_task
try:
loop = asyncio.get_running_loop()
except RuntimeError:
return
if _global_worker_task is None or _global_worker_task.done():
_global_worker_task = loop.create_task(_global_worker())
async def _global_worker():
global _global_currently_processing
while True:
await _global_queue_event.wait()
async with _global_queue_lock:
if not _global_queue_list:
_global_queue_event.clear()
continue
item = _global_queue_list.pop(0)
client, msg, status_msg, job_id = item
_global_currently_processing = job_id
try:
job = ACTIVE_JOBS.get(job_id)
if not job or job.cancelled or job.system_cancelled:
try:
await status_msg.edit_text("❌ **Cancelado.**\nTu video fue eliminado de la cola.", reply_markup=None)
except Exception:
pass
if job:
await _cleanup_job(job)
continue
job.is_processing = True
job.queue_name = "free"
_job_touch(job, stage="en cola", progress=job.progress_pct)
await _process(client, msg, status_msg=status_msg, job=job)
except asyncio.CancelledError:
job = ACTIVE_JOBS.get(job_id)
if job and job.cancelled:
logger.info("Global worker: cancelacion de usuario para job %s.", job_id)
else:
logger.warning("Global worker: cancelacion de sistema para job %s, continuando.", job_id)
except Exception as exc:
logger.exception("Global worker error: %s", exc)
finally:
_global_currently_processing = None
if _global_queue_list:
_global_queue_event.set()
# =====================
# COLAS POR PLAN (basic / pro / premium / groups)
# =====================
def _get_user_queue(queue_key: str) -> dict:
"""Obtiene o crea la estructura de cola para un plan o grupos."""
if queue_key not in _user_queues:
_user_queues[queue_key] = {
"list": [],
"lock": asyncio.Lock(),
"event": asyncio.Event(),
"worker": None,
"processing": None,
}
return _user_queues[queue_key]
async def _ensure_user_worker(queue_key: str):
uq = _get_user_queue(queue_key)
try:
loop = asyncio.get_running_loop()
except RuntimeError:
return
if uq["worker"] is None or uq["worker"].done():
uq["worker"] = loop.create_task(_user_worker(queue_key))
async def _user_worker(queue_key: str):
"""Worker dedicado para una cola de plan."""
uq = _get_user_queue(queue_key)
while True:
await uq["event"].wait()
async with uq["lock"]:
if not uq["list"]:
uq["event"].clear()
continue
item = uq["list"].pop(0)
client, msg, status_msg, job_id = item
uq["processing"] = job_id
try:
job = ACTIVE_JOBS.get(job_id)
if not job or job.cancelled or job.system_cancelled:
try:
await status_msg.edit_text("❌ **Cancelado.**", reply_markup=None)
except Exception:
pass
if job:
await _cleanup_job(job)
continue
job.is_processing = True
job.queue_name = queue_key
_job_touch(job, stage="en cola", progress=job.progress_pct)
await _process(client, msg, status_msg=status_msg, job=job)
except asyncio.CancelledError:
job = ACTIVE_JOBS.get(job_id)
if job and job.cancelled:
logger.info("Worker %s: cancelacion de usuario para job %s.", queue_key, job_id)
else:
logger.warning("Worker %s: cancelacion de sistema para job %s, continuando.", queue_key, job_id)
except Exception as exc:
logger.exception("Worker %s error: %s", queue_key, exc)
finally:
uq["processing"] = None
if uq["list"]:
uq["event"].set()
# =====================
# PROCESO PRINCIPAL
# =====================
async def _process(client, message: Message, status_msg: Message = None, job: Job = None):
if job:
job.task = asyncio.current_task()
editor = _Editor(status_msg, job_id=(job.job_id if job else None))
uid = message.from_user.id
cid = message.chat.id
media = message.video or message.document
in_group = cid != uid and await is_authorized_group(cid)
can, used, limit = await check_daily_limit(uid, cid)
if not can:
await editor.set(
f"⛔ **Límite diario alcanzado**\n\n"
f"📊 Usados hoy: `{used}` / `{_unlim(limit)}`\n"
f"💡 Cambia tu plan: /planes",
force=True, keep_cancel=False
)
return
if not in_group:
plan_info = await get_plan_info(uid)
max_mb = plan_info["max_file_size_mb"]
size_b = getattr(media, "file_size", 0) or 0
size_mb = size_b / (1024 * 1024)
if size_mb > max_mb and max_mb < 99999:
await editor.set(
f"⛔ **Video demasiado grande**\n\n"
f"📦 Tamaño: `{size_mb:.1f} MB`\n"
f"🔒 Límite de tu plan: `{max_mb} MB`\n\n"
f"💡 Actualiza tu plan: /planes",
force=True, keep_cancel=False
)
return
raw_name = getattr(media, "file_name", None) or f"{getattr(media,'file_id','vid')}.mp4"
base, _ = os.path.splitext(raw_name)
safe = re.sub(r"[^\w\-_. ]", "_", base)
fname = f"{safe}.mp4"
in_f = os.path.join(DOWNLOADS_DIR, f"{message.chat.id}_{message.id}_{fname}")
out_f = os.path.join(COMPRESSED_DIR, f"{message.chat.id}_{message.id}_{fname}")
thumb = None
if job:
job.files += [in_f, out_f]
job.fname = getattr(media, 'file_name', fname) or fname
job.stage = 'descargando'
job.is_processing = True
job.started_at = time.time()
job.last_activity_at = job.started_at
job.upload_started_at = 0.0
job.upload_last_progress_at = 0.0
job.upload_completed_at = 0.0
job.upload_last_bytes = 0
job.upload_total_bytes = 0
try:
await _download(client, message, in_f, editor, job=job, title=fname)
dur = await _duration(in_f)
if dur <= 0:
await editor.set(
"⚠️ **Archivo roto o incompleto**\n\n"
"El video no se pudo leer correctamente.\n"
"Intenta reenviarlo o usa otro formato.",
force=True
)
return
orig_mb = os.path.getsize(in_f) / (1024 * 1024)
t0 = time.time()
await editor.set(
f"🎬 `{fname}`\n"
f"🗜️ **Iniciando compresión...**\n"
+ _bar(0) + " `0.0%`",
force=True
)
if job:
_job_touch(job, stage='comprimiendo', progress=0)
rc = await _compress(in_f, out_f, uid, status_msg=status_msg, job=job, title=fname)
elapsed = time.time() - t0
if rc != 0:
await editor.set("⭕ Error al comprimir.", force=True)
return
comp_mb = os.path.getsize(out_f) / (1024 * 1024)
saved = orig_mb - comp_mb
pct = saved / orig_mb * 100 if orig_mb > 0 else 0
video_dur = 0
try:
video_dur = int((message.video.duration if message.video and message.video.duration else None) or await _duration(out_f) or dur)
except Exception:
video_dur = int(dur)
try:
sec = random.randint(1, min(10, max(1, video_dur - 1)))
thumb = os.path.join(DOWNLOADS_DIR, f"th_{message.chat.id}_{message.id}.jpg")
if not await _thumbnail(out_f, thumb, sec):
thumb = None
except Exception:
thumb = None
ratio_icon = "🟢" if pct >= 50 else ("🟡" if pct >= 20 else "🔴")
caption = (
"✅ **Compresión completada**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"📦 Original: `{orig_mb:.2f} MB`\n"
f"🗜️ Comprimido: `{comp_mb:.2f} MB`\n"
f"{ratio_icon} Reducción: `{saved:.2f} MB ({pct:.1f}%)`\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"⏱️ Proceso: `{_fmt_time(elapsed)}`\n"
f"🎞️ Duración: `{_fmt_time(video_dur)}`\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
"♠ ¡Que lo disfrutes! ♣"
)
upload_heartbeat_task = None
if job:
now_upload = time.time()
job.upload_started_at = now_upload
job.upload_last_progress_at = now_upload
job.upload_completed_at = 0.0
job.upload_last_bytes = 0
job.upload_total_bytes = 0
_job_touch(job, stage='subiendo', progress=0)
await editor.set(
f"📤 **Subiendo video...**\n🎬 `{fname}`\nPor favor espera...",
force=True, keep_cancel=False
)
up_t = time.time()
async def _upload_heartbeat():
while True:
await asyncio.sleep(UPLOAD_HEARTBEAT_EVERY)
if job and not job.cancelled and not job.system_cancelled and job.stage in {"subiendo", "finalizando"}:
_job_touch(job, stage=job.stage, progress=job.progress_pct)
up_last_ui_at = 0.0
up_last_speed_at = up_t
up_last_speed_bytes = 0
up_smoothed_speed = 0.0
async def _up_cb(cur, tot):
nonlocal up_last_ui_at, up_last_speed_at, up_last_speed_bytes, up_smoothed_speed
if job and (job.cancelled or job.system_cancelled):
raise asyncio.CancelledError()
now = time.time()
dt_speed = now - up_last_speed_at
if dt_speed >= TRANSFER_SPEED_WINDOW_SECONDS or (tot and cur >= tot):
delta_bytes = max(0, int(cur) - int(up_last_speed_bytes))
inst_speed = (delta_bytes / dt_speed) if dt_speed > 0 else 0.0
if inst_speed > 0:
up_smoothed_speed = inst_speed if up_smoothed_speed <= 0 else (up_smoothed_speed * 0.35) + (inst_speed * 0.65)
up_last_speed_at = now
up_last_speed_bytes = int(cur)
elapsed = max(0.001, now - up_t)
sp = up_smoothed_speed if up_smoothed_speed > 0 else (cur / elapsed)
p = cur / tot if tot else 0
eta = (tot - cur) / sp if sp > 0 and tot else None
if job:
job.upload_last_progress_at = now
job.upload_last_bytes = int(cur or 0)
job.upload_total_bytes = int(tot or 0)
_job_touch(job, stage="subiendo", progress=(p * 100.0))
if (now - up_last_ui_at) < TRANSFER_PROGRESS_MIN_INTERVAL and not (tot and cur >= tot):
return
up_last_ui_at = now
await editor.set(
f"📤 **Subiendo...**\n{_bar(p)} `{p*100:5.1f}%`\n"
f"📦 {_fmt_bytes(cur)} / {_fmt_bytes(tot)}\n"
f"⚡ {_fmt_bytes(sp)}/s\n"
f"⏳ ETA: `{_fmt_eta(eta)}`",
keep_cancel=False,
force=bool(tot and cur >= tot),
)
upload_heartbeat_task = asyncio.create_task(_upload_heartbeat())
try:
await client.send_video(
message.chat.id, out_f,
caption=caption,
duration=video_dur,
thumb=thumb,
supports_streaming=True,
reply_to_message_id=message.id,
progress=_up_cb,
)
finally:
if upload_heartbeat_task:
upload_heartbeat_task.cancel()
with contextlib.suppress(asyncio.CancelledError, Exception):
await upload_heartbeat_task
if job:
job.upload_completed_at = time.time()
_job_touch(job, stage='finalizando', progress=100.0)
await editor.set(
"✅ **¡Video enviado correctamente!**\n"
"Comprueba el mensaje justo arriba 👆",
force=True, keep_cancel=False
)
await increment_daily_usage(uid)
await log_stat(uid, orig_mb, comp_mb, elapsed)
except asyncio.CancelledError:
explicit_cancel = bool(job and job.cancelled)
system_cancel = bool(job and job.system_cancelled and not job.cancelled)
if explicit_cancel:
try:
if job and ACTIVE_JOBS.get(job.job_id) is job:
await editor.set("❌ **Proceso cancelado.**\nArchivos temporales eliminados.", force=True, keep_cancel=False)
except Exception:
pass
raise
if system_cancel:
# El watchdog ya editó el mensaje; solo re-lanzamos para limpiar el worker
raise
logger.warning("Cancelación inesperada de tarea en etapa final: job=%s stage=%s", getattr(job, "job_id", "?"), getattr(job, "stage", "?"))
try:
await editor.set(
"⭕ **La subida final se interrumpió inesperadamente.**\n\n"
"La compresión sí terminó, pero Telegram o el worker cortaron el envío al final.\n"
"Vuelve a probar el video.",
force=True, keep_cancel=False
)
except Exception:
pass
return
except Exception as e:
logger.error("Error proceso: %s", e)
try:
await editor.set(
f"⭕ **Error en el proceso**\n\n"
f"`{str(e)[:120]}`\n\n"
"Intenta reenviar el video.",
force=True, keep_cancel=False
)
except Exception:
pass
finally:
if job:
job.task = None
await _cleanup_job(job)
else:
for p in (in_f, out_f, thumb):
try:
if p and os.path.exists(p):
os.remove(p)
except Exception:
pass
# =====================
# BOT CLIENT
# =====================
bot = Client("compresultra01", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN, workdir=SESSION_DIR)
# =====================
# LOGS HELPER
# =====================
async def _log(text: str, is_video: bool = False):
if not LOG_CHAT_ID:
return
if is_video and not LOG_VIDEOS:
return
try:
await bot.send_message(LOG_CHAT_ID, text, disable_notification=True)
except Exception as e:
logger.warning("Log send failed: %s", e)
async def _log_video(msg, uid: int, cid: int, fname: str, size_mb: float, plan_name: str):
if not LOG_CHAT_ID or not LOG_VIDEOS:
return
caption = (
"Video recibido\n"
"ID: " + str(uid) + " | Chat: " + str(cid) + "\n"
"Archivo: " + fname + " - " + f"{size_mb:.1f}" + " MB\n"
"Plan: " + plan_name
)
try:
await bot.copy_message(
chat_id=LOG_CHAT_ID,
from_chat_id=msg.chat.id,
message_id=msg.id,
caption=caption,
disable_notification=True,
)
except Exception:
try:
await bot.send_message(LOG_CHAT_ID, caption, disable_notification=True)
except Exception as exc:
logger.warning("Log video send failed: %s", exc)
# =====================
# ACCESS DENIED
# =====================
_DEV_BTN = InlineKeyboardMarkup([[InlineKeyboardButton("👨💻 Desarrollador", url="https://t.me/Sasuke286")]])
async def _no_access(msg: Message):
await msg.reply_text("⛔ **No tienes acceso.**\nHabla con el desarrollador.", reply_markup=_DEV_BTN)
# ========================
# ENQUEUE OR PROCESS
# ========================
async def _enqueue(client, message: Message, status_msg: Message):
uid = message.from_user.id
cid = message.chat.id
jid = f"{cid}:{message.id}"
in_group = cid != uid and await is_authorized_group(cid)
job = Job(jid, uid, cid, status_msg.id)
ACTIVE_JOBS[jid] = job
# Admins siempre sin cola
if await is_admin(uid):
job.queue_name = "admin-direct"
job.task = asyncio.create_task(_process(client, message, status_msg=status_msg, job=job))
return
plan_key = await get_user_plan(uid)
plan = await get_plan_info(uid)
queue_key = _plan_queue_key(plan_key, in_group, uid)
job.queue_name = queue_key
if queue_key == "free":
await _ensure_global_worker()
async with _global_queue_lock:
item = (client, message, status_msg, jid)
_global_queue_list.append(item)
pos = _global_queue_list.index(item) + 1
total = len(_global_queue_list)
_global_queue_event.set()
queue_text = (
f"🆓 **Cola Free — Posición #{pos} de {total}**\n\n"
f"📋 Plan: {plan['name']}\n"
f"⏳ Esta cola está reservada para usuarios Free.\n\n"
f"✨ Los planes de pago ya no adelantan esta cola."
)
try:
await status_msg.edit_text(queue_text, reply_markup=_queue_markup(jid))
except Exception:
pass
return
uq = _get_user_queue(queue_key)
await _ensure_user_worker(queue_key)
async with uq["lock"]:
item = (client, message, status_msg, jid)
uq["list"].append(item)
pos = len(uq["list"])
total = len(uq["list"]) + (1 if uq["processing"] else 0)
uq["event"].set()
queue_title = _plan_queue_label(queue_key)
if pos == 1 and uq["processing"] is None:
queue_text = (
f"⚡ **{queue_title} — Procesando ahora**\n\n"
f"📋 Plan: {plan['name']}\n"
f"🎬 Tu video es el siguiente en esta cola.\n\n"
f"✨ Cola personal por usuario dentro de tu plan."
)
else:
queue_text = (
f"🧵 **{queue_title} — Posición #{pos} de {total}**\n\n"
f"📋 Plan: {plan['name']}\n"
f"⏳ Esperas solo dentro de tu cola personal.\n\n"
f"✨ Ya no se mezcla ni con Free ni con otros usuarios de pago."
)
try:
await status_msg.edit_text(queue_text, reply_markup=_queue_markup(jid))
except Exception:
pass
# ========================
# COMANDOS BÁSICOS
# ========================
@bot.on_message(filters.command("start") & (filters.private | filters.group))
async def cmd_start(client, msg: Message):
uid = msg.from_user.id
cid = msg.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await _no_access(msg)
return
plan_key = await get_user_plan(uid)
plan_info = PLANS.get(plan_key, PLANS["free"])
asyncio.create_task(_log(f"🟢 /start — 👤 `{uid}` en chat `{cid}`"))
modo_emoji = "🌐" if BOT_MODE == "public" else "🔒"
modo_txt = "Público" if BOT_MODE == "public" else "Privado"
name = msg.from_user.first_name or "Usuario"
# Botones del menú principal
buttons = InlineKeyboardMarkup([
[
InlineKeyboardButton("👤 Mi Perfil", callback_data="menu:perfil"),
InlineKeyboardButton("📋 Mi Plan", callback_data="menu:plan"),
],
[
InlineKeyboardButton("🎛️ Cambiar Calidad", callback_data="menu:calidad"),
InlineKeyboardButton("📊 Planes", callback_data="menu:planes"),
],
[
InlineKeyboardButton("🧵 Ver Cola", callback_data="menu:cola"),
InlineKeyboardButton("❓ Ayuda", callback_data="menu:help"),
],
[
InlineKeyboardButton("👨💻 Desarrollador", url="https://t.me/Sasuke286"),
InlineKeyboardButton("📝 Reportar", callback_data="menu:reporte"),
],
])
await msg.reply_text(
f"👋 **¡Hola, {name}!**\n\n"
f"🤖 Bienvenido a **CompresUltra Bot** {BOT_VERSION}\n"
f"━━━━━━━━━━━━━━━━━━━━━\n"
f"🗜️ Comprimo tus videos con la **mejor calidad**\n"
f"⚡ Motor: **FFmpeg + libx265**\n"
f"━━━━━━━━━━━━━━━━━━━━━\n"
f"📋 Tu plan: **{plan_info['name']}**\n"
f"{modo_emoji} Modo: **{modo_txt}**\n"
f"━━━━━━━━━━━━━━━━━━━━━\n\n"
f"📌 **Envía un video** como documento o directo para comprimirlo.\n\n"
f"_Usa los botones de abajo para navegar_ 👇",
reply_markup=buttons
)
# ── Callbacks del menú /start ──────────────────────────────────────
@bot.on_callback_query(filters.regex(r"^menu:"))
async def cb_menu(client, cq: CallbackQuery):
action = cq.data.split(":", 1)[1]
uid = cq.from_user.id
cid = cq.message.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await cq.answer("⛔ Sin acceso.", show_alert=True)
return
if action == "perfil":
await cq.answer()
# Reusar lógica de miperfil
doc = await get_user(uid) or {}
plan_key = await get_user_plan(uid)
plan_info = PLANS.get(plan_key, PLANS["free"])
can, used, limit = await check_daily_limit(uid)
expires_str = doc.get("plan_expires")
if expires_str and plan_key not in ("free", "admin", "superadmin"):
try:
exp_dt = datetime.fromisoformat(expires_str)
days_left = (exp_dt - datetime.utcnow()).days
expiry_line = f"⏳ Plan expira: `{exp_dt.strftime('%Y-%m-%d')}` ({days_left}d)"
except Exception:
expiry_line = ""
elif plan_key == "free":
expiry_line = "⏳ Sin expiración"
else:
expiry_line = ""
await cq.message.reply_text(
f"👤 **Tu Perfil**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🆔 ID: `{uid}`\n"
f"📋 Plan: **{plan_info['name']}**\n"
+ (expiry_line + "\n" if expiry_line else "") +
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🎬 Compresiones totales: **{doc.get('total_compressions', 0)}**\n"
f"💾 Espacio ahorrado: **{doc.get('total_saved_mb', 0.0):.1f} MB**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"📅 Hoy: {used} / {_unlim(limit)}\n"
f"📦 Tamaño máx: {_unlim(plan_info['max_file_size_mb'])} MB\n"
f"⚡ Cola por plan: {'✅' if plan_info.get('own_queue') else '❌'}\n"
f"🎛️ Calidad personalizada: {'✅' if plan_info['custom_quality'] else '❌'}"
)
elif action == "plan":
await cq.answer()
doc = await get_user(uid) or {}
plan_key = await get_user_plan(uid)
plan_inf = PLANS.get(plan_key, PLANS["free"])
exp_str = doc.get("plan_expires")
if plan_key in ("free", "admin", "superadmin"):
expiry_block = "⏳ Sin fecha de expiración"
elif exp_str:
try:
exp_dt = datetime.fromisoformat(exp_str)
days_left = (exp_dt - datetime.utcnow()).days
if days_left < 0:
expiry_block = "🔴 **Plan expirado**"
elif days_left <= 3:
expiry_block = f"🟠 Expira en **{days_left} días**"
else:
expiry_block = f"🟢 Expira en **{days_left} días** (`{exp_dt.strftime('%Y-%m-%d')}`)"
except Exception:
expiry_block = "⚠️ Fecha no válida"
else:
expiry_block = "⚠️ Sin fecha (contacta al admin)"
can, used, limit = await check_daily_limit(uid)
await cq.message.reply_text(
f"📋 **Tu Plan Actual**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🏷️ **{plan_inf['name']}**\n"
f"{expiry_block}\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🎬 Videos/día: `{_unlim(plan_inf['daily_videos'])}`\n"
f"📦 Tamaño máx: `{_unlim(plan_inf['max_file_size_mb'])} MB`\n"
f"🎛️ Calidad personalizada: {'✅' if plan_inf['custom_quality'] else '❌'}\n"
f"⚡ Cola por plan: {'✅' if plan_inf.get('own_queue') else '❌'}\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"📊 Usados hoy: `{used}` / `{_unlim(limit)}`\n"
"\n💡 Ver todos los planes: /planes"
)
elif action == "calidad":
await cq.answer()
plan_info = await get_plan_info(uid)
if not plan_info.get("custom_quality"):
await cq.answer("⛔ Tu plan no permite calidad personalizada. Usa /planes", show_alert=True)
return
q = await get_user_quality(uid)
# Detectar preset actual
current_preset = "Personalizada"
for pk, pv in QUALITY_PRESETS.items():
pv2 = {k: v for k, v in pv.items() if k != "label"}
if all(q.get(k) == pv2.get(k) for k in pv2):
current_preset = pv["label"]
break
await cq.message.reply_text(
f"🎛️ **Cambiar Calidad de Compresión**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"⚙️ Calidad actual: **{current_preset}**\n"
f"🖥️ Resolución: `{q.get('resolution', '?')}`\n"
f"🎯 CRF: `{q.get('crf', '?')}` | 🎵 Audio: `{q.get('audio_bitrate', '?')}`\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
"📺 **Elige una calidad predefinida:**\n"
"_Todas reducen el tamaño del archivo_",
reply_markup=_quality_menu_markup()
)
elif action == "planes":
await cq.answer()
actual = await get_user_plan(uid)
txt = "📋 **Planes disponibles:**\n\n"
for k, p in PLANS.items():
if k in ("admin", "superadmin"):
continue
m = " ◀ Tu plan" if k == actual else ""
own_q = "✅" if p.get("own_queue") else "❌"
txt += (
f"**{p['name']}**{m}\n"
f" 🎬 Videos/día: {_unlim(p['daily_videos'])}\n"
f" 📦 Tamaño máx: {_unlim(p['max_file_size_mb'])} MB\n"
f" ⚡ Cola por plan: {own_q}\n"
f" 🎛️ Calidad personalizada: {'✅' if p['custom_quality'] else '❌'}\n\n"
)
txt += "💡 Contacta al admin para cambiar tu plan."
await cq.message.reply_text(txt)
elif action == "cola":
await cq.answer()
# Reusar lógica de /cola
await _show_cola_info(cq.message, uid)
elif action == "help":
await cq.answer()
adm = await is_admin(uid)
sadm = await is_super_admin(uid)
txt = _build_help_text(adm, sadm)
await cq.message.reply_text(txt)
elif action == "reporte":
await cq.answer("Usa /reporte [descripción del problema]", show_alert=True)
# ── Callback para seleccionar calidad ──────────────────────────────
@bot.on_callback_query(filters.regex(r"^setq:"))
async def cb_set_quality(client, cq: CallbackQuery):
uid = cq.from_user.id
plan_info = await get_plan_info(uid)
if not plan_info.get("custom_quality"):
await cq.answer("⛔ Tu plan no permite calidad personalizada.", show_alert=True)
return
preset_key = cq.data.split(":", 1)[1]
if preset_key not in QUALITY_PRESETS:
await cq.answer("⭕ Calidad no válida.", show_alert=True)
return
preset = QUALITY_PRESETS[preset_key].copy()
label = preset.pop("label", preset_key)
await set_user_quality(uid, preset)
await cq.answer(f"✅ Calidad cambiada a {label}", show_alert=False)
try:
await cq.message.edit_text(
f"✅ **Calidad actualizada**\n\n"
f"📺 **{label}**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🖥️ Resolución: `{preset['resolution']}`\n"
f"🎯 CRF: `{preset['crf']}` (menor = mejor calidad)\n"
f"🎵 Audio: `{preset['audio_bitrate']}`\n"
f"🎞️ FPS: `{preset['fps']}`\n"
f"⚡ Preset: `{preset['preset']}`\n"
f"🔧 Codec: `{preset['codec']}`\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
"_Siempre se reduce el tamaño del archivo._\n\n"
"Usa /calidad para volver a cambiar.",
reply_markup=None
)
except Exception:
pass
@bot.on_callback_query(filters.regex(r"^qcancel$"))
async def cb_quality_cancel(client, cq: CallbackQuery):
await cq.answer("Cancelado.")
try:
await cq.message.delete()
except Exception:
pass
@bot.on_message(filters.command("help") & (filters.private | filters.group))
async def cmd_help(client, msg: Message):
uid = msg.from_user.id
cid = msg.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await _no_access(msg)
return
adm = await is_admin(uid)
sadm = await is_super_admin(uid)
await msg.reply_text(_build_help_text(adm, sadm))
def _build_help_text(adm: bool, sadm: bool) -> str:
txt = (
"🤖 **CompresUltra Bot — Comandos**\n\n"
"**👤 Usuario:**\n"
"/start — 👋 Bienvenida con menú\n"
"/help — 📖 Ver comandos\n"
"/miperfil — 👤 Tu perfil y estadísticas\n"
"/miplan — 📋 Tu plan con días restantes\n"
"/planes — 📊 Ver planes disponibles\n"
"/micalidad — ⚙️ Tu calidad actual\n"
"/calidad — 🎛️ Cambiar calidad (menú visual)\n"
"/cola — 🧵 Ver estado de la cola\n"
"/cancelar — ❌ Cancelar tu compresión\n"
"/reporte [texto] — 📝 Reportar un problema\n"
"/id — 🆔 Ver tu ID\n"
"/about — ℹ️ Info del bot\n"
"/ping — 🏓 Verificar si el bot responde\n"
"/velocidad — ⚡ Test de velocidad\n"
)
if adm:
txt += (
"\n**👨✈️ Admin:**\n"
"/add [id] — ➕ Autorizar usuario\n"
"/ban [id] — 🚫 Desautorizar\n"
"/listusers — 👥 Lista usuarios\n"
"/grup [id] — 🏘️ Autorizar grupo\n"
"/bangrup [id] — 🚫 Desautorizar grupo\n"
"/listgrup — 📗 Lista grupos\n"
"/listadmins — 📓 Lista admins\n"
"/setplan [id] [plan] — 📋 Asignar plan\n"
"/renovar [id] [dias] — 🔄 Renovar plan\n"
"/userinfo [id] — 🔍 Info usuario\n"
"/proxvencer [dias] — ⏰ Planes por vencer\n"
"/stats — 📊 Stats del bot\n"
"/status_bot — 🖥️ Estado del servidor\n"
"/trabajos — 🧰 Ver trabajos activos y en espera\n"
"/diagnostico_cpu — 🧪 Ver límites reales de CPU\n"
"/info [msg] — 📢 Mensaje a autorizados\n"
"/msgusr [id] [msg] — 📨 Mensaje privado\n"
"/reportes — 📋 Ver reportes\n"
"/adelantar [id] — ⚡ Adelantar en cola\n"
"/cancelarcola [id] — 🗑️ Cancelar cola\n"
)
if sadm:
txt += (
"\n**⚡ Super Admin:**\n"
"/modo — 🔒 Ver/cambiar modo del bot\n"
"/colaindividual — 🧵 ON/OFF colas por plan\n"
"/add_admins [id] — 🛡️ Agregar admin\n"
"/ban_admins [id] — 🛡️ Quitar admin\n"
"/add_superadmin [id] — ⚡ Agregar super admin\n"
"/ban_superadmin [id] — ⚡ Quitar super admin\n"
"/listsuperadmins — ⚡ Lista super admins\n"
"/editplan [plan] [campo] [valor] — ✏️ Editar plan\n"
"/verplanes — 📋 Ver todos los planes\n"
"/resetplan [plan] — 🔄 Restaurar plan\n"
"/resetstats [id] — 🔄 Resetear stats\n"
"/broadcast [msg] — 📣 Broadcast global\n"
"/dbstats — 🗄️ Stats Supabase\n"
"/logs — 📡 Config de logs\n"
"/forzarwatchdog — 🛠️ Reparar colas/workers\n"
"/actualizarmenu — 🔄 Actualizar menú\n"
)
return txt
@bot.on_message(filters.command("about") & (filters.private | filters.group))
async def cmd_about(client, msg: Message):
await msg.reply_text(
f"🤖 **CompresUltra Bot**\n\n"
f"📔 Versión: **{BOT_VERSION}**\n"
f"👨💻 Creador: {BOT_CREATOR}\n"
f"🗄️ DB: **Supabase / Postgres — {DB_NAME}**\n"
f"⚡ Motor: **FFmpeg + libx265**\n"
f"🔧 Calidades: 144p a 1080p\n"
f"🧵 Colas separadas por plan\n"
f"🚀 Planes editables, estadísticas y más.\n\n"
f"¡Espero te guste! 🤗",
reply_markup=InlineKeyboardMarkup([[
InlineKeyboardButton("👨💻 Desarrollador", url="https://t.me/Sasuke286"),
InlineKeyboardButton("📊 Stats", callback_data="menu:perfil"),
]])
)
@bot.on_message(filters.command("ping") & (filters.private | filters.group))
async def cmd_ping(client, msg: Message):
t = time.time()
m = await msg.reply_text("🏓 Pong...")
elapsed = (time.time() - t) * 1000
await m.edit_text(f"🏓 **Pong!** `{elapsed:.0f}ms`")
@bot.on_message(filters.command("velocidad") & (filters.private | filters.group))
async def cmd_velocidad(client, msg: Message):
uid = msg.from_user.id
if not (await is_authorized_user(uid) or await is_authorized_group(msg.chat.id)):
await _no_access(msg)
return
m = await msg.reply_text("⚡ Calculando velocidad del servidor...")
t0 = time.time()
proc = await asyncio.create_subprocess_exec(
"ffmpeg", "-f", "lavfi", "-i", "color=c=black:size=640x480:rate=30",
"-t", "2", "-c:v", "libx265", "-preset", "ultrafast", "-crf", "30",
"-f", "null", "-",
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE
)
_, _ = await proc.communicate()
elapsed = time.time() - t0
fps_est = 60 / elapsed if elapsed > 0 else 0
speed = min(fps_est / 30, 10)
await m.edit_text(
f"⚡ **Test de Velocidad**\n\n"
f"🖥️ Tiempo: `{elapsed:.2f}s`\n"
f"🚀 Velocidad estimada: `{speed:.1f}x`\n"
f"🎬 FPS procesados: `{fps_est:.0f}`\n\n"
f"_Basado en compresión de 2s de video 640x480_"
)
@bot.on_message(filters.command("id") & (filters.private | filters.group))
async def cmd_id(client, msg: Message):
uid = msg.from_user.id
cid = msg.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await _no_access(msg)
return
if msg.reply_to_message and msg.reply_to_message.from_user:
u = msg.reply_to_message.from_user
await msg.reply_text(f"👤 {u.first_name}\n🆔 `{u.id}`\n🔗 @{u.username or 'N/A'}")
elif len(msg.command) > 1:
try:
u = await client.get_users(msg.command[1])
await msg.reply_text(f"👤 {u.first_name}\n🆔 `{u.id}`\n🔗 @{u.username or 'N/A'}")
except Exception as e:
await msg.reply_text(f"⭕ No encontré ese usuario: {e}")
else:
await msg.reply_text(f"🆔 Tu ID: `{uid}`\n💬 Chat ID: `{cid}`")
@bot.on_message(filters.command("miperfil") & (filters.private | filters.group))
async def cmd_miperfil(client, msg: Message):
uid = msg.from_user.id
cid = msg.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await _no_access(msg)
return
doc = await get_user(uid) or {}
plan_key = await get_user_plan(uid)
plan_info = PLANS.get(plan_key, PLANS["free"])
can, used, limit = await check_daily_limit(uid)
expires_str = doc.get("plan_expires")
if expires_str and plan_key not in ("free", "admin", "superadmin"):
try:
exp_dt = datetime.fromisoformat(expires_str)
days_left = (exp_dt - datetime.utcnow()).days
expiry_line = f"⏳ Plan expira: `{exp_dt.strftime('%Y-%m-%d')}` ({days_left}d)"
except Exception:
expiry_line = ""
elif plan_key == "free":
expiry_line = "⏳ Sin expiración"
else:
expiry_line = ""
await msg.reply_text(
f"👤 **Tu Perfil**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🆔 ID: `{uid}`\n"
f"📋 Plan: **{plan_info['name']}**\n"
+ (expiry_line + "\n" if expiry_line else "") +
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🎬 Compresiones totales: **{doc.get('total_compressions', 0)}**\n"
f"💾 Espacio ahorrado: **{doc.get('total_saved_mb', 0.0):.1f} MB**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"📅 Hoy: {used} / {_unlim(limit)}\n"
f"📦 Tamaño máx: {_unlim(plan_info['max_file_size_mb'])} MB\n"
f"⚡ Cola por plan: {'✅' if plan_info.get('own_queue') else '❌'}\n"
f"🎛️ Calidad personalizada: {'✅' if plan_info['custom_quality'] else '❌'}"
)
@bot.on_message(filters.command("miplan") & (filters.private | filters.group))
async def cmd_miplan(client, msg: Message):
uid = msg.from_user.id
cid = msg.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await _no_access(msg)
return
doc = await get_user(uid) or {}
plan_key = await get_user_plan(uid)
plan_inf = PLANS.get(plan_key, PLANS["free"])
exp_str = doc.get("plan_expires")
if plan_key in ("free", "admin", "superadmin"):
expiry_block = "⏳ Sin fecha de expiración"
elif exp_str:
try:
exp_dt = datetime.fromisoformat(exp_str)
days_left = (exp_dt - datetime.utcnow()).days
if days_left < 0:
expiry_block = "🔴 **Plan expirado** (contacta al admin)"
elif days_left == 0:
expiry_block = "🔴 **Expira hoy**"
elif days_left <= 3:
expiry_block = f"🟠 Expira en **{days_left} días** (`{exp_dt.strftime('%Y-%m-%d')}`)"
elif days_left <= 7:
expiry_block = f"🟡 Expira en **{days_left} días** (`{exp_dt.strftime('%Y-%m-%d')}`)"
else:
expiry_block = f"🟢 Expira en **{days_left} días** (`{exp_dt.strftime('%Y-%m-%d')}`)"
except Exception:
expiry_block = "⚠️ Fecha no válida"
else:
expiry_block = "⚠️ Sin fecha configurada (contacta al admin)"
can, used, limit = await check_daily_limit(uid)
await msg.reply_text(
f"📋 **Tu Plan Actual**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🏷️ **{plan_inf['name']}**\n"
f"{expiry_block}\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🎬 Videos/día: `{_unlim(plan_inf['daily_videos'])}`\n"
f"📦 Tamaño máx: `{_unlim(plan_inf['max_file_size_mb'])} MB`\n"
f"🎛️ Calidad personalizada: {'✅' if plan_inf['custom_quality'] else '❌'}\n"
f"⚡ Cola por plan: {'✅' if plan_inf.get('own_queue') else '❌'}\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"📊 Usados hoy: `{used}` / `{_unlim(limit)}`\n"
"\n💡 Ver todos los planes: /planes"
)
@bot.on_message(filters.command("planes") & (filters.private | filters.group))
async def cmd_planes(client, msg: Message):
uid = msg.from_user.id
cid = msg.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await _no_access(msg)
return
actual = await get_user_plan(uid)
txt = "📋 **Planes disponibles:**\n\n"
for k, p in PLANS.items():
if k in ("admin", "superadmin"):
continue
m = " ◀ Tu plan" if k == actual else ""
own_q = "✅ Cola por plan" if p.get("own_queue") else "❌ Cola Free/global"
txt += (
f"**{p['name']}**{m}\n"
f" 🎬 Videos/día: {_unlim(p['daily_videos'])}\n"
f" 📦 Tamaño máx: {_unlim(p['max_file_size_mb'])} MB\n"
f" ⚡ {own_q}\n"
f" 🎛️ Calidad personalizada: {'✅' if p['custom_quality'] else '❌'}\n\n"
)
txt += "💡 Contacta al admin para cambiar tu plan.\n\n"
txt += "🧵 **¿Qué es la cola separada por plan?**\n"
txt += "_Cada plan tiene su propia cola; Free no se mezcla con Basic/Pro/Premium._"
await msg.reply_text(txt)
@bot.on_message(filters.command("micalidad") & (filters.private | filters.group))
async def cmd_micalidad(client, msg: Message):
uid = msg.from_user.id
cid = msg.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await _no_access(msg)
return
q = await get_user_quality(uid)
# Detectar preset
current_preset = "Personalizada"
for pk, pv in QUALITY_PRESETS.items():
pv2 = {k: v for k, v in pv.items() if k != "label"}
if all(q.get(k) == pv2.get(k) for k in pv2):
current_preset = pv["label"]
break
await msg.reply_text(
f"⚙️ **Tu calidad actual:**\n\n"
f"📺 **{current_preset}**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🖥️ Resolución: `{q['resolution']}`\n"
f"🎯 CRF: `{q['crf']}` (menor = mayor calidad)\n"
f"🎵 Audio: `{q['audio_bitrate']}`\n"
f"🎞️ FPS: `{q['fps']}`\n"
f"⚡ Preset: `{q['preset']}`\n"
f"🔧 Codec: `{q['codec']}`\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
"_Para cambiar usa /calidad_"
)
@bot.on_message(filters.command("calidad") & (filters.private | filters.group))
async def cmd_calidad(client, msg: Message):
"""
/calidad — Muestra menú visual con botones de calidad predefinida.
/calidad clave=valor ... — Permite configuración manual avanzada.
"""
uid = msg.from_user.id
cid = msg.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await _no_access(msg)
return
plan_info = await get_plan_info(uid)
if not plan_info.get("custom_quality"):
await msg.reply_text(
"⛔ **Tu plan no permite calidad personalizada.**\n\n"
"💡 Actualiza tu plan para cambiar la calidad: /planes"
)
return
args = msg.text.split()[1:]
if not args:
# Mostrar menú visual con botones
q = await get_user_quality(uid)
current_preset = "Personalizada"
for pk, pv in QUALITY_PRESETS.items():
pv2 = {k: v for k, v in pv.items() if k != "label"}
if all(q.get(k) == pv2.get(k) for k in pv2):
current_preset = pv["label"]
break
await msg.reply_text(
f"🎛️ **Cambiar Calidad de Compresión**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"⚙️ Calidad actual: **{current_preset}**\n"
f"🖥️ `{q.get('resolution', '?')}` | 🎯 CRF `{q.get('crf', '?')}`\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
"📺 **Selecciona una calidad:**\n"
"_Todas las calidades siempre reducen el tamaño_\n\n"
"🔹 **144p** — Máxima compresión, mínimo tamaño\n"
"🔹 **240p** — Muy ligero, bueno para ahorrar espacio\n"
"🔹 **360p** — Ligero, calidad aceptable\n"
"🔹 **480p** — Equilibrado ⭐ (recomendado)\n"
"🔹 **720p** — HD, buena calidad\n"
"🔹 **1080p** — Full HD, mayor calidad\n\n"
"**Configuración manual avanzada:**\n"
"`/calidad resolution=1280x720 crf=28 fps=30`",
reply_markup=_quality_menu_markup()
)
return
# Configuración manual
q = await get_user_quality(uid)
for arg in args:
if "=" not in arg:
await msg.reply_text(f"⭕ Formato incorrecto: `{arg}`\nUsa `/calidad` sin argumentos para el menú visual.")
return
k, v = arg.split("=", 1)
if k not in q:
await msg.reply_text(f"⭕ Campo desconocido: `{k}`\n**Campos válidos:** resolution, crf, audio_bitrate, fps, preset, codec")
return
q[k] = v
await set_user_quality(uid, q)
await msg.reply_text(
f"✅ **Calidad personalizada actualizada:**\n\n"
f"🖥️ `{q['resolution']}` | 🎯 CRF `{q['crf']}`\n"
f"🎵 `{q['audio_bitrate']}` | 🎞️ `{q['fps']}`fps\n"
f"⚡ `{q['preset']}` | 🔧 `{q['codec']}`\n\n"
"_Usa /calidad sin argumentos para el menú visual._"
)
@bot.on_message(filters.command("cancelar") & (filters.private | filters.group))
async def cmd_cancelar(client, msg: Message):
uid = msg.from_user.id
found = False
async with _global_queue_lock:
to_remove = [i for i, (_, qm, _, _) in enumerate(_global_queue_list) if qm.from_user.id == uid]
for i in reversed(to_remove):
_, _, qstatus, qjid = _global_queue_list.pop(i)
job = ACTIVE_JOBS.get(qjid)
if job:
job.cancelled = True
await _cleanup_job(job)
try:
await qstatus.edit_text("❌ Cancelado de la cola.", reply_markup=None)
except Exception:
pass
found = True
for queue_key, uq in _user_queues.items():
async with uq["lock"]:
to_remove = []
kept = []
for item in uq["list"]:
if item[1].from_user.id == uid:
to_remove.append(item)
else:
kept.append(item)
uq["list"][:] = kept
for _, _, qstatus, qjid in to_remove:
job = ACTIVE_JOBS.get(qjid)
if job:
job.cancelled = True
await _cleanup_job(job)
try:
await qstatus.edit_text(f"❌ Cancelado de la {_plan_queue_label(queue_key).lower()}.", reply_markup=None)
except Exception:
pass
found = True
for job in list(ACTIVE_JOBS.values()):
if job.user_id != uid:
continue
if job.cancelled:
continue
if _is_job_processing(job.job_id) or (job.task and not job.task.done()):
job.cancelled = True
if job.process and job.process.returncode is None:
await _terminate_process(job.process)
if job.task and not job.task.done():
job.task.cancel()
found = True
await msg.reply_text("❌ Cancelando tu compresión..." if found else "ℹ️ No tienes ninguna compresión activa.")
# ========================
# ADMIN COMMANDS
# ========================
@bot.on_message(filters.command("add") & (filters.private | filters.group))
async def cmd_add(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text(
"📖 **Uso:** `/add user_id [user_id2 ...]`\n\n"
"Autoriza al usuario con plan **Free** por defecto.\n"
"Para asignar otro plan usa: `/setplan user_id plan`\n\n"
"**Planes disponibles:** free, basic, pro, premium"
)
return
res = []
for s in args:
try:
tid = int(s)
doc = await get_user(tid)
if doc and doc.get("authorized"):
res.append(f"⚠️ `{tid}` ya está autorizado.")
else:
await _assign_plan(tid, "free", notify=True,
reason=f"Autorizado por admin `{msg.from_user.id}`")
res.append(f"✅ `{tid}` autorizado (plan Free).")
except ValueError:
res.append(f"⭕ ID inválido: `{s}`")
await msg.reply_text("\n".join(res))
@bot.on_message(filters.command("ban") & (filters.private | filters.group))
async def cmd_ban(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text("📖 Uso: `/ban user_id`")
return
res = []
for s in args:
try:
tid = int(s)
if await is_super_admin(tid):
res.append(f"⛔ No puedes banear a un super admin.")
continue
old_doc = await get_user(tid)
old_plan = (old_doc or {}).get("plan", "free")
await col_users.update_one({"user_id": tid}, {"$set": {"authorized": False}}, upsert=True)
try:
await bot.send_message(tid,
"⛔ **Tu acceso al bot ha sido revocado.**\n\n"
"Contacta al desarrollador si crees que es un error."
)
except Exception:
pass
res.append(f"✅ `{tid}` desautorizado (era plan {old_plan}).")
except ValueError:
res.append(f"⭕ ID inválido: `{s}`")
await msg.reply_text("\n".join(res))
@bot.on_message(filters.command("listusers") & (filters.private | filters.group))
async def cmd_listusers(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
users = await col_users.find({"authorized": True}).to_list(300)
if not users:
await msg.reply_text("❌ No hay usuarios autorizados.")
return
def _expiry_txt(u: dict) -> str:
plan = u.get("plan", "free")
if plan in ("free", "admin", "superadmin"):
return ""
exp = u.get("plan_expires")
if not exp:
return " ⚠️ sin fecha"
try:
days_left = (datetime.fromisoformat(exp) - datetime.utcnow()).days
if days_left < 0:
return " 🔴 expirado"
elif days_left <= 3:
return f" 🟠 {days_left}d"
elif days_left <= 7:
return f" 🟡 {days_left}d"
else:
return f" 🟢 {days_left}d"
except Exception:
return ""
lines = ["📘 **Usuarios autorizados:**\n"]
for u in users:
plan_key = u.get("plan", "free")
plan_name = PLANS.get(plan_key, {}).get("name", plan_key)
exp_txt = _expiry_txt(u)
lines.append(f"• `{u['user_id']}` — {plan_name}{exp_txt}")
full = "\n".join(lines)
await _send_long(msg, full)
@bot.on_message(filters.command("grup") & (filters.private | filters.group))
async def cmd_grup(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text("📖 Uso: `/grup group_id`")
return
res = []
for s in args:
try:
gid = int(s)
await col_groups.update_one({"group_id": gid}, {"$set": {"group_id": gid}}, upsert=True)
try:
chat = await client.get_chat(gid)
gname = getattr(chat, 'title', str(gid)) or str(gid)
except Exception:
gname = str(gid)
res.append(f"✅ Grupo autorizado:\n 🆔 `{gid}`\n 📛 {gname}\n ✅ Sin límites.")
except ValueError:
res.append(f"⭕ ID inválido: `{s}`")
await msg.reply_text("\n".join(res))
@bot.on_message(filters.command("bangrup") & (filters.private | filters.group))
async def cmd_bangrup(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text("📖 Uso: `/bangrup group_id`")
return
res = []
for s in args:
try:
gid = int(s)
await col_groups.delete_one({"group_id": gid})
res.append(f"✅ Grupo `{gid}` desautorizado.")
except ValueError:
res.append(f"⭕ ID inválido: `{s}`")
await msg.reply_text("\n".join(res))
@bot.on_message(filters.command("listgrup") & (filters.private | filters.group))
async def cmd_listgrup(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
groups = await col_groups.find({}).to_list(300)
if not groups:
await msg.reply_text("❌ No hay grupos autorizados.")
return
lines = ["📗 **Grupos autorizados:**\n", "_✅ Sin límites de tamaño ni videos diarios_\n"]
for g in groups:
gid = g['group_id']
try:
chat = await client.get_chat(gid)
gname = getattr(chat, 'title', str(gid)) or str(gid)
except Exception:
gname = str(gid)
lines.append(f"• `{gid}` — {gname}")
await msg.reply_text("\n".join(lines))
@bot.on_message(filters.command("listadmins") & (filters.private | filters.group))
async def cmd_listadmins(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
admins = await col_admins.find({}).to_list(200)
if not admins:
await msg.reply_text("❌ No hay admins.")
return
lines = ["📓 **Administradores:**\n"]
for a in admins:
mark = " ⚡" if a["user_id"] in SUPER_ADMINS_STATIC else ""
lines.append(f"• `{a['user_id']}`{mark}")
await msg.reply_text("\n".join(lines))
@bot.on_message(filters.command("setplan") & (filters.private | filters.group))
async def cmd_setplan(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if len(args) < 2:
valid = ", ".join(k for k in PLANS if k not in ("admin","superadmin"))
await msg.reply_text(
f"📖 **Uso:** `/setplan user_id plan [dias]`\n\n"
f"**Planes:** {valid}\n"
f"**Días por defecto:** {PLAN_EXPIRY_DAYS}\n\n"
"Ejemplos:\n"
"`/setplan 123456 pro` — 30 días\n"
"`/setplan 123456 premium 60` — 60 días\n"
"`/setplan 123456 free` — Sin expiración"
)
return
try:
tid = int(args[0])
pk = args[1].lower()
days = int(args[2]) if len(args) > 2 else None
if pk not in PLANS or pk in ("admin","superadmin"):
await msg.reply_text("⭕ Plan inválido.")
return
await _assign_plan(
tid, pk, days=days, notify=True,
reason=f"Asignado por admin `{msg.from_user.id}`"
)
expiry_days = days if days is not None else (PLAN_EXPIRY_DAYS if pk != "free" else None)
expiry_txt = f"{expiry_days} días" if expiry_days else "Sin expiración"
await msg.reply_text(
f"✅ **Plan actualizado**\n\n"
f"👤 Usuario: `{tid}`\n"
f"📋 Plan: **{PLANS[pk]['name']}**\n"
f"⏳ Duración: {expiry_txt}\n\n"
f"_El usuario ha sido notificado._"
)
asyncio.create_task(_log(
f"📋 /setplan — Admin `{msg.from_user.id}` → usuario `{tid}`: {pk} ({expiry_txt})"
))
except ValueError:
await msg.reply_text("⭕ ID o días inválido.")
@bot.on_message(filters.command("renovar") & filters.private)
async def cmd_renovar(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if len(args) < 2:
await msg.reply_text(
"📖 **Uso:** `/renovar user_id dias`\n\n"
"Establece o extiende la expiración del plan.\n\n"
"**Ejemplos:**\n"
"`/renovar 123456 30` — 30 días desde hoy\n"
"`/renovar 123456 +15` — añadir 15 días"
)
return
try:
tid = int(args[0])
dias_str = args[1]
extend = dias_str.startswith("+")
dias = int(dias_str.lstrip("+"))
if dias <= 0:
await msg.reply_text("⭕ Los días deben ser positivos.")
return
except ValueError:
await msg.reply_text("⭕ Formato incorrecto.")
return
doc = await get_user(tid)
if not doc:
await msg.reply_text(f"❌ Usuario `{tid}` no encontrado.")
return
plan_key = doc.get("plan", "free")
if plan_key in ("free", "admin", "superadmin"):
await msg.reply_text(f"⭕ El usuario tiene plan **{PLANS.get(plan_key,{}).get('name', plan_key)}**.\nUsa `/setplan` primero.")
return
exp_str = doc.get("plan_expires")
if extend and exp_str:
try:
base_dt = datetime.fromisoformat(exp_str)
if base_dt < datetime.utcnow():
base_dt = datetime.utcnow()
except Exception:
base_dt = datetime.utcnow()
else:
base_dt = datetime.utcnow()
new_expiry = base_dt + timedelta(days=dias)
await col_users.update_one(
{"user_id": tid},
{"$set": {"plan_expires": new_expiry.isoformat(), "plan_days": dias}}
)
accion = "extendido" if extend else "establecido"
try:
await bot.send_message(tid,
f"🔄 **Tu plan ha sido {accion}**\n\n"
f"📋 Plan: **{PLANS.get(plan_key, {}).get('name', plan_key)}**\n"
f"⏳ Nueva expiración: `{new_expiry.strftime('%Y-%m-%d')}`\n"
f"📅 Días: {dias}"
)
except Exception:
pass
days_from_now = (new_expiry - datetime.utcnow()).days
await msg.reply_text(
f"✅ **Expiración actualizada**\n\n"
f"👤 Usuario: `{tid}`\n"
f"📋 Plan: **{PLANS.get(plan_key, {}).get('name', plan_key)}**\n"
f"⏳ Expira: `{new_expiry.strftime('%Y-%m-%d')}` ({days_from_now}d)\n\n"
"_El usuario ha sido notificado._"
)
@bot.on_message(filters.command("userinfo") & (filters.private | filters.group))
async def cmd_userinfo(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text("📖 Uso: `/userinfo user_id`")
return
try:
tid = int(args[0])
doc = await get_user(tid)
if not doc:
await msg.reply_text(f"❌ Usuario `{tid}` no encontrado.")
return
pk = doc.get("plan", "free")
today = datetime.utcnow().strftime("%Y-%m-%d")
used = doc.get("daily_usage", {}).get(today, 0)
expires_str = doc.get("plan_expires")
if expires_str:
try:
exp_dt = datetime.fromisoformat(expires_str)
days_left = (exp_dt - datetime.utcnow()).days
expiry_txt = f"`{exp_dt.strftime('%Y-%m-%d')}` ({days_left}d restantes)"
except Exception:
expiry_txt = "Desconocida"
else:
expiry_txt = "Sin expiración" if pk == "free" else "No configurada"
# Ver si tiene actividad en su cola por plan
user_queue_key = _plan_queue_key(pk, uid=tid)
user_queue = _user_queues.get(user_queue_key)
own_q_active = bool(user_queue and user_queue["list"])
own_q_proc = bool(user_queue and user_queue["processing"] is not None)
await msg.reply_text(
f"👤 **Usuario `{tid}`**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"📋 Plan: **{PLANS.get(pk,{}).get('name',pk)}**\n"
f"⏳ Expiración: {expiry_txt}\n"
f"✅ Autorizado: {doc.get('authorized', False)}\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🎬 Total compresiones: {doc.get('total_compressions',0)}\n"
f"💾 Espacio ahorrado: {doc.get('total_saved_mb',0.0):.1f} MB\n"
f"📅 Usadas hoy: {used}\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🧵 Cola por plan: {'✅ Activa' if own_q_proc else ('⏳ En espera' if own_q_active else '—')}"
)
except ValueError:
await msg.reply_text("⭕ ID inválido.")
@bot.on_message(filters.command("proxvencer") & filters.private)
async def cmd_proxvencer(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
dias = int(args[0]) if args and args[0].isdigit() else 7
deadline = (datetime.utcnow() + timedelta(days=dias)).isoformat()
now_iso = datetime.utcnow().isoformat()
docs = await col_users.find({
"plan": {"$nin": ["free", "admin", "superadmin", None]},
"plan_expires": {"$lte": deadline, "$gte": now_iso}
}).sort("plan_expires", 1).to_list(200)
no_fecha = await col_users.find({
"plan": {"$nin": ["free", "admin", "superadmin", None]},
"$or": [{"plan_expires": None}, {"plan_expires": {"$exists": False}}]
}).to_list(200)
lines = [f"⏰ **Planes por vencer (próximos {dias} días):**\n"]
if docs:
for d in docs:
try:
exp_dt = datetime.fromisoformat(d["plan_expires"])
days_left = (exp_dt - datetime.utcnow()).days
icon = "🔴" if days_left <= 1 else ("🟠" if days_left <= 3 else "🟡")
plan_name = PLANS.get(d.get("plan", ""), {}).get("name", d.get("plan","?"))
lines.append(f"{icon} `{d['user_id']}` — {plan_name}\n 📅 Vence: `{exp_dt.strftime('%Y-%m-%d')}` ({days_left}d)")
except Exception:
pass
else:
lines.append("✅ Ningún plan vence en este período.")
if no_fecha:
lines.append(f"\n⚠️ **Sin fecha configurada ({len(no_fecha)}):**")
for d in no_fecha:
plan_name = PLANS.get(d.get("plan", ""), {}).get("name", d.get("plan","?"))
lines.append(f" ⚠️ `{d['user_id']}` — {plan_name} → usa `/renovar {d['user_id']} 30`")
await _send_long(msg, "\n".join(lines))
@bot.on_message(filters.command("stats") & filters.private)
async def cmd_stats(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
tu = await col_users.count_documents({"authorized": True})
tg = await col_groups.count_documents({})
ta = await col_admins.count_documents({})
tc = await col_stats.count_documents({})
res = await col_stats.aggregate([{"$group":{"_id":None,"o":{"$sum":"$original_mb"},"c":{"$sum":"$compressed_mb"}}}]).to_list(1)
saved = (res[0]["o"] - res[0]["c"]) if res else 0
queue_counts = _queue_snapshot_counts()
active_plan_queues = sum(1 for uq in _user_queues.values() if uq.get("processing") or uq.get("list"))
await msg.reply_text(
f"📊 **Stats del bot:**\n\n"
f"👥 Usuarios autorizados: **{tu}**\n"
f"👥 Grupos: **{tg}**\n"
f"🛡️ Admins: **{ta}**\n"
f"🎬 Compresiones totales: **{tc}**\n"
f"💾 Espacio ahorrado: **{saved:.1f} MB**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🆓 Cola Free: **{queue_counts.get('free', 0)}**\n"
f"⭐ Cola Basic: **{queue_counts.get('basic', 0)}**\n"
f"💎 Cola Pro: **{queue_counts.get('pro', 0)}**\n"
f"👑 Cola Premium: **{queue_counts.get('premium', 0)}**\n"
f"🏘️ Cola grupos: **{queue_counts.get('group', 0)}**\n"
f"🧵 Colas separadas activas: **{active_plan_queues}**\n"
f"🟢 Colas por plan: **{'ON' if INDIVIDUAL_QUEUES_ENABLED else 'OFF'}**"
)
# ========================
# SUPERADMIN: COLA INDIVIDUAL
# ========================
@bot.on_message(filters.command("colaindividual") & filters.private)
async def cmd_colaindividual(client, msg: Message):
"""
/colaindividual — Ver estado actual
/colaindividual on — Activar colas por plan
/colaindividual off — Desactivar (todos a cola Free/global)
"""
global INDIVIDUAL_QUEUES_ENABLED
uid = msg.from_user.id
if not await is_super_admin(uid):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
estado = "✅ **ACTIVADAS**" if INDIVIDUAL_QUEUES_ENABLED else "❌ **DESACTIVADAS**"
desc = ("Con colas por plan: Free, Basic, Pro, Premium y grupos van por carriles separados."
if INDIVIDUAL_QUEUES_ENABLED
else "Sin colas por plan: todo vuelve a la cola Free/global.")
await msg.reply_text(
f"🧵 **Colas por Plan**\n\n"
f"Estado actual: {estado}\n\n"
f"📋 {desc}\n\n"
"**Comandos:**\n"
"`/colaindividual on` — Activar\n"
"`/colaindividual off` — Desactivar",
reply_markup=InlineKeyboardMarkup([
[
InlineKeyboardButton("✅ Activar", callback_data="ci:on"),
InlineKeyboardButton("❌ Desactivar", callback_data="ci:off"),
]
])
)
return
arg = args[0].lower()
if arg in ("on", "activar", "1"):
INDIVIDUAL_QUEUES_ENABLED = True
await _save_config_to_db("individual_queues", True)
await msg.reply_text(
"✅ **Colas por plan ACTIVADAS**\n\n"
"Basic, Pro, Premium y grupos ahora usan colas separadas.\n"
"_Cambio inmediato._"
)
asyncio.create_task(_log(f"🧵 Colas por plan activadas por superadmin `{uid}`"))
elif arg in ("off", "desactivar", "0"):
INDIVIDUAL_QUEUES_ENABLED = False
await _save_config_to_db("individual_queues", False)
await msg.reply_text(
"❌ **Colas por plan DESACTIVADAS**\n\n"
"Todos los usuarios ahora vuelven a la cola Free/global.\n"
"_Cambio inmediato._"
)
asyncio.create_task(_log(f"🧵 Colas por plan desactivadas por superadmin `{uid}`"))
else:
await msg.reply_text("⭕ Usa `on` o `off`.")
@bot.on_callback_query(filters.regex(r"^ci:"))
async def cb_cola_individual(client, cq: CallbackQuery):
uid = cq.from_user.id
if not await is_super_admin(uid):
await cq.answer("⛔ Sin permisos.", show_alert=True)
return
global INDIVIDUAL_QUEUES_ENABLED
action = cq.data.split(":", 1)[1]
if action == "on":
INDIVIDUAL_QUEUES_ENABLED = True
await _save_config_to_db("individual_queues", True)
await cq.answer("✅ Colas por plan activadas.", show_alert=True)
elif action == "off":
INDIVIDUAL_QUEUES_ENABLED = False
await _save_config_to_db("individual_queues", False)
await cq.answer("❌ Colas por plan desactivadas.", show_alert=True)
try:
estado = "✅ **ACTIVADAS**" if INDIVIDUAL_QUEUES_ENABLED else "❌ **DESACTIVADAS**"
await cq.message.edit_text(
f"🧵 **Colas por Plan**\n\nEstado: {estado}",
reply_markup=InlineKeyboardMarkup([
[
InlineKeyboardButton("✅ Activar", callback_data="ci:on"),
InlineKeyboardButton("❌ Desactivar", callback_data="ci:off"),
]
])
)
except Exception:
pass
@bot.on_message(filters.command("modo") & filters.private)
async def cmd_modo(client, msg: Message):
global BOT_MODE
uid = msg.from_user.id
if not await is_super_admin(uid):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
emoji = "🌐" if BOT_MODE == "public" else "🔒"
estado = "Público" if BOT_MODE == "public" else "Privado"
await msg.reply_text(
emoji + " **Modo actual del bot: " + estado + "**\n\n"
"Para cambiar:\n"
"`/modo publico` — Abre el bot a todos\n"
"`/modo privado` — Solo usuarios autorizados"
)
return
arg = args[0].lower()
if arg in ("publico", "público", "public", "abierto", "open"):
new_mode = "public"
elif arg in ("privado", "private", "cerrado", "closed"):
new_mode = "private"
else:
await msg.reply_text("⛔ Opción inválida.")
return
BOT_MODE = new_mode
await _save_config_to_db("bot_mode", new_mode)
emoji = "🌐" if new_mode == "public" else "🔒"
estado = "Público" if new_mode == "public" else "Privado"
await msg.reply_text(emoji + " **Modo cambiado a: " + estado + "**\n\n_Cambio activo inmediatamente._")
# =====================
# SUPERADMIN COMMANDS
# =====================
@bot.on_message(filters.command("add_admins") & filters.private)
async def cmd_add_admins(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text("📖 Uso: `/add_admins user_id`")
return
res = []
for s in args:
try:
tid = int(s)
await col_admins.update_one({"user_id": tid}, {"$set": {"user_id": tid}}, upsert=True)
await upsert_user(tid, {"user_id": tid, "authorized": True, "plan": "admin"})
res.append(f"✅ `{tid}` → **Admin** 🛡️")
except ValueError:
res.append(f"⭕ ID inválido: `{s}`")
await msg.reply_text("\n".join(res))
@bot.on_message(filters.command("ban_admins") & filters.private)
async def cmd_ban_admins(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text("📖 Uso: `/ban_admins user_id`")
return
res = []
for s in args:
try:
tid = int(s)
if await is_super_admin(tid):
res.append(f"⛔ No puedes quitar a un super admin.")
continue
await col_admins.delete_one({"user_id": tid})
await upsert_user(tid, {"plan": "free"})
res.append(f"✅ `{tid}` removido de Admins.")
except ValueError:
res.append(f"⭕ ID inválido: `{s}`")
await msg.reply_text("\n".join(res))
@bot.on_message(filters.command("add_superadmin") & filters.private)
async def cmd_add_superadmin(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text("📖 Uso: `/add_superadmin user_id`")
return
res = []
for s in args:
try:
tid = int(s)
await col_super_admins.update_one({"user_id": tid}, {"$set": {"user_id": tid}}, upsert=True)
await col_admins.update_one({"user_id": tid}, {"$set": {"user_id": tid}}, upsert=True)
await upsert_user(tid, {"user_id": tid, "authorized": True, "plan": "superadmin"})
res.append(f"✅ `{tid}` → **Super Admin** ⚡")
except ValueError:
res.append(f"⭕ ID inválido: `{s}`")
await msg.reply_text("\n".join(res))
@bot.on_message(filters.command("ban_superadmin") & filters.private)
async def cmd_ban_superadmin(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text("📖 Uso: `/ban_superadmin user_id`")
return
res = []
for s in args:
try:
tid = int(s)
if tid in SUPER_ADMINS_STATIC:
res.append(f"⛔ No puedes quitar al super admin principal.")
continue
await col_super_admins.delete_one({"user_id": tid})
await col_admins.delete_one({"user_id": tid})
await upsert_user(tid, {"plan": "free"})
res.append(f"✅ `{tid}` removido de Super Admins.")
except ValueError:
res.append(f"⭕ ID inválido: `{s}`")
await msg.reply_text("\n".join(res))
@bot.on_message(filters.command("listsuperadmins") & filters.private)
async def cmd_listsuperadmins(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
sadmins = await col_super_admins.find({}).to_list(100)
if not sadmins:
await msg.reply_text("❌ No hay super admins.")
return
lines = ["⚡ **Super Admins:**\n"]
for s in sadmins:
mark = " (principal)" if s["user_id"] in SUPER_ADMINS_STATIC else ""
lines.append(f"• `{s['user_id']}`{mark}")
await msg.reply_text("\n".join(lines))
@bot.on_message(filters.command("editplan") & filters.private)
async def cmd_editplan(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if len(args) < 3:
await msg.reply_text(
"📖 **Uso:** `/editplan <plan> <campo> <valor>`\n\n"
"**Planes editables:** free, basic, pro, premium\n"
"**Campos:**\n"
" • `daily_videos` — número (ej: 10, 999999 para ∞)\n"
" • `max_file_size_mb` — número en MB\n"
" • `queue_priority` — true / false\n"
" • `custom_quality` — true / false\n"
" • `own_queue` — true / false (cola separada por plan)\n\n"
"**Ejemplos:**\n"
"`/editplan free daily_videos 10`\n"
"`/editplan basic own_queue true`"
)
return
plan_key = args[0].lower()
field_name = args[1].lower()
raw_val = args[2].lower()
if plan_key not in PLANS or plan_key in ("admin", "superadmin"):
await msg.reply_text(f"⭕ Plan inválido: `{plan_key}`")
return
int_fields = ("daily_videos", "max_file_size_mb")
bool_fields = ("queue_priority", "custom_quality", "own_queue")
if field_name in int_fields:
try:
value = int(raw_val)
if value < 0:
raise ValueError
except ValueError:
await msg.reply_text(f"⭕ `{field_name}` debe ser un número entero >= 0.")
return
elif field_name in bool_fields:
if raw_val in ("true", "1", "si", "yes", "on"):
value = True
elif raw_val in ("false", "0", "no", "off"):
value = False
else:
await msg.reply_text(f"⭕ `{field_name}` debe ser `true` o `false`.")
return
else:
await msg.reply_text(f"⭕ Campo inválido: `{field_name}`")
return
old_val = PLANS[plan_key].get(field_name)
PLANS[plan_key][field_name] = value
await _save_plan_to_db(plan_key)
await msg.reply_text(
f"✅ **Plan actualizado:**\n\n"
f"📋 Plan: **{PLANS[plan_key]['name']}**\n"
f"🔧 Campo: `{field_name}`\n"
f"📌 Antes: `{old_val}`\n"
f"✨ Ahora: `{value}`\n\n"
f"_Los cambios son inmediatos y persistentes._"
)
@bot.on_message(filters.command("verplanes") & filters.private)
async def cmd_verplanes(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
txt = "📋 **Todos los planes actuales:**\n\n"
for k, p in PLANS.items():
own_q = "✅" if p.get("own_queue") else "❌"
txt += (
f"**{p['name']}** (`{k}`)\n"
f" 🎬 daily_videos: `{_unlim(p['daily_videos'])}`\n"
f" 📦 max_file_size_mb: `{_unlim(p['max_file_size_mb'])}`\n"
f" ⚡ queue_priority: `{p.get('queue_priority', False)}`\n"
f" 🎛️ custom_quality: `{p.get('custom_quality', False)}`\n"
f" 🧵 own_queue: {own_q}\n\n"
)
await msg.reply_text(txt)
@bot.on_message(filters.command("resetplan") & filters.private)
async def cmd_resetplan(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text("📖 Uso: `/resetplan <plan>`")
return
pk = args[0].lower()
if pk not in DEFAULT_PLANS:
await msg.reply_text(f"⭕ Plan inválido: `{pk}`")
return
PLANS[pk] = dict(DEFAULT_PLANS[pk])
await _save_plan_to_db(pk)
await msg.reply_text(f"✅ Plan **{PLANS[pk]['name']}** restaurado a valores predeterminados.")
@bot.on_message(filters.command("resetstats") & filters.private)
async def cmd_resetstats(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text("📖 Uso: `/resetstats user_id`")
return
try:
tid = int(args[0])
await col_users.update_one({"user_id": tid}, {"$set": {"total_compressions": 0, "total_saved_mb": 0.0, "daily_usage": {}}})
await msg.reply_text(f"✅ Stats de `{tid}` reseteadas.")
except ValueError:
await msg.reply_text("⭕ ID inválido.")
@bot.on_message(filters.command("dbstats") & filters.private)
async def cmd_dbstats(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
tu = await col_users.count_documents({})
ta = await col_users.count_documents({"authorized": True})
tg = await col_groups.count_documents({})
tadm = await col_admins.count_documents({})
tsa = await col_super_admins.count_documents({})
tc = await col_stats.count_documents({})
tr = await db["reports"].count_documents({})
await msg.reply_text(
f"🗄️ **Supabase / Postgres — {DB_NAME}:**\n\n"
f"👥 Usuarios total: {tu} (auth: {ta})\n"
f"👥 Grupos: {tg}\n"
f"🛡️ Admins: {tadm}\n"
f"⚡ Super Admins: {tsa}\n"
f"📊 Compresiones: {tc}\n"
f"📝 Reportes: {tr}\n\n"
"**Backups:**\n"
"`/exportdb` — Exportar toda la base en .zip con .json\n"
"`/importdb` — Importar un backup respondiendo al .zip"
)
@bot.on_message(filters.command("exportdb") & filters.private)
async def cmd_exportdb(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
wait = await msg.reply_text("🗄️ Preparando exportación completa de la base de datos...")
try:
zip_path = await _export_database_zip()
await client.send_document(
msg.chat.id,
zip_path,
caption=(
"✅ **Backup generado**\n\n"
f"🗄️ DB: `{DB_NAME}`\n"
f"📦 Archivo: `{os.path.basename(zip_path)}`\n"
"📁 Incluye JSON completos por colección."
),
reply_to_message_id=msg.id,
)
await wait.edit_text("✅ Exportación lista y enviada.")
except Exception as e:
await wait.edit_text(f"⭕ No pude exportar la base: `{str(e)[:180]}`")
@bot.on_message(filters.command("importdb") & filters.private)
async def cmd_importdb(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
rm = msg.reply_to_message
doc = rm.document if rm and rm.document else None
if not doc:
await msg.reply_text(
"📖 **Uso:** responde a un `.zip` de backup con `/importdb`\n\n"
"El archivo debe ser un export generado por `/exportdb`."
)
return
wait = await msg.reply_text("📥 Descargando backup para importarlo...")
local_path = os.path.join(BACKUPS_DIR, f"import_{msg.id}_{doc.file_name or 'backup.zip'}")
try:
await rm.download(file_name=local_path)
await wait.edit_text("🗄️ Restaurando base de datos desde el backup...")
imported = await _import_database_export(local_path)
if not imported:
await wait.edit_text("⚠️ El backup no contenía colecciones importables.")
return
lines = [f"• `{name}`: {count}" for name, count in imported.items()]
await wait.edit_text(
"✅ **Importación completada**\n\n"
f"🗄️ DB: `{DB_NAME}`\n"
+ "\n".join(lines)
)
except Exception as e:
await wait.edit_text(f"⭕ No pude importar la base: `{str(e)[:180]}`")
finally:
try:
if os.path.exists(local_path):
os.remove(local_path)
except Exception:
pass
# ========================
# CALLBACKS
# ========================
@bot.on_callback_query(filters.regex(r"^cyes:"))
async def cb_confirm_yes(client, cq: CallbackQuery):
key = cq.data.split(":", 1)[1]
pending = PENDING_CONFIRM.pop(key, None)
if not pending:
await cq.answer("⏰ Esta solicitud ya expiró.", show_alert=True)
try:
await cq.message.edit_text("⏰ Solicitud expirada.", reply_markup=None)
except Exception:
pass
return
orig_client, orig_message = pending
uid = cq.from_user.id
if uid != orig_message.from_user.id and not await is_admin(uid):
await cq.answer("⛔ Solo el dueño puede confirmar.", show_alert=True)
PENDING_CONFIRM[key] = pending
return
await cq.answer("✅ Iniciando compresión...")
try:
await cq.message.edit_text("📥 Preparando...", reply_markup=None)
except Exception:
pass
await _enqueue(orig_client, orig_message, cq.message)
@bot.on_callback_query(filters.regex(r"^cno:"))
async def cb_confirm_no(client, cq: CallbackQuery):
key = cq.data.split(":", 1)[1]
PENDING_CONFIRM.pop(key, None)
await cq.answer("Cancelado.")
try:
await cq.message.edit_text("🔴 Compresión cancelada.", reply_markup=None)
except Exception:
pass
@bot.on_callback_query(filters.regex(r"^vcola:"))
async def cb_ver_cola(client, cq: CallbackQuery):
jid = cq.data.split(":", 1)[1]
if _global_currently_processing == jid:
await cq.answer("⚙️ Tu video se está procesando ahora en la cola Free.", show_alert=True)
return
async with _global_queue_lock:
snapshot = list(_global_queue_list)
for i, (_, _, _, qjid) in enumerate(snapshot, 1):
if qjid == jid:
total = len(snapshot)
await cq.answer(
f"🆓 Cola Free — Posición {i} de {total}\n"
f"⬆️ Delante: {i - 1} ⬇️ Detrás: {total - i}",
show_alert=True,
)
return
for queue_key, uq in _user_queues.items():
if uq.get("processing") == jid:
await cq.answer(f"⚙️ Tu video se está procesando ahora en {_plan_queue_label(queue_key)}.", show_alert=True)
return
async with uq["lock"]:
uq_snap = list(uq["list"])
for i, (_, _, _, qjid) in enumerate(uq_snap, 1):
if qjid == jid:
total = len(uq_snap) + (1 if uq.get("processing") else 0)
await cq.answer(
f"{_plan_queue_label(queue_key)} — Posición {i} de {total}\n"
f"✨ Esperas solo dentro de tu cola personal.",
show_alert=True,
)
return
await cq.answer("ℹ️ Tu video ya no está en cola.", show_alert=True)
@bot.on_callback_query(filters.regex(r"^cancel:"))
async def cb_cancel(client, cq: CallbackQuery):
jid = cq.data.split(":", 1)[1]
job = ACTIVE_JOBS.get(jid)
if not job:
await cq.answer("No hay nada que cancelar.", show_alert=False)
return
caller = cq.from_user.id
if caller != job.user_id and not await is_admin(caller):
await cq.answer("⛔ No puedes cancelar este proceso.", show_alert=False)
return
job.cancelled = True
queue_key, removed_item = await _remove_job_from_queues(jid)
if removed_item is not None:
try:
txt = "🔴 Cancelado de la cola." if queue_key == "free" else f"🔴 Cancelado de {_plan_queue_label(queue_key).lower()}."
await cq.message.edit_text(txt, reply_markup=None)
except Exception:
pass
await _cleanup_job(job)
await cq.answer("Cancelado.", show_alert=False)
return
if job.process and job.process.returncode is None:
await _terminate_process(job.process)
if job.task and not job.task.done():
job.task.cancel()
try:
await cq.message.edit_text("🔴 Cancelando...", reply_markup=None)
except Exception:
pass
await cq.answer("Cancelado.", show_alert=False)
# ========================
# MANEJADOR DE VIDEOS
# ========================
@bot.on_message((filters.video | filters.document) & (filters.private | filters.group))
async def handle_video(client, msg: Message):
uid = msg.from_user.id
cid = msg.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await _no_access(msg)
return
media = msg.video or msg.document
if not media:
return
if msg.document and not _is_video_doc(msg.document):
return
fname = getattr(media, "file_name", None) or "video"
size_b = getattr(media, "file_size", 0) or 0
size_mb = size_b / (1024 * 1024)
plan_key = await get_user_plan(uid)
plan_info = PLANS.get(plan_key, PLANS["free"])
can, used, limit = await check_daily_limit(uid)
key = f"{uid}:{msg.id}:{int(time.time())}"
PENDING_CONFIRM[key] = (client, msg)
async def _expire():
await asyncio.sleep(300)
PENDING_CONFIRM.pop(key, None)
asyncio.create_task(_expire())
asyncio.create_task(_log_video(msg, uid, cid, fname, size_mb, plan_info['name']))
in_group = cid != uid and await is_authorized_group(cid)
# Detectar cola por plan
queue_key = _plan_queue_key(plan_key, in_group, uid)
queue_icon = _plan_queue_label(queue_key)
if in_group:
confirm_text = (
f"🎬 **¿Comprimir este video?**\n"
f"━━━━━━━━━━━━━━━━━━━━━\n"
f"📄 Nombre: `{fname}`\n"
f"📦 Tamaño: `{size_mb:.2f} MB`\n"
f"🏘️ Grupo autorizado: **sin límites**\n"
f"━━━━━━━━━━━━━━━━━━━━━\n"
f"_⏰ Tienes 5 minutos para confirmar._"
)
else:
confirm_text = (
f"🎬 **¿Quieres comprimir este video?**\n"
f"━━━━━━━━━━━━━━━━━━━━━\n"
f"📄 Nombre: `{fname}`\n"
f"📦 Tamaño: `{size_mb:.2f} MB`\n"
f"📋 Plan: **{plan_info['name']}**\n"
f"📊 Videos hoy: `{used}` / `{_unlim(limit)}`\n"
f"🧵 Cola: **{queue_icon}**\n"
f"🔀 Sistema: **colas separadas por plan**\n"
f"━━━━━━━━━━━━━━━━━━━━━\n"
f"_⏰ Tienes 5 minutos para confirmar._"
)
await msg.reply_text(
confirm_text,
reply_markup=_confirm_markup(key),
)
# ========================
# /status_bot
# ========================
@bot.on_message(filters.command("status_bot") & (filters.private | filters.group))
async def cmd_status_bot(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
import psutil
import datetime as _dt
cpu_pct = psutil.cpu_percent(interval=0.5)
cpu_count = psutil.cpu_count(logical=True) or 1
vm = psutil.virtual_memory()
ram_pct = vm.percent
ram_total = vm.total / (1024**3)
ram_used = vm.used / (1024**3)
du = psutil.disk_usage("/")
disk_pct = du.percent
disk_total= du.total / (1024**3)
disk_used = du.used / (1024**3)
try:
net = psutil.net_io_counters()
net_s = net.bytes_sent / (1024**3)
net_r = net.bytes_recv / (1024**3)
net_txt = f"↑ {net_s:.2f} GB | ↓ {net_r:.2f} GB"
except Exception:
net_txt = "N/A"
boot_ts = psutil.boot_time()
uptime_s = int(time.time() - boot_ts)
up_d, rem = divmod(uptime_s, 86400)
up_h, rem2 = divmod(rem, 3600)
up_m = rem2 // 60
uptime_txt = f"{up_d}d {up_h:02}h {up_m:02}m"
cpu_quota_cpus = _cgroup_cpu_quota_cpus()
cpu_capacity = _effective_cpu_capacity()
usable_affinity = len(_usable_cpu_ids()) or 1
max_parallel_slots = _max_parallel_cpu_slots()
quota_txt = "sin límite" if cpu_quota_cpus is None else f"{cpu_quota_cpus:.2f}"
def _sbp(p, n=12):
filled = int(round(p / 100 * n))
return "█" * filled + "░" * (n - filled)
ci = "🟢" if cpu_pct < 60 else ("🟡" if cpu_pct < 85 else "🔴")
ri = "🟢" if ram_pct < 60 else ("🟡" if ram_pct < 85 else "🔴")
di = "🟢" if disk_pct < 70 else ("🟡" if disk_pct < 90 else "🔴")
queue_counts = _queue_snapshot_counts()
active_jobs = [job for job in ACTIVE_JOBS.values() if job.is_processing]
active_compress = [job for job in active_jobs if job.stage == "comprimiendo"]
ffmpeg_cpu_total = sum(max(0.0, job.cpu_usage_pct) for job in active_compress)
active_ffmpeg = await _active_ffmpeg_count()
now_str = _dt.datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC")
extra = ""
if active_compress:
hottest = max(active_compress, key=lambda j: j.cpu_usage_pct)
extra = (
f"🎞️ Compresiones activas: `{len(active_compress)}` | Pool FFmpeg: `{active_ffmpeg}`\n"
f"🔥 CPU FFmpeg total: `{ffmpeg_cpu_total:.1f}%` | Mayor carga: `{hottest.user_id}` ({hottest.cpu_usage_pct:.1f}%)\n"
)
await msg.reply_text(
f"🖥️ **Estado del Servidor**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"⚙️ **CPU:** {ci} {_sbp(cpu_pct)} `{cpu_pct:.1f}%` ({cpu_count} núcleos)\n"
f"🧩 CPU usable: `{cpu_capacity:.2f}` | afinidad: `{usable_affinity}` | cuota: `{quota_txt}` | pool bot: `{max_parallel_slots}`\n"
f"🧠 **RAM:** {ri} {_sbp(ram_pct)} `{ram_pct:.1f}%` ({ram_used:.1f}/{ram_total:.1f} GB)\n"
f"💽 **Disco:** {di} {_sbp(disk_pct)} `{disk_pct:.1f}%` ({disk_used:.1f}/{disk_total:.1f} GB)\n"
f"🌐 **Red:** {net_txt}\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"⏱️ Uptime: `{uptime_txt}`\n"
f"🆓 Cola Free: `{queue_counts.get('free', 0)}` en espera\n"
f"⭐ Basic: `{queue_counts.get('basic', 0)}` | 💎 Pro: `{queue_counts.get('pro', 0)}`\n"
f"👑 Premium: `{queue_counts.get('premium', 0)}` | 🏘️ Grupos: `{queue_counts.get('group', 0)}`\n"
f"🔀 Colas por plan: `{'ON' if INDIVIDUAL_QUEUES_ENABLED else 'OFF'}`\n"
f"{extra}"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"_🕐 {now_str}_"
)
def _job_elapsed(job: Job) -> str:
if not job.started_at:
return "—"
return _fmt_eta(max(0, time.time() - job.started_at))
@bot.on_message(filters.command("trabajos") & (filters.private | filters.group))
async def cmd_trabajos(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
active = [job for job in ACTIVE_JOBS.values() if not job.cancelled]
if not active:
await msg.reply_text("📭 **No hay trabajos activos o pendientes ahora mismo.**")
return
lines = ["🧰 **Trabajos del bot**", "━━━━━━━━━━━━━━━━━━━━━"]
for idx, job in enumerate(sorted(active, key=lambda j: (j.is_processing, j.started_at or 0), reverse=True)[:20], 1):
qpos = _job_queue_position(job.job_id)
really_processing = bool(job.is_processing and (job.process and job.process.returncode is None or qpos and qpos[1] == 0 or job.task))
state = "🟢 Activo" if really_processing else "🟡 En espera"
queue_label = _plan_queue_label((qpos[0] if qpos else job.queue_name) or "free") if (qpos or job.queue_name) else "🧵 Cola pendiente"
extra_queue = ""
if qpos and qpos[1] > 0:
extra_queue = f" | Pos: `#{qpos[1]}/{qpos[2]}`"
lines.append(
f"{idx}. {state} | `{job.user_id}` | `{job.fname or job.job_id}`\n"
f" • Etapa: `{job.stage or 'pendiente'}` | Cola: `{queue_label}`{extra_queue}\n"
f" • Progreso: `{job.progress_pct:.1f}%` | CPU: `{job.cpu_usage_pct:.1f}%` | Slots: `{job.cpu_slots}/{job.cpu_slots_max}`\n"
f" • Última actividad: `{_fmt_eta(max(0, time.time() - (job.last_activity_at or time.time())))}` atrás | Tiempo: `{_job_elapsed(job)}`"
)
await _send_long(msg, "\n".join(lines))
@bot.on_message(filters.command("diagnostico_cpu") & (filters.private | filters.group))
async def cmd_diagnostico_cpu(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
proc = psutil.Process()
affinity = []
with contextlib.suppress(Exception):
affinity = list(proc.cpu_affinity())
cpu_quota_cpus = _cgroup_cpu_quota_cpus()
cpu_capacity = _effective_cpu_capacity()
quota_txt = "sin límite" if cpu_quota_cpus is None else f"{cpu_quota_cpus:.2f}"
active_ffmpeg = await _active_ffmpeg_count()
await msg.reply_text(
"🧪 **Diagnóstico de CPU**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"⚙️ Host lógico: `{psutil.cpu_count(logical=True) or 1}` CPU\n"
f"🧵 Afinidad proceso: `{len(affinity) or len(_usable_cpu_ids())}` CPU -> `{affinity or _usable_cpu_ids()}`\n"
f"🧩 Cuota cgroup: `{quota_txt}` CPU\n"
f"🎯 Capacidad efectiva: `{cpu_capacity:.2f}` CPU\n"
f"🛡️ MAX_CPU_PERCENT: `{MAX_CPU_PERCENT}%`\n"
f"🏊 Pool máximo bot: `{_max_parallel_cpu_slots()}` slots\n"
f"⏱️ CPU_MONITOR_INTERVAL: `{CPU_MONITOR_INTERVAL}`\n"
f"🧯 COMPRESS_STALL_SECONDS: `{COMPRESS_STALL_SECONDS}`\n"
f"🎞️ FFmpeg activos: `{active_ffmpeg}`\n"
f"📊 CPU servidor actual: `{psutil.cpu_percent(interval=0.4):.1f}%`"
)
@bot.on_message(filters.command("forzarwatchdog") & filters.private)
async def cmd_forzarwatchdog(client, msg: Message):
global _global_currently_processing
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
repaired = []
if _global_currently_processing and _global_currently_processing not in ACTIVE_JOBS:
repaired.append("cola free")
_global_currently_processing = None
if _global_queue_list:
await _ensure_global_worker()
_global_queue_event.set()
repaired.append("worker free")
for queue_key, uq in list(_user_queues.items()):
processing_id = uq.get("processing")
if processing_id and processing_id not in ACTIVE_JOBS:
uq["processing"] = None
repaired.append(f"ref {queue_key}")
if uq.get("list"):
await _ensure_user_worker(queue_key)
uq["event"].set()
repaired.append(f"worker {queue_key}")
if not repaired:
await msg.reply_text("✅ **Watchdog manual ejecutado.** No había nada que reparar.")
return
await msg.reply_text("✅ **Watchdog manual ejecutado**\n\n" + "\n".join(f"• {x}" for x in repaired[:20]))
# ========================
# /cola — Ver cola de compresión
# ========================
async def _send_long(msg: Message, text: str, **kw):
MAX = 4000
parts = [text[i:i+MAX] for i in range(0, len(text), MAX)]
sent = None
for part in parts:
sent = await msg.reply_text(part, **kw)
kw = {}
return sent
async def _show_cola_info(msg: Message, uid: int):
adm = await is_admin(uid)
sep = "━━━━━━━━━━━━━━━━━━━━━"
lines = [f"📋 **Estado de las colas**\n{sep}\n"]
processing_job = ACTIVE_JOBS.get(_global_currently_processing) if _global_currently_processing else None
if processing_job:
pct = processing_job.progress_pct
bar = processing_job.progress_bar or _bar(pct / 100)
stage_icon = {"descargando": "📥", "comprimiendo": "🗜️", "subiendo": "📤"}.get(processing_job.stage, "⚙️")
is_mine = processing_job.user_id == uid
header = f"{stage_icon} **Cola Free — Procesando:**\n 👤 `{processing_job.user_id}`"
if is_mine:
header += " (tuyo)"
if is_mine or adm:
header += f"\n {bar} `{pct:.1f}%`"
lines.append(header)
else:
lines.append("🆓 Cola Free: sin procesamiento activo.\n")
async with _global_queue_lock:
free_snapshot = list(_global_queue_list)
if free_snapshot:
lines.append(f"🆓 **Cola Free: {len(free_snapshot)} en espera**")
for i, (_, q_msg, _, _) in enumerate(free_snapshot[:15], 1):
q_uid = q_msg.from_user.id
marker = " ◀ **tú**" if q_uid == uid else ""
lines.append(f" {i}. 👤 `{q_uid}`{marker}")
else:
lines.append("🆓 Cola Free vacía.")
in_group = msg.chat.id != uid and await is_authorized_group(msg.chat.id)
plan_key = await get_user_plan(uid)
my_queue_key = _plan_queue_key(plan_key, in_group, uid)
if my_queue_key != "free":
uq = _get_user_queue(my_queue_key)
processing_now = uq.get("processing")
async with uq["lock"]:
uq_snap = list(uq["list"])
lines.append(f"\n{sep}")
lines.append(f"{_plan_queue_label(my_queue_key)}")
if processing_now:
pjob = ACTIVE_JOBS.get(processing_now)
if pjob:
s_icon = {"descargando": "📥", "comprimiendo": "🗜️", "subiendo": "📤"}.get(pjob.stage, "⚙️")
mine = " (tuyo)" if pjob.user_id == uid else ""
lines.append(f" {s_icon} Procesando: `{pjob.fname or processing_now}`{mine} — `{pjob.progress_pct:.1f}%`")
else:
lines.append(" Sin procesamiento activo.")
if uq_snap:
lines.append(f" ⏳ En espera: {len(uq_snap)} video(s)")
for i, (_, qm, _, _) in enumerate(uq_snap[:10], 1):
qfname = getattr(qm.video or qm.document, "file_name", "?") or "?"
marker = " ◀ **tú**" if qm.from_user.id == uid else ""
lines.append(f" {i}. 🎬 `{qfname}`{marker}")
else:
lines.append(" Cola vacía.")
if adm:
active_plan_queues = [
(qk, uq) for qk, uq in _user_queues.items()
if qk != my_queue_key and (uq.get("processing") or uq.get("list"))
]
if active_plan_queues:
lines.append(f"\n{sep}\n🧵 **Otras colas por plan:**")
for qk, uq in active_plan_queues[:10]:
proc = "⚙️ proc." if uq.get("processing") else ""
wait = f"{len(uq['list'])} esp." if uq.get("list") else ""
lines.append(f" {_plan_queue_label(qk)} — {proc} {wait}".rstrip())
full_text = "\n".join(lines)
await _send_long(msg, full_text)
@bot.on_message(filters.command("cola") & (filters.private | filters.group))
async def cmd_cola(client, msg: Message):
uid = msg.from_user.id
cid = msg.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await _no_access(msg)
return
await _show_cola_info(msg, uid)
# ========================
# /reporte
# ========================
@bot.on_message(filters.command("reporte") & (filters.private | filters.group))
async def cmd_reporte(client, msg: Message):
uid = msg.from_user.id
cid = msg.chat.id
if not (await is_authorized_user(uid) or await is_authorized_group(cid)):
await _no_access(msg)
return
args = msg.text.split(None, 1)
if len(args) < 2:
await msg.reply_text(
"📝 **Enviar reporte**\n\n"
"Uso: `/reporte [descripción del problema]`\n\n"
"Ejemplo:\n"
"`/reporte El video tardó mucho y no se envió`"
)
return
texto = args[1].strip()
report = {
"id": await _next_numeric_id("reports"),
"user_id": uid,
"chat_id": cid,
"texto": texto,
"fecha": datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC"),
"leido": False,
}
REPORTS.append(report)
await db["reports"].insert_one(dict(report))
for sa_id in SUPER_ADMINS_STATIC:
try:
await client.send_message(
sa_id,
f"📣 **Nuevo reporte #{report['id']}**\n\n"
f"👤 Usuario: `{uid}`\n"
f"📅 Fecha: {report['fecha']}\n\n"
f"📝 {texto}"
)
except Exception:
pass
await msg.reply_text(
f"✅ **Reporte enviado** (#{report['id']})\n\n"
f"Gracias, el equipo lo revisará pronto."
)
@bot.on_message(filters.command("reportes") & filters.private)
async def cmd_reportes(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if args:
try:
rid = int(args[0])
doc = await db["reports"].find_one({"id": rid})
if not doc:
await msg.reply_text(f"❌ Reporte #{rid} no encontrado.")
return
await db["reports"].update_one({"id": rid}, {"$set": {"leido": True}})
await msg.reply_text(
f"📋 **Reporte #{rid}**\n\n"
f"👤 Usuario: `{doc['user_id']}`\n"
f"📅 Fecha: {doc['fecha']}\n"
f"✅ Leído: {'Sí' if doc.get('leido') else 'No'}\n\n"
f"📝 {doc['texto']}"
)
return
except ValueError:
pass
cursor = db["reports"].find({}).sort("id", -1).limit(10)
docs = await cursor.to_list(length=10)
if not docs:
await msg.reply_text("📭 No hay reportes.")
return
no_leidos = await db["reports"].count_documents({"leido": False})
lines = [f"📋 **Reportes** (sin leer: {no_leidos})\n"]
for d in docs:
mark = "🔴" if not d.get("leido") else "✅"
resumen = d["texto"][:50] + ("..." if len(d["texto"]) > 50 else "")
lines.append(f"{mark} #{d['id']} — `{d['user_id']}` — {resumen}")
lines.append("\n_Usa `/reportes <número>` para ver un reporte completo._")
await msg.reply_text("\n".join(lines))
@bot.on_message(filters.command("msgusr") & filters.private)
async def cmd_msgusr(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split(None, 2)
if len(args) < 2:
await msg.reply_text("📖 **Uso:**\n`/msgusr user_id mensaje`")
return
try:
tid = int(args[1])
except ValueError:
await msg.reply_text("⭕ ID de usuario inválido.")
return
texto = args[2].strip() if len(args) > 2 else ""
remitente = f"📨 **Mensaje del administrador:**\n\n"
try:
if msg.reply_to_message:
rm = msg.reply_to_message
caption = remitente + texto if texto else remitente.strip()
if rm.photo:
await client.send_photo(tid, rm.photo.file_id, caption=caption)
elif rm.video:
await client.send_video(tid, rm.video.file_id, caption=caption)
elif rm.document:
await client.send_document(tid, rm.document.file_id, caption=caption)
else:
await client.send_message(tid, remitente + (rm.text or texto or ""))
else:
if not texto:
await msg.reply_text("⭕ Escribe un mensaje.")
return
await client.send_message(tid, remitente + texto)
await msg.reply_text(f"✅ Mensaje enviado a `{tid}`.")
except Exception as e:
await msg.reply_text(f"⭕ No pude enviar el mensaje a `{tid}`: {e}")
@bot.on_message(filters.command("broadcast") & filters.private)
async def cmd_broadcast_media(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split(None, 1)
caption_txt = args[1].strip() if len(args) > 1 else ""
header = "📣 **Anuncio global:**\n\n"
rm = msg.reply_to_message
has_media = rm and (rm.photo or rm.video or rm.document or rm.audio or rm.voice)
if not has_media and not caption_txt:
await msg.reply_text("📖 **Uso del broadcast:**\n\nSolo texto: `/broadcast mensaje`\nCon media: responde a ella con `/broadcast [caption]`")
return
all_users = await col_users.find({}).to_list(5000)
sent = failed = 0
caption = header + caption_txt if caption_txt else header.strip()
status_msg = await msg.reply_text(f"📣 Enviando broadcast a {len(all_users)} usuarios...")
for u in all_users:
try:
if has_media:
if rm.photo:
await client.send_photo(u["user_id"], rm.photo.file_id, caption=caption)
elif rm.video:
await client.send_video(u["user_id"], rm.video.file_id, caption=caption)
elif rm.document:
await client.send_document(u["user_id"], rm.document.file_id, caption=caption)
else:
await client.send_message(u["user_id"], caption)
sent += 1
except Exception:
failed += 1
await asyncio.sleep(0.05)
await status_msg.edit_text(
f"📣 **Broadcast terminado.**\n\n✅ Enviado: {sent}\n❌ Fallidos: {failed}"
)
@bot.on_message(filters.command("info") & filters.private)
async def cmd_info_media(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split(None, 1)
caption_txt = args[1].strip() if len(args) > 1 else ""
header = "📢 **Aviso del bot:**\n\n"
rm = msg.reply_to_message
has_media = rm and (rm.photo or rm.video or rm.document)
if not has_media and not caption_txt:
await msg.reply_text("📖 **Uso:** `/info mensaje`")
return
targets_u = await col_users.find({"authorized": True}).to_list(1000)
targets_g = await col_groups.find({}).to_list(200)
sent = failed = 0
caption = header + caption_txt if caption_txt else header.strip()
async def _send(dest_id):
nonlocal sent, failed
try:
if has_media:
if rm.photo:
await client.send_photo(dest_id, rm.photo.file_id, caption=caption)
elif rm.video:
await client.send_video(dest_id, rm.video.file_id, caption=caption)
elif rm.document:
await client.send_document(dest_id, rm.document.file_id, caption=caption)
else:
await client.send_message(dest_id, caption)
sent += 1
except Exception:
failed += 1
for u in targets_u:
await _send(u["user_id"])
await asyncio.sleep(0.03)
for g in targets_g:
await _send(g["group_id"])
await asyncio.sleep(0.03)
await msg.reply_text(f"✅ Enviado: {sent} | ❌ Fallidos: {failed}")
# ========================
# /adelantar
# ========================
@bot.on_message(filters.command("adelantar") & filters.private)
async def cmd_adelantar(client, msg: Message):
if not await is_admin(msg.from_user.id):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
await msg.reply_text(
"""📖 **Uso:**
`/adelantar user_id` — Mueve sus videos al frente de su cola actual
`/adelantar user_id pos` — Mueve sus videos a la posición `pos` de su cola"""
)
return
try:
target_uid = int(args[0])
insert_pos = int(args[1]) - 1 if len(args) > 1 else 0
insert_pos = max(0, insert_pos)
except ValueError:
await msg.reply_text("⭕ ID o posición inválida.")
return
async with _global_queue_lock:
user_items = [(i, it) for i, it in enumerate(_global_queue_list) if it[1].from_user.id == target_uid]
if user_items:
other_items = [it for it in _global_queue_list if it[1].from_user.id != target_uid]
count = len(user_items)
extracted = [it for _, it in user_items]
ip = min(insert_pos, len(other_items))
_global_queue_list[:] = other_items[:ip] + extracted + other_items[ip:]
await msg.reply_text(
f"""⚡ **Cola actualizada**
👤 Usuario `{target_uid}` adelantado en **{_plan_queue_label('free')}**.
🎬 {count} video(s) movidos a la posición #{ip + 1}."""
)
return
for queue_key, uq in _user_queues.items():
async with uq["lock"]:
user_items = [(i, it) for i, it in enumerate(uq["list"]) if it[1].from_user.id == target_uid]
if not user_items:
continue
other_items = [it for it in uq["list"] if it[1].from_user.id != target_uid]
count = len(user_items)
extracted = [it for _, it in user_items]
ip = min(insert_pos, len(other_items))
uq["list"][:] = other_items[:ip] + extracted + other_items[ip:]
await msg.reply_text(
f"""⚡ **Cola actualizada**
👤 Usuario `{target_uid}` adelantado en **{_plan_queue_label(queue_key)}**.
🎬 {count} video(s) movidos a la posición #{ip + 1}."""
)
return
await msg.reply_text(f"❌ El usuario `{target_uid}` no tiene videos en ninguna cola administrable.")
# ========================
# /cancelarcola
# ========================
@bot.on_message(filters.command("cancelarcola") & filters.private)
async def cmd_cancelarcola(client, msg: Message):
uid = msg.from_user.id
if not await is_admin(uid):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
if not await is_super_admin(uid):
await msg.reply_text("⛔ Solo el Super Admin puede cancelar todas las colas.")
return
cancelled_items = []
async with _global_queue_lock:
cancelled_items.extend(list(_global_queue_list))
_global_queue_list.clear()
for uq in _user_queues.values():
async with uq["lock"]:
cancelled_items.extend(list(uq["list"]))
uq["list"].clear()
for _, _, qstatus, qjid in cancelled_items:
job = ACTIVE_JOBS.get(qjid)
if job:
job.cancelled = True
await _cleanup_job(job)
try:
await qstatus.edit_text("❌ **Cola vaciada por el administrador.**", reply_markup=None)
except Exception:
pass
await msg.reply_text(f"""🗑️ **Todas las colas vaciadas.**
❌ {len(cancelled_items)} video(s) cancelados.""")
return
try:
target_uid = int(args[0])
except ValueError:
await msg.reply_text("⭕ ID inválido.")
return
removed = []
async with _global_queue_lock:
removed.extend([it for it in _global_queue_list if it[1].from_user.id == target_uid])
_global_queue_list[:] = [it for it in _global_queue_list if it[1].from_user.id != target_uid]
for uq in _user_queues.values():
async with uq["lock"]:
removed.extend([it for it in uq["list"] if it[1].from_user.id == target_uid])
uq["list"][:] = [it for it in uq["list"] if it[1].from_user.id != target_uid]
if not removed:
await msg.reply_text(f"❌ `{target_uid}` no tiene videos en ninguna cola administrable.")
return
for _, _, qstatus, qjid in removed:
job = ACTIVE_JOBS.get(qjid)
if job:
job.cancelled = True
await _cleanup_job(job)
try:
await qstatus.edit_text("🔴 **Tu video fue cancelado por el administrador.**", reply_markup=None)
except Exception:
pass
await msg.reply_text(
f"""✅ **Videos cancelados**
👤 Usuario: `{target_uid}`
❌ {len(removed)} video(s) eliminados."""
)
# ========================
# /logs
# ========================
@bot.on_message(filters.command("logs") & filters.private)
async def cmd_logs(client, msg: Message):
global LOG_CHAT_ID, LOG_VIDEOS
uid = msg.from_user.id
if not await is_super_admin(uid):
await _no_access(msg)
return
args = msg.text.split()[1:]
if not args:
status = f"`{LOG_CHAT_ID}`" if LOG_CHAT_ID else "No configurado"
await msg.reply_text(
f"📡 **Configuración de Logs**\n\n"
f"📍 Canal/Grupo: {status}\n"
f"🎬 Log de videos: {'✅ Activo' if LOG_VIDEOS else '❌ Inactivo'}\n\n"
"**Comandos:**\n"
"`/logs canal <id>` — Configura un canal\n"
"`/logs grupo <id>` — Configura un grupo\n"
"`/logs off` — Desactiva los logs\n"
"`/logs videos on/off` — Log de videos"
)
return
sub = args[0].lower()
if sub == "off":
LOG_CHAT_ID = None
await _save_config_to_db("log_chat_id", None)
await msg.reply_text("✅ Logs desactivados.")
return
if sub == "videos":
val = args[1].lower() if len(args) > 1 else ""
if val in ("on", "1", "si", "true"):
LOG_VIDEOS = True
await _save_config_to_db("log_videos", True)
await msg.reply_text("✅ Log de videos **activado**.")
elif val in ("off", "0", "no", "false"):
LOG_VIDEOS = False
await _save_config_to_db("log_videos", False)
await msg.reply_text("✅ Log de videos **desactivado**.")
else:
await msg.reply_text("⭕ Usa `/logs videos on` o `/logs videos off`")
return
if sub in ("canal", "grupo") and len(args) > 1:
try:
chat_id = int(args[1])
except ValueError:
await msg.reply_text("⭕ ID inválido.")
return
LOG_CHAT_ID = chat_id
await _save_config_to_db("log_chat_id", chat_id)
try:
await bot.send_message(chat_id, f"📡 **Logs de CompresUltra Bot activados**\n⚡ Configurado por: `{uid}`")
await msg.reply_text(f"✅ Configurado: `{chat_id}`\n_Mensaje de prueba enviado._")
except Exception as e:
await msg.reply_text(f"⚠️ Configurado pero no pude enviar mensaje de prueba: `{e}`")
return
await msg.reply_text("⭕ Opción inválida. Usa `/logs` sin argumentos para ver la ayuda.")
# ========================
# VERIFICADOR PERIÓDICO DE PLANES EXPIRADOS
# ========================
async def _plan_expiry_checker():
while True:
await asyncio.sleep(3600)
try:
now = datetime.utcnow().isoformat()
expired = await col_users.find({
"plan": {"$nin": ["free", "admin", "superadmin", None]},
"plan_expires": {"$lt": now, "$ne": None}
}).to_list(length=500)
for doc in expired:
uid = doc["user_id"]
plan = doc["plan"]
await col_users.update_one(
{"user_id": uid},
{"$set": {"plan": "free", "plan_expires": None}}
)
await _notify_plan_change(uid, plan, "free", "Tu plan ha expirado automáticamente.")
asyncio.create_task(_log(f"⏰ Plan expirado (checker): `{uid}` — {plan} → free"))
if expired:
logger.info("Plan expiry checker: %d usuarios degradados a free", len(expired))
except Exception as e:
logger.error("Plan expiry checker error: %s", e)
async def _queue_watchdog():
global _global_currently_processing
while True:
await asyncio.sleep(QUEUE_WATCHDOG_INTERVAL)
try:
if _global_currently_processing and _global_currently_processing not in ACTIVE_JOBS:
_global_currently_processing = None
if _global_queue_list:
await _ensure_global_worker()
if _global_worker_task and _global_worker_task.done():
logger.warning("Watchdog: reiniciando worker global con %d elemento(s) pendientes.", len(_global_queue_list))
await _ensure_global_worker()
_global_queue_event.set()
for queue_key, uq in list(_user_queues.items()):
processing_id = uq.get("processing")
if processing_id and processing_id not in ACTIVE_JOBS:
uq["processing"] = None
if uq.get("list"):
await _ensure_user_worker(queue_key)
worker = uq.get("worker")
if worker and worker.done():
logger.warning("Watchdog: reiniciando worker %s con %d elemento(s) pendientes.", queue_key, len(uq["list"]))
await _ensure_user_worker(queue_key)
uq["event"].set()
now = time.time()
stale_limit = COMPRESS_STALL_SECONDS + 30
for job in list(ACTIVE_JOBS.values()):
if job.cancelled or job.system_cancelled:
# Ya fue cancelado (usuario o sistema); solo limpiar si sigue registrado
await _cleanup_job(job)
continue
idle_for = now - (job.last_activity_at or now)
queue_pos = _job_queue_position(job.job_id)
task_done = bool(job.task and job.task.done())
proc_running = bool(job.process and job.process.returncode is None)
if queue_pos is None and not proc_running and not job.is_processing:
logger.warning("Watchdog: limpiando trabajo huérfano %s fuera de cola.", job.job_id)
await _force_finish_job(job, "❌ **Trabajo eliminado por limpieza automática.**")
continue
if queue_pos is not None and queue_pos[1] > 0:
job.is_processing = False
job.queue_name = queue_pos[0]
continue
if proc_running:
ffmpeg_progress_at = job.ffmpeg_last_progress_at or job.last_activity_at or now
ffmpeg_output_at = job.ffmpeg_last_output_at or ffmpeg_progress_at
progress_idle = now - ffmpeg_progress_at
output_idle = now - ffmpeg_output_at
cpu_busy = (job.cpu_usage_pct or 0.0) >= STALL_CPU_FLOOR_PERCENT
watchdog_hard_limit = max(stale_limit, COMPRESS_STALL_SECONDS + FFMPEG_OUTPUT_IDLE_SECONDS + 120)
if progress_idle > watchdog_hard_limit and output_idle > FFMPEG_OUTPUT_IDLE_SECONDS and not cpu_busy:
logger.warning("Watchdog: trabajo %s cancelado por inactividad real (progress=%ss output=%ss).", job.job_id, int(progress_idle), int(output_idle))
reason = "❌ **Trabajo cancelado por inactividad real.**\n\nFFmpeg dejó de dar progreso y salida durante demasiado tiempo.\nReenvía el video para intentarlo otra vez."
if job.ffmpeg_last_stderr:
reason += f"\n\nÚltimo mensaje FFmpeg:\n`{job.ffmpeg_last_stderr[:160]}`"
job.system_cancelled = True
if job.task and not job.task.done():
with contextlib.suppress(Exception):
job.task.cancel()
await _force_finish_job(job, reason)
continue
if job.is_processing and job.stage in {"subiendo", "finalizando"}:
upload_ref = job.upload_last_progress_at or job.upload_started_at or job.last_activity_at or now
upload_idle = now - upload_ref
upload_elapsed = now - (job.upload_started_at or job.started_at or now)
if job.stage == "subiendo":
if upload_idle > UPLOAD_STALL_SECONDS and upload_elapsed > UPLOAD_STALL_SECONDS:
logger.warning("Watchdog: subida atascada para %s (idle=%ss elapsed=%ss bytes=%s/%s).", job.job_id, int(upload_idle), int(upload_elapsed), job.upload_last_bytes, job.upload_total_bytes)
if job.task and not task_done:
with contextlib.suppress(Exception):
job.system_cancelled = True
job.task.cancel()
await _force_finish_job(
job,
"❌ **La subida a Telegram quedó atascada.**\n\nLa compresión terminó, pero el envío final no avanzó durante demasiado tiempo.\nPuedes reenviar el video.",
)
if _global_currently_processing == job.job_id:
_global_currently_processing = None
for uq in _user_queues.values():
if uq.get("processing") == job.job_id:
uq["processing"] = None
continue
finalize_idle = now - (job.upload_completed_at or job.last_activity_at or now)
if finalize_idle > FINALIZE_GRACE_SECONDS:
logger.warning("Watchdog: finalización atascada para %s tras enviar video (%ss).", job.job_id, int(finalize_idle))
await _force_finish_job(
job,
"✅ **Video enviado, pero el cierre del trabajo quedó atascado.**\n\nSi ya recibiste el video, puedes ignorar este aviso.",
)
continue
if job.is_processing and idle_for > stale_limit:
logger.warning("Watchdog: trabajo %s atascado en etapa %s sin proceso activo.", job.job_id, job.stage or "desconocida")
if job.task and not task_done:
with contextlib.suppress(Exception):
job.system_cancelled = True
job.task.cancel()
await _force_finish_job(
job,
"❌ **Trabajo atascado y limpiado automáticamente.**\n\nLa cola quedó liberada. Puedes reenviar el video.",
)
if _global_currently_processing == job.job_id:
_global_currently_processing = None
for uq in _user_queues.values():
if uq.get("processing") == job.job_id:
uq["processing"] = None
if task_done and not proc_running and idle_for > 10:
logger.warning("Watchdog: limpiando trabajo %s con task finalizada pero aún registrado.", job.job_id)
await _force_finish_job(job, "❌ **Trabajo finalizado con estado inconsistente y fue limpiado.**")
except Exception as e:
logger.error("Queue watchdog error: %s", e)
@bot.on_message(filters.command("version") & (filters.private | filters.group))
async def cmd_version(client, msg: Message):
await msg.reply_text(
f"🧾 **Versión del bot**\n\n"
f"🤖 {BOT_VERSION}\n"
f"🔒 Modo: `{'Público' if BOT_MODE == 'public' else 'Privado'}`\n"
f"🧵 Colas por plan: `{'ON' if INDIVIDUAL_QUEUES_ENABLED else 'OFF'}`\n"
f"🛡️ Tope CPU host: `{MAX_CPU_PERCENT}%`\n"
f"🧯 Stall watchdog: `{COMPRESS_STALL_SECONDS}s`"
)
@bot.on_message(filters.command("misjobs") & (filters.private | filters.group))
async def cmd_misjobs(client, msg: Message):
uid = msg.from_user.id
jobs = [job for job in ACTIVE_JOBS.values() if job.user_id == uid and not job.cancelled]
if not jobs:
await msg.reply_text("📭 **No tienes trabajos activos ni en cola.**")
return
lines = ["🎞️ **Tus trabajos**", "━━━━━━━━━━━━━━━━━━━━━"]
for idx, job in enumerate(sorted(jobs, key=lambda j: j.started_at or 0, reverse=True)[:15], 1):
qpos = _job_queue_position(job.job_id)
queue_label = _plan_queue_label((qpos[0] if qpos else job.queue_name) or "free")
pos_txt = "procesando" if qpos and qpos[1] == 0 else (f"#{qpos[1]}/{qpos[2]}" if qpos else "—")
lines.append(
f"{idx}. `{job.fname or job.job_id}`\n"
f" • Etapa: `{job.stage or 'pendiente'}`\n"
f" • Cola: `{queue_label}` | Posición: `{pos_txt}`\n"
f" • Progreso: `{job.progress_pct:.1f}%` | Tiempo: `{_job_elapsed(job)}`"
)
await _send_long(msg, "\n".join(lines))
@bot.on_message(filters.command("limpiaratascos") & filters.private)
async def cmd_limpiaratascos(client, msg: Message):
global _global_currently_processing
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
cleaned = []
now = time.time()
for job in list(ACTIVE_JOBS.values()):
qpos = _job_queue_position(job.job_id)
idle_for = now - (job.last_activity_at or now)
proc_running = bool(job.process and job.process.returncode is None)
if job.cancelled or (job.is_processing and not proc_running and idle_for > 30) or (qpos is None and idle_for > 30):
cleaned.append(job.job_id)
await _force_finish_job(job, "❌ **Trabajo limpiado manualmente por administración.**")
if _global_currently_processing == job.job_id:
_global_currently_processing = None
for uq in _user_queues.values():
if uq.get("processing") == job.job_id:
uq["processing"] = None
if _global_queue_list:
_global_queue_event.set()
for uq in _user_queues.values():
if uq.get("list"):
uq["event"].set()
if not cleaned:
await msg.reply_text("✅ **No encontré trabajos atascados para limpiar.**")
return
await msg.reply_text("✅ **Limpieza completada**\n\n" + "\n".join(f"• `{jid}`" for jid in cleaned[:30]))
# ========================
# /setcpu — Cambiar límite de CPU de FFmpeg en caliente
# ========================
@bot.on_message(filters.command("setcpu") & filters.private)
async def cmd_setcpu(client, msg: Message):
global MAX_CPU_PERCENT
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
parts = msg.text.split()
if len(parts) < 2:
current_slots = _max_parallel_cpu_slots()
await msg.reply_text(
"⚙️ **Configuración de CPU para FFmpeg**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🎚️ Límite actual: `{MAX_CPU_PERCENT}%`\n"
f"🏊 Pool de slots: `{current_slots}`\n"
f"🧩 Capacidad efectiva: `{_effective_cpu_capacity():.2f}` CPU\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
"Uso: `/setcpu <porcentaje>`\n"
"Ejemplo: `/setcpu 60` (limita FFmpeg al 60% de CPU)\n"
"Rango permitido: `10` – `95`"
)
return
try:
new_val = int(parts[1])
except ValueError:
await msg.reply_text("❌ Valor inválido. Usa un número entero entre 10 y 95.")
return
if not (10 <= new_val <= 95):
await msg.reply_text("❌ El valor debe estar entre **10** y **95**.")
return
old_val = MAX_CPU_PERCENT
MAX_CPU_PERCENT = new_val
new_slots = _max_parallel_cpu_slots()
await msg.reply_text(
f"✅ **CPU de FFmpeg actualizado**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"📉 Anterior: `{old_val}%`\n"
f"📈 Nuevo: `{MAX_CPU_PERCENT}%`\n"
f"🏊 Slots de pool resultantes: `{new_slots}`\n"
"_El cambio aplica a los próximos trabajos de compresión._"
)
# ========================
# /limpiar — Liberar RAM, disco y caché de archivos huérfanos
# ========================
@bot.on_message(filters.command("limpiar") & filters.private)
async def cmd_limpiar(client, msg: Message):
global MAX_CPU_PERCENT
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
await msg.reply_text("🧹 **Iniciando limpieza del sistema…**")
import gc
import signal
freed_files = 0
freed_bytes = 0
errors_found = []
# ── 1. CPU: matar procesos ffmpeg zombies/huérfanos ──────────────────────
# Son ffmpeg que ya no tienen job asociado en ACTIVE_JOBS (o job cancelado)
known_pids: set = set()
for job in list(ACTIVE_JOBS.values()):
if not job.cancelled and job.process is not None:
try:
known_pids.add(job.process.pid)
except Exception:
pass
zombie_killed = 0
nice_applied = 0
try:
for proc in psutil.process_iter(["pid", "name", "status"]):
try:
pname = (proc.info.get("name") or "").lower()
if "ffmpeg" not in pname:
continue
pid = proc.info["pid"]
status = proc.info.get("status", "")
# Matar zombies reales
if status == psutil.STATUS_ZOMBIE:
proc.kill()
zombie_killed += 1
continue
# Si no es un pid conocido por el bot, es huérfano → matar
if pid not in known_pids:
proc.kill()
zombie_killed += 1
continue
# Para los ffmpeg activos y legítimos: bajar prioridad (nice 10)
# Esto libera CPU para el SO sin cancelar la compresión
try:
current_nice = proc.nice()
if current_nice < 10:
proc.nice(10)
nice_applied += 1
except Exception:
pass
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
except Exception as e:
errors_found.append(f"cpu_scan: {str(e)[:60]}")
# ── 2. CPU: limpiar jobs del bot con proceso muerto ───────────────────────
jobs_cleaned = 0
now = time.time()
for job in list(ACTIVE_JOBS.values()):
if job.cancelled:
continue
proc_dead = job.process is not None and job.process.returncode is not None
idle_for = now - (job.last_activity_at or now)
if proc_dead and idle_for > 30:
await _force_finish_job(job, "❌ **Trabajo limpiado automáticamente (proceso muerto detectado).**")
jobs_cleaned += 1
# ── 3. Disco: limpiar archivos huérfanos en downloads/ y compressed/ ─────
active_files: set = set()
for job in list(ACTIVE_JOBS.values()):
if not job.cancelled:
try:
if hasattr(job, "in_file") and job.in_file:
active_files.add(os.path.abspath(job.in_file))
if hasattr(job, "out_file") and job.out_file:
active_files.add(os.path.abspath(job.out_file))
except Exception:
pass
for folder in (DOWNLOADS_DIR, COMPRESSED_DIR):
try:
for fpath in os.listdir(folder):
full = os.path.join(folder, fpath)
if not os.path.isfile(full):
continue
if os.path.abspath(full) in active_files:
continue
try:
size = os.path.getsize(full)
age = time.time() - os.path.getmtime(full)
if age > 600: # huérfano si lleva más de 10 min
os.remove(full)
freed_files += 1
freed_bytes += size
except Exception as e:
errors_found.append(str(e)[:60])
except Exception as e:
errors_found.append(f"folder {folder}: {str(e)[:60]}")
# ── 4. RAM: garbage collector ─────────────────────────────────────────────
before_ram = psutil.virtual_memory()
gc_collected = gc.collect()
after_ram = psutil.virtual_memory()
ram_freed_mb = max(0.0, (before_ram.used - after_ram.used) / (1024 ** 2))
# ── 5. Resumen final ──────────────────────────────────────────────────────
freed_mb = freed_bytes / (1024 ** 2)
du_after = psutil.disk_usage("/")
vm_after = psutil.virtual_memory()
cpu_after = psutil.cpu_percent(interval=0.5)
report = (
"✅ **Limpieza completada**\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"⚙️ CPU ahora: `{cpu_after:.1f}%`\n"
f"💀 FFmpeg zombies/huérfanos matados: `{zombie_killed}`\n"
f"📉 FFmpeg activos con prioridad bajada: `{nice_applied}`\n"
f"🗂️ Jobs bot con proceso muerto limpiados: `{jobs_cleaned}`\n"
"━━━━━━━━━━━━━━━━━━━━━\n"
f"🗑️ Archivos huérfanos eliminados: `{freed_files}` ({freed_mb:.1f} MB)\n"
f"🧠 RAM liberada (GC): `{ram_freed_mb:.1f} MB` | Ciclos GC: `{gc_collected}`\n"
f"💽 Disco libre: `{(du_after.total - du_after.used) / (1024**3):.1f} GB` "
f"({100 - du_after.percent:.1f}% libre)\n"
f"🧠 RAM libre: `{vm_after.available / (1024**3):.1f} GB` "
f"({100 - vm_after.percent:.1f}% libre)\n"
)
if errors_found:
report += f"⚠️ Errores menores: `{len(errors_found)}`\n"
report += "━━━━━━━━━━━━━━━━━━━━━"
await msg.reply_text(report)
# ========================
# COMANDOS DE MENÚ
# ========================
USER_COMMANDS = [
("start", "👋 Bienvenida al bot"),
("help", "📖 Ver lista de comandos"),
("miperfil", "👤 Tu perfil y estadísticas"),
("miplan", "📋 Ver tu plan con días restantes"),
("planes", "📊 Ver planes disponibles"),
("micalidad", "⚙️ Ver tu calidad actual"),
("calidad", "🎛️ Cambiar calidad de compresión"),
("cola", "🧵 Ver estado de la cola"),
("cancelar", "❌ Cancelar tu compresión activa"),
("reporte", "📝 Reportar un problema"),
("ping", "🏓 Verificar si el bot responde"),
("misjobs", "🎞️ Ver tus trabajos activos"),
("version", "🧾 Ver versión y modo del bot"),
("velocidad", "⚡ Test de velocidad del servidor"),
("id", "🆔 Ver tu ID"),
("about", "ℹ️ Información del bot"),
]
ADMIN_COMMANDS = USER_COMMANDS + [
("add", "➕ Autorizar usuario"),
("ban", "🚫 Desautorizar usuario"),
("listusers", "👥 Lista de usuarios autorizados"),
("setplan", "📋 Asignar plan a un usuario"),
("renovar", "🔄 Poner o extender días de plan"),
("proxvencer", "⏰ Planes por vencer pronto"),
("userinfo", "🔍 Info detallada de un usuario"),
("grup", "🏘️ Autorizar grupo"),
("bangrup", "🚫 Desautorizar grupo"),
("listgrup", "📗 Lista de grupos autorizados"),
("listadmins", "📓 Lista de administradores"),
("stats", "📊 Estadísticas del bot"),
("status_bot", "🖥️ Estado del servidor"),
("trabajos", "🧰 Ver trabajos activos y cola"),
("diagnostico_cpu", "🧪 Ver límites reales de CPU"),
("info", "📢 Enviar aviso a autorizados"),
("msgusr", "📨 Mensaje privado a usuario"),
("reportes", "📋 Ver reportes de usuarios"),
("adelantar", "⚡ Adelantar usuario en cola"),
("cancelarcola", "🗑️ Cancelar videos de la cola"),
]
SUPERADMIN_COMMANDS = ADMIN_COMMANDS + [
("modo", "🔒 Cambiar modo público/privado"),
("colaindividual", "🧵 Activar/desactivar colas por plan"),
("add_admins", "🛡️ Agregar administrador"),
("ban_admins", "🛡️ Quitar administrador"),
("add_superadmin", "⚡ Agregar super admin"),
("ban_superadmin", "⚡ Quitar super admin"),
("listsuperadmins", "⚡ Lista de super admins"),
("editplan", "✏️ Editar límites de un plan"),
("verplanes", "📋 Ver todos los planes actuales"),
("resetplan", "🔄 Restaurar plan a valores default"),
("resetstats", "🔄 Resetear stats de usuario"),
("broadcast", "📣 Broadcast global con media"),
("dbstats", "🗄️ Estadísticas de Supabase"),
("exportdb", "📦 Exportar backup DB"),
("importdb", "📥 Importar backup DB"),
("logs", "📡 Configurar canal de logs"),
("forzarwatchdog", "🛠️ Reparar workers/colas atascadas"),
("limpiaratascos", "🧹 Limpiar trabajos colgados"),
("setcpu", "⚙️ Cambiar límite de CPU de FFmpeg"),
("limpiar", "🧹 Liberar RAM, disco y caché"),
("actualizarmenu", "🔄 Actualizar menú de comandos"),
]
def _make_bot_commands(cmd_list):
from pyrogram.types import BotCommand
return [BotCommand(cmd, desc) for cmd, desc in cmd_list]
async def _set_menus():
from pyrogram.types import BotCommandScopeDefault, BotCommandScopeChat
errors = []
try:
await bot.set_bot_commands(_make_bot_commands(USER_COMMANDS), scope=BotCommandScopeDefault())
except Exception as e:
errors.append(f"default: {e}")
admins = await col_admins.find({}).to_list(500)
for a in admins:
uid = a["user_id"]
try:
is_sa = await is_super_admin(uid)
cmds = SUPERADMIN_COMMANDS if is_sa else ADMIN_COMMANDS
await bot.set_bot_commands(_make_bot_commands(cmds), scope=BotCommandScopeChat(chat_id=uid))
except Exception as e:
errors.append(f"admin {uid}: {e}")
for uid in SUPER_ADMINS_STATIC:
try:
await bot.set_bot_commands(_make_bot_commands(SUPERADMIN_COMMANDS), scope=BotCommandScopeChat(chat_id=uid))
except Exception as e:
errors.append(f"superadmin {uid}: {e}")
return errors
@bot.on_message(filters.command("actualizarmenu") & filters.private)
async def cmd_actualizarmenu(client, msg: Message):
if not await is_super_admin(msg.from_user.id):
await _no_access(msg)
return
wait = await msg.reply_text("⏳ Actualizando menús...")
errors = await _set_menus()
if errors:
err_txt = "\n".join(str(e) for e in errors[:10])
await wait.edit_text(f"✅ Menús actualizados con algunos errores:\n\n`{err_txt}`")
else:
await wait.edit_text(
"✅ **Menús actualizados correctamente**\n\n"
"👤 Usuarios normales → comandos básicos\n"
"🛡️ Admins → comandos de admin\n"
"⚡ Super Admins → todos los comandos"
)
import asyncio
import sys
# ========================
# INICIO / PARADA
# ========================
async def start_bot():
await db_init()
await bot.start()
me = await bot.get_me()
logger.info("🚀 Bot @%s iniciado | DB: %s", me.username, DB_NAME)
for sa_id in SUPER_ADMINS_STATIC:
try:
await bot.send_message(
sa_id,
f"✅ **CompresUltra Bot iniciado**\n\n"
f"🤖 @{me.username}\n"
f"🗄️ DB: {DB_NAME}\n"
f"⚡ {BOT_VERSION}\n"
f"🧵 Colas por plan: {'ON' if INDIVIDUAL_QUEUES_ENABLED else 'OFF'}",
)
except Exception:
pass
await _log(
f"🚀 **Bot iniciado**\n"
f"🤖 @{me.username} | {BOT_VERSION}\n"
f"🔒 Modo: {BOT_MODE} | 🎬 Log videos: {LOG_VIDEOS}\n"
f"🧵 Colas por plan: {INDIVIDUAL_QUEUES_ENABLED}"
)
await _ensure_global_worker()
asyncio.create_task(_plan_expiry_checker())
asyncio.create_task(_queue_watchdog())
asyncio.create_task(_set_menus())
async def stop_bot():
global _pg_pool
try:
await bot.stop()
except Exception:
pass
try:
if _pg_pool is not None:
await _pg_pool.close()
_pg_pool = None
except Exception:
pass
# ========================
# BLOQUE DE EJECUCIÓN PRINCIPAL
# ========================
if __name__ == "__main__":
# Soluciona problemas de bucles de eventos asíncronos en Windows si usas ese OS
if sys.platform == "win32":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# Obtenemos el bucle de eventos de asyncio
loop = asyncio.get_event_loop()
try:
print("⏳ Inicializando base de datos y levantando el bot...")
# Corremos la función que conecta la DB, inicia el bot y envía los mensajes
loop.run_until_complete(start_bot())
print("🚀 Bot iniciado correctamente y escuchando actualizaciones.")
# Mantiene el bot vivo y procesando comandos/mensajes de Telegram
loop.run_forever()
except KeyboardInterrupt:
print("\n🛑 Apagando el bot por señal del usuario (Ctrl+C)...")
finally:
# Esto asegura que cuando el bot se detenga, limpie las conexiones a la DB
print("💤 Cerrando sesiones de forma segura...")
loop.run_until_complete(stop_bot())
print("✅ Bot completamente apagado.")
import os
import asyncio
import logging
import time
import random
import contextlib
import gc
from collections import deque
import re
import subprocess
import json
import shutil
import tempfile
import zipfile
from typing import Optional, Dict, Any, List
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from urllib.parse import quote_plus, urlparse
try:
from dotenv import load_dotenv
except Exception:
def load_dotenv(*args, **kwargs):
return False
import asyncpg
import psutil
from pyrogram import Client, filters
from pyrogram.types import (
Message, InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
)
# =====================
# CONFIGURACIÓN
# =====================
load_dotenv()
API_ID = os.environ.get("API_ID", "24288670")
API_HASH = os.environ.get("API_HASH", "81c58005802498656d6b689dae1edacc")
BOT_TOKEN = os.environ.get("BOT_TOKEN", "")
BOT_VERSION = "V.6 Ultra Supabase"
BOT_CREATOR = "@Sasuke286"
SUPABASE_URL = os.environ.get("SUPABASE_URL", "https://lkqihreksoitujnwanik.supabase.co")
SUPABASE_PUBLISHABLE_KEY = os.environ.get("SUPABASE_PUBLISHABLE_KEY", "")
SUPABASE_SERVICE_ROLE_KEY = os.environ.get("SUPABASE_SERVICE_ROLE_KEY", "")
SUPABASE_DB_PASSWORD = os.environ.get("SUPABASE_DB_PASSWORD", "")
SUPABASE_PROJECT_REF = os.environ.get("SUPABASE_PROJECT_REF") or (urlparse(SUPABASE_URL).hostname or "").split(".")[0]
DATABASE_URL = os.environ.get("DATABASE_URL", "").strip()
SUPABASE_DB_URL = os.environ.get("SUPABASE_DB_URL", "").strip() or DATABASE_URL
SUPABASE_POOLER_URL = os.environ.get("SUPABASE_POOLER_URL", "").strip()
SUPABASE_DIRECT_URL = os.environ.get("SUPABASE_DIRECT_URL", "").strip()
SUPABASE_POOL_MODE = os.environ.get("SUPABASE_POOL_MODE", "session").strip().lower() or "session"
SUPABASE_USE_TRANSACTION_POOLER = SUPABASE_POOL_MODE == "transaction"
DB_NAME = f"supabase:{SUPABASE_PROJECT_REF or 'unknown'}"
def _redact_db_url(url: str) -> str:
if not url:
return ""
return re.sub(r"://([^:]+):([^@]+)@", r"://\1:***@", url)
def _looks_like_direct_supabase_url(url: str) -> bool:
if not url:
return False
host = (urlparse(url).hostname or "").lower()
return host.startswith("db.") and host.endswith(".supabase.co")
def _build_default_supabase_db_url() -> str:
if SUPABASE_DB_URL:
return SUPABASE_DB_URL
if SUPABASE_POOLER_URL:
return SUPABASE_POOLER_URL
if SUPABASE_DIRECT_URL:
return SUPABASE_DIRECT_URL
if not SUPABASE_PROJECT_REF or not SUPABASE_DB_PASSWORD:
return ""
# Último recurso: conexión directa. Si tu hosting es IPv4-only, el error posterior te indicará que uses el pooler.
return f"postgresql://postgres:{quote_plus(SUPABASE_DB_PASSWORD)}@db.{SUPABASE_PROJECT_REF}.supabase.co:5432/postgres?sslmode=require"
SUPER_ADMINS_STATIC = [5702506445]
# =====================
# CALIDADES PREDEFINIDAS
# Siempre reducen el tamaño del archivo
# =====================
QUALITY_PRESETS = {
"144p": {"resolution": "256x144", "crf": "38", "audio_bitrate": "48k", "fps": "24", "preset": "ultrafast", "codec": "libx265", "label": "144p — Mínimo tamaño"},
"240p": {"resolution": "426x240", "crf": "36", "audio_bitrate": "56k", "fps": "24", "preset": "ultrafast", "codec": "libx265", "label": "240p — Muy ligero"},
"360p": {"resolution": "640x360", "crf": "33", "audio_bitrate": "64k", "fps": "25", "preset": "ultrafast", "codec": "libx265", "label": "360p — Ligero"},
"480p": {"resolution": "854x480", "crf": "30", "audio_bitrate": "80k", "fps": "28", "preset": "ultrafast", "codec": "libx265", "label": "480p — Equilibrado ⭐"},
"720p": {"resolution": "1280x720", "crf": "28", "audio_bitrate": "96k", "fps": "30", "preset": "ultrafast", "codec": "libx265", "label": "720p — HD"},
"1080p": {"resolution": "1920x1080","crf": "26", "audio_bitrate": "128k", "fps": "30", "preset": "ultrafast", "codec": "libx265", "label": "1080p — Full HD"},
}
DEFAULT_QUALITY = QUALITY_PRESETS["480p"].copy()
DEFAULT_QUALITY.pop("label", None)
DEFAULT_PLANS = {
"free": {