V2 Pro: Logging rotativo, Redis cache, Health Check de LibreTranslate y Rate Limiting en botones (#7)

This commit is contained in:
2026-03-20 18:03:56 -06:00
parent 57d570ad31
commit 06da793709
13 changed files with 264 additions and 17 deletions

View File

@@ -3,6 +3,8 @@ import re
import asyncio
from botdiscord.config import get_libretranslate_url, get_languages
from botdiscord.database import get_available_languages, get_bot_languages
from utils.logger import discord_logger as log
from utils.cache import cache_get, cache_set
def load_lang_mappings(bot_type: str = None):
global LANG_MAPPING, REVERSE_MAPPING, FLAG_MAPPING, _cached_bot_type, NAME_TO_CODE
@@ -15,14 +17,14 @@ def load_lang_mappings(bot_type: str = None):
if not available:
from botdiscord.config import get_languages
available = get_languages()
print(f"[DEBUG] Idiomas desde config: {available}")
log.debug(f"Idiomas desde config: {available}")
all_codes = [lang["code"] for lang in available]
print(f"[DEBUG] Códigos disponibles: {all_codes}")
log.debug(f"Códigos disponibles: {all_codes}")
if _cached_bot_type:
active_codes = get_bot_languages(_cached_bot_type)
print(f"[DEBUG] Códigos activos para {_cached_bot_type}: {active_codes}")
log.debug(f"Códigos activos para {_cached_bot_type}: {active_codes}")
if not active_codes:
active_codes = all_codes
else:
@@ -35,9 +37,6 @@ def load_lang_mappings(bot_type: str = None):
code_to_name = {lang["code"]: lang["name"] for lang in available if lang["code"] in active_codes}
flag_dict = {lang["code"]: lang.get("flag", "") for lang in available}
print(f"[DEBUG] FLAG_MAPPING: {flag_dict}")
print(f"[DEBUG] NAME_TO_CODE: {name_to_code}")
LANG_MAPPING = code_to_name
NAME_TO_CODE = name_to_code
FLAG_MAPPING = flag_dict
@@ -67,18 +66,57 @@ async def _translate_segment(session, url, segment, target_code):
except Exception:
return segment
_libretranslate_healthy: bool = True
_last_health_check: float = 0
async def check_libretranslate_health(url: str) -> bool:
"""Verifica si LibreTranslate está disponible. Cachea el resultado 30 segundos."""
global _libretranslate_healthy, _last_health_check
import time
now = time.monotonic()
if now - _last_health_check < 30:
return _libretranslate_healthy
_last_health_check = now
try:
async with aiohttp.ClientSession() as session:
async with session.get(url.replace("/translate", "/languages"), timeout=3) as resp:
_libretranslate_healthy = resp.status == 200
except Exception:
_libretranslate_healthy = False
if not _libretranslate_healthy:
log.warning("⚠️ LibreTranslate no está disponible o tardó demasiado en responder.")
return _libretranslate_healthy
async def translate_text(text: str, target_lang: str) -> str:
url = get_libretranslate_url()
if not url: return text
# Health Check: si LibreTranslate está caído, retornamos el texto con aviso
if not await check_libretranslate_health(url):
return f"⚠️ *Servicio de traducción en mantenimiento.* | {text}"
target_code = NAME_TO_CODE.get(target_lang, target_lang)
# Revisamos caché Redis antes de hacer cualquier petición
redis_key = f"trans:{target_code}:{hash(text)}"
cached = cache_get(redis_key)
if cached:
return cached
segments = re.split(r'([.?!]+\s*|\n+)', text)
try:
async with aiohttp.ClientSession() as session:
tasks = [_translate_segment(session, url, seg, target_code) for seg in segments]
translated_segments = await asyncio.gather(*tasks)
return "".join(translated_segments)
result = "".join(translated_segments)
# Guardar en Redis por 24 horas
if result != text:
cache_set(redis_key, result, ttl=86400)
return result
except Exception:
return text