-
Notifications
You must be signed in to change notification settings - Fork 2
/
whatsapp-connector.js
390 lines (308 loc) · 9.98 KB
/
whatsapp-connector.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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
require('console-stamp')(console, '[HH:MM:ss.l]');
var fs = require('fs');
var qrcode = require('qrcode-terminal');
const https = require("https");
const http = require('http');
const url = require('url');
const { Client, Location, MessageMedia, LocalAuth } = require("whatsapp-web.js");
const config = require('./config.json');
try {
//Makes the script crash on unhandled rejections instead of silently
//ignoring them. In the future, promise rejections that are not handled will
//terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', (reason, promise) => {
console.log('unhandledRejection: ');// + JSON.stringify(promise, null, 2));
if (reason) console.log(JSON.stringify(reason, null, 2));
if (promise) console.log(JSON.stringify(promise, null, 2));
// console.log(process);
process.exit(5);
});
// var somevar = false;
// var PTest = function () {
// return new Promise(function (resolve, reject) {
// if (somevar === true)
// resolve();
// else
// reject();
// });
// }
// var myfunc = PTest();
// myfunc.then(function () {
// console.log("Promise Resolved");
// });
// .catch(function () {
// console.log("Promise Rejected");
// });
var client = new Client({
authStrategy: new LocalAuth(),
puppeteer: {
headless: true
, args: [
'--log-level=3', // fatal only
'--start-maximized',
'--no-default-browser-check',
'--disable-infobars',
'--disable-web-security',
'--disable-site-isolation-trials',
'--no-experiments',
'--ignore-gpu-blacklist',
'--ignore-certificate-errors',
'--ignore-certificate-errors-spki-list',
'--disable-gpu',
'--disable-extensions',
'--disable-default-apps',
'--enable-features=NetworkService',
'--disable-setuid-sandbox',
'--no-sandbox',
'--disable-dev-shm-usage',
'--disable-accelerated-2d-canvas',
'--no-first-run',
'--no-zygote'
]
},
authTimeoutMs: 145000
});
var usersData = new Map(); //store user data
var lastMessageTimestamp = new Map(); //store last message time for every chat
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}
setInterval(archiveOldChats, getRandomInt(7, 20) * 60 * 1000);
setInterval(heartBeat, 5 * 60 * 1000);
function heartBeat() {
var httpsOptions = {
host: config.resendHost,
port: config.resendPort,
path: config.resendPath,
method: 'POST'
};
var req = https.request(httpsOptions, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function(chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with heartbeat request: ' + e.message);
});
const texto = '{"to":"' + client.info.wid._serialized + '","type":"heartBeat"}';
console.log(texto);
req.write(texto);
req.end();
}
function archiveOldChats() {
console.log('archiving old chats');
const f = async function(value, key, map) {
// console.debug(Date.now());
// console.debug(value);
// console.debug(key);
if ((Date.now() - value) > getRandomInt(30, 60) * 60 * 1000) {
var chat = await client.getChatById(key);
console.log('archiving '
+ key);
chat.archive();
map.delete(key);
}
};
console.log(lastMessageTimestamp);
lastMessageTimestamp
.forEach(f)
}
http.createServer(async function(req, res) {
res.writeHead(200, { 'Content-Type': 'application/json' });
// console.log(req);
var url_parts = url.parse(req.url, true);
console.log(url_parts.query.action);
switch (url_parts.query.action) {
case 'getChatById':
console.log(`el chat {$url_parts.query.chatId}`);
var chat = await client.getChatById(url_parts.query.chatId);
res.write(JSON.stringify(chat));
res.end();
break;
case 'getChats':
var chat = await client.getChats();
res.write(JSON.stringify(chat));
res.end();
break;
case 'sendMessage':
var mensageRes = "";
if (req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString(); // convert Buffer to string
});
req.on('end', async () => {
bodyJson = JSON.parse(body);
console.log(body);
if (typeof bodyJson.attachment !== 'undefined') {
const media = await MessageMedia.fromUrl(bodyJson.attachment).catch(function(err) { console.log(err); mensageRes = err });
// const media = MessageMedia.fromFilePath('/home/gaby/Descargas/DIA DE LA TIERRA.jpg');
console.log(await client.sendMessage(bodyJson.chatId, media).catch(function(err) { console.log(err); mensageRes = err }));
if (mensageRes == "")
res.write('{"success":true}');
else
res.write('{"success":false,"message":"' + mensageRes + '"}');
res.end();
} else {
var msg = bodyJson.message;
const regexpGeo = /^(?:geo:)([+-]?\d+\.\d+),([+-]?\d+\.\d+)(?:;label=(.*))?$/m;
//const str = 'geo:-11.03287,45.89174;label= trinidad y bobago';
const arrGeo = msg.match(regexpGeo);
if (arrGeo) {
msg = msg.replace(regexpGeo, '')
console.log("coordenadas: ");
var lat = arrGeo[1];
var long = arrGeo[2];
console.log(lat);
console.log(long);
var label = '';
if (arrGeo[3]) {
label = arrGeo[3];
}
console.log(label);
msgGeo = new Location(lat, long, label);
}
if ((arrGeo && msg != '') || !arrGeo) // si no encontro coordenadas, o si encontro coordenadas y el mensaje aun tiene algo mas lo manda
console.log(await client.sendMessage(bodyJson.chatId, msg).catch(function(err) { console.log(err); mensageRes = err }));
if (arrGeo)
console.log(await client.sendMessage(bodyJson.chatId, msgGeo).catch(function(err) { console.log(err); mensageRes = err }));
if (mensageRes == "")
res.write('{"success":true}');
else
res.write('{"success":false,"message":"' + mensageRes + '"}');
res.end();
}
}
);
} else {
await client.sendMessage(url_parts.query.chatId, url_parts.query.message).catch(function(err) { console.log(err); mensageRes = err });
if (mensageRes == "")
res.write('{"success":true}');
else
res.write('{"success":false,"message":"' + mensageRes + '"}');
res.end();
}
console.log("ENVIADO");
break;
default:
break;
}
}).listen(config.port);
client.initialize();
client.on('qr', (qr) => {
// NOTE: This event will not be fired if a session is specified.
console.log('QR RECEIVED', qr);
qrcode.generate(qr, { small: true }, function(qr) {
console.log("QR:\n" + qr);
});
});
client.on('authenticated', (session) => {
console.log('AUTHENTICATED', session);
});
client.on('auth_failure', async msg => {
// Fired if session restore was unsuccessfull
console.error('AUTHENTICATION FAILURE', msg);
process.exit(3);
})
client.on('ready', () => {
console.log('READY');
});
client.on('message', async msg => {
console.log('MESSAGE RECEIVED', msg);
if (msg.from == 'status@broadcast') {
console.log('STATUS MESSAGE');
return;
}
if (!usersData.has(msg.from)) {
var chat = await client.getChatById(msg.from);
console.log("adding chat to map");
var contact = "";
Promise.race([
contact = await msg.getContact(),
new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 11.5e3))
]).catch(function(err) {
if (err.name === 'timeout') {
console.log("timeout getContact.");
lastMessageTimestamp.delete(msg.from); //if there is an error I remove chat from the map so that it is not archived in whatsapp
} else {
throw err;
}
});
chat.contact = contact;
usersData.set(msg.from, chat);
}
msg.profile = usersData.get(msg.from);
lastMessageTimestamp.set(msg.from, Date.now());
if (msg.hasMedia) {
var attachmentData = "";
Promise.race([
attachmentData = await msg.downloadMedia(),
new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 11.5e3))
]).catch(function(err) {
if (err.name === 'timeout') {
console.log("timeout downloadMedia.");
lastMessageTimestamp.delete(msg.from); //if there is an error I remove chat from the map so that it is not archived in whatsapp
} else {
throw err;
}
});
console.log(`
*Media info*
MimeType: ${attachmentData.mimetype}
Filename: ${attachmentData.filename}
Data (length): ${attachmentData.data.length}
`);
msg.attachmentData = attachmentData;
}
transmitMessage(msg);
if (msg.body == 'IsAlive?') {
msg.reply('YesSir');
}
});
function transmitMessage(msg) {
var httpsOptions = {
host: config.resendHost,
port: config.resendPort,
path: config.resendPath,
method: 'POST'
};
var req = https.request(httpsOptions, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function(chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
lastMessageTimestamp.delete(msg.from); //if there is an error I remove chat from the map so that it is not archived in whatsapp
});
// write data to request body
req.write(JSON.stringify(msg));
req.end();
}
client.on('message_create', (msg) => {
// Fired on all message creations, including your own
if (msg.fromMe) {
// do stuff here
}
})
function sleep(ms) {
return new Promise(resolve => {
setTimeout(resolve, ms)
})
}
client.on('disconnected', async () => {
console.log('Client was logged out');
process.exit(2);
})
} catch (err) {
console.log(err);
process.exit(4);
}