bot-mwsm 3.0.4 → 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/.github/workflows/Mwsm.yml +20 -57
- package/Dockerfile +95 -37
- package/README.md +31 -18
- package/bash/mwsm.sh +392 -182
- package/bash/setup.sh +102 -100
- package/img/emojis.png +0 -0
- package/img/emojiselect.png +0 -0
- package/mwsm.db +0 -0
- package/mwsm.js +529 -524
- package/package.json +10 -9
- package/style.css +5 -1
- package/version.json +2 -2
package/mwsm.js
CHANGED
|
@@ -1213,343 +1213,368 @@ async function WwjsVersion(GET) {
|
|
|
1213
1213
|
}
|
|
1214
1214
|
|
|
1215
1215
|
|
|
1216
|
-
|
|
1217
1216
|
// ==================================================
|
|
1218
|
-
//
|
|
1217
|
+
// 🧠Inteligência Artificial
|
|
1219
1218
|
// ==================================================
|
|
1220
1219
|
|
|
1221
1220
|
async function getEmbedding(text) {
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1221
|
+
try {
|
|
1222
|
+
if (!text) return null;
|
|
1223
|
+
const mwsmHost = Debug('OPTIONS').mwsmhost;
|
|
1224
|
+
const mwsmPort = Debug('OPTIONS').mwsmport;
|
|
1225
|
+
|
|
1226
|
+
const localResp = await axios.post(
|
|
1227
|
+
`http://${mwsmHost}:${mwsmPort}/embed`, {
|
|
1228
|
+
text
|
|
1229
|
+
}, {
|
|
1230
|
+
timeout: 10000
|
|
1231
|
+
}
|
|
1232
|
+
);
|
|
1233
|
+
|
|
1234
|
+
if (localResp.data?.embedding) return localResp.data.embedding;
|
|
1235
|
+
throw new Error('No embedding returned');
|
|
1236
|
+
} catch {
|
|
1237
|
+
return Array.from(text)
|
|
1238
|
+
.map((ch, i) => ((ch.charCodeAt(0) + i * 13) % 255) / 255)
|
|
1239
|
+
.slice(0, 256);
|
|
1240
|
+
}
|
|
1241
1241
|
}
|
|
1242
1242
|
|
|
1243
1243
|
// ==================================================
|
|
1244
|
-
//
|
|
1244
|
+
// 🕒 Timezone e Cumprimentos Dinâmicos
|
|
1245
1245
|
// ==================================================
|
|
1246
1246
|
async function getTimezoneByUF(uf) {
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1247
|
+
return new Promise((resolve) => {
|
|
1248
|
+
db.get("SELECT timezone FROM localzone WHERE uf = ?", [uf], (err, row) => {
|
|
1249
|
+
if (err || !row) return resolve("America/Sao_Paulo"); // padrão SP
|
|
1250
|
+
resolve(row.timezone);
|
|
1251
|
+
});
|
|
1252
|
+
});
|
|
1253
1253
|
}
|
|
1254
1254
|
|
|
1255
1255
|
function getGreetingPeriod(timezone) {
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1256
|
+
try {
|
|
1257
|
+
const now = new Date();
|
|
1258
|
+
const localHour = new Intl.DateTimeFormat("pt-BR", {
|
|
1259
|
+
timeZone: timezone,
|
|
1260
|
+
hour: "numeric",
|
|
1261
|
+
hour12: false
|
|
1262
|
+
}).format(now);
|
|
1263
|
+
|
|
1264
|
+
const hour = parseInt(localHour, 10);
|
|
1265
|
+
|
|
1266
|
+
if (hour >= 5 && hour < 12) return "bom dia";
|
|
1267
|
+
if (hour >= 12 && hour < 18) return "boa tarde";
|
|
1268
|
+
if (hour >= 18 && hour < 24) return "boa noite";
|
|
1269
|
+
if (hour >= 0 && hour < 5) return "boa madrugada";
|
|
1270
|
+
} catch (err) {
|
|
1271
|
+
console.error("[ERRO] Falha ao determinar saudação:", err);
|
|
1272
|
+
return "";
|
|
1273
|
+
}
|
|
1267
1274
|
}
|
|
1268
1275
|
|
|
1276
|
+
|
|
1269
1277
|
// ==================================================
|
|
1270
|
-
//
|
|
1278
|
+
// 🔒 Filtro Temático (Palavras-chave no BD)
|
|
1271
1279
|
// ==================================================
|
|
1272
1280
|
async function isRelevantQuestion(text) {
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1281
|
+
return new Promise((resolve) => {
|
|
1282
|
+
db.all("SELECT filter FROM keywords", [], (err, rows) => {
|
|
1283
|
+
if (err) {
|
|
1284
|
+
console.error("Keyword filter error:", err.message);
|
|
1285
|
+
return resolve(true); // não bloqueia em erro
|
|
1286
|
+
}
|
|
1287
|
+
if (!rows || rows.length === 0) return resolve(true);
|
|
1288
|
+
|
|
1289
|
+
const keywords = rows.map(r => (r.filter || "").toLowerCase().trim());
|
|
1290
|
+
text = (text || "").toLowerCase().trim();
|
|
1291
|
+
const found = keywords.some(k => text.includes(k));
|
|
1292
|
+
resolve(found);
|
|
1293
|
+
});
|
|
1294
|
+
});
|
|
1287
1295
|
}
|
|
1288
1296
|
|
|
1297
|
+
|
|
1298
|
+
|
|
1289
1299
|
// ==================================================
|
|
1290
|
-
//
|
|
1300
|
+
// 🎯 Lógica Principal da IA
|
|
1291
1301
|
// ==================================================
|
|
1292
1302
|
async function askAI(question) {
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
});
|
|
1304
|
-
});
|
|
1305
|
-
|
|
1306
|
-
if (isGreeting) {
|
|
1307
|
-
const uf = Debug('OPTIONS').timezone || 'SP';
|
|
1308
|
-
const tz = await getTimezoneByUF(uf);
|
|
1309
|
-
const turno = getGreetingPeriod(tz);
|
|
1310
|
-
|
|
1311
|
-
if (turno) {
|
|
1312
|
-
return resolve(`👋 Olá, ${turno}! Como posso te ajudar com sua conexão de internet?`);
|
|
1313
|
-
} else {
|
|
1314
|
-
return resolve(`👋 Olá! Como posso te ajudar com sua conexão de internet?`);
|
|
1315
|
-
}
|
|
1316
|
-
}
|
|
1303
|
+
return new Promise(async (resolve) => {
|
|
1304
|
+
try {
|
|
1305
|
+
const text = (question || "").toLowerCase().trim();
|
|
1306
|
+
const isGreeting = await new Promise((resolveGreet) => {
|
|
1307
|
+
db.all("SELECT word FROM greetings", [], (err, rows) => {
|
|
1308
|
+
if (err || !rows?.length) return resolveGreet(false);
|
|
1309
|
+
const greetings = rows.map(r => (r.word || "").toLowerCase());
|
|
1310
|
+
resolveGreet(greetings.some(g => text.includes(g)));
|
|
1311
|
+
});
|
|
1312
|
+
});
|
|
1317
1313
|
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
return resolve("⚠️ Posso ajudar apenas com dúvidas sobre sua conexão de internet e suporte técnico.");
|
|
1323
|
-
}
|
|
1314
|
+
if (isGreeting) {
|
|
1315
|
+
const uf = Debug('OPTIONS').timezone || 'SP';
|
|
1316
|
+
const tz = await getTimezoneByUF(uf);
|
|
1317
|
+
const turno = getGreetingPeriod(tz);
|
|
1324
1318
|
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
const aiTimeout = parseInt(Debug('OPTIONS').aitimeout);
|
|
1332
|
-
const appName = Debug('OPTIONS').appname;
|
|
1319
|
+
if (turno) {
|
|
1320
|
+
return resolve(`👋 Olá, ${turno}! Como posso te ajudar com sua conexão de internet?`);
|
|
1321
|
+
} else {
|
|
1322
|
+
return resolve(`👋 Olá! Como posso te ajudar com sua conexão de internet?`);
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1333
1325
|
|
|
1334
|
-
|
|
1326
|
+
const isRelevant = await isRelevantQuestion(text);
|
|
1327
|
+
if (!isRelevant) {
|
|
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.");
|
|
1330
|
+
}
|
|
1335
1331
|
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1332
|
+
const aiMode = parseInt(Debug('OPTIONS').aimode);
|
|
1333
|
+
const apiKey = Debug('OPTIONS').keygen;
|
|
1334
|
+
const threshold = parseFloat(Debug('OPTIONS').threshold);
|
|
1335
|
+
const systemPrompt = Debug('OPTIONS').prompt;
|
|
1336
|
+
const aiTimeout = parseInt(Debug('OPTIONS').aitimeout);
|
|
1337
|
+
const appName = Debug('OPTIONS').appname;
|
|
1338
|
+
var Engine = Debug('OPTIONS').engine;
|
|
1339
|
+
var Regedit = null;
|
|
1340
|
+
|
|
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);
|
|
1344
|
+
|
|
1345
|
+
if (ActiveModel) {
|
|
1346
|
+
Regedit = ActiveModel;
|
|
1347
|
+
} else if (Levels.length > 0) {
|
|
1348
|
+
const randomIndex = Math.floor(Math.random() * Levels.length);
|
|
1349
|
+
Regedit = Levels[randomIndex];
|
|
1350
|
+
}
|
|
1339
1351
|
|
|
1340
|
-
|
|
1352
|
+
if (Regedit) {
|
|
1353
|
+
Engine = Regedit.title
|
|
1354
|
+
Module = Regedit.module
|
|
1355
|
+
Level = Regedit.level
|
|
1356
|
+
}
|
|
1357
|
+
} else {
|
|
1358
|
+
Regedit = await Debug("ENGINE", "*", "DIRECT", Engine);
|
|
1359
|
+
Module = Regedit?.module || null;
|
|
1360
|
+
Level = parseInt(Regedit?.level);
|
|
1361
|
+
}
|
|
1362
|
+
if (!Module) return resolve("âš ï¸ IndisponÃvel no momento.");
|
|
1341
1363
|
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1364
|
+
const qEmbedding = await getEmbedding(question);
|
|
1365
|
+
let bestMatch = null;
|
|
1366
|
+
let bestScore = 0;
|
|
1345
1367
|
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1368
|
+
if (aiMode === 0) {
|
|
1369
|
+
console.log(`> ${appName} : Brain: Cloud | Relevance: 0.00`);
|
|
1370
|
+
const aiAnswer = await fetchCloudAnswer(question, apiKey, Engine, Module, systemPrompt, aiTimeout, Level);
|
|
1371
|
+
return resolve(aiAnswer);
|
|
1372
|
+
}
|
|
1351
1373
|
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
}
|
|
1374
|
+
const rows = await Debug('INTELIGENCE', '*', 'ALL');
|
|
1375
|
+
for (const r of rows) {
|
|
1376
|
+
if (!r.embedding) continue;
|
|
1377
|
+
try {
|
|
1378
|
+
const emb = JSON.parse(r.embedding);
|
|
1379
|
+
const score = cosineSimilarity(emb, qEmbedding);
|
|
1380
|
+
if (score > bestScore) {
|
|
1381
|
+
bestScore = score;
|
|
1382
|
+
bestMatch = r;
|
|
1383
|
+
}
|
|
1384
|
+
} catch {}
|
|
1385
|
+
}
|
|
1365
1386
|
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
}
|
|
1387
|
+
if (bestMatch && bestScore >= threshold) {
|
|
1388
|
+
console.log(`> ${appName} : Brain: Local | Relevance: ${bestScore.toFixed(2)}`);
|
|
1389
|
+
db.run("UPDATE inteligence SET usage_count = usage_count + 1 WHERE id = ?", [bestMatch.id]);
|
|
1390
|
+
return resolve(bestMatch.answer);
|
|
1391
|
+
}
|
|
1372
1392
|
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
const aiAnswer = await fetchCloudAnswer(question, apiKey, Engine, Module, systemPrompt, aiTimeout, Level);
|
|
1393
|
+
console.log(`> ${appName} : Brain: Cloud | Relevance: ${bestScore.toFixed(2)}`);
|
|
1394
|
+
const aiAnswer = await fetchCloudAnswer(question, apiKey, Engine, Module, systemPrompt, aiTimeout, Level);
|
|
1376
1395
|
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
const embeddingStr = _embedding ? JSON.stringify(_embedding) : null;
|
|
1396
|
+
if (aiMode === 2 && aiAnswer && !aiAnswer.startsWith("âš ")) {
|
|
1397
|
+
try {
|
|
1398
|
+
await enforceKnowledgeLimit();
|
|
1399
|
+
const _embedding = await getEmbedding(question);
|
|
1400
|
+
const embeddingStr = _embedding ? JSON.stringify(_embedding) : null;
|
|
1383
1401
|
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1402
|
+
db.serialize(() => {
|
|
1403
|
+
db.get("SELECT id FROM inteligence WHERE question = ?", [question], (err, row) => {
|
|
1404
|
+
if (err) return console.error("DB check error:", err.message);
|
|
1387
1405
|
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1406
|
+
const sql = row ?
|
|
1407
|
+
"UPDATE inteligence SET answer=?, embedding=?, source=?, usage_count=usage_count+1 WHERE id=?" :
|
|
1408
|
+
"INSERT INTO inteligence (question, answer, embedding, source, usage_count) VALUES (?, ?, ?, ?, 1)";
|
|
1391
1409
|
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1410
|
+
const params = row ?
|
|
1411
|
+
[aiAnswer, embeddingStr, "local", row.id] :
|
|
1412
|
+
[question, aiAnswer, embeddingStr, "local"];
|
|
1395
1413
|
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1414
|
+
db.run(sql, params, (e) => e && console.error("DB write error:", e.message));
|
|
1415
|
+
});
|
|
1416
|
+
});
|
|
1417
|
+
} catch (e) {
|
|
1418
|
+
console.error("Embedding generation failed:", e?.message || e);
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1403
1421
|
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1422
|
+
return resolve(aiAnswer);
|
|
1423
|
+
} catch (err) {
|
|
1424
|
+
console.error("IA error:", err.message || err);
|
|
1425
|
+
return resolve("âš ï¸ Não consegui acessar a inteligência artificial no momento.");
|
|
1426
|
+
}
|
|
1427
|
+
});
|
|
1410
1428
|
}
|
|
1411
1429
|
|
|
1412
1430
|
// ==================================================
|
|
1413
|
-
//
|
|
1431
|
+
// 🌠Comunicação com API (OpenRouter) + Limite de Tentativas
|
|
1414
1432
|
// ==================================================
|
|
1415
1433
|
async function fetchCloudAnswer(question, apiKey, Engine, Module, systemPrompt, aiTimeout, Level = 0) {
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
if (Engine.toLowerCase() === "freerouter") {
|
|
1421
|
-
variants = await new Promise((resolve) => {
|
|
1422
|
-
db.all("SELECT * FROM engine WHERE level = 0 ORDER BY active DESC, id ASC", [], (err, rows) => {
|
|
1423
|
-
if (err) return resolve([]);
|
|
1424
|
-
resolve(rows);
|
|
1425
|
-
});
|
|
1426
|
-
});
|
|
1427
|
-
} else {
|
|
1428
|
-
variants = await new Promise((resolve) => {
|
|
1429
|
-
db.all("SELECT * FROM engine WHERE title = ? AND level = ? ORDER BY active DESC, id ASC", [Engine, Level], (err, rows) => {
|
|
1430
|
-
if (err) return resolve([]);
|
|
1431
|
-
resolve(rows);
|
|
1432
|
-
});
|
|
1433
|
-
});
|
|
1434
|
-
}
|
|
1434
|
+
const tried = [];
|
|
1435
|
+
try {
|
|
1436
|
+
let variants = [];
|
|
1435
1437
|
|
|
1436
|
-
|
|
1438
|
+
if (Engine.toLowerCase() === "freerouter") {
|
|
1439
|
+
variants = await new Promise((resolve) => {
|
|
1440
|
+
db.all("SELECT * FROM engine WHERE level = 0 ORDER BY active DESC, id ASC", [], (err, rows) => {
|
|
1441
|
+
if (err) return resolve([]);
|
|
1442
|
+
resolve(rows);
|
|
1443
|
+
});
|
|
1444
|
+
});
|
|
1445
|
+
} else {
|
|
1446
|
+
variants = await new Promise((resolve) => {
|
|
1447
|
+
db.all("SELECT * FROM engine WHERE title = ? AND level = ? ORDER BY active DESC, id ASC", [Engine, Level], (err, rows) => {
|
|
1448
|
+
if (err) return resolve([]);
|
|
1449
|
+
resolve(rows);
|
|
1450
|
+
});
|
|
1451
|
+
});
|
|
1452
|
+
}
|
|
1437
1453
|
|
|
1438
|
-
|
|
1439
|
-
const orderedVariants = activeVariant
|
|
1440
|
-
? [activeVariant, ...variants.filter(v => v.id !== activeVariant.id)]
|
|
1441
|
-
: variants;
|
|
1454
|
+
if (!variants.length) throw new Error("âš ï¸ Erro ao buscar resposta da IA online.");
|
|
1442
1455
|
|
|
1443
|
-
|
|
1444
|
-
|
|
1456
|
+
const activeVariant = variants.find(v => v.active === 1);
|
|
1457
|
+
const orderedVariants = activeVariant ?
|
|
1458
|
+
[activeVariant, ...variants.filter(v => v.id !== activeVariant.id)] :
|
|
1459
|
+
variants;
|
|
1445
1460
|
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
console.log(`> ${Debug('OPTIONS').appname} : Brain: Max Attempts (${maxAttempts}) reached.`);
|
|
1449
|
-
break;
|
|
1450
|
-
}
|
|
1451
|
-
attempts++;
|
|
1461
|
+
const maxAttempts = parseInt(Debug('OPTIONS').aimaxattempts) || 0;
|
|
1462
|
+
let attempts = 0;
|
|
1452
1463
|
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
messages: [
|
|
1460
|
-
{ role: "system", content: systemPrompt },
|
|
1461
|
-
{ role: "user", content: question }
|
|
1462
|
-
]
|
|
1463
|
-
},
|
|
1464
|
-
{
|
|
1465
|
-
headers: {
|
|
1466
|
-
Authorization: `Bearer ${apiKey}`,
|
|
1467
|
-
"Content-Type": "application/json"
|
|
1468
|
-
},
|
|
1469
|
-
timeout: aiTimeout
|
|
1470
|
-
}
|
|
1471
|
-
);
|
|
1472
|
-
|
|
1473
|
-
const aiAnswer =
|
|
1474
|
-
response.data?.choices?.[0]?.message?.content?.trim() ||
|
|
1475
|
-
"Desculpe, não consegui entender sua solicitação.";
|
|
1476
|
-
|
|
1477
|
-
db.run("UPDATE engine SET active = 0 WHERE title = ?", [variant.title]);
|
|
1478
|
-
db.run("UPDATE engine SET active = 1 WHERE id = ?", [variant.id]);
|
|
1479
|
-
|
|
1480
|
-
console.log(`> ${Debug('OPTIONS').appname} : AskAI: ${variant.title} ${variant.variant} → ATIVA`);
|
|
1481
|
-
return aiAnswer.replace(/\s+/g, " ").trim();
|
|
1482
|
-
} catch (err) {
|
|
1483
|
-
console.log(`> ${Debug('OPTIONS').appname} : AskAI: ${variant.title} ${variant.variant} → INATIVA`);
|
|
1484
|
-
db.run("UPDATE engine SET active = 0 WHERE id = ?", [variant.id]);
|
|
1485
|
-
continue;
|
|
1486
|
-
}
|
|
1487
|
-
}
|
|
1464
|
+
for (const variant of orderedVariants) {
|
|
1465
|
+
if (maxAttempts && attempts >= maxAttempts) {
|
|
1466
|
+
console.log(`> ${Debug('OPTIONS').appname} : Brain: Max Attempts (${maxAttempts}) reached.`);
|
|
1467
|
+
break;
|
|
1468
|
+
}
|
|
1469
|
+
attempts++;
|
|
1488
1470
|
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1471
|
+
tried.push(variant.module);
|
|
1472
|
+
try {
|
|
1473
|
+
const response = await axios.post(
|
|
1474
|
+
"https://openrouter.ai/api/v1/chat/completions", {
|
|
1475
|
+
model: variant.module,
|
|
1476
|
+
messages: [{
|
|
1477
|
+
role: "system",
|
|
1478
|
+
content: systemPrompt
|
|
1479
|
+
},
|
|
1480
|
+
{
|
|
1481
|
+
role: "user",
|
|
1482
|
+
content: question
|
|
1483
|
+
}
|
|
1484
|
+
]
|
|
1485
|
+
}, {
|
|
1486
|
+
headers: {
|
|
1487
|
+
Authorization: `Bearer ${apiKey}`,
|
|
1488
|
+
"Content-Type": "application/json"
|
|
1489
|
+
},
|
|
1490
|
+
timeout: aiTimeout
|
|
1491
|
+
}
|
|
1492
|
+
);
|
|
1493
|
+
|
|
1494
|
+
const aiAnswer =
|
|
1495
|
+
response.data?.choices?.[0]?.message?.content?.trim() ||
|
|
1496
|
+
"Desculpe, não consegui entender sua solicitação.";
|
|
1497
|
+
|
|
1498
|
+
db.run("UPDATE engine SET active = 0 WHERE title = ?", [variant.title]);
|
|
1499
|
+
db.run("UPDATE engine SET active = 1 WHERE id = ?", [variant.id]);
|
|
1500
|
+
|
|
1501
|
+
console.log(`> ${Debug('OPTIONS').appname} : AskAI: ${variant.title} ${variant.variant} → ATIVA`);
|
|
1502
|
+
return aiAnswer.replace(/\s+/g, " ").trim();
|
|
1503
|
+
} catch (err) {
|
|
1504
|
+
console.log(`> ${Debug('OPTIONS').appname} : AskAI: ${variant.title} ${variant.variant} → INATIVA`);
|
|
1505
|
+
db.run("UPDATE engine SET active = 0 WHERE id = ?", [variant.id]);
|
|
1506
|
+
continue;
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
return "âš ï¸ Erro ao buscar resposta da IA online.";
|
|
1511
|
+
} catch {
|
|
1512
|
+
return "âš ï¸ Erro ao buscar resposta da IA online.";
|
|
1513
|
+
}
|
|
1493
1514
|
}
|
|
1494
1515
|
|
|
1495
1516
|
// ==================================================
|
|
1496
|
-
//
|
|
1517
|
+
// 📊 Similaridade Vetorial
|
|
1497
1518
|
// ==================================================
|
|
1498
1519
|
function cosineSimilarity(vecA, vecB) {
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1520
|
+
if (!vecA || !vecB || vecA.length !== vecB.length) return 0;
|
|
1521
|
+
let dot = 0,
|
|
1522
|
+
normA = 0,
|
|
1523
|
+
normB = 0;
|
|
1524
|
+
for (let i = 0; i < vecA.length; i++) {
|
|
1525
|
+
dot += vecA[i] * vecB[i];
|
|
1526
|
+
normA += vecA[i] * vecA[i];
|
|
1527
|
+
normB += vecB[i] * vecB[i];
|
|
1528
|
+
}
|
|
1529
|
+
return normA && normB ? dot / (Math.sqrt(normA) * Math.sqrt(normB)) : 0;
|
|
1507
1530
|
}
|
|
1508
1531
|
|
|
1509
1532
|
// ==================================================
|
|
1510
|
-
//
|
|
1533
|
+
// 🧹 Limpeza Dinâmica e Inteligente do Conhecimento
|
|
1511
1534
|
// ==================================================
|
|
1512
1535
|
async function enforceKnowledgeLimit() {
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1536
|
+
try {
|
|
1537
|
+
const maxKnowledge = parseInt(Debug("OPTIONS").maxknowledge) || 1000;
|
|
1538
|
+
if (!maxKnowledge || maxKnowledge < 100) return;
|
|
1539
|
+
|
|
1540
|
+
db.all("SELECT COUNT(*) as total FROM inteligence", async (err, rows) => {
|
|
1541
|
+
if (err) return console.error("DB count error:", err.message);
|
|
1542
|
+
const total = rows[0]?.total || 0;
|
|
1543
|
+
if (total <= maxKnowledge) return;
|
|
1544
|
+
|
|
1545
|
+
const excess = total - maxKnowledge;
|
|
1546
|
+
db.run(
|
|
1547
|
+
`DELETE FROM inteligence
|
|
1525
1548
|
WHERE id IN (
|
|
1526
1549
|
SELECT id FROM inteligence
|
|
1527
1550
|
ORDER BY usage_count ASC, id ASC
|
|
1528
1551
|
LIMIT ?
|
|
1529
1552
|
)`,
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1553
|
+
[excess],
|
|
1554
|
+
function(delErr) {
|
|
1555
|
+
if (delErr) console.error("Cleanup error:", delErr.message);
|
|
1556
|
+
else console.log(`✅ ${this.changes} registros antigos removidos.`);
|
|
1557
|
+
}
|
|
1558
|
+
);
|
|
1559
|
+
});
|
|
1560
|
+
} catch (err) {
|
|
1561
|
+
console.error("Erro no enforceKnowledgeLimit:", err.message);
|
|
1562
|
+
}
|
|
1540
1563
|
}
|
|
1541
1564
|
|
|
1542
1565
|
// ==================================================
|
|
1543
|
-
//
|
|
1566
|
+
// 🔹 Embedding Local (Backup Seguro)
|
|
1544
1567
|
// ==================================================
|
|
1545
1568
|
async function getLocalEmbedding(text) {
|
|
1546
|
-
|
|
1569
|
+
return Array.from(text).map((c, i) => ((c.charCodeAt(0) + i * 7) % 255) / 255);
|
|
1547
1570
|
}
|
|
1548
1571
|
|
|
1549
1572
|
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
|
1550
1573
|
|
|
1551
1574
|
delay(0).then(async function() {
|
|
1552
1575
|
|
|
1576
|
+
|
|
1577
|
+
|
|
1553
1578
|
});
|
|
1554
1579
|
|
|
1555
1580
|
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
|
@@ -1559,6 +1584,7 @@ const MkAuth = async (UID, FIND, EXT = 'titulos', TYPE = 'titulo', MODE = true)
|
|
|
1559
1584
|
JSON = [],
|
|
1560
1585
|
Json = undefined,
|
|
1561
1586
|
JDebug = undefined,
|
|
1587
|
+
Owner = Boolean(Debug('MKAUTH').owner),
|
|
1562
1588
|
Jump;
|
|
1563
1589
|
var Server = Debug('MKAUTH').client_link;
|
|
1564
1590
|
|
|
@@ -1689,7 +1715,7 @@ const MkAuth = async (UID, FIND, EXT = 'titulos', TYPE = 'titulo', MODE = true)
|
|
|
1689
1715
|
Json = {
|
|
1690
1716
|
"Status": STATUS,
|
|
1691
1717
|
"ID": Send.titulo,
|
|
1692
|
-
"Name": Send.nome,
|
|
1718
|
+
"Name": Owner ? Send.nome_res : Send.nome,
|
|
1693
1719
|
"Payments": [{
|
|
1694
1720
|
"value": Send.linhadig,
|
|
1695
1721
|
"caption": "Bar",
|
|
@@ -1793,7 +1819,7 @@ const MkAuth = async (UID, FIND, EXT = 'titulos', TYPE = 'titulo', MODE = true)
|
|
|
1793
1819
|
Json = {
|
|
1794
1820
|
"Order": (new Date(Send.datavenc)).getDate(),
|
|
1795
1821
|
"Identifier": Send.titulo,
|
|
1796
|
-
"Client": Send.nome,
|
|
1822
|
+
"Client": Owner ? Send.nome_res : Send.nome,
|
|
1797
1823
|
"Reward": Send.datavenc,
|
|
1798
1824
|
"Payment": Send.status,
|
|
1799
1825
|
"Connect": Send.login,
|
|
@@ -4639,178 +4665,23 @@ const Build = async (SET) => {
|
|
|
4639
4665
|
};
|
|
4640
4666
|
|
|
4641
4667
|
|
|
4642
|
-
// WhatsApp Bot
|
|
4643
|
-
client.on('message', async msg => {
|
|
4644
|
-
|
|
4645
|
-
// ==================================================
|
|
4646
|
-
// 🤖 Bot Menu e Controle Inteligente de IA
|
|
4647
|
-
// ==================================================
|
|
4648
4668
|
const lastRequestTimes = new Map();
|
|
4649
4669
|
let lastGlobalRequest = 0;
|
|
4650
4670
|
let globalQueue = Promise.resolve();
|
|
4651
4671
|
|
|
4652
|
-
|
|
4653
|
-
|
|
4654
|
-
|
|
4655
|
-
|
|
4656
|
-
|
|
4657
|
-
// 🔹 Encerrar atendimento
|
|
4658
|
-
if (["0", "sair", "tchau", "tchal"].includes(_iaExit)) {
|
|
4659
|
-
activeSupportIA.delete(msg.from);
|
|
4660
|
-
activeMenus.delete(msg.from);
|
|
4661
|
-
await client.sendMessage(msg.from, "✅ Atendimento encerrado. Obrigado pelo contato!");
|
|
4662
|
-
return;
|
|
4663
|
-
}
|
|
4664
|
-
|
|
4665
|
-
// 🔹 Voltar ao menu principal
|
|
4666
|
-
if (_iaExit === "menu") {
|
|
4667
|
-
activeSupportIA.delete(msg.from);
|
|
4668
|
-
activeMenus.set(msg.from, true);
|
|
4669
|
-
await client.sendMessage(
|
|
4670
|
-
msg.from,
|
|
4671
|
-
'📋 *Menu Principal*\n\n' +
|
|
4672
|
-
'1️⃣ Boleto\n' +
|
|
4673
|
-
'2️⃣ Suporte\n' +
|
|
4674
|
-
'0️⃣ Encerrar\n\n' +
|
|
4675
|
-
'👉 Responda com o número da opção desejada.'
|
|
4676
|
-
);
|
|
4677
|
-
return;
|
|
4678
|
-
}
|
|
4679
|
-
} catch (e) {
|
|
4680
|
-
console.error('IA exit handler error:', e?.message || e);
|
|
4681
|
-
}
|
|
4682
|
-
|
|
4683
|
-
try {
|
|
4684
|
-
const chat = await msg.getChat();
|
|
4685
|
-
const Engine = Debug('OPTIONS').engine;
|
|
4686
|
-
const Level = parseInt(Debug("ENGINE", "*", "DIRECT", Engine).level || 0);
|
|
4687
|
-
const perUserDelay = parseInt(Debug('OPTIONS').airequestdelay) || 3000;
|
|
4688
|
-
const globalDelay = parseInt(Debug('OPTIONS').aiglobaldelay) || 1000;
|
|
4689
|
-
|
|
4690
|
-
const now = Date.now();
|
|
4691
|
-
const lastUser = lastRequestTimes.get(msg.from) || 0;
|
|
4692
|
-
const sinceUser = now - lastUser;
|
|
4693
|
-
const sinceGlobal = now - lastGlobalRequest;
|
|
4694
|
-
const waitUser = Math.max(0, perUserDelay - sinceUser);
|
|
4695
|
-
const waitGlobal = Math.max(0, globalDelay - sinceGlobal);
|
|
4696
|
-
const totalWait = Math.max(waitUser, waitGlobal);
|
|
4697
|
-
|
|
4698
|
-
// ==================================================
|
|
4699
|
-
// 🔹 Modo Free — com fila e controle global
|
|
4700
|
-
// ==================================================
|
|
4701
|
-
if (Level === 0) {
|
|
4702
|
-
globalQueue = globalQueue.then(async () => {
|
|
4703
|
-
try {
|
|
4704
|
-
if (totalWait > 0) {
|
|
4705
|
-
const typingInterval = setInterval(async () => {
|
|
4706
|
-
try { await chat.sendStateTyping(); } catch {}
|
|
4707
|
-
}, 4000);
|
|
4708
|
-
|
|
4709
|
-
await new Promise(r => setTimeout(r, totalWait));
|
|
4710
|
-
clearInterval(typingInterval);
|
|
4711
|
-
try { await chat.clearState(); } catch {}
|
|
4712
|
-
}
|
|
4713
|
-
|
|
4714
|
-
lastRequestTimes.set(msg.from, Date.now());
|
|
4715
|
-
lastGlobalRequest = Date.now();
|
|
4716
|
-
|
|
4717
|
-
const tLevel = parseInt(Debug('OPTIONS').typingspeed);
|
|
4718
|
-
const multiplier = 1 + (5 - tLevel) * 0.25;
|
|
4719
|
-
const baseTime = 800 * multiplier;
|
|
4720
|
-
const extraPerChar = 25 * multiplier;
|
|
4721
|
-
const maxTime = 4000 * multiplier;
|
|
4722
|
-
const estimatedDelay = Math.min(baseTime + msg.body.length * extraPerChar, maxTime);
|
|
4723
|
-
|
|
4724
|
-
await chat.sendStateTyping();
|
|
4725
|
-
await new Promise(resolve => setTimeout(resolve, estimatedDelay));
|
|
4726
|
-
await chat.clearState();
|
|
4727
|
-
|
|
4728
|
-
const reply = await askAI(msg.body);
|
|
4729
|
-
await client.sendMessage(msg.from, reply);
|
|
4730
|
-
} catch (err) {
|
|
4731
|
-
console.error("Erro ao processar IA (free):", err.message);
|
|
4732
|
-
try {
|
|
4733
|
-
const reply = await askAI(msg.body);
|
|
4734
|
-
await client.sendMessage(msg.from, reply);
|
|
4735
|
-
} catch (e2) {
|
|
4736
|
-
console.error("Erro secundário:", e2.message);
|
|
4737
|
-
}
|
|
4738
|
-
}
|
|
4739
|
-
}).catch(e => console.error("Erro na fila global:", e.message));
|
|
4740
|
-
}
|
|
4741
|
-
|
|
4742
|
-
// ==================================================
|
|
4743
|
-
// 🔹 Modo Premium — Resposta direta (sem fila)
|
|
4744
|
-
// ==================================================
|
|
4745
|
-
else {
|
|
4746
|
-
const tLevel = parseInt(Debug('OPTIONS').typingspeed);
|
|
4747
|
-
const multiplier = 1 + (5 - tLevel) * 0.25;
|
|
4748
|
-
const baseTime = 800 * multiplier;
|
|
4749
|
-
const extraPerChar = 25 * multiplier;
|
|
4750
|
-
const maxTime = 4000 * multiplier;
|
|
4751
|
-
const estimatedDelay = Math.min(baseTime + msg.body.length * extraPerChar, maxTime);
|
|
4752
|
-
|
|
4753
|
-
await chat.sendStateTyping();
|
|
4754
|
-
await new Promise(r => setTimeout(r, estimatedDelay));
|
|
4755
|
-
await chat.clearState();
|
|
4756
|
-
|
|
4757
|
-
const reply = await askAI(msg.body);
|
|
4758
|
-
await client.sendMessage(msg.from, reply);
|
|
4759
|
-
}
|
|
4760
|
-
|
|
4761
|
-
} catch (err) {
|
|
4762
|
-
console.error("Erro ao simular digitando:", err.message);
|
|
4763
|
-
try {
|
|
4764
|
-
const reply = await askAI(msg.body);
|
|
4765
|
-
await client.sendMessage(msg.from, reply);
|
|
4766
|
-
} catch (e2) {
|
|
4767
|
-
console.error("Erro no fallback de IA:", e2.message);
|
|
4768
|
-
}
|
|
4769
|
-
}
|
|
4770
|
-
return;
|
|
4771
|
-
}
|
|
4772
|
-
|
|
4773
|
-
// ==================================================
|
|
4774
|
-
// 📋 Menu principal
|
|
4775
|
-
// ==================================================
|
|
4776
|
-
if (msg.body.startsWith('1')) {
|
|
4777
|
-
await client.sendMessage(msg.from, '🔗 Aqui está o link do seu boleto: https://seudominio.com/boleto');
|
|
4778
|
-
return;
|
|
4779
|
-
}
|
|
4780
|
-
|
|
4781
|
-
if (msg.body.startsWith('2')) {
|
|
4782
|
-
await client.sendMessage(msg.from, '🤖 Você está agora em atendimento de suporte com IA. Envie sua dúvida.');
|
|
4783
|
-
activeSupportIA.set(msg.from, true);
|
|
4784
|
-
return;
|
|
4785
|
-
}
|
|
4786
|
-
|
|
4787
|
-
if (msg.body.startsWith('0')) {
|
|
4788
|
-
await client.sendMessage(msg.from, '✅ Atendimento encerrado. Obrigado pelo contato!');
|
|
4789
|
-
activeMenus.delete(msg.from);
|
|
4790
|
-
return;
|
|
4791
|
-
}
|
|
4792
|
-
}
|
|
4793
|
-
|
|
4794
|
-
if (msg.body.toLowerCase() === 'menu') {
|
|
4795
|
-
activeMenus.set(msg.from, true);
|
|
4796
|
-
await client.sendMessage(msg.from,
|
|
4797
|
-
'📋 *Menu Principal*\n\n' +
|
|
4798
|
-
'1️⃣ Boleto\n' +
|
|
4799
|
-
'2️⃣ Suporte\n' +
|
|
4800
|
-
'0️⃣ Encerrar\n\n' +
|
|
4801
|
-
'👉 Responda com o número da opção desejada.'
|
|
4802
|
-
);
|
|
4803
|
-
return;
|
|
4804
|
-
}
|
|
4805
|
-
|
|
4672
|
+
// ==================================================
|
|
4673
|
+
// 🤖 WhatsApp Bot — Menu + IA
|
|
4674
|
+
// ==================================================
|
|
4675
|
+
client.on('message', async msg => {
|
|
4806
4676
|
const nomeContato = msg._data.notifyName;
|
|
4807
4677
|
let groupChat = await msg.getChat();
|
|
4808
4678
|
|
|
4809
4679
|
if (msg.type.toLowerCase() == "e2e_notification") return null;
|
|
4810
4680
|
if (msg.body == "") return null;
|
|
4811
4681
|
if (msg.from.includes("@g.us")) return null;
|
|
4682
|
+
|
|
4812
4683
|
const NULLED = [undefined, "XXX", null, ""];
|
|
4813
|
-
var isWid = msg.from;
|
|
4684
|
+
var isWid = msg.from.replace(/@.*/, '');
|
|
4814
4685
|
const RegEx = new Set("!@#:$%^&*()_");
|
|
4815
4686
|
for (let Return of isWid) {
|
|
4816
4687
|
if (RegEx.has(Return)) {
|
|
@@ -4818,16 +4689,146 @@ if (activeMenus.has(msg.from)) {
|
|
|
4818
4689
|
}
|
|
4819
4690
|
}
|
|
4820
4691
|
isWid = isWid.split("%")[0];
|
|
4821
|
-
|
|
4822
|
-
const
|
|
4823
|
-
|
|
4824
|
-
|
|
4825
|
-
|
|
4826
|
-
|
|
4827
|
-
|
|
4828
|
-
|
|
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
|
+
}
|
|
4699
|
+
|
|
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
|
+
}
|
|
4711
|
+
|
|
4712
|
+
if (activeMenus.has(msg.from)) {
|
|
4713
|
+
if (activeSupportIA.has(msg.from)) {
|
|
4714
|
+
try {
|
|
4715
|
+
const _iaExit = (msg.body || '').toString().trim().toLowerCase();
|
|
4716
|
+
if (["0", "sair", "tchau", "tchal"].includes(_iaExit)) {
|
|
4717
|
+
activeSupportIA.delete(msg.from);
|
|
4718
|
+
activeMenus.delete(msg.from);
|
|
4719
|
+
await client.sendMessage(msg.from, "✅ Atendimento encerrado.\nObrigado pelo contato!");
|
|
4720
|
+
return;
|
|
4721
|
+
}
|
|
4722
|
+
if (_iaExit === "menu") {
|
|
4723
|
+
activeSupportIA.delete(msg.from);
|
|
4724
|
+
activeMenus.set(msg.from, true);
|
|
4725
|
+
await client.sendMessage(
|
|
4726
|
+
msg.from,
|
|
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:'
|
|
4732
|
+
);
|
|
4733
|
+
return;
|
|
4734
|
+
}
|
|
4735
|
+
} catch (e) {
|
|
4736
|
+
console.error('IA exit handler error:', e?.message || e);
|
|
4737
|
+
}
|
|
4738
|
+
|
|
4739
|
+
try {
|
|
4740
|
+
const chat = await msg.getChat();
|
|
4741
|
+
const Engine = Debug('OPTIONS').engine;
|
|
4742
|
+
const Level = parseInt(Debug("ENGINE", "*", "DIRECT", Engine).level || 0);
|
|
4743
|
+
const perUserDelay = parseInt(Debug('OPTIONS').airequestdelay) || 3000;
|
|
4744
|
+
const globalDelay = parseInt(Debug('OPTIONS').aiglobaldelay) || 1000;
|
|
4745
|
+
|
|
4746
|
+
const now = Date.now();
|
|
4747
|
+
const lastUser = lastRequestTimes.get(msg.from) || 0;
|
|
4748
|
+
const sinceUser = now - lastUser;
|
|
4749
|
+
const sinceGlobal = now - lastGlobalRequest;
|
|
4750
|
+
const waitUser = Math.max(0, perUserDelay - sinceUser);
|
|
4751
|
+
const waitGlobal = Math.max(0, globalDelay - sinceGlobal);
|
|
4752
|
+
const totalWait = Math.max(waitUser, waitGlobal);
|
|
4753
|
+
|
|
4754
|
+
if (Level === 0) {
|
|
4755
|
+
globalQueue = globalQueue.then(async () => {
|
|
4756
|
+
try {
|
|
4757
|
+
if (totalWait > 0) {
|
|
4758
|
+
const typingInterval = setInterval(async () => {
|
|
4759
|
+
try { await chat.sendStateTyping(); } catch {}
|
|
4760
|
+
}, 4000);
|
|
4761
|
+
|
|
4762
|
+
await new Promise(r => setTimeout(r, totalWait));
|
|
4763
|
+
clearInterval(typingInterval);
|
|
4764
|
+
try { await chat.clearState(); } catch {}
|
|
4765
|
+
}
|
|
4766
|
+
|
|
4767
|
+
lastRequestTimes.set(msg.from, Date.now());
|
|
4768
|
+
lastGlobalRequest = Date.now();
|
|
4769
|
+
|
|
4770
|
+
const tLevel = parseInt(Debug('OPTIONS').typingspeed);
|
|
4771
|
+
const multiplier = 1 + (5 - tLevel) * 0.25;
|
|
4772
|
+
const baseTime = 800 * multiplier;
|
|
4773
|
+
const extraPerChar = 25 * multiplier;
|
|
4774
|
+
const maxTime = 4000 * multiplier;
|
|
4775
|
+
const estimatedDelay = Math.min(baseTime + msg.body.length * extraPerChar, maxTime);
|
|
4776
|
+
|
|
4777
|
+
await chat.sendStateTyping();
|
|
4778
|
+
await new Promise(resolve => setTimeout(resolve, estimatedDelay));
|
|
4779
|
+
await chat.clearState();
|
|
4780
|
+
|
|
4781
|
+
const reply = await askAI(msg.body);
|
|
4782
|
+
await client.sendMessage(msg.from, reply, { quotedMessageId: undefined });
|
|
4783
|
+
} catch (err) {
|
|
4784
|
+
console.error("Erro ao processar IA (free):", err.message);
|
|
4785
|
+
}
|
|
4786
|
+
}).catch(e => console.error("Erro na fila global:", e.message));
|
|
4787
|
+
} else {
|
|
4788
|
+
const tLevel = parseInt(Debug('OPTIONS').typingspeed);
|
|
4789
|
+
const multiplier = 1 + (5 - tLevel) * 0.25;
|
|
4790
|
+
const baseTime = 800 * multiplier;
|
|
4791
|
+
const extraPerChar = 25 * multiplier;
|
|
4792
|
+
const maxTime = 4000 * multiplier;
|
|
4793
|
+
const estimatedDelay = Math.min(baseTime + msg.body.length * extraPerChar, maxTime);
|
|
4794
|
+
|
|
4795
|
+
await chat.sendStateTyping();
|
|
4796
|
+
await new Promise(r => setTimeout(r, estimatedDelay));
|
|
4797
|
+
await chat.clearState();
|
|
4798
|
+
|
|
4799
|
+
const reply = await askAI(msg.body);
|
|
4800
|
+
await client.sendMessage(msg.from, reply, { quotedMessageId: undefined });
|
|
4801
|
+
}
|
|
4802
|
+
|
|
4803
|
+
} catch (err) {
|
|
4804
|
+
console.error("Erro ao simular digitando:", err.message);
|
|
4805
|
+
try {
|
|
4806
|
+
const reply = await askAI(msg.body);
|
|
4807
|
+
await client.sendMessage(msg.from, reply, { quotedMessageId: undefined });
|
|
4808
|
+
} catch (e2) {
|
|
4809
|
+
console.error("Erro no fallback de IA:", e2.message);
|
|
4810
|
+
}
|
|
4811
|
+
}
|
|
4812
|
+
return;
|
|
4813
|
+
}
|
|
4814
|
+
|
|
4815
|
+
if (msg.body.startsWith('1')) {
|
|
4816
|
+
await client.sendMessage(msg.from, '🔗 Aqui está o link do seu boleto: https://seudominio.com/boleto');
|
|
4817
|
+
return;
|
|
4818
|
+
}
|
|
4819
|
+
|
|
4820
|
+
if (msg.body.startsWith('2')) {
|
|
4821
|
+
await client.sendMessage(msg.from, '🤖 Você está agora em atendimento de suporte com IA. Envie sua dúvida.');
|
|
4822
|
+
activeSupportIA.set(msg.from, true);
|
|
4823
|
+
return;
|
|
4824
|
+
}
|
|
4825
|
+
|
|
4826
|
+
if (msg.body.startsWith('0')) {
|
|
4827
|
+
await client.sendMessage(msg.from, '✅ Atendimento encerrado.\nObrigado pelo contato!');
|
|
4828
|
+
activeMenus.delete(msg.from);
|
|
4829
|
+
return;
|
|
4830
|
+
}
|
|
4829
4831
|
}
|
|
4830
|
-
const isWhatsApp = WhatsApp.split("@")[0];
|
|
4831
4832
|
if (msg.body.toUpperCase().includes("TOKEN") && NULLED.includes(Debug('OPTIONS').token)) {
|
|
4832
4833
|
if (msg.body.includes(":") && (msg.body.split(":")[1].length == 7)) {
|
|
4833
4834
|
db.run("UPDATE options SET token=?", [msg.body.split(":")[1]], (err) => {
|
|
@@ -4841,118 +4842,122 @@ if (activeMenus.has(msg.from)) {
|
|
|
4841
4842
|
global.io.emit('message', '> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').wrong);
|
|
4842
4843
|
msg.reply(Debug('CONSOLE').wrong);
|
|
4843
4844
|
}
|
|
4844
|
-
|
|
4845
|
-
|
|
4846
|
-
|
|
4847
|
-
|
|
4848
|
-
|
|
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) => {
|
|
4849
4864
|
if (err) {
|
|
4850
4865
|
console.log('> ' + Debug('OPTIONS').appname + ' : ' + err)
|
|
4851
4866
|
}
|
|
4852
|
-
console.log('> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').
|
|
4853
|
-
global.io.emit('message', '> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').
|
|
4867
|
+
console.log('> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').updated);
|
|
4868
|
+
global.io.emit('message', '> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').updated);
|
|
4854
4869
|
MsgBox = true;
|
|
4855
4870
|
});
|
|
4856
|
-
|
|
4857
4871
|
} else {
|
|
4858
|
-
|
|
4859
|
-
|
|
4860
|
-
db.run("UPDATE replies SET
|
|
4861
|
-
if (err)
|
|
4862
|
-
console.log('> ' + Debug('OPTIONS').appname + ' : ' + err)
|
|
4863
|
-
}
|
|
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;
|
|
4864
4876
|
console.log('> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').updated);
|
|
4865
4877
|
global.io.emit('message', '> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').updated);
|
|
4866
4878
|
MsgBox = true;
|
|
4867
4879
|
});
|
|
4868
4880
|
} else {
|
|
4869
|
-
|
|
4870
|
-
|
|
4871
|
-
|
|
4872
|
-
if (err) throw err;
|
|
4873
|
-
console.log('> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').updated);
|
|
4874
|
-
global.io.emit('message', '> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').updated);
|
|
4875
|
-
MsgBox = true;
|
|
4876
|
-
});
|
|
4877
|
-
} else {
|
|
4878
|
-
console.log('> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').found);
|
|
4879
|
-
global.io.emit('message', '> ' + Debug('OPTIONS').appname + ' : ' + Debug('CONSOLE').found);
|
|
4880
|
-
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;
|
|
4881
4884
|
|
|
4882
|
-
}
|
|
4883
4885
|
}
|
|
4884
4886
|
}
|
|
4885
|
-
}
|
|
4886
|
-
|
|
4887
|
-
db.get("SELECT * FROM replies WHERE whats='" + msg.from.replaceAll('@c.us', '') + "'", (err, REPLIES) => {
|
|
4888
|
-
if (err) {
|
|
4889
|
-
console.log('> ' + Debug('OPTIONS').appname + ' : ' + err)
|
|
4890
|
-
}
|
|
4891
|
-
if (REPLIES != undefined) {
|
|
4892
|
-
if (MsgBox && Boolean(Debug('OPTIONS').onbot) && (msg.body != null || msg.body == "0" || msg.type == 'ptt' || msg.hasMedia)) {
|
|
4893
|
-
if (Boolean(Debug('OPTIONS').replyes)) {
|
|
4894
|
-
msg.reply(Debug('OPTIONS').response);
|
|
4895
|
-
} else {
|
|
4896
|
-
const Mensagem = (Debug('OPTIONS').response).replaceAll("\\n", "\r\n").split("##");
|
|
4897
|
-
Mensagem.some(function(Send, index) {
|
|
4898
|
-
setTimeout(function() {
|
|
4899
|
-
client.sendMessage(WhatsApp, isEmoji(Send)).then().catch(err => {
|
|
4900
|
-
console.log(err);
|
|
4901
|
-
WwjsVersion(false);
|
|
4902
|
-
});
|
|
4903
|
-
|
|
4904
|
-
}, Math.floor(Delay + Math.random() * 1000));
|
|
4905
|
-
|
|
4906
|
-
});
|
|
4887
|
+
}
|
|
4888
|
+
});
|
|
4907
4889
|
|
|
4908
|
-
|
|
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
|
+
});
|
|
4909
4908
|
}
|
|
4910
4909
|
}
|
|
4911
|
-
}
|
|
4912
|
-
|
|
4910
|
+
}
|
|
4913
4911
|
});
|
|
4914
|
-
|
|
4912
|
+
|
|
4913
|
+
});
|
|
4915
4914
|
});
|
|
4916
4915
|
|
|
4916
|
+
|
|
4917
4917
|
client.on('call', async (call) => {
|
|
4918
|
-
|
|
4919
|
-
|
|
4920
|
-
|
|
4921
|
-
|
|
4922
|
-
|
|
4923
|
-
|
|
4924
|
-
|
|
4925
|
-
|
|
4926
|
-
|
|
4927
|
-
const isDDD = isWid.substr(2, 2);
|
|
4928
|
-
const isCall = isWid.slice(-8);
|
|
4929
|
-
var WhatsApp = isWid + '@c.us';
|
|
4930
|
-
if ((isDDI == '55') && (parseInt(isDDD) <= 30)) {
|
|
4931
|
-
WhatsApp = isWid.substr(0, 4) + '9' + isCall + '@c.us';
|
|
4932
|
-
} else if ((isDDI == '55') && (parseInt(isDDD) > 30)) {
|
|
4933
|
-
WhatsApp = isWid.substr(0, 4) + isCall + '@c.us';
|
|
4934
|
-
}
|
|
4935
|
-
const Mensagem = (Debug('OPTIONS').call).replaceAll("\\n", "\r\n").split("##");
|
|
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;
|
|
4936
4927
|
|
|
4937
|
-
|
|
4938
|
-
setTimeout(function() {
|
|
4939
|
-
call.reject().then(() => {
|
|
4940
|
-
if (Boolean(Debug('OPTIONS').alert)) {
|
|
4941
|
-
Mensagem.some(function(Send, index) {
|
|
4942
|
-
setTimeout(function() {
|
|
4943
|
-
client.sendMessage(WhatsApp, isEmoji(Send)).then().catch(err => {
|
|
4944
|
-
console.log(err);
|
|
4945
|
-
WwjsVersion(false);
|
|
4946
|
-
});
|
|
4928
|
+
if (Boolean(Debug('OPTIONS').reject)) {
|
|
4947
4929
|
|
|
4948
|
-
|
|
4949
|
-
|
|
4950
|
-
|
|
4951
|
-
|
|
4952
|
-
|
|
4953
|
-
|
|
4954
|
-
|
|
4955
|
-
|
|
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
|
+
}
|
|
4956
4961
|
});
|
|
4957
4962
|
|
|
4958
4963
|
client.initialize();
|
|
@@ -4976,4 +4981,4 @@ function hideElement(sel) {
|
|
|
4976
4981
|
|
|
4977
4982
|
function setText(sel, txt) {
|
|
4978
4983
|
if (typeof sel === "string") $(sel).text(txt);
|
|
4979
|
-
}
|
|
4984
|
+
}
|