bot-mwsm 3.0.5 → 3.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/mwsm.js CHANGED
@@ -1213,9 +1213,8 @@ async function WwjsVersion(GET) {
1213
1213
  }
1214
1214
 
1215
1215
 
1216
-
1217
1216
  // ==================================================
1218
- // 🧠 Inteligência Artificial
1217
+ // 🧠 Inteligência Artificial
1219
1218
  // ==================================================
1220
1219
 
1221
1220
  async function getEmbedding(text) {
@@ -1235,7 +1234,6 @@ async function getEmbedding(text) {
1235
1234
  if (localResp.data?.embedding) return localResp.data.embedding;
1236
1235
  throw new Error('No embedding returned');
1237
1236
  } catch {
1238
- // 🔹 fallback determinístico (garante vetor estável)
1239
1237
  return Array.from(text)
1240
1238
  .map((ch, i) => ((ch.charCodeAt(0) + i * 13) % 255) / 255)
1241
1239
  .slice(0, 256);
@@ -1243,12 +1241,12 @@ async function getEmbedding(text) {
1243
1241
  }
1244
1242
 
1245
1243
  // ==================================================
1246
- // 🕒 Timezone e Cumprimentos Dinâmicos
1244
+ // 🕒 Timezone e Cumprimentos Dinâmicos
1247
1245
  // ==================================================
1248
1246
  async function getTimezoneByUF(uf) {
1249
1247
  return new Promise((resolve) => {
1250
1248
  db.get("SELECT timezone FROM localzone WHERE uf = ?", [uf], (err, row) => {
1251
- if (err || !row) return resolve("America/Sao_Paulo"); // padrão SP
1249
+ if (err || !row) return resolve("America/Sao_Paulo"); // padrão SP
1252
1250
  resolve(row.timezone);
1253
1251
  });
1254
1252
  });
@@ -1256,7 +1254,6 @@ async function getTimezoneByUF(uf) {
1256
1254
 
1257
1255
  function getGreetingPeriod(timezone) {
1258
1256
  try {
1259
- // Captura a hora local correta sem dupla conversão
1260
1257
  const now = new Date();
1261
1258
  const localHour = new Intl.DateTimeFormat("pt-BR", {
1262
1259
  timeZone: timezone,
@@ -1271,21 +1268,21 @@ function getGreetingPeriod(timezone) {
1271
1268
  if (hour >= 18 && hour < 24) return "boa noite";
1272
1269
  if (hour >= 0 && hour < 5) return "boa madrugada";
1273
1270
  } catch (err) {
1274
- console.error("[ERRO] Falha ao determinar saudação:", err);
1271
+ console.error("[ERRO] Falha ao determinar saudação:", err);
1275
1272
  return "";
1276
1273
  }
1277
1274
  }
1278
1275
 
1279
1276
 
1280
1277
  // ==================================================
1281
- // 🔒 Filtro Temático (Palavras-chave no BD)
1278
+ // 🔒 Filtro Temático (Palavras-chave no BD)
1282
1279
  // ==================================================
1283
1280
  async function isRelevantQuestion(text) {
1284
1281
  return new Promise((resolve) => {
1285
1282
  db.all("SELECT filter FROM keywords", [], (err, rows) => {
1286
1283
  if (err) {
1287
1284
  console.error("Keyword filter error:", err.message);
1288
- return resolve(true); // não bloqueia em erro
1285
+ return resolve(true); // não bloqueia em erro
1289
1286
  }
1290
1287
  if (!rows || rows.length === 0) return resolve(true);
1291
1288
 
@@ -1297,15 +1294,15 @@ async function isRelevantQuestion(text) {
1297
1294
  });
1298
1295
  }
1299
1296
 
1297
+
1298
+
1300
1299
  // ==================================================
1301
- // 🎯 Lógica Principal da IA
1300
+ // 🎯 Lógica Principal da IA
1302
1301
  // ==================================================
1303
1302
  async function askAI(question) {
1304
1303
  return new Promise(async (resolve) => {
1305
1304
  try {
1306
1305
  const text = (question || "").toLowerCase().trim();
1307
-
1308
- // 🔹 1️⃣ Verifica se é um cumprimento antes do filtro
1309
1306
  const isGreeting = await new Promise((resolveGreet) => {
1310
1307
  db.all("SELECT word FROM greetings", [], (err, rows) => {
1311
1308
  if (err || !rows?.length) return resolveGreet(false);
@@ -1320,33 +1317,30 @@ async function askAI(question) {
1320
1317
  const turno = getGreetingPeriod(tz);
1321
1318
 
1322
1319
  if (turno) {
1323
- return resolve(`👋 Olá, ${turno}! Como posso te ajudar com sua conexão de internet?`);
1320
+ return resolve(`👋 Olá, ${turno}! Como posso te ajudar com sua conexão de internet?`);
1324
1321
  } else {
1325
- return resolve(`👋 Olá! Como posso te ajudar com sua conexão de internet?`);
1322
+ return resolve(`👋 Olá! Como posso te ajudar com sua conexão de internet?`);
1326
1323
  }
1327
1324
  }
1328
1325
 
1329
- // 🔹 2️⃣ Se não for cumprimento, aplica o filtro temático
1330
1326
  const isRelevant = await isRelevantQuestion(text);
1331
1327
  if (!isRelevant) {
1332
- console.log(`> ${Debug('OPTIONS').appname} : Brain: Filter Ignored.`);
1333
- return resolve("⚠️ Posso ajudar apenas com dúvidas sobre sua conexão de internet e suporte técnico.");
1328
+ console.log(`> ${Debug('OPTIONS').appname} : Brain: Filter → Ignored.`);
1329
+ return resolve("⚠️ Posso ajudar apenas com dúvidas sobre sua conexão de internet e suporte técnico.");
1334
1330
  }
1335
1331
 
1336
- // 🔹 3️⃣ A partir daqui segue o fluxo normal da IA
1337
1332
  const aiMode = parseInt(Debug('OPTIONS').aimode);
1338
1333
  const apiKey = Debug('OPTIONS').keygen;
1339
- var Engine = Debug('OPTIONS').engine;
1340
1334
  const threshold = parseFloat(Debug('OPTIONS').threshold);
1341
1335
  const systemPrompt = Debug('OPTIONS').prompt;
1342
1336
  const aiTimeout = parseInt(Debug('OPTIONS').aitimeout);
1343
1337
  const appName = Debug('OPTIONS').appname;
1338
+ var Engine = Debug('OPTIONS').engine;
1339
+ var Regedit = null;
1344
1340
 
1345
- if (!apiKey) return resolve("⚠️ IA não configurada.");
1346
-
1347
- if (Engine.toLowerCase() === 'freerouter') {
1348
- const Levels = Debug('ENGINE', '*', 'ALL').filter(item => item.level === 0);
1349
- const ActiveModel = Levels.find(item => item.active === 1);
1341
+ if ((Engine).toLowerCase() == 'freerouter') {
1342
+ const Levels = Debug('ENGINE', '*', 'ALL').filter(item => item.level == 0);
1343
+ const ActiveModel = Levels.find(item => item.active == 1);
1350
1344
 
1351
1345
  if (ActiveModel) {
1352
1346
  Regedit = ActiveModel;
@@ -1356,31 +1350,27 @@ async function askAI(question) {
1356
1350
  }
1357
1351
 
1358
1352
  if (Regedit) {
1359
- Engine = Regedit.title;
1360
- Module = Regedit.module;
1361
- Level = parseInt(Regedit.level);
1353
+ Engine = Regedit.title
1354
+ Module = Regedit.module
1355
+ Level = Regedit.level
1362
1356
  }
1363
1357
  } else {
1364
1358
  Regedit = await Debug("ENGINE", "*", "DIRECT", Engine);
1365
- if (Regedit) {
1366
- Engine = Regedit.title;
1367
- Module = Regedit.module;
1368
- Level = parseInt(Regedit.level);
1369
- }
1359
+ Module = Regedit?.module || null;
1360
+ Level = parseInt(Regedit?.level);
1370
1361
  }
1371
- if (!Module) return resolve("⚠️ Indisponível no momento.");
1362
+ if (!Module) return resolve("⚠️ Indisponível no momento.");
1372
1363
 
1373
1364
  const qEmbedding = await getEmbedding(question);
1374
1365
  let bestMatch = null;
1375
1366
  let bestScore = 0;
1376
1367
 
1377
1368
  if (aiMode === 0) {
1378
- console.log(`> ${appName} : Brain: Cloud | Relevance: 0%`);
1369
+ console.log(`> ${appName} : Brain: Cloud | Relevance: 0.00`);
1379
1370
  const aiAnswer = await fetchCloudAnswer(question, apiKey, Engine, Module, systemPrompt, aiTimeout, Level);
1380
1371
  return resolve(aiAnswer);
1381
1372
  }
1382
1373
 
1383
- // 🔸 Busca local
1384
1374
  const rows = await Debug('INTELIGENCE', '*', 'ALL');
1385
1375
  for (const r of rows) {
1386
1376
  if (!r.embedding) continue;
@@ -1394,19 +1384,16 @@ async function askAI(question) {
1394
1384
  } catch {}
1395
1385
  }
1396
1386
 
1397
- // 🔹 Resposta local encontrada
1398
1387
  if (bestMatch && bestScore >= threshold) {
1399
- console.log(`> ${appName} : Brain: Local | Relevance: ${(bestScore * 100).toFixed(0)}%`);
1388
+ console.log(`> ${appName} : Brain: Local | Relevance: ${bestScore.toFixed(2)}`);
1400
1389
  db.run("UPDATE inteligence SET usage_count = usage_count + 1 WHERE id = ?", [bestMatch.id]);
1401
1390
  return resolve(bestMatch.answer);
1402
1391
  }
1403
1392
 
1404
- // 🔹 Caso não tenha resposta local — vai para nuvem
1405
- console.log(`> ${appName} : Brain: Cloud | Relevance: ${(bestScore * 100).toFixed(0)}%`);
1393
+ console.log(`> ${appName} : Brain: Cloud | Relevance: ${bestScore.toFixed(2)}`);
1406
1394
  const aiAnswer = await fetchCloudAnswer(question, apiKey, Engine, Module, systemPrompt, aiTimeout, Level);
1407
1395
 
1408
- // 🔸 Aprendizado local (modo 2)
1409
- if (aiMode === 2 && aiAnswer && !aiAnswer.startsWith("⚠")) {
1396
+ if (aiMode === 2 && aiAnswer && !aiAnswer.startsWith("âš ")) {
1410
1397
  try {
1411
1398
  await enforceKnowledgeLimit();
1412
1399
  const _embedding = await getEmbedding(question);
@@ -1435,13 +1422,13 @@ async function askAI(question) {
1435
1422
  return resolve(aiAnswer);
1436
1423
  } catch (err) {
1437
1424
  console.error("IA error:", err.message || err);
1438
- return resolve("⚠️ Não consegui acessar a inteligência artificial no momento.");
1425
+ return resolve("⚠️ Não consegui acessar a inteligência artificial no momento.");
1439
1426
  }
1440
1427
  });
1441
1428
  }
1442
1429
 
1443
1430
  // ==================================================
1444
- // 🌐 Comunicação com API (OpenRouter) + Limite de Tentativas
1431
+ // 🌐 Comunicação com API (OpenRouter) + Limite de Tentativas
1445
1432
  // ==================================================
1446
1433
  async function fetchCloudAnswer(question, apiKey, Engine, Module, systemPrompt, aiTimeout, Level = 0) {
1447
1434
  const tried = [];
@@ -1464,7 +1451,7 @@ async function fetchCloudAnswer(question, apiKey, Engine, Module, systemPrompt,
1464
1451
  });
1465
1452
  }
1466
1453
 
1467
- if (!variants.length) throw new Error("⚠️ Erro ao buscar resposta da IA online.");
1454
+ if (!variants.length) throw new Error("⚠️ Erro ao buscar resposta da IA online.");
1468
1455
 
1469
1456
  const activeVariant = variants.find(v => v.active === 1);
1470
1457
  const orderedVariants = activeVariant ?
@@ -1506,28 +1493,28 @@ async function fetchCloudAnswer(question, apiKey, Engine, Module, systemPrompt,
1506
1493
 
1507
1494
  const aiAnswer =
1508
1495
  response.data?.choices?.[0]?.message?.content?.trim() ||
1509
- "Desculpe, não consegui entender sua solicitação.";
1510
- aiAnswer = aiAnswer.replace(/◁think▷[\s\S]*?◁\/think▷/g, "").trim();
1496
+ "Desculpe, não consegui entender sua solicitação.";
1497
+
1511
1498
  db.run("UPDATE engine SET active = 0 WHERE title = ?", [variant.title]);
1512
1499
  db.run("UPDATE engine SET active = 1 WHERE id = ?", [variant.id]);
1513
1500
 
1514
- console.log(`> ${Debug('OPTIONS').appname} : AskAI: ${variant.title} ${variant.variant} ATIVA`);
1501
+ console.log(`> ${Debug('OPTIONS').appname} : AskAI: ${variant.title} ${variant.variant} → ATIVA`);
1515
1502
  return aiAnswer.replace(/\s+/g, " ").trim();
1516
1503
  } catch (err) {
1517
- console.log(`> ${Debug('OPTIONS').appname} : AskAI: ${variant.title} ${variant.variant} INATIVA`);
1504
+ console.log(`> ${Debug('OPTIONS').appname} : AskAI: ${variant.title} ${variant.variant} → INATIVA`);
1518
1505
  db.run("UPDATE engine SET active = 0 WHERE id = ?", [variant.id]);
1519
1506
  continue;
1520
1507
  }
1521
1508
  }
1522
1509
 
1523
- return "⚠️ Erro ao buscar resposta da IA online.";
1510
+ return "⚠️ Erro ao buscar resposta da IA online.";
1524
1511
  } catch {
1525
- return "⚠️ Erro ao buscar resposta da IA online.";
1512
+ return "⚠️ Erro ao buscar resposta da IA online.";
1526
1513
  }
1527
1514
  }
1528
1515
 
1529
1516
  // ==================================================
1530
- // 📊 Similaridade Vetorial
1517
+ // 📊 Similaridade Vetorial
1531
1518
  // ==================================================
1532
1519
  function cosineSimilarity(vecA, vecB) {
1533
1520
  if (!vecA || !vecB || vecA.length !== vecB.length) return 0;
@@ -1543,7 +1530,7 @@ function cosineSimilarity(vecA, vecB) {
1543
1530
  }
1544
1531
 
1545
1532
  // ==================================================
1546
- // 🧹 Limpeza Dinâmica e Inteligente do Conhecimento
1533
+ // 🧹 Limpeza Dinâmica e Inteligente do Conhecimento
1547
1534
  // ==================================================
1548
1535
  async function enforceKnowledgeLimit() {
1549
1536
  try {
@@ -1566,7 +1553,7 @@ async function enforceKnowledgeLimit() {
1566
1553
  [excess],
1567
1554
  function(delErr) {
1568
1555
  if (delErr) console.error("Cleanup error:", delErr.message);
1569
- else console.log(`✅ ${this.changes} registros antigos removidos.`);
1556
+ else console.log(`✅ ${this.changes} registros antigos removidos.`);
1570
1557
  }
1571
1558
  );
1572
1559
  });
@@ -1576,7 +1563,7 @@ async function enforceKnowledgeLimit() {
1576
1563
  }
1577
1564
 
1578
1565
  // ==================================================
1579
- // 🔹 Embedding Local (Backup Seguro)
1566
+ // 🔹 Embedding Local (Backup Seguro)
1580
1567
  // ==================================================
1581
1568
  async function getLocalEmbedding(text) {
1582
1569
  return Array.from(text).map((c, i) => ((c.charCodeAt(0) + i * 7) % 255) / 255);
@@ -1586,6 +1573,8 @@ async function getLocalEmbedding(text) {
1586
1573
 
1587
1574
  delay(0).then(async function() {
1588
1575
 
1576
+
1577
+
1589
1578
  });
1590
1579
 
1591
1580
  //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@@ -1595,6 +1584,7 @@ const MkAuth = async (UID, FIND, EXT = 'titulos', TYPE = 'titulo', MODE = true)
1595
1584
  JSON = [],
1596
1585
  Json = undefined,
1597
1586
  JDebug = undefined,
1587
+ Owner = Boolean(Debug('MKAUTH').owner),
1598
1588
  Jump;
1599
1589
  var Server = Debug('MKAUTH').client_link;
1600
1590
 
@@ -1725,7 +1715,7 @@ const MkAuth = async (UID, FIND, EXT = 'titulos', TYPE = 'titulo', MODE = true)
1725
1715
  Json = {
1726
1716
  "Status": STATUS,
1727
1717
  "ID": Send.titulo,
1728
- "Name": Send.nome,
1718
+ "Name": Owner ? Send.nome_res : Send.nome,
1729
1719
  "Payments": [{
1730
1720
  "value": Send.linhadig,
1731
1721
  "caption": "Bar",
@@ -1829,7 +1819,7 @@ const MkAuth = async (UID, FIND, EXT = 'titulos', TYPE = 'titulo', MODE = true)
1829
1819
  Json = {
1830
1820
  "Order": (new Date(Send.datavenc)).getDate(),
1831
1821
  "Identifier": Send.titulo,
1832
- "Client": Send.nome,
1822
+ "Client": Owner ? Send.nome_res : Send.nome,
1833
1823
  "Reward": Send.datavenc,
1834
1824
  "Payment": Send.status,
1835
1825
  "Connect": Send.login,
@@ -4675,40 +4665,70 @@ const Build = async (SET) => {
4675
4665
  };
4676
4666
 
4677
4667
 
4678
- // WhatsApp Bot
4668
+ const lastRequestTimes = new Map();
4669
+ let lastGlobalRequest = 0;
4670
+ let globalQueue = Promise.resolve();
4671
+
4672
+ // ==================================================
4673
+ // 🤖 WhatsApp Bot — Menu + IA
4674
+ // ==================================================
4679
4675
  client.on('message', async msg => {
4676
+ const nomeContato = msg._data.notifyName;
4677
+ let groupChat = await msg.getChat();
4678
+
4679
+ if (msg.type.toLowerCase() == "e2e_notification") return null;
4680
+ if (msg.body == "") return null;
4681
+ if (msg.from.includes("@g.us")) return null;
4682
+
4683
+ const NULLED = [undefined, "XXX", null, ""];
4684
+ var isWid = msg.from.replace(/@.*/, '');
4685
+ const RegEx = new Set("!@#:$%^&*()_");
4686
+ for (let Return of isWid) {
4687
+ if (RegEx.has(Return)) {
4688
+ isWid = isWid.replace(Return, '%');
4689
+ }
4690
+ }
4691
+ isWid = isWid.split("%")[0];
4692
+ var WhatsApp = msg.from;
4693
+ const isWhatsApp = isWid;
4694
+ if (msg.body.trim().toLowerCase() === "menu") {
4695
+ if (activeMenus.has(msg.from)) {
4696
+ await client.sendMessage(msg.from, "⚠️ Você já está dentro do menu.\nEnvie *0* para sair primeiro.");
4697
+ return;
4698
+ }
4680
4699
 
4681
- // ==================================================
4682
- // 🤖 Bot Menu e Controle Inteligente de IA
4683
- // ==================================================
4684
- const lastRequestTimes = new Map();
4685
- let lastGlobalRequest = 0;
4686
- let globalQueue = Promise.resolve();
4700
+ activeMenus.set(msg.from, true);
4701
+ await client.sendMessage(
4702
+ msg.from,
4703
+ '📋 *Menu Principal*\n\n' +
4704
+ '1️⃣ Boleto\n' +
4705
+ '2️⃣ Suporte\n' +
4706
+ '0️⃣ Encerrar\n\n' +
4707
+ '👉 Responda com o número da opção:'
4708
+ );
4709
+ return;
4710
+ }
4687
4711
 
4688
4712
  if (activeMenus.has(msg.from)) {
4689
4713
  if (activeSupportIA.has(msg.from)) {
4690
4714
  try {
4691
4715
  const _iaExit = (msg.body || '').toString().trim().toLowerCase();
4692
-
4693
- // 🔹 Encerrar atendimento
4694
4716
  if (["0", "sair", "tchau", "tchal"].includes(_iaExit)) {
4695
4717
  activeSupportIA.delete(msg.from);
4696
4718
  activeMenus.delete(msg.from);
4697
- await client.sendMessage(msg.from, " Atendimento encerrado. Obrigado pelo contato!");
4719
+ await client.sendMessage(msg.from, "✅ Atendimento encerrado.\nObrigado pelo contato!");
4698
4720
  return;
4699
4721
  }
4700
-
4701
- // 🔹 Voltar ao menu principal
4702
4722
  if (_iaExit === "menu") {
4703
4723
  activeSupportIA.delete(msg.from);
4704
4724
  activeMenus.set(msg.from, true);
4705
4725
  await client.sendMessage(
4706
4726
  msg.from,
4707
- '📋 *Menu Principal*\n\n' +
4708
- '1️⃣ Boleto\n' +
4709
- '2️⃣ Suporte\n' +
4710
- '0️⃣ Encerrar\n\n' +
4711
- '👉 Responda com o número da opção desejada.'
4727
+ '📋 *Menu Principal*\n\n' +
4728
+ '1️⃣ Boleto\n' +
4729
+ '2️⃣ Suporte\n' +
4730
+ '0️⃣ Encerrar\n\n' +
4731
+ '👉 Responda com o número da opção:'
4712
4732
  );
4713
4733
  return;
4714
4734
  }
@@ -4731,24 +4751,17 @@ client.on('message', async msg => {
4731
4751
  const waitGlobal = Math.max(0, globalDelay - sinceGlobal);
4732
4752
  const totalWait = Math.max(waitUser, waitGlobal);
4733
4753
 
4734
- // ==================================================
4735
- // 🔹 Modo Free — com fila e controle global
4736
- // ==================================================
4737
4754
  if (Level === 0) {
4738
4755
  globalQueue = globalQueue.then(async () => {
4739
4756
  try {
4740
4757
  if (totalWait > 0) {
4741
4758
  const typingInterval = setInterval(async () => {
4742
- try {
4743
- await chat.sendStateTyping();
4744
- } catch {}
4759
+ try { await chat.sendStateTyping(); } catch {}
4745
4760
  }, 4000);
4746
4761
 
4747
4762
  await new Promise(r => setTimeout(r, totalWait));
4748
4763
  clearInterval(typingInterval);
4749
- try {
4750
- await chat.clearState();
4751
- } catch {}
4764
+ try { await chat.clearState(); } catch {}
4752
4765
  }
4753
4766
 
4754
4767
  lastRequestTimes.set(msg.from, Date.now());
@@ -4766,23 +4779,12 @@ client.on('message', async msg => {
4766
4779
  await chat.clearState();
4767
4780
 
4768
4781
  const reply = await askAI(msg.body);
4769
- await client.sendMessage(msg.from, reply);
4782
+ await client.sendMessage(msg.from, reply, { quotedMessageId: undefined });
4770
4783
  } catch (err) {
4771
4784
  console.error("Erro ao processar IA (free):", err.message);
4772
- try {
4773
- const reply = await askAI(msg.body);
4774
- await client.sendMessage(msg.from, reply);
4775
- } catch (e2) {
4776
- console.error("Erro secundário:", e2.message);
4777
- }
4778
4785
  }
4779
4786
  }).catch(e => console.error("Erro na fila global:", e.message));
4780
- }
4781
-
4782
- // ==================================================
4783
- // 🔹 Modo Premium — Resposta direta (sem fila)
4784
- // ==================================================
4785
- else {
4787
+ } else {
4786
4788
  const tLevel = parseInt(Debug('OPTIONS').typingspeed);
4787
4789
  const multiplier = 1 + (5 - tLevel) * 0.25;
4788
4790
  const baseTime = 800 * multiplier;
@@ -4795,14 +4797,14 @@ client.on('message', async msg => {
4795
4797
  await chat.clearState();
4796
4798
 
4797
4799
  const reply = await askAI(msg.body);
4798
- await client.sendMessage(msg.from, reply);
4800
+ await client.sendMessage(msg.from, reply, { quotedMessageId: undefined });
4799
4801
  }
4800
4802
 
4801
4803
  } catch (err) {
4802
4804
  console.error("Erro ao simular digitando:", err.message);
4803
4805
  try {
4804
4806
  const reply = await askAI(msg.body);
4805
- await client.sendMessage(msg.from, reply);
4807
+ await client.sendMessage(msg.from, reply, { quotedMessageId: undefined });
4806
4808
  } catch (e2) {
4807
4809
  console.error("Erro no fallback de IA:", e2.message);
4808
4810
  }
@@ -4810,64 +4812,23 @@ client.on('message', async msg => {
4810
4812
  return;
4811
4813
  }
4812
4814
 
4813
- // ==================================================
4814
- // 📋 Menu principal
4815
- // ==================================================
4816
4815
  if (msg.body.startsWith('1')) {
4817
- await client.sendMessage(msg.from, '🔗 Aqui está o link do seu boleto: https://seudominio.com/boleto');
4816
+ await client.sendMessage(msg.from, '🔗 Aqui está o link do seu boleto: https://seudominio.com/boleto');
4818
4817
  return;
4819
4818
  }
4820
4819
 
4821
4820
  if (msg.body.startsWith('2')) {
4822
- await client.sendMessage(msg.from, '🤖 Você está agora em atendimento de suporte com IA. Envie sua dúvida.');
4821
+ await client.sendMessage(msg.from, '🤖 Você está agora em atendimento de suporte com IA. Envie sua dúvida.');
4823
4822
  activeSupportIA.set(msg.from, true);
4824
4823
  return;
4825
4824
  }
4826
4825
 
4827
4826
  if (msg.body.startsWith('0')) {
4828
- await client.sendMessage(msg.from, ' Atendimento encerrado. Obrigado pelo contato!');
4827
+ await client.sendMessage(msg.from, '✅ Atendimento encerrado.\nObrigado pelo contato!');
4829
4828
  activeMenus.delete(msg.from);
4830
4829
  return;
4831
4830
  }
4832
4831
  }
4833
-
4834
- if (msg.body.toLowerCase() === 'menu') {
4835
- activeMenus.set(msg.from, true);
4836
- await client.sendMessage(msg.from,
4837
- '📋 *Menu Principal*\n\n' +
4838
- '1️⃣ Boleto\n' +
4839
- '2️⃣ Suporte\n' +
4840
- '0️⃣ Encerrar\n\n' +
4841
- '👉 Responda com o número da opção desejada.'
4842
- );
4843
- return;
4844
- }
4845
-
4846
- const nomeContato = msg._data.notifyName;
4847
- let groupChat = await msg.getChat();
4848
-
4849
- if (msg.type.toLowerCase() == "e2e_notification") return null;
4850
- if (msg.body == "") return null;
4851
- if (msg.from.includes("@g.us")) return null;
4852
- const NULLED = [undefined, "XXX", null, ""];
4853
- var isWid = msg.from;
4854
- const RegEx = new Set("!@#:$%^&*()_");
4855
- for (let Return of isWid) {
4856
- if (RegEx.has(Return)) {
4857
- isWid = isWid.replace(Return, '%');
4858
- }
4859
- }
4860
- isWid = isWid.split("%")[0];
4861
- const isDDI = isWid.substr(0, 2);
4862
- const isDDD = isWid.substr(2, 2);
4863
- const isCall = isWid.slice(-8);
4864
- var WhatsApp = isWid + '@c.us';
4865
- if ((isDDI == '55') && (parseInt(isDDD) <= 30)) {
4866
- WhatsApp = isWid.substr(0, 4) + '9' + isCall + '@c.us';
4867
- } else if ((isDDI == '55') && (parseInt(isDDD) > 30)) {
4868
- WhatsApp = isWid.substr(0, 4) + isCall + '@c.us';
4869
- }
4870
- const isWhatsApp = WhatsApp.split("@")[0];
4871
4832
  if (msg.body.toUpperCase().includes("TOKEN") && NULLED.includes(Debug('OPTIONS').token)) {
4872
4833
  if (msg.body.includes(":") && (msg.body.split(":")[1].length == 7)) {
4873
4834
  db.run("UPDATE options SET token=?", [msg.body.split(":")[1]], (err) => {
@@ -4881,118 +4842,122 @@ client.on('message', async msg => {
4881
4842
  global.io.emit('message', '> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').wrong);
4882
4843
  msg.reply(Debug('CONSOLE').wrong);
4883
4844
  }
4884
- } else {
4885
- db.serialize(() => {
4886
- db.get("SELECT * FROM replies WHERE whats='" + isWhatsApp + "'", (err, REPLIES) => {
4887
- if (REPLIES == undefined) {
4888
- db.run("INSERT INTO replies(whats,date,count) VALUES(?, ?, ?)", [isWhatsApp, register, 1], (err) => {
4845
+ return;
4846
+ }
4847
+
4848
+ db.serialize(() => {
4849
+ db.get("SELECT * FROM replies WHERE whats='" + isWhatsApp + "'", (err, REPLIES) => {
4850
+ if (REPLIES == undefined) {
4851
+ db.run("INSERT INTO replies(whats,date,count) VALUES(?, ?, ?)", [isWhatsApp, register, 1], (err) => {
4852
+ if (err) {
4853
+ console.log('> ' + Debug('OPTIONS').appname + ' : ' + err)
4854
+ }
4855
+ console.log('> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').inserted);
4856
+ global.io.emit('message', '> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').inserted);
4857
+ MsgBox = true;
4858
+ });
4859
+
4860
+ } else {
4861
+
4862
+ if (register.toString() > REPLIES.date) {
4863
+ db.run("UPDATE replies SET date=?, count=? WHERE whats=?", [register, 1, isWhatsApp], (err) => {
4889
4864
  if (err) {
4890
4865
  console.log('> ' + Debug('OPTIONS').appname + ' : ' + err)
4891
4866
  }
4892
- console.log('> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').inserted);
4893
- global.io.emit('message', '> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').inserted);
4867
+ console.log('> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').updated);
4868
+ global.io.emit('message', '> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').updated);
4894
4869
  MsgBox = true;
4895
4870
  });
4896
-
4897
4871
  } else {
4898
-
4899
- if (register.toString() > REPLIES.date) {
4900
- db.run("UPDATE replies SET date=?, count=? WHERE whats=?", [register, 1, isWhatsApp], (err) => {
4901
- if (err) {
4902
- console.log('> ' + Debug('OPTIONS').appname + ' : ' + err)
4903
- }
4872
+ if (Debug('OPTIONS').count > REPLIES.count) {
4873
+ COUNT = REPLIES.count + 1;
4874
+ db.run("UPDATE replies SET count=? WHERE whats=?", [COUNT, isWhatsApp], (err) => {
4875
+ if (err) throw err;
4904
4876
  console.log('> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').updated);
4905
4877
  global.io.emit('message', '> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').updated);
4906
4878
  MsgBox = true;
4907
4879
  });
4908
4880
  } else {
4909
- if (Debug('OPTIONS').count > REPLIES.count) {
4910
- COUNT = REPLIES.count + 1;
4911
- db.run("UPDATE replies SET count=? WHERE whats=?", [COUNT, isWhatsApp], (err) => {
4912
- if (err) throw err;
4913
- console.log('> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').updated);
4914
- global.io.emit('message', '> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').updated);
4915
- MsgBox = true;
4916
- });
4917
- } else {
4918
- console.log('> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').found);
4919
- global.io.emit('message', '> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').found);
4920
- MsgBox = false;
4881
+ console.log('> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').found);
4882
+ global.io.emit('message', '> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').found);
4883
+ MsgBox = false;
4921
4884
 
4922
- }
4923
4885
  }
4924
4886
  }
4925
- });
4926
-
4927
- db.get("SELECT * FROM replies WHERE whats='" + msg.from.replaceAll('@c.us', '') + "'", (err, REPLIES) => {
4928
- if (err) {
4929
- console.log('> ' + Debug('OPTIONS').appname + ' : ' + err)
4930
- }
4931
- if (REPLIES != undefined) {
4932
- if (MsgBox && Boolean(Debug('OPTIONS').onbot) && (msg.body != null || msg.body == "0" || msg.type == 'ptt' || msg.hasMedia)) {
4933
- if (Boolean(Debug('OPTIONS').replyes)) {
4934
- msg.reply(Debug('OPTIONS').response);
4935
- } else {
4936
- const Mensagem = (Debug('OPTIONS').response).replaceAll("\\n", "\r\n").split("##");
4937
- Mensagem.some(function(Send, index) {
4938
- setTimeout(function() {
4939
- client.sendMessage(WhatsApp, isEmoji(Send)).then().catch(err => {
4940
- console.log(err);
4941
- WwjsVersion(false);
4942
- });
4943
-
4944
- }, Math.floor(Delay + Math.random() * 1000));
4945
-
4946
- });
4887
+ }
4888
+ });
4947
4889
 
4948
- }
4890
+ db.get("SELECT * FROM replies WHERE whats='" + isWhatsApp + "'", (err, REPLIES) => {
4891
+ if (err) {
4892
+ console.log('> ' + Debug('OPTIONS').appname + ' : ' + err)
4893
+ }
4894
+ if (REPLIES != undefined) {
4895
+ if (MsgBox && Boolean(Debug('OPTIONS').onbot) && (msg.body != null || msg.body == "0" || msg.type == 'ptt' || msg.hasMedia)) {
4896
+ if (Boolean(Debug('OPTIONS').replyes)) {
4897
+ msg.reply(Debug('OPTIONS').response);
4898
+ } else {
4899
+ const Mensagem = (Debug('OPTIONS').response).replaceAll("\\n", "\r\n").split("##");
4900
+ Mensagem.some(function(Send, index) {
4901
+ setTimeout(function() {
4902
+ client.sendMessage(WhatsApp, isEmoji(Send)).then().catch(err => {
4903
+ console.log(err);
4904
+ WwjsVersion(false);
4905
+ });
4906
+ }, Math.floor(Delay + Math.random() * 1000));
4907
+ });
4949
4908
  }
4950
4909
  }
4951
- });
4952
-
4910
+ }
4953
4911
  });
4954
- }
4955
- });
4956
4912
 
4957
- client.on('call', async (call) => {
4958
- var isWid = call.from;
4959
- const RegEx = new Set("!@#:$%^&*()_");
4960
- for (let Return of isWid) {
4961
- if (RegEx.has(Return)) {
4962
- isWid = isWid.replace(Return, '%');
4963
- }
4964
- }
4965
- isWid = isWid.split("%")[0];
4966
- const isDDI = isWid.substr(0, 2);
4967
- const isDDD = isWid.substr(2, 2);
4968
- const isCall = isWid.slice(-8);
4969
- var WhatsApp = isWid + '@c.us';
4970
- if ((isDDI == '55') && (parseInt(isDDD) <= 30)) {
4971
- WhatsApp = isWid.substr(0, 4) + '9' + isCall + '@c.us';
4972
- } else if ((isDDI == '55') && (parseInt(isDDD) > 30)) {
4973
- WhatsApp = isWid.substr(0, 4) + isCall + '@c.us';
4974
- }
4975
- const Mensagem = (Debug('OPTIONS').call).replaceAll("\\n", "\r\n").split("##");
4913
+ });
4914
+ });
4976
4915
 
4977
- if (Boolean(Debug('OPTIONS').reject)) {
4978
- setTimeout(function() {
4979
- call.reject().then(() => {
4980
- if (Boolean(Debug('OPTIONS').alert)) {
4981
- Mensagem.some(function(Send, index) {
4982
- setTimeout(function() {
4983
- client.sendMessage(WhatsApp, isEmoji(Send)).then().catch(err => {
4984
- console.log(err);
4985
- WwjsVersion(false);
4986
- });
4987
4916
 
4988
- }, Math.floor(Delay + Math.random() * 1000));
4989
- });
4990
- }
4991
- }).catch(err => {
4992
- console.log(err);
4993
- });
4994
- }, Math.floor(Debug('OPTIONS').sleep + Math.random() * 1000));
4995
- }
4917
+ client.on('call', async (call) => {
4918
+ var isWid = (call.from || '').split('@')[0];
4919
+ const RegEx = new Set("!@#:$%^&*()_");
4920
+ for (let Return of isWid) {
4921
+ if (RegEx.has(Return)) {
4922
+ isWid = isWid.replace(Return, '%');
4923
+ }
4924
+ }
4925
+ isWid = isWid.split("%")[0];
4926
+ var WhatsApp = call.from;
4927
+
4928
+ if (Boolean(Debug('OPTIONS').reject)) {
4929
+
4930
+ const sleepTime = Math.floor(Debug('OPTIONS').sleep + Math.random() * 1000);
4931
+
4932
+ setTimeout(async () => {
4933
+ try {
4934
+ await call.reject();
4935
+ enviarAlertaCall();
4936
+ } catch (err) {
4937
+
4938
+ try {
4939
+ await client.pupPage.evaluate((id) => {
4940
+ window.WWebJS.rejectCall(id);
4941
+ }, call.id);
4942
+ enviarAlertaCall();
4943
+ } catch (e) {
4944
+ }
4945
+ }
4946
+ }, sleepTime);
4947
+ }
4948
+
4949
+ function enviarAlertaCall() {
4950
+ if (Boolean(Debug('OPTIONS').alert)) {
4951
+ const Mensagem = (Debug('OPTIONS').call).replaceAll("\\n", "\r\n").split("##");
4952
+ Mensagem.some(function(Send, index) {
4953
+ setTimeout(function() {
4954
+ client.sendMessage(WhatsApp, isEmoji(Send)).then().catch(err => {
4955
+ if (typeof WwjsVersion === 'function') WwjsVersion(false);
4956
+ });
4957
+ }, Math.floor(Delay + Math.random() * 1000) * (index + 1));
4958
+ });
4959
+ }
4960
+ }
4996
4961
  });
4997
4962
 
4998
4963
  client.initialize();