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_PASS=
# Appwrite (for reminders)
# Appwrite (for reminders, AI conversations, and guild cache)
APPWRITE_ENDPOINT=
APPWRITE_PROJECT_ID=
APPWRITE_API_KEY=
APPWRITE_DATABASE_ID=
APPWRITE_COLLECTION_REMINDERS_ID=
APPWRITE_COLLECTION_AI_CONVERSATIONS_ID=
APPWRITE_COLLECTION_GUILD_CACHE_ID=
# Reminders
REMINDERS_POLL_INTERVAL_SECONDS=30

View File

@@ -5,6 +5,7 @@
"main": "src/main.ts",
"scripts": {
"start": "npx tsx watch src/main.ts",
"script:guild": "node scripts/setupGuildCacheCollection.js",
"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:mem": "MEMORY_LOG_INTERVAL_SECONDS=120 npx tsx watch src/main.ts",

View File

@@ -1,14 +1,18 @@
// Simple Appwrite client wrapper
// @ts-ignore
import { Client, Databases } from 'node-appwrite';
import { Client, Databases } from "node-appwrite";
const endpoint = process.env.APPWRITE_ENDPOINT || '';
const projectId = process.env.APPWRITE_PROJECT_ID || '';
const apiKey = process.env.APPWRITE_API_KEY || '';
const endpoint = process.env.APPWRITE_ENDPOINT || "";
const projectId = process.env.APPWRITE_PROJECT_ID || "";
const apiKey = process.env.APPWRITE_API_KEY || "";
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_AI_CONVERSATIONS_ID = process.env.APPWRITE_COLLECTION_AI_CONVERSATIONS_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_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 databases: Databases | null = null;
@@ -16,7 +20,10 @@ let databases: Databases | null = null;
function ensureClient() {
if (!endpoint || !projectId || !apiKey) return null;
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);
return client;
}
@@ -26,9 +33,31 @@ export function getDatabases(): Databases | null {
}
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 {
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

@@ -5,6 +5,7 @@ import {commands} from "../core/loaders/loader";
import { alliance } from "./extras/alliace";
import logger from "../core/lib/logger";
import { aiService } from "../core/services/AIService";
import { getGuildConfig } from "../core/database/guildCache";
// Función para manejar respuestas automáticas a la AI
async function handleAIReply(message: any) {
@@ -12,16 +13,20 @@ async function handleAIReply(message: any) {
if (!message.reference?.messageId || message.author.bot) return;
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
if (referencedMessage.author.id !== message.client.user?.id) return;
// Verificar que el contenido no sea un comando (para evitar loops)
const server = await bot.prisma.guild.findUnique({
where: { id: message.guildId || undefined }
});
const PREFIX = server?.prefix || "!";
const guildConfig = await getGuildConfig(
message.guildId || message.guild!.id,
message.guild!.name,
bot.prisma
);
const PREFIX = guildConfig.prefix || "!";
if (message.content.startsWith(PREFIX)) return;
@@ -30,11 +35,15 @@ async function handleAIReply(message: any) {
// Limitar longitud del mensaje
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;
}
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
const typingInterval = setInterval(() => {
@@ -43,7 +52,10 @@ async function handleAIReply(message: any) {
try {
// 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 {
const guild = message.guild;
if (guild) {
@@ -77,28 +89,46 @@ async function handleAIReply(message: any) {
parts.push(`Canal: #${msg.channel.name}`);
}
const userMentions = msg.mentions?.users ? Array.from(msg.mentions.users.values()) : [];
const roleMentions = msg.mentions?.roles ? Array.from(msg.mentions.roles.values()) : [];
const userMentions = msg.mentions?.users
? Array.from(msg.mentions.users.values())
: [];
const roleMentions = msg.mentions?.roles
? Array.from(msg.mentions.roles.values())
: [];
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) {
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) {
parts.push('Es una respuesta a mensaje de AI');
parts.push("Es una respuesta a mensaje de AI");
}
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;
} catch {
return '';
return "";
}
};
@@ -106,7 +136,8 @@ async function handleAIReply(message: any) {
// Verificar si hay imágenes adjuntas
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
const aiResponse = await aiService.processAIRequestWithMemory(
@@ -117,37 +148,44 @@ async function handleAIReply(message: any) {
message.id,
message.reference.messageId,
message.client,
'normal',
"normal",
{
meta: messageMeta + (hasImages ? ` | Tiene ${attachments.length} imagen(es) adjunta(s)` : ''),
attachments: hasImages ? attachments : undefined
meta:
messageMeta +
(hasImages
? ` | Tiene ${attachments.length} imagen(es) adjunta(s)`
: ""),
attachments: hasImages ? attachments : undefined,
}
);
// Reemplazar emojis personalizados
let finalResponse = aiResponse;
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];
return found ? found : match;
});
}
);
}
// Enviar respuesta (dividir si es muy larga)
const MAX_CONTENT = 2000;
if (finalResponse.length > MAX_CONTENT) {
const chunks: string[] = [];
let currentChunk = '';
const lines = finalResponse.split('\n');
let currentChunk = "";
const lines = finalResponse.split("\n");
for (const line of lines) {
if (currentChunk.length + line.length + 1 > MAX_CONTENT) {
if (currentChunk) {
chunks.push(currentChunk.trim());
currentChunk = '';
currentChunk = "";
}
}
currentChunk += (currentChunk ? '\n' : '') + line;
currentChunk += (currentChunk ? "\n" : "") + line;
}
if (currentChunk) {
@@ -158,31 +196,33 @@ async function handleAIReply(message: any) {
if (i === 0) {
await message.reply({ content: chunks[i] });
} else {
if ('send' in message.channel) {
if ("send" in message.channel) {
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 ('send' in message.channel) {
await message.channel.send({ content: "⚠️ Respuesta truncada por longitud." });
if ("send" in message.channel) {
await message.channel.send({
content: "⚠️ Respuesta truncada por longitud.",
});
}
}
} else {
await message.reply({ content: finalResponse });
}
} catch (error: any) {
logger.error(`Error en respuesta automática AI:`, error);
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 {
clearInterval(typingInterval);
}
} catch (error) {
// Mensaje referenciado no encontrado o error, ignorar silenciosamente
logger.debug(`Error obteniendo mensaje referenciado: ${error}`);
@@ -196,20 +236,21 @@ bot.on(Events.MessageCreate, async (message) => {
await handleAIReply(message);
await alliance(message);
const server = await bot.prisma.guild.upsert({
where: {
id: message.guildId || undefined
},
create: {
id: message!.guildId || message.guild!.id,
name: message.guild!.name
},
update: {}
})
const PREFIX = server.prefix || "!"
// Usar caché para obtener la configuración del guild
const guildConfig = await getGuildConfig(
message.guildId || message.guild!.id,
message.guild!.name,
bot.prisma
);
const PREFIX = guildConfig.prefix || "!";
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);
if (!command) return;
@@ -221,18 +262,19 @@ bot.on(Events.MessageCreate, async (message) => {
logger.debug(`Key: ${key}, TTL: ${ttl}`);
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+
await redis.set(key, "1", { EX: cooldown });
}
try {
await command.run(message, args, message.client);
} catch (error) {
logger.error({ err: error }, "Error ejecutando comando");
await message.reply("❌ Hubo un error ejecutando el comando.");
}
})
});

View File

@@ -1,4 +1,3 @@
import Amayo from "./core/client";
import { loadCommands } from "./core/loaders/loader";
import { loadEvents } from "./core/loaders/loaderEvents";
@@ -9,18 +8,19 @@ import { startMemoryMonitor } from "./core/memory/memoryMonitor";
import { memoryOptimizer } from "./core/memory/memoryOptimizer";
import { startReminderPoller } from "./core/api/reminders";
import { ensureRemindersSchema } from "./core/api/remindersSchema";
import { cleanExpiredGuildCache } from "./core/database/guildCache";
import logger from "./core/lib/logger";
import { applyModalSubmitInteractionPatch } from "./core/patches/discordModalPatch";
import { server } from "./server/server";
// 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) {
startMemoryMonitor({ intervalSeconds: __memInt });
}
// Activar optimizador de memoria adicional
if (process.env.ENABLE_MEMORY_OPTIMIZER === 'true') {
if (process.env.ENABLE_MEMORY_OPTIMIZER === "true") {
memoryOptimizer.start();
}
@@ -28,38 +28,52 @@ if (process.env.ENABLE_MEMORY_OPTIMIZER === 'true') {
try {
applyModalSubmitInteractionPatch();
} 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();
// Listeners de robustez del cliente Discord
bot.on('error', (e) => logger.error({ err: e }, '🐞 Discord client error'));
bot.on('warn', (m) => logger.warn('⚠️ Discord warn: %s', m));
bot.on("error", (e) => logger.error({ err: e }, "🐞 Discord client error"));
bot.on("warn", (m) => logger.warn("⚠️ Discord warn: %s", m));
// Evitar reintentos de re-login simultáneos
let relogging = false;
// Cuando la sesión es invalidada, intentamos reconectar/login
bot.on('invalidated', () => {
bot.on("invalidated", () => {
if (relogging) return;
relogging = true;
logger.error('🔄 Sesión de Discord invalidada. Reintentando login...');
withRetry('Re-login tras invalidated', () => bot.play(), { minDelayMs: 2000, maxDelayMs: 60_000 })
.catch(() => {
logger.error('No se pudo reloguear tras invalidated, se seguirá intentando en el bucle general.');
logger.error("🔄 Sesión de Discord invalidada. Reintentando login...");
withRetry("Re-login tras invalidated", () => bot.play(), {
minDelayMs: 2000,
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
async function withRetry<T>(name: string, fn: () => Promise<T>, opts?: {
async function withRetry<T>(
name: string,
fn: () => Promise<T>,
opts?: {
retries?: number;
minDelayMs?: number;
maxDelayMs?: number;
factor?: number;
jitter?: boolean;
isRetryable?: (err: unknown, attempt: number) => boolean;
}): Promise<T> {
}
): Promise<T> {
const {
retries = Infinity,
minDelayMs = 1000,
@@ -78,11 +92,14 @@ async function withRetry<T>(name: string, fn: () => Promise<T>, opts?: {
return await fn();
} catch (err) {
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);
if (!isRetryable(err, attempt)) {
logger.error(`${name}: error no recuperable, deteniendo reintentos.`);
logger.error(
`${name}: error no recuperable, deteniendo reintentos.`
);
throw err;
}
@@ -104,36 +121,43 @@ async function withRetry<T>(name: string, fn: () => Promise<T>, opts?: {
}
// Handlers globales para robustez
process.on('unhandledRejection', (reason: any, p) => {
logger.error({ promise: p, reason }, '🚨 UnhandledRejection en Promise');
process.on("unhandledRejection", (reason: any, p) => {
logger.error({ promise: p, reason }, "🚨 UnhandledRejection en Promise");
});
process.on('uncaughtException', (err) => {
logger.error({ err }, '🚨 UncaughtException');
process.on("uncaughtException", (err) => {
logger.error({ err }, "🚨 UncaughtException");
// 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)
if (type === 'resolve' && (reason === undefined || reason === null)) {
if (type === "resolve" && (reason === undefined || reason === null)) {
return;
}
const msg = reason instanceof Error ? `${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 msg =
reason instanceof Error
? `${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);
if (isAbortErr && isDiscordWs) {
// Ruido benigno de reconexiones del WS de Discord: ignorar
return;
}
logger.warn('⚠️ multipleResolves: %s %s', type, msg);
logger.warn("⚠️ multipleResolves: %s %s", type, msg);
});
let shuttingDown = false;
async function gracefulShutdown() {
if (shuttingDown) return;
shuttingDown = true;
logger.info('🛑 Apagado controlado iniciado...');
logger.info("🛑 Apagado controlado iniciado...");
try {
// Detener optimizador de memoria
memoryOptimizer.stop();
@@ -142,10 +166,10 @@ async function gracefulShutdown() {
try {
if (redis?.isOpen) {
await redis.quit();
logger.info('🔌 Redis cerrado');
logger.info("🔌 Redis cerrado");
}
} 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
try {
@@ -155,62 +179,95 @@ async function gracefulShutdown() {
await bot.destroy();
} catch {}
} finally {
logger.info('✅ Apagado controlado completo');
logger.info("✅ Apagado controlado completo");
}
}
process.on('SIGINT', gracefulShutdown);
process.on('SIGTERM', gracefulShutdown);
process.on("SIGINT", gracefulShutdown);
process.on("SIGTERM", gracefulShutdown);
async function bootstrap() {
logger.info("🚀 Iniciando bot...");
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)
try { loadCommands(); } 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'); }
try {
loadCommands();
} 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
withRetry('Registrar slash commands', async () => {
withRetry("Registrar slash commands", async () => {
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
await withRetry('Conectar a Redis', async () => {
await withRetry("Conectar a Redis", async () => {
await redisConnect();
});
// 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();
}, {
},
{
isRetryable: (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
return !/missing discord token|invalid token/i.test(msg);
},
}
});
);
// 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
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");
}
// Bucle de arranque resiliente: si bootstrap completo falla, reintenta sin matar el proceso
(async function startLoop() {
await withRetry('Arranque', bootstrap, {
await withRetry("Arranque", bootstrap, {
minDelayMs: 1000,
maxDelayMs: 60_000,
isRetryable: (err) => {
const msg = err instanceof Error ? `${err.message}` : String(err);
// No reintentar en bucle si el problema es falta/invalid token
return !/missing discord token|invalid token/i.test(msg);
}
},
});
})();