feat: introduce Appwrite guild cache support and refactor guild config caching

This commit is contained in:
2025-10-07 10:52:47 -05:00
parent 8be8ea5925
commit a9087261ca
5 changed files with 492 additions and 359 deletions

View File

@@ -21,10 +21,14 @@ ENABLE_MEMORY_OPTIMIZER=false
REDIS_URL= REDIS_URL=
REDIS_PASS= REDIS_PASS=
# Appwrite (for reminders) # Appwrite (for reminders, AI conversations, and guild cache)
APPWRITE_ENDPOINT= APPWRITE_ENDPOINT=
APPWRITE_PROJECT_ID= APPWRITE_PROJECT_ID=
APPWRITE_API_KEY= APPWRITE_API_KEY=
APPWRITE_DATABASE_ID=
APPWRITE_COLLECTION_REMINDERS_ID=
APPWRITE_COLLECTION_AI_CONVERSATIONS_ID=
APPWRITE_COLLECTION_GUILD_CACHE_ID=
# Reminders # Reminders
REMINDERS_POLL_INTERVAL_SECONDS=30 REMINDERS_POLL_INTERVAL_SECONDS=30

View File

@@ -5,6 +5,7 @@
"main": "src/main.ts", "main": "src/main.ts",
"scripts": { "scripts": {
"start": "npx tsx watch src/main.ts", "start": "npx tsx watch src/main.ts",
"script:guild": "node scripts/setupGuildCacheCollection.js",
"dev": "npx tsx watch src/main.ts", "dev": "npx tsx watch src/main.ts",
"dev:light": "CACHE_MESSAGES_LIMIT=25 CACHE_MEMBERS_LIMIT=50 SWEEP_MESSAGES_LIFETIME_SECONDS=600 SWEEP_MESSAGES_INTERVAL_SECONDS=240 npx tsx watch --clear-screen=false src/main.ts", "dev:light": "CACHE_MESSAGES_LIMIT=25 CACHE_MEMBERS_LIMIT=50 SWEEP_MESSAGES_LIFETIME_SECONDS=600 SWEEP_MESSAGES_INTERVAL_SECONDS=240 npx tsx watch --clear-screen=false src/main.ts",
"dev:mem": "MEMORY_LOG_INTERVAL_SECONDS=120 npx tsx watch src/main.ts", "dev:mem": "MEMORY_LOG_INTERVAL_SECONDS=120 npx tsx watch src/main.ts",

View File

@@ -1,14 +1,18 @@
// Simple Appwrite client wrapper // Simple Appwrite client wrapper
// @ts-ignore // @ts-ignore
import { Client, Databases } from 'node-appwrite'; import { Client, Databases } from "node-appwrite";
const endpoint = process.env.APPWRITE_ENDPOINT || ''; const endpoint = process.env.APPWRITE_ENDPOINT || "";
const projectId = process.env.APPWRITE_PROJECT_ID || ''; const projectId = process.env.APPWRITE_PROJECT_ID || "";
const apiKey = process.env.APPWRITE_API_KEY || ''; const apiKey = process.env.APPWRITE_API_KEY || "";
export const APPWRITE_DATABASE_ID = process.env.APPWRITE_DATABASE_ID || ''; export const APPWRITE_DATABASE_ID = process.env.APPWRITE_DATABASE_ID || "";
export const APPWRITE_COLLECTION_REMINDERS_ID = process.env.APPWRITE_COLLECTION_REMINDERS_ID || ''; export const APPWRITE_COLLECTION_REMINDERS_ID =
export const APPWRITE_COLLECTION_AI_CONVERSATIONS_ID = process.env.APPWRITE_COLLECTION_AI_CONVERSATIONS_ID || ''; process.env.APPWRITE_COLLECTION_REMINDERS_ID || "";
export const APPWRITE_COLLECTION_AI_CONVERSATIONS_ID =
process.env.APPWRITE_COLLECTION_AI_CONVERSATIONS_ID || "";
export const APPWRITE_COLLECTION_GUILD_CACHE_ID =
process.env.APPWRITE_COLLECTION_GUILD_CACHE_ID || "";
let client: Client | null = null; let client: Client | null = null;
let databases: Databases | null = null; let databases: Databases | null = null;
@@ -16,7 +20,10 @@ let databases: Databases | null = null;
function ensureClient() { function ensureClient() {
if (!endpoint || !projectId || !apiKey) return null; if (!endpoint || !projectId || !apiKey) return null;
if (client) return client; if (client) return client;
client = new Client().setEndpoint(endpoint).setProject(projectId).setKey(apiKey); client = new Client()
.setEndpoint(endpoint)
.setProject(projectId)
.setKey(apiKey);
databases = new Databases(client); databases = new Databases(client);
return client; return client;
} }
@@ -26,9 +33,31 @@ export function getDatabases(): Databases | null {
} }
export function isAppwriteConfigured(): boolean { export function isAppwriteConfigured(): boolean {
return Boolean(endpoint && projectId && apiKey && APPWRITE_DATABASE_ID && APPWRITE_COLLECTION_REMINDERS_ID); return Boolean(
endpoint &&
projectId &&
apiKey &&
APPWRITE_DATABASE_ID &&
APPWRITE_COLLECTION_REMINDERS_ID
);
} }
export function isAIConversationsConfigured(): boolean { export function isAIConversationsConfigured(): boolean {
return Boolean(endpoint && projectId && apiKey && APPWRITE_DATABASE_ID && APPWRITE_COLLECTION_AI_CONVERSATIONS_ID); return Boolean(
endpoint &&
projectId &&
apiKey &&
APPWRITE_DATABASE_ID &&
APPWRITE_COLLECTION_AI_CONVERSATIONS_ID
);
}
export function isGuildCacheConfigured(): boolean {
return Boolean(
endpoint &&
projectId &&
apiKey &&
APPWRITE_DATABASE_ID &&
APPWRITE_COLLECTION_GUILD_CACHE_ID
);
} }

View File

@@ -1,10 +1,11 @@
import {bot} from "../main"; import { bot } from "../main";
import {Events} from "discord.js"; import { Events } from "discord.js";
import {redis} from "../core/database/redis"; import { redis } from "../core/database/redis";
import {commands} from "../core/loaders/loader"; import { commands } from "../core/loaders/loader";
import {alliance} from "./extras/alliace"; import { alliance } from "./extras/alliace";
import logger from "../core/lib/logger"; import logger from "../core/lib/logger";
import { aiService } from "../core/services/AIService"; import { aiService } from "../core/services/AIService";
import { getGuildConfig } from "../core/database/guildCache";
// Función para manejar respuestas automáticas a la AI // Función para manejar respuestas automáticas a la AI
async function handleAIReply(message: any) { async function handleAIReply(message: any) {
@@ -12,16 +13,20 @@ async function handleAIReply(message: any) {
if (!message.reference?.messageId || message.author.bot) return; if (!message.reference?.messageId || message.author.bot) return;
try { try {
const referencedMessage = await message.channel.messages.fetch(message.reference.messageId); const referencedMessage = await message.channel.messages.fetch(
message.reference.messageId
);
// Verificar si el mensaje referenciado es del bot // Verificar si el mensaje referenciado es del bot
if (referencedMessage.author.id !== message.client.user?.id) return; if (referencedMessage.author.id !== message.client.user?.id) return;
// Verificar que el contenido no sea un comando (para evitar loops) // Verificar que el contenido no sea un comando (para evitar loops)
const server = await bot.prisma.guild.findUnique({ const guildConfig = await getGuildConfig(
where: { id: message.guildId || undefined } message.guildId || message.guild!.id,
}); message.guild!.name,
const PREFIX = server?.prefix || "!"; bot.prisma
);
const PREFIX = guildConfig.prefix || "!";
if (message.content.startsWith(PREFIX)) return; if (message.content.startsWith(PREFIX)) return;
@@ -30,11 +35,15 @@ async function handleAIReply(message: any) {
// Limitar longitud del mensaje // Limitar longitud del mensaje
if (message.content.length > 4000) { if (message.content.length > 4000) {
await message.reply('❌ **Error:** Tu mensaje es demasiado largo (máximo 4000 caracteres).'); await message.reply(
"❌ **Error:** Tu mensaje es demasiado largo (máximo 4000 caracteres)."
);
return; return;
} }
logger.info(`Respuesta automática a AI detectada - Usuario: ${message.author.id}, Guild: ${message.guildId}`); logger.info(
`Respuesta automática a AI detectada - Usuario: ${message.author.id}, Guild: ${message.guildId}`
);
// Indicador de que está escribiendo // Indicador de que está escribiendo
const typingInterval = setInterval(() => { const typingInterval = setInterval(() => {
@@ -43,7 +52,10 @@ async function handleAIReply(message: any) {
try { try {
// Obtener emojis personalizados del servidor // Obtener emojis personalizados del servidor
const emojiResult = { names: [] as string[], map: {} as Record<string, string> }; const emojiResult = {
names: [] as string[],
map: {} as Record<string, string>,
};
try { try {
const guild = message.guild; const guild = message.guild;
if (guild) { if (guild) {
@@ -77,28 +89,46 @@ async function handleAIReply(message: any) {
parts.push(`Canal: #${msg.channel.name}`); parts.push(`Canal: #${msg.channel.name}`);
} }
const userMentions = msg.mentions?.users ? Array.from(msg.mentions.users.values()) : []; const userMentions = msg.mentions?.users
const roleMentions = msg.mentions?.roles ? Array.from(msg.mentions.roles.values()) : []; ? Array.from(msg.mentions.users.values())
: [];
const roleMentions = msg.mentions?.roles
? Array.from(msg.mentions.roles.values())
: [];
if (userMentions.length) { if (userMentions.length) {
parts.push(`Menciones usuario: ${userMentions.slice(0, 5).map((u: any) => u.username ?? u.tag ?? u.id).join(', ')}`); parts.push(
`Menciones usuario: ${userMentions
.slice(0, 5)
.map((u: any) => u.username ?? u.tag ?? u.id)
.join(", ")}`
);
} }
if (roleMentions.length) { if (roleMentions.length) {
parts.push(`Menciones rol: ${roleMentions.slice(0, 5).map((r: any) => r.name ?? r.id).join(', ')}`); parts.push(
`Menciones rol: ${roleMentions
.slice(0, 5)
.map((r: any) => r.name ?? r.id)
.join(", ")}`
);
} }
if (msg.reference?.messageId) { if (msg.reference?.messageId) {
parts.push('Es una respuesta a mensaje de AI'); parts.push("Es una respuesta a mensaje de AI");
} }
if (emojiNames && emojiNames.length) { if (emojiNames && emojiNames.length) {
parts.push(`Emojis personalizados disponibles (usa :nombre:): ${emojiNames.join(', ')}`); parts.push(
`Emojis personalizados disponibles (usa :nombre:): ${emojiNames.join(
", "
)}`
);
} }
const metaRaw = parts.join(' | '); const metaRaw = parts.join(" | ");
return metaRaw.length > 800 ? metaRaw.slice(0, 800) : metaRaw; return metaRaw.length > 800 ? metaRaw.slice(0, 800) : metaRaw;
} catch { } catch {
return ''; return "";
} }
}; };
@@ -106,7 +136,8 @@ async function handleAIReply(message: any) {
// Verificar si hay imágenes adjuntas // Verificar si hay imágenes adjuntas
const attachments = Array.from(message.attachments.values()); const attachments = Array.from(message.attachments.values());
const hasImages = attachments.length > 0 && aiService.hasImageAttachments(attachments); const hasImages =
attachments.length > 0 && aiService.hasImageAttachments(attachments);
// Procesar con el servicio de AI usando memoria persistente y soporte para imágenes // Procesar con el servicio de AI usando memoria persistente y soporte para imágenes
const aiResponse = await aiService.processAIRequestWithMemory( const aiResponse = await aiService.processAIRequestWithMemory(
@@ -117,37 +148,44 @@ async function handleAIReply(message: any) {
message.id, message.id,
message.reference.messageId, message.reference.messageId,
message.client, message.client,
'normal', "normal",
{ {
meta: messageMeta + (hasImages ? ` | Tiene ${attachments.length} imagen(es) adjunta(s)` : ''), meta:
attachments: hasImages ? attachments : undefined messageMeta +
(hasImages
? ` | Tiene ${attachments.length} imagen(es) adjunta(s)`
: ""),
attachments: hasImages ? attachments : undefined,
} }
); );
// Reemplazar emojis personalizados // Reemplazar emojis personalizados
let finalResponse = aiResponse; let finalResponse = aiResponse;
if (emojiResult.names.length > 0) { if (emojiResult.names.length > 0) {
finalResponse = finalResponse.replace(/:([a-zA-Z0-9_]{2,32}):/g, (match, p1: string) => { finalResponse = finalResponse.replace(
/:([a-zA-Z0-9_]{2,32}):/g,
(match, p1: string) => {
const found = emojiResult.map[p1]; const found = emojiResult.map[p1];
return found ? found : match; return found ? found : match;
}); }
);
} }
// Enviar respuesta (dividir si es muy larga) // Enviar respuesta (dividir si es muy larga)
const MAX_CONTENT = 2000; const MAX_CONTENT = 2000;
if (finalResponse.length > MAX_CONTENT) { if (finalResponse.length > MAX_CONTENT) {
const chunks: string[] = []; const chunks: string[] = [];
let currentChunk = ''; let currentChunk = "";
const lines = finalResponse.split('\n'); const lines = finalResponse.split("\n");
for (const line of lines) { for (const line of lines) {
if (currentChunk.length + line.length + 1 > MAX_CONTENT) { if (currentChunk.length + line.length + 1 > MAX_CONTENT) {
if (currentChunk) { if (currentChunk) {
chunks.push(currentChunk.trim()); chunks.push(currentChunk.trim());
currentChunk = ''; currentChunk = "";
} }
} }
currentChunk += (currentChunk ? '\n' : '') + line; currentChunk += (currentChunk ? "\n" : "") + line;
} }
if (currentChunk) { if (currentChunk) {
@@ -158,31 +196,33 @@ async function handleAIReply(message: any) {
if (i === 0) { if (i === 0) {
await message.reply({ content: chunks[i] }); await message.reply({ content: chunks[i] });
} else { } else {
if ('send' in message.channel) { if ("send" in message.channel) {
await message.channel.send({ content: chunks[i] }); await message.channel.send({ content: chunks[i] });
await new Promise(resolve => setTimeout(resolve, 500)); await new Promise((resolve) => setTimeout(resolve, 500));
} }
} }
} }
if (chunks.length > 3) { if (chunks.length > 3) {
if ('send' in message.channel) { if ("send" in message.channel) {
await message.channel.send({ content: "⚠️ Respuesta truncada por longitud." }); await message.channel.send({
content: "⚠️ Respuesta truncada por longitud.",
});
} }
} }
} else { } else {
await message.reply({ content: finalResponse }); await message.reply({ content: finalResponse });
} }
} catch (error: any) { } catch (error: any) {
logger.error(`Error en respuesta automática AI:`, error); logger.error(`Error en respuesta automática AI:`, error);
await message.reply({ await message.reply({
content: `❌ **Error:** ${error.message || 'No pude procesar tu respuesta. Intenta de nuevo.'}` content: `❌ **Error:** ${
error.message || "No pude procesar tu respuesta. Intenta de nuevo."
}`,
}); });
} finally { } finally {
clearInterval(typingInterval); clearInterval(typingInterval);
} }
} catch (error) { } catch (error) {
// Mensaje referenciado no encontrado o error, ignorar silenciosamente // Mensaje referenciado no encontrado o error, ignorar silenciosamente
logger.debug(`Error obteniendo mensaje referenciado: ${error}`); logger.debug(`Error obteniendo mensaje referenciado: ${error}`);
@@ -196,20 +236,21 @@ bot.on(Events.MessageCreate, async (message) => {
await handleAIReply(message); await handleAIReply(message);
await alliance(message); await alliance(message);
const server = await bot.prisma.guild.upsert({
where: { // Usar caché para obtener la configuración del guild
id: message.guildId || undefined const guildConfig = await getGuildConfig(
}, message.guildId || message.guild!.id,
create: { message.guild!.name,
id: message!.guildId || message.guild!.id, bot.prisma
name: message.guild!.name );
},
update: {} const PREFIX = guildConfig.prefix || "!";
})
const PREFIX = server.prefix || "!"
if (!message.content.startsWith(PREFIX)) return; if (!message.content.startsWith(PREFIX)) return;
const [cmdName, ...args] = message.content.slice(PREFIX.length).trim().split(/\s+/); const [cmdName, ...args] = message.content
.slice(PREFIX.length)
.trim()
.split(/\s+/);
const command = commands.get(cmdName); const command = commands.get(cmdName);
if (!command) return; if (!command) return;
@@ -221,18 +262,19 @@ bot.on(Events.MessageCreate, async (message) => {
logger.debug(`Key: ${key}, TTL: ${ttl}`); logger.debug(`Key: ${key}, TTL: ${ttl}`);
if (ttl > 0) { if (ttl > 0) {
return message.reply(`⏳ Espera ${ttl}s antes de volver a usar **${command.name}**.`); return message.reply(
`⏳ Espera ${ttl}s antes de volver a usar **${command.name}**.`
);
} }
// SET con expiración correcta para redis v4+ // SET con expiración correcta para redis v4+
await redis.set(key, "1", { EX: cooldown }); await redis.set(key, "1", { EX: cooldown });
} }
try { try {
await command.run(message, args, message.client); await command.run(message, args, message.client);
} catch (error) { } catch (error) {
logger.error({ err: error }, "Error ejecutando comando"); logger.error({ err: error }, "Error ejecutando comando");
await message.reply("❌ Hubo un error ejecutando el comando."); await message.reply("❌ Hubo un error ejecutando el comando.");
} }
}) });

View File

@@ -1,26 +1,26 @@
import Amayo from "./core/client"; import Amayo from "./core/client";
import { loadCommands } from "./core/loaders/loader"; import { loadCommands } from "./core/loaders/loader";
import { loadEvents } from "./core/loaders/loaderEvents"; import { loadEvents } from "./core/loaders/loaderEvents";
import { redis, redisConnect } from "./core/database/redis"; import { redis, redisConnect } from "./core/database/redis";
import { registeringCommands } from "./core/api/discordAPI"; import { registeringCommands } from "./core/api/discordAPI";
import {loadComponents} from "./core/lib/components"; import { loadComponents } from "./core/lib/components";
import { startMemoryMonitor } from "./core/memory/memoryMonitor"; import { startMemoryMonitor } from "./core/memory/memoryMonitor";
import {memoryOptimizer} from "./core/memory/memoryOptimizer"; import { memoryOptimizer } from "./core/memory/memoryOptimizer";
import { startReminderPoller } from "./core/api/reminders"; import { startReminderPoller } from "./core/api/reminders";
import { ensureRemindersSchema } from "./core/api/remindersSchema"; import { ensureRemindersSchema } from "./core/api/remindersSchema";
import { cleanExpiredGuildCache } from "./core/database/guildCache";
import logger from "./core/lib/logger"; import logger from "./core/lib/logger";
import { applyModalSubmitInteractionPatch } from "./core/patches/discordModalPatch"; import { applyModalSubmitInteractionPatch } from "./core/patches/discordModalPatch";
import { server } from "./server/server"; import { server } from "./server/server";
// Activar monitor de memoria si se define la variable // Activar monitor de memoria si se define la variable
const __memInt = parseInt(process.env.MEMORY_LOG_INTERVAL_SECONDS || '0', 10); const __memInt = parseInt(process.env.MEMORY_LOG_INTERVAL_SECONDS || "0", 10);
if (__memInt > 0) { if (__memInt > 0) {
startMemoryMonitor({ intervalSeconds: __memInt }); startMemoryMonitor({ intervalSeconds: __memInt });
} }
// Activar optimizador de memoria adicional // Activar optimizador de memoria adicional
if (process.env.ENABLE_MEMORY_OPTIMIZER === 'true') { if (process.env.ENABLE_MEMORY_OPTIMIZER === "true") {
memoryOptimizer.start(); memoryOptimizer.start();
} }
@@ -28,38 +28,52 @@ if (process.env.ENABLE_MEMORY_OPTIMIZER === 'true') {
try { try {
applyModalSubmitInteractionPatch(); applyModalSubmitInteractionPatch();
} catch (e) { } catch (e) {
logger.warn({ err: e }, 'No se pudo aplicar el patch de ModalSubmitInteraction'); logger.warn(
{ err: e },
"No se pudo aplicar el patch de ModalSubmitInteraction"
);
} }
export const bot = new Amayo(); export const bot = new Amayo();
// Listeners de robustez del cliente Discord // Listeners de robustez del cliente Discord
bot.on('error', (e) => logger.error({ err: e }, '🐞 Discord client error')); bot.on("error", (e) => logger.error({ err: e }, "🐞 Discord client error"));
bot.on('warn', (m) => logger.warn('⚠️ Discord warn: %s', m)); bot.on("warn", (m) => logger.warn("⚠️ Discord warn: %s", m));
// Evitar reintentos de re-login simultáneos // Evitar reintentos de re-login simultáneos
let relogging = false; let relogging = false;
// Cuando la sesión es invalidada, intentamos reconectar/login // Cuando la sesión es invalidada, intentamos reconectar/login
bot.on('invalidated', () => { bot.on("invalidated", () => {
if (relogging) return; if (relogging) return;
relogging = true; relogging = true;
logger.error('🔄 Sesión de Discord invalidada. Reintentando login...'); logger.error("🔄 Sesión de Discord invalidada. Reintentando login...");
withRetry('Re-login tras invalidated', () => bot.play(), { minDelayMs: 2000, maxDelayMs: 60_000 }) withRetry("Re-login tras invalidated", () => bot.play(), {
.catch(() => { minDelayMs: 2000,
logger.error('No se pudo reloguear tras invalidated, se seguirá intentando en el bucle general.'); maxDelayMs: 60_000,
}) })
.finally(() => { relogging = false; }); .catch(() => {
logger.error(
"No se pudo reloguear tras invalidated, se seguirá intentando en el bucle general."
);
})
.finally(() => {
relogging = false;
});
}); });
// Utilidad: reintentos con backoff exponencial + jitter // Utilidad: reintentos con backoff exponencial + jitter
async function withRetry<T>(name: string, fn: () => Promise<T>, opts?: { async function withRetry<T>(
name: string,
fn: () => Promise<T>,
opts?: {
retries?: number; retries?: number;
minDelayMs?: number; minDelayMs?: number;
maxDelayMs?: number; maxDelayMs?: number;
factor?: number; factor?: number;
jitter?: boolean; jitter?: boolean;
isRetryable?: (err: unknown, attempt: number) => boolean; isRetryable?: (err: unknown, attempt: number) => boolean;
}): Promise<T> { }
): Promise<T> {
const { const {
retries = Infinity, retries = Infinity,
minDelayMs = 1000, minDelayMs = 1000,
@@ -78,11 +92,14 @@ async function withRetry<T>(name: string, fn: () => Promise<T>, opts?: {
return await fn(); return await fn();
} catch (err) { } catch (err) {
attempt++; attempt++;
const errMsg = err instanceof Error ? `${err.name}: ${err.message}` : String(err); const errMsg =
err instanceof Error ? `${err.name}: ${err.message}` : String(err);
logger.error(`${name} falló (intento ${attempt}) => %s`, errMsg); logger.error(`${name} falló (intento ${attempt}) => %s`, errMsg);
if (!isRetryable(err, attempt)) { if (!isRetryable(err, attempt)) {
logger.error(`${name}: error no recuperable, deteniendo reintentos.`); logger.error(
`${name}: error no recuperable, deteniendo reintentos.`
);
throw err; throw err;
} }
@@ -104,36 +121,43 @@ async function withRetry<T>(name: string, fn: () => Promise<T>, opts?: {
} }
// Handlers globales para robustez // Handlers globales para robustez
process.on('unhandledRejection', (reason: any, p) => { process.on("unhandledRejection", (reason: any, p) => {
logger.error({ promise: p, reason }, '🚨 UnhandledRejection en Promise'); logger.error({ promise: p, reason }, "🚨 UnhandledRejection en Promise");
}); });
process.on('uncaughtException', (err) => { process.on("uncaughtException", (err) => {
logger.error({ err }, '🚨 UncaughtException'); logger.error({ err }, "🚨 UncaughtException");
// No salimos; dejamos que el bot continúe vivo // No salimos; dejamos que el bot continúe vivo
}); });
process.on('multipleResolves', (type, promise, reason: any) => { process.on("multipleResolves", (type, promise, reason: any) => {
// Ignorar resoluciones sin razón (ruido) // Ignorar resoluciones sin razón (ruido)
if (type === 'resolve' && (reason === undefined || reason === null)) { if (type === "resolve" && (reason === undefined || reason === null)) {
return; return;
} }
const msg = reason instanceof Error ? `${reason.name}: ${reason.message}` : String(reason); const msg =
const stack = (reason && (reason as any).stack) ? String((reason as any).stack) : ''; reason instanceof Error
const isAbortErr = (reason && ((reason as any).code === 'ABORT_ERR' || /AbortError|operation was aborted/i.test(msg))); ? `${reason.name}: ${reason.message}`
: String(reason);
const stack =
reason && (reason as any).stack ? String((reason as any).stack) : "";
const isAbortErr =
reason &&
((reason as any).code === "ABORT_ERR" ||
/AbortError|operation was aborted/i.test(msg));
const isDiscordWs = /@discordjs\/ws|WebSocketShard/.test(stack); const isDiscordWs = /@discordjs\/ws|WebSocketShard/.test(stack);
if (isAbortErr && isDiscordWs) { if (isAbortErr && isDiscordWs) {
// Ruido benigno de reconexiones del WS de Discord: ignorar // Ruido benigno de reconexiones del WS de Discord: ignorar
return; return;
} }
logger.warn('⚠️ multipleResolves: %s %s', type, msg); logger.warn("⚠️ multipleResolves: %s %s", type, msg);
}); });
let shuttingDown = false; let shuttingDown = false;
async function gracefulShutdown() { async function gracefulShutdown() {
if (shuttingDown) return; if (shuttingDown) return;
shuttingDown = true; shuttingDown = true;
logger.info('🛑 Apagado controlado iniciado...'); logger.info("🛑 Apagado controlado iniciado...");
try { try {
// Detener optimizador de memoria // Detener optimizador de memoria
memoryOptimizer.stop(); memoryOptimizer.stop();
@@ -142,10 +166,10 @@ async function gracefulShutdown() {
try { try {
if (redis?.isOpen) { if (redis?.isOpen) {
await redis.quit(); await redis.quit();
logger.info('🔌 Redis cerrado'); logger.info("🔌 Redis cerrado");
} }
} catch (e) { } catch (e) {
logger.warn({ err: e }, 'No se pudo cerrar Redis limpiamente'); logger.warn({ err: e }, "No se pudo cerrar Redis limpiamente");
} }
// Cerrar Prisma y Discord // Cerrar Prisma y Discord
try { try {
@@ -155,62 +179,95 @@ async function gracefulShutdown() {
await bot.destroy(); await bot.destroy();
} catch {} } catch {}
} finally { } finally {
logger.info('✅ Apagado controlado completo'); logger.info("✅ Apagado controlado completo");
} }
} }
process.on('SIGINT', gracefulShutdown); process.on("SIGINT", gracefulShutdown);
process.on('SIGTERM', gracefulShutdown); process.on("SIGTERM", gracefulShutdown);
async function bootstrap() { async function bootstrap() {
logger.info("🚀 Iniciando bot..."); logger.info("🚀 Iniciando bot...");
await server.listen(process.env.PORT || 3000, () => { await server.listen(process.env.PORT || 3000, () => {
logger.info(`📘 Amayo Docs disponible en http://localhost:${process.env.PORT || 3000}`); logger.info(
`📘 Amayo Docs disponible en http://localhost:${process.env.PORT || 3000}`
);
}); });
// Cargar recursos locales (no deberían tirar el proceso si fallan) // Cargar recursos locales (no deberían tirar el proceso si fallan)
try { loadCommands(); } catch (e) { logger.error({ err: e }, 'Error cargando comandos'); } try {
try { loadComponents(); } catch (e) { logger.error({ err: e }, 'Error cargando componentes'); } loadCommands();
try { loadEvents(); } catch (e) { logger.error({ err: e }, 'Error cargando eventos'); } } catch (e) {
logger.error({ err: e }, "Error cargando comandos");
}
try {
loadComponents();
} catch (e) {
logger.error({ err: e }, "Error cargando componentes");
}
try {
loadEvents();
} catch (e) {
logger.error({ err: e }, "Error cargando eventos");
}
// Registrar comandos en segundo plano con reintentos; no bloquea el arranque del bot // Registrar comandos en segundo plano con reintentos; no bloquea el arranque del bot
withRetry('Registrar slash commands', async () => { withRetry("Registrar slash commands", async () => {
await registeringCommands(); await registeringCommands();
}).catch((e) => logger.error({ err: e }, 'Registro de comandos agotó reintentos')); }).catch((e) =>
logger.error({ err: e }, "Registro de comandos agotó reintentos")
);
// Conectar Redis con reintentos // Conectar Redis con reintentos
await withRetry('Conectar a Redis', async () => { await withRetry("Conectar a Redis", async () => {
await redisConnect(); await redisConnect();
}); });
// Login Discord + DB con reintentos (gestionado en Amayo.play -> conecta Prisma + login) // Login Discord + DB con reintentos (gestionado en Amayo.play -> conecta Prisma + login)
await withRetry('Login de Discord', async () => { await withRetry(
"Login de Discord",
async () => {
await bot.play(); await bot.play();
}, { },
{
isRetryable: (err) => { isRetryable: (err) => {
const msg = err instanceof Error ? `${err.message}` : String(err); const msg = err instanceof Error ? `${err.message}` : String(err);
// Si falta el TOKEN o token inválido, no tiene sentido reintentar sin cambiar config // Si falta el TOKEN o token inválido, no tiene sentido reintentar sin cambiar config
return !/missing discord token|invalid token/i.test(msg); return !/missing discord token|invalid token/i.test(msg);
},
} }
}); );
// Asegurar esquema de Appwrite para recordatorios (colección + atributos + índice) // Asegurar esquema de Appwrite para recordatorios (colección + atributos + índice)
try { await ensureRemindersSchema(); } catch (e) { logger.warn({ err: e }, 'No se pudo asegurar el esquema de recordatorios'); } try {
await ensureRemindersSchema();
} catch (e) {
logger.warn({ err: e }, "No se pudo asegurar el esquema de recordatorios");
}
// Iniciar poller de recordatorios si Appwrite está configurado // Iniciar poller de recordatorios si Appwrite está configurado
startReminderPoller(bot); startReminderPoller(bot);
// Iniciar limpieza periódica de caché de guilds (cada 10 minutos)
setInterval(async () => {
try {
await cleanExpiredGuildCache();
} catch (error) {
logger.error({ error }, "❌ Error en limpieza periódica de caché");
}
}, 10 * 60 * 1000); // 10 minutos
logger.info("✅ Bot conectado a Discord"); logger.info("✅ Bot conectado a Discord");
} }
// Bucle de arranque resiliente: si bootstrap completo falla, reintenta sin matar el proceso // Bucle de arranque resiliente: si bootstrap completo falla, reintenta sin matar el proceso
(async function startLoop() { (async function startLoop() {
await withRetry('Arranque', bootstrap, { await withRetry("Arranque", bootstrap, {
minDelayMs: 1000, minDelayMs: 1000,
maxDelayMs: 60_000, maxDelayMs: 60_000,
isRetryable: (err) => { isRetryable: (err) => {
const msg = err instanceof Error ? `${err.message}` : String(err); const msg = err instanceof Error ? `${err.message}` : String(err);
// No reintentar en bucle si el problema es falta/invalid token // No reintentar en bucle si el problema es falta/invalid token
return !/missing discord token|invalid token/i.test(msg); return !/missing discord token|invalid token/i.test(msg);
} },
}); });
})(); })();