From 213199475627a3b69b4ba5f6ff197e6d14d6dc28 Mon Sep 17 00:00:00 2001 From: marsalva Date: Mon, 16 Feb 2026 22:29:05 +0000 Subject: [PATCH] Actualizar server.js --- server.js | 57 ++++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 48 insertions(+), 9 deletions(-) diff --git a/server.js b/server.js index 2946b01..cf6b1b1 100644 --- a/server.js +++ b/server.js @@ -311,19 +311,58 @@ async function sendWhatsAppCode(phone, code) { } async function sendWhatsAppAuto(phone, text, instanceName) { - if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY || !instanceName) return; + if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY || !instanceName) { + console.error("❌ Faltan datos para enviar WhatsApp automático (Revisa URLs o instancia)"); + return; + } + try { + console.log(`\n📲 Intentando enviar WA a ${phone} desde la instancia [${instanceName}]...`); + // MATEMÁTICA HUMANA: Tiempo simulado de escritura const typingTimeMs = Math.min(Math.max(text.length * 30, 1500), 8000); - await fetch(`${EVOLUTION_BASE_URL.replace(/\/$/, "")}/message/sendText/${instanceName}`, { - method: "POST", headers: { "Content-Type": "application/json", "apikey": EVOLUTION_API_KEY }, - body: JSON.stringify({ - number: phone.replace("+", ""), - text: text, - delay: typingTimeMs - }) + + // Payload en formato Evolution v2 (con options) + const payloadConEscribiendo = { + number: phone.replace("+", ""), + text: text, + options: { + delay: typingTimeMs, + presence: "composing" + } + }; + + const res = await fetch(`${EVOLUTION_BASE_URL.replace(/\/$/, "")}/message/sendText/${instanceName}`, { + method: "POST", + headers: { "Content-Type": "application/json", "apikey": EVOLUTION_API_KEY }, + body: JSON.stringify(payloadConEscribiendo) }); - } catch (e) { console.error("Error envío WA:", e.message); } + + // Si Evolution rechaza el formato con "delay"... + if (!res.ok) { + const errCode = res.status; + console.warn(`⚠️ Evolution rechazó el modo "Escribiendo" (Código ${errCode}). Activando Plan B (Modo seguro)...`); + + // PLAN B: Reenviamos sin el delay, formato puro. + const payloadSeguro = { number: phone.replace("+", ""), text: text }; + const res2 = await fetch(`${EVOLUTION_BASE_URL.replace(/\/$/, "")}/message/sendText/${instanceName}`, { + method: "POST", + headers: { "Content-Type": "application/json", "apikey": EVOLUTION_API_KEY }, + body: JSON.stringify(payloadSeguro) + }); + + if (!res2.ok) { + const errText = await res2.text(); + console.error("❌ Error definitivo en Evolution API:", errText); + } else { + console.log("✅ WA enviado correctamente (Modo Seguro Instantáneo)."); + } + } else { + console.log("✅ WA enviado con éxito (Modo Humano con Escribiendo...)."); + } + } catch (e) { + console.error("❌ Error crítico en función WA:", e.message); + } } async function ensureInstance(instanceName) {