-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection.js
144 lines (126 loc) · 4.47 KB
/
connection.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
/* eslint-disable prefer-const */
/* eslint-disable no-unused-vars */
const { default: makeWASocket, Browsers, makeInMemoryStore } = require("@whiskeysockets/baileys");
const pino = require("pino");
const path = require("path");
const NodeCache = require("node-cache");
const { useMultiFileAuthState } = require("@whiskeysockets/baileys");
const groupCache = new NodeCache({ stdTTL: 5 * 60, useClones: false });
const { messagesProcess } = require("./messagesProcess");
const RECONNECT_INITIAL_DELAY = 2000;
const RECONNECT_MAX_DELAY = 60000;
let reconnectAttempts = 0;
let metricsIntervalId = null;
const logger = require("../utils/logger");
const patchInteractiveMessage = message => {
return message?.interactiveMessage
? {
viewOnceMessage: {
message: {
messageContextInfo: {
deviceListMetadataVersion: 2,
deviceListMetadata: {},
},
...message,
},
},
}
: message;
};
const scheduleReconnect = () => {
reconnectAttempts++;
const delay = Math.min(RECONNECT_INITIAL_DELAY * 2 ** reconnectAttempts, RECONNECT_MAX_DELAY);
setTimeout(() => connectToWhatsApp(), delay);
};
const registerAllEventHandlers = (client, saveCreds) => {
const simpleEvents = {
"chats.upsert": () => {},
"contacts.upsert": () => {},
};
Object.entries(simpleEvents).forEach(([event, handler]) => client.ev.on(event, handler));
const groupEvents = {
"groups.update": async ([event]) => {
const metadata = await client.groupMetadata(event.id);
groupCache.set(event.id, metadata);
},
"group-participants.update": async event => {
const metadata = await client.groupMetadata(event.id);
groupCache.set(event.id, metadata);
},
};
Object.entries(groupEvents).forEach(([event, handler]) => client.ev.on(event, handler));
client.ev.process(async events => {
const eventHandlers = {
"connection.update": async data => await handleConnectionUpdate(data, client),
"creds.update": async data => {
await saveCreds();
},
"messages.upsert": async data => {
require(path.join(__dirname, "..", "controllers", "botController.js"))(data, client);
messagesProcess(data, client);
},
};
for (const [event, data] of Object.entries(events)) {
try {
if (eventHandlers[event]) {
await eventHandlers[event](data);
}
} catch (error) {
console.log(`Erro ao processar o evento ${event}: ${error.message}`.green);
}
}
});
};
//
const handleConnectionUpdate = async (update, client) => {
try {
const { connection } = update;
if (connection === "open") {
logger.info("✅ Conexão aberta com sucesso. Bot disponível.");
reconnectAttempts = 0;
const config = require("../config/options.json");
await client.sendMessage(config.owner.number, {
text: "🟢 O bot foi iniciado com sucesso.",
});
logger.info("🛠️ Mensagem de status enviada para o proprietário.");
}
if (connection === "close") {
if (metricsIntervalId) {
clearInterval(metricsIntervalId);
metricsIntervalId = null;
}
scheduleReconnect();
}
} catch (error) {
scheduleReconnect();
}
};
const connectToWhatsApp = async () => {
try {
const connectionLogs = path.join(__dirname, "temp");
const { state, saveCreds } = await useMultiFileAuthState(connectionLogs);
logger.info("🌐 Iniciando a conexão com o WhatsApp...");
const client = makeWASocket({
auth: state,
logger: pino({ level: "silent" }),
printQRInTerminal: true,
mobile: false,
browser: Browsers.macOS("Desktop"),
syncFullHistory: true,
cachedGroupMetadata: async jid => groupCache.get(jid),
patchMessageBeforeSending: patchInteractiveMessage,
});
const store = makeInMemoryStore({});
store.bind(client.ev);
registerAllEventHandlers(client, saveCreds);
} catch (error) {
scheduleReconnect();
logger.error(`🔴 Erro ao iniciar a conexão: ${error.message}`);
throw new Error("Erro ao iniciar a conexão com o WhatsApp:", error);
}
};
connectToWhatsApp().catch(async error => {
scheduleReconnect();
logger.error(`🔴 Erro ao iniciar a conexão: ${error.message}`);
throw new Error("Error ao inciar a conexão com o WhatsApp:", error);
});