fix: Simplificar traducción y corregir imports

- Eliminar segmentación, traducir texto completo de una vez
- Añadir imports faltantes get_name_to_code, get_flag_mapping
- Restaurar filtro: solo enviar botones si hay texto (sin multimedia)
This commit is contained in:
2026-03-20 04:55:13 -06:00
parent afc446a9aa
commit 100fef5c90
2 changed files with 20 additions and 59 deletions

View File

@@ -10,8 +10,8 @@ import html
from botdiscord.config import get_discord_token, load_config, get_languages
from botdiscord.database import init_db, get_active_languages, get_bot_languages, save_message, get_welcome_message
from botdiscord.ui import PersistentTranslationView, ConfigView, WelcomeTranslationView
from botdiscord.translate import get_reverse_mapping, load_lang_mappings
from botdiscord.ui import PersistentTranslationView, ConfigView, WelcomeTranslationView, TranslationButton
from botdiscord.translate import get_reverse_mapping, load_lang_mappings, get_name_to_code, get_flag_mapping
load_config()
@@ -116,14 +116,14 @@ async def on_message(message):
if message.author.bot: return
text_content = message.content.strip()
if not text_content and not message.attachments: return
if not text_content: return
# Filtros de stickers/emojis/etc
if message.stickers or text_content.startswith('https://tenor.com/') or \
re.fullmatch(r'<(a?):[a-zA-Z0-9_]+:[0-9]+>', text_content):
return
if text_content and len(text_content) < 2: return
if len(text_content) < 2: return
active_codes = get_active_langs_for_guild(message.guild.id)
if not active_codes: return
@@ -141,7 +141,6 @@ async def on_message(message):
text_to_translate = mention_pattern.sub(replace_mention, text_escaped)
save_message(message.id, message.guild.id, message.author.id, text_to_translate, mentions_map, 'discord')
from botdiscord.ui import TranslationButton
view = discord.ui.View(timeout=None)
name_to_code = get_name_to_code("discord")
flag_mapping = get_flag_mapping("discord")

View File

@@ -49,50 +49,6 @@ REVERSE_MAPPING = {}
FLAG_MAPPING = {}
NAME_TO_CODE = {}
async def _do_translate_request(session, url, text, target_code, max_length=500):
"""Función interna para realizar una única petición de traducción."""
if not text.strip() or not re.search(r'[a-zA-Z\u00C0-\u017F]', text):
return text
chunks = []
if len(text) > max_length:
parts = text.split(' ')
current_chunk = ''
for part in parts:
if len(current_chunk) + len(part) + 1 <= max_length:
current_chunk += (' ' if current_chunk else '') + part
else:
if current_chunk:
chunks.append(current_chunk)
current_chunk = part
if current_chunk:
chunks.append(current_chunk)
else:
chunks.append(text)
results = []
for chunk in chunks:
payload = {
"q": chunk,
"source": "auto",
"target": target_code,
"format": "html"
}
try:
async with session.post(url, json=payload, timeout=30) as resp:
if resp.status == 200:
data = await resp.json()
translated = data.get("translatedText", chunk)
results.append(translated)
else:
results.append(chunk)
except Exception as e:
print(f"[TRANSLATE] Error en petición: {e}")
results.append(chunk)
return ' '.join(results)
async def translate_text(text: str, target_lang: str) -> str:
url = get_libretranslate_url()
if not url:
@@ -100,17 +56,23 @@ async def translate_text(text: str, target_lang: str) -> str:
target_code = NAME_TO_CODE.get(target_lang, target_lang)
segments = re.split(r'([.!?]+\s*|\n+)', text)
segments = [s for s in segments if s]
payload = {
"q": text,
"source": "auto",
"target": target_code,
"format": "html"
}
async with aiohttp.ClientSession() as session:
tasks = []
for segment in segments:
tasks.append(_do_translate_request(session, url, segment, target_code, max_length=400))
translated_segments = await asyncio.gather(*tasks)
return "".join(translated_segments)
try:
async with aiohttp.ClientSession() as session:
async with session.post(url, json=payload, timeout=30) as resp:
if resp.status == 200:
data = await resp.json()
return data.get("translatedText", text)
else:
return text
except Exception:
return text
def translate_text_sync(text: str, target_lang: str) -> str:
"""Versión síncrona de translate_text utilizando un hilo separado."""