V2 Pro: Logging rotativo, Redis cache, Health Check de LibreTranslate y Rate Limiting en botones (#7)
This commit is contained in:
@@ -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
|
||||
|
||||
|
||||
@@ -11,6 +11,11 @@ from botdiscord.database import (
|
||||
get_available_languages,
|
||||
save_message
|
||||
)
|
||||
from utils.logger import discord_logger as log
|
||||
from utils.cache import cache_increment
|
||||
|
||||
# Rate Limit: máximo 1 clic por usuario por idioma cada 3 segundos
|
||||
_RATE_LIMIT_SECONDS = 3
|
||||
|
||||
class TranslationButton(discord.ui.Button):
|
||||
def __init__(self, lang_name: str, lang_code: str, flag: str):
|
||||
@@ -24,6 +29,16 @@ class TranslationButton(discord.ui.Button):
|
||||
async def callback(self, interaction: discord.Interaction):
|
||||
await interaction.response.defer()
|
||||
|
||||
# Rate Limiting: verificamos que el usuario no esté haciendo spam
|
||||
rate_key = f"rl:discord:{interaction.user.id}:{self.lang_code}"
|
||||
clicks = cache_increment(rate_key, ttl=_RATE_LIMIT_SECONDS)
|
||||
if clicks > 1:
|
||||
await interaction.followup.send(
|
||||
f"⏳ Por favor espera {_RATE_LIMIT_SECONDS} segundos entre traducciones.",
|
||||
ephemeral=True
|
||||
)
|
||||
return
|
||||
|
||||
try:
|
||||
if not interaction.message.reference:
|
||||
await interaction.followup.send("⚠️ No se pudo encontrar el mensaje original.", ephemeral=True)
|
||||
@@ -52,25 +67,22 @@ class TranslationButton(discord.ui.Button):
|
||||
translated = translated.replace(placeholder, mention)
|
||||
translated = translated.replace(placeholder.replace(" ", ""), mention)
|
||||
|
||||
# --- FILTRADO DINÁMICO Y BANDERAS DE LA BD ---
|
||||
guild_id = interaction.guild_id
|
||||
active_codes = get_active_languages(guild_id)
|
||||
if not active_codes:
|
||||
active_codes = get_bot_languages("discord")
|
||||
|
||||
# Obtenemos los idiomas y banderas REALES de la base de datos
|
||||
db_langs = get_available_languages()
|
||||
|
||||
new_view = discord.ui.View(timeout=None)
|
||||
for lang in db_langs:
|
||||
if lang['code'] in active_codes:
|
||||
# Usamos el nombre y la bandera que vienen de MySQL
|
||||
new_view.add_item(TranslationButton(lang['name'], lang['code'], lang.get('flag', '')))
|
||||
|
||||
await interaction.edit_original_response(content=translated, view=new_view)
|
||||
|
||||
except Exception as e:
|
||||
print(f"[ERROR UI] {e}")
|
||||
log.error(f"Error en botón de traducción Discord: {e}")
|
||||
await interaction.followup.send(f"❌ Error: {str(e)}", ephemeral=True)
|
||||
|
||||
class PersistentTranslationView(discord.ui.View):
|
||||
|
||||
Reference in New Issue
Block a user