-
Notifications
You must be signed in to change notification settings - Fork 529
/
app.js
87 lines (73 loc) · 2.28 KB
/
app.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
const { Client } = require('whatsapp-web.js');
const express = require('express');
const socketIO = require('socket.io');
const qrcode = require('qrcode');
const http = require('http');
const fs = require('fs');
const app = express();
const server = http.createServer(app);
const io = socketIO(server);
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const SESSION_FILE_PATH = './whatsapp-session.json';
let sessionCfg;
if (fs.existsSync(SESSION_FILE_PATH)) {
sessionCfg = require(SESSION_FILE_PATH);
}
app.get('/', (req, res) => {
res.sendFile('index.html', { root: __dirname });
});
const client = new Client({ puppeteer: { headless: true }, session: sessionCfg });
client.on('message', msg => {
if (msg.body == '!ping') {
msg.reply('pong');
} else if (msg.body == 'good morning') {
msg.reply('selamat pagi');
}
});
client.initialize();
// Socket IO
io.on('connection', function(socket) {
socket.emit('message', 'Connecting...');
client.on('qr', (qr) => {
console.log('QR RECEIVED', qr);
qrcode.toDataURL(qr, (err, url) => {
socket.emit('qr', url);
socket.emit('message', 'QR Code received, scan please!');
});
});
client.on('ready', () => {
socket.emit('ready', 'Whatsapp is ready!');
socket.emit('message', 'Whatsapp is ready!');
});
client.on('authenticated', (session) => {
socket.emit('authenticated', 'Whatsapp is authenticated!');
socket.emit('message', 'Whatsapp is authenticated!');
console.log('AUTHENTICATED', session);
sessionCfg=session;
fs.writeFile(SESSION_FILE_PATH, JSON.stringify(session), function (err) {
if (err) {
console.error(err);
}
});
});
});
// Send message
app.post('/send-message', (req, res) => {
const number = req.body.number;
const message = req.body.message;
client.sendMessage(number, message).then(response => {
res.status(200).json({
status: true,
response: response
});
}).catch(err => {
res.status(500).json({
status: false,
response: err
});
});
});
server.listen(8000, function() {
console.log('App running on *: ' + 8000);
});