fix(discord): solución definitiva de persistencia con registro global y custom_ids estáticos
This commit is contained in:
@@ -6,10 +6,11 @@ import discord
|
||||
from discord.ext import commands
|
||||
from discord import app_commands
|
||||
import re
|
||||
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
|
||||
from botdiscord.ui import TranslationView, ConfigView
|
||||
from botdiscord.ui import PersistentTranslationView, ConfigView
|
||||
from botdiscord.translate import get_reverse_mapping, load_lang_mappings
|
||||
|
||||
load_config()
|
||||
@@ -23,117 +24,88 @@ async def on_ready():
|
||||
init_db()
|
||||
load_lang_mappings("discord")
|
||||
|
||||
# Registramos la vista persistente para que los botones funcionen tras reinicios
|
||||
# Primero obtenemos todos los idiomas habilitados globalmente para crear la vista base
|
||||
try:
|
||||
from botdiscord.translate import get_lang_mapping
|
||||
lang_mapping = get_lang_mapping("discord")
|
||||
all_langs = list(lang_mapping.keys())
|
||||
bot.add_view(TranslationView(all_langs))
|
||||
except Exception as e:
|
||||
print(f"Error registrando vista persistente: {e}")
|
||||
# Registramos la vista persistente GLOBALMENTE
|
||||
# Esto asegura que cualquier botón con el custom_id adecuado sea escuchado
|
||||
bot.add_view(PersistentTranslationView())
|
||||
|
||||
print(f"Bot Discord conectado como {bot.user}")
|
||||
try:
|
||||
synced = await bot.tree.sync()
|
||||
print(f"Sincronizados {len(synced)} comandos.")
|
||||
except Exception as e:
|
||||
print(e)
|
||||
print(f"Error sync: {e}")
|
||||
|
||||
def get_active_langs_for_guild(guild_id):
|
||||
from botdiscord.translate import get_reverse_mapping, get_flag_mapping
|
||||
|
||||
from botdiscord.translate import get_reverse_mapping
|
||||
active = get_active_languages(guild_id)
|
||||
print(f"[BOT DEBUG] guild_id={guild_id}, active from db: {active}")
|
||||
if not active:
|
||||
active = get_bot_languages("discord")
|
||||
print(f"[BOT DEBUG] active from bot_languages: {active}")
|
||||
if not active:
|
||||
active = [lang["code"] for lang in get_languages()]
|
||||
print(f"[BOT DEBUG] active from config: {active}")
|
||||
|
||||
reverse_mapping = get_reverse_mapping("discord")
|
||||
print(f"[BOT DEBUG] reverse_mapping: {reverse_mapping}")
|
||||
|
||||
result = [reverse_mapping[l] for l in active if l in reverse_mapping]
|
||||
print(f"[BOT DEBUG] langs_to_show: {result}")
|
||||
return result
|
||||
# Devolvemos códigos para filtrar la vista persistente
|
||||
return active
|
||||
|
||||
@bot.event
|
||||
async def on_message(message):
|
||||
if message.author.bot:
|
||||
return
|
||||
if message.author.bot: return
|
||||
|
||||
text_content = message.content.strip()
|
||||
has_attachments = len(message.attachments) > 0
|
||||
has_embeds = len(message.embeds) > 0
|
||||
if not text_content and not message.attachments: return
|
||||
|
||||
is_sticker = message.stickers
|
||||
is_gif_url = text_content.startswith('https://tenor.com/') or text_content.startswith('https://giphy.com/')
|
||||
is_discord_emoji = re.fullmatch(r'<(a?):[a-zA-Z0-9_]+:[0-9]+>', text_content)
|
||||
|
||||
if is_sticker or is_gif_url or is_discord_emoji:
|
||||
# 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 not text_content and not has_attachments:
|
||||
return
|
||||
|
||||
if has_attachments and not text_content:
|
||||
return
|
||||
if text_content and len(text_content) < 2: return
|
||||
|
||||
active_langs = get_active_langs_for_guild(message.guild.id)
|
||||
if not active_langs:
|
||||
return
|
||||
active_codes = get_active_langs_for_guild(message.guild.id)
|
||||
if not active_codes: return
|
||||
|
||||
import html
|
||||
# Escapar y procesar menciones
|
||||
text_escaped = html.escape(message.content)
|
||||
|
||||
# Buscamos menciones que ya están escapadas (<@...>)
|
||||
mention_pattern = re.compile(r'<@!?(\d+)>|<@&(\d+)>|<#(\d+)>')
|
||||
mentions_map = {}
|
||||
|
||||
def replace_mention(match):
|
||||
# Usamos una etiqueta autocerrada para que el traductor no intente cerrarla él mismo
|
||||
placeholder = f"<m{len(mentions_map)} />"
|
||||
# Guardamos la mención original (sin escapar) para restaurarla luego
|
||||
mentions_map[placeholder] = html.unescape(match.group(0))
|
||||
return placeholder
|
||||
|
||||
text_to_translate = mention_pattern.sub(replace_mention, text_escaped)
|
||||
|
||||
# Guardamos el mensaje en la base de datos para persistencia y caché
|
||||
save_message(message.id, message.guild.id, message.author.id, text_to_translate, mentions_map, 'discord')
|
||||
|
||||
langs_to_show = active_langs
|
||||
# Creamos una vista filtrada basada en la persistente para mostrar solo los botones activos
|
||||
# Pero los botones mantienen sus custom_ids globales
|
||||
from botdiscord.ui import TranslationButton
|
||||
view = discord.ui.View(timeout=None)
|
||||
|
||||
# Cargamos mapeos para etiquetas de botones
|
||||
from botdiscord.translate import get_name_to_code, get_flag_mapping
|
||||
name_to_code = get_name_to_code("discord")
|
||||
flag_mapping = get_flag_mapping("discord")
|
||||
code_to_name = {v: k for k, v in name_to_code.items()}
|
||||
|
||||
if langs_to_show:
|
||||
print(f"[BOT DEBUG] Creating TranslationView with langs: {langs_to_show}")
|
||||
view = TranslationView(langs_to_show)
|
||||
print(f"[BOT DEBUG] View created, sending message...")
|
||||
try:
|
||||
await message.reply("¿Traducir este mensaje?", view=view, mention_author=False)
|
||||
print(f"[BOT DEBUG] Message sent successfully")
|
||||
except Exception as e:
|
||||
print(f"[BOT DEBUG] Error sending message: {e}")
|
||||
for code in active_codes:
|
||||
name = code_to_name.get(code, code)
|
||||
flag = flag_mapping.get(code, "")
|
||||
view.add_item(TranslationButton(name, code, flag))
|
||||
|
||||
@bot.tree.command(name="configurar", description="Configura los idiomas de traducción para este servidor")
|
||||
try:
|
||||
await message.reply("¿Traducir este mensaje?", view=view, mention_author=False)
|
||||
except Exception as e:
|
||||
print(f"Error enviando reply: {e}")
|
||||
|
||||
@bot.tree.command(name="configurar", description="Configura los idiomas de traducción")
|
||||
@app_commands.checks.has_permissions(administrator=True)
|
||||
async def configurar(interaction: discord.Interaction):
|
||||
view = ConfigView(interaction.guild_id, "discord")
|
||||
await interaction.response.send_message(
|
||||
"Selecciona los idiomas que quieres habilitar para los botones de traducción:",
|
||||
view=view,
|
||||
ephemeral=True
|
||||
)
|
||||
await interaction.response.send_message("Selecciona idiomas habilitados:", view=view, ephemeral=True)
|
||||
|
||||
def run_discord_bot():
|
||||
token = get_discord_token()
|
||||
if not token or token == "TU_DISCORD_BOT_TOKEN":
|
||||
print("ERROR: Configura el token de Discord en config.yaml")
|
||||
return
|
||||
bot.run(token)
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user