-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
67 lines (50 loc) · 1.61 KB
/
main.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
import WebSocket from 'ws';
import readline from 'readline';
import pkg from 'whatsapp-web.js';
import qrcode from 'qrcode-terminal';
const ws = new WebSocket("ws://127.0.0.1:8010/user/user1"); // Listening Websocket server
const { Client, LocalAuth } = pkg;
ws.on('error', console.error);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function sendRequest() {
rl.question('', (value) => {
const request = {
msg: value
};
ws.send(JSON.stringify(request));
});
}
// Save whatsapp session to .wwebjs_auth directory
const client = new Client({
authStrategy: new LocalAuth()
});
// QR code generation
client.on('qr', qr => {
qrcode.generate(qr, {small: true});
});
// Prompt successful to console when connected
client.on('ready', () => {
console.log('Client Ready');
const messageMap = new Map();
// Send JSON message to websocket server
client.on('message', message => {
ws.send(JSON.stringify({msg: message.body, from: message.from}));
messageMap.set(message.from, message);
});
// Listening message from WebSocket
ws.on('message', function message(data) {
let response = JSON.parse(data);
console.log('', response.msg);
const lastMessage = messageMap.get(response.from);
// Send a reply to the sender of the last received WhatsApp message
if (lastMessage && lastMessage.from) {
client.sendMessage(lastMessage.from, response.msg);
}
//Initialzation
sendRequest();
});
});
client.initialize();