Actualizar server.js
This commit is contained in:
45
server.js
45
server.js
@@ -310,46 +310,55 @@ async function sendWhatsAppCode(phone, code) {
|
|||||||
} catch (e) { console.error("Error envío WA:", e.message); }
|
} catch (e) { console.error("Error envío WA:", e.message); }
|
||||||
}
|
}
|
||||||
|
|
||||||
async function sendWhatsAppAuto(phone, text, instanceName, useDelay = true) { // <--- Nuevo parámetro useDelay
|
async function sendWhatsAppAuto(phone, text, instanceName, useDelay = true) {
|
||||||
if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY || !instanceName) {
|
if (!EVOLUTION_BASE_URL || !EVOLUTION_API_KEY || !instanceName) {
|
||||||
console.error("❌ Faltan datos para enviar WhatsApp automático");
|
console.error("❌ Faltan datos para enviar WhatsApp automático (Revisa URLs o instancia)");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
console.log(`\n📲 Intentando enviar WA a ${phone} [Modo Delay: ${useDelay}]...`);
|
console.log(`\n📲 Intentando enviar WA a ${phone} desde la instancia [${instanceName}] | Modo Lento: ${useDelay}...`);
|
||||||
|
|
||||||
let payload;
|
let payloadConEscribiendo;
|
||||||
|
|
||||||
if (useDelay) {
|
|
||||||
// PLAN A: Escribiendo lento
|
|
||||||
const typingTimeMs = Math.min(Math.max(text.length * 30, 1500), 8000);
|
const typingTimeMs = Math.min(Math.max(text.length * 30, 1500), 8000);
|
||||||
payload = {
|
|
||||||
|
if(useDelay) {
|
||||||
|
payloadConEscribiendo = {
|
||||||
number: phone.replace("+", ""),
|
number: phone.replace("+", ""),
|
||||||
text: text,
|
text: text,
|
||||||
options: { delay: typingTimeMs, presence: "composing" }
|
options: { delay: typingTimeMs, presence: "composing" }
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
// PLAN B: Directo e instantáneo
|
payloadConEscribiendo = { number: phone.replace("+", ""), text: text };
|
||||||
payload = { number: phone.replace("+", ""), text: text };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const res = await fetch(`${EVOLUTION_BASE_URL.replace(/\/$/, "")}/message/sendText/${instanceName}`, {
|
const res = await fetch(`${EVOLUTION_BASE_URL.replace(/\/$/, "")}/message/sendText/${instanceName}`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json", "apikey": EVOLUTION_API_KEY },
|
headers: { "Content-Type": "application/json", "apikey": EVOLUTION_API_KEY },
|
||||||
body: JSON.stringify(payload)
|
body: JSON.stringify(payloadConEscribiendo)
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!res.ok && useDelay) {
|
if (!res.ok && useDelay) {
|
||||||
console.warn(`⚠️ Evolution rechazó el modo "Escribiendo". Reenviando instantáneo...`);
|
const errCode = res.status;
|
||||||
|
console.warn(`⚠️ Evolution rechazó el modo "Escribiendo" (Código ${errCode}). Activando Plan B (Modo seguro instantáneo)...`);
|
||||||
|
|
||||||
const payloadSeguro = { number: phone.replace("+", ""), text: text };
|
const payloadSeguro = { number: phone.replace("+", ""), text: text };
|
||||||
await fetch(`${EVOLUTION_BASE_URL.replace(/\/$/, "")}/message/sendText/${instanceName}`, {
|
const res2 = await fetch(`${EVOLUTION_BASE_URL.replace(/\/$/, "")}/message/sendText/${instanceName}`, {
|
||||||
method: "POST", headers: { "Content-Type": "application/json", "apikey": EVOLUTION_API_KEY },
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json", "apikey": EVOLUTION_API_KEY },
|
||||||
body: JSON.stringify(payloadSeguro)
|
body: JSON.stringify(payloadSeguro)
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (!res2.ok) console.error("❌ Error definitivo en Evolution API:", await res2.text());
|
||||||
|
else console.log("✅ WA enviado correctamente (Plan B Seguro).");
|
||||||
|
} else if (res.ok) {
|
||||||
|
console.log(`✅ WA enviado con éxito (${useDelay ? 'Modo Humano' : 'Modo Rápido'}).`);
|
||||||
|
} else {
|
||||||
|
console.error("❌ Error en Evolution API:", await res.text());
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error("❌ Error crítico en función WA:", e.message);
|
||||||
}
|
}
|
||||||
console.log("✅ WA procesado por Evolution.");
|
|
||||||
} catch (e) { console.error("❌ Error WA:", e.message); }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function ensureInstance(instanceName) {
|
async function ensureInstance(instanceName) {
|
||||||
@@ -534,7 +543,7 @@ app.get("/providers/scraped", authMiddleware, async (req, res) => {
|
|||||||
app.post("/providers/automate/:id", authMiddleware, async (req, res) => {
|
app.post("/providers/automate/:id", authMiddleware, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
const { guild_id, cp } = req.body;
|
const { guild_id, cp, useDelay } = req.body;
|
||||||
|
|
||||||
if (!guild_id || !cp) return res.status(400).json({ ok: false, error: "Faltan datos (Gremio o CP)" });
|
if (!guild_id || !cp) return res.status(400).json({ ok: false, error: "Faltan datos (Gremio o CP)" });
|
||||||
|
|
||||||
@@ -594,7 +603,7 @@ app.post("/providers/automate/:id", authMiddleware, async (req, res) => {
|
|||||||
|
|
||||||
// SAAS: INSTANCIA DE CLIENTE ESPECÍFICA SIN AWAIT PARA NO BLOQUEAR
|
// SAAS: INSTANCIA DE CLIENTE ESPECÍFICA SIN AWAIT PARA NO BLOQUEAR
|
||||||
const instanceName = `cliente_${req.user.accountId}`;
|
const instanceName = `cliente_${req.user.accountId}`;
|
||||||
sendWhatsAppAuto(worker.phone, mensaje, instanceName).catch(console.error);
|
sendWhatsAppAuto(worker.phone, mensaje, instanceName, useDelay).catch(console.error);
|
||||||
|
|
||||||
res.json({ ok: true, message: "Automatismo iniciado con " + worker.full_name });
|
res.json({ ok: true, message: "Automatismo iniciado con " + worker.full_name });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
Reference in New Issue
Block a user