forked from didinahmadi/whatsapp-api-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp-multiple-account.js
More file actions
239 lines (203 loc) · 5.95 KB
/
app-multiple-account.js
File metadata and controls
239 lines (203 loc) · 5.95 KB
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
const { Client, MessageMedia, LocalAuth } = 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 { phoneNumberFormatter } = require('./helpers/formatter');
const fileUpload = require('express-fileupload');
const axios = require('axios');
const port = process.env.PORT || 8000;
const app = express();
const server = http.createServer(app);
const io = socketIO(server);
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
/**
* BASED ON MANY QUESTIONS
* Actually ready mentioned on the tutorials
*
* The two middlewares above only handle for data json & urlencode (x-www-form-urlencoded)
* So, we need to add extra middleware to handle form-data
* Here we can use express-fileupload
*/
app.use(fileUpload({
debug: false
}));
app.get('/', (req, res) => {
res.sendFile('index-multiple-account.html', {
root: __dirname
});
});
const sessions = [];
const SESSIONS_FILE = './whatsapp-sessions.json';
const createSessionsFileIfNotExists = function() {
if (!fs.existsSync(SESSIONS_FILE)) {
try {
fs.writeFileSync(SESSIONS_FILE, JSON.stringify([]));
console.log('Sessions file created successfully.');
} catch(err) {
console.log('Failed to create sessions file: ', err);
}
}
}
createSessionsFileIfNotExists();
const setSessionsFile = function(sessions) {
fs.writeFile(SESSIONS_FILE, JSON.stringify(sessions), function(err) {
if (err) {
console.log(err);
}
});
}
const getSessionsFile = function() {
return JSON.parse(fs.readFileSync(SESSIONS_FILE));
}
const createSession = function(id, description) {
console.log('Creating session: ' + id);
const client = new Client({
restartOnAuthFail: true,
puppeteer: {
headless: true,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-accelerated-2d-canvas',
'--no-first-run',
'--no-zygote',
'--single-process', // <- this one doesn't works in Windows
'--disable-gpu'
],
},
authStrategy: new LocalAuth({
clientId: id
})
});
client.initialize();
client.on('qr', (qr) => {
console.log('QR RECEIVED', qr);
qrcode.toDataURL(qr, (err, url) => {
io.emit('qr', { id: id, src: url });
io.emit('message', { id: id, text: 'QR Code received, scan please!' });
});
});
client.on('ready', () => {
io.emit('ready', { id: id });
io.emit('message', { id: id, text: 'Whatsapp is ready!' });
const savedSessions = getSessionsFile();
const sessionIndex = savedSessions.findIndex(sess => sess.id == id);
savedSessions[sessionIndex].ready = true;
setSessionsFile(savedSessions);
});
client.on('authenticated', () => {
io.emit('authenticated', { id: id });
io.emit('message', { id: id, text: 'Whatsapp is authenticated!' });
});
client.on('auth_failure', function() {
io.emit('message', { id: id, text: 'Auth failure, restarting...' });
});
client.on('disconnected', (reason) => {
io.emit('message', { id: id, text: 'Whatsapp is disconnected!' });
client.destroy();
client.initialize();
// Menghapus pada file sessions
const savedSessions = getSessionsFile();
const sessionIndex = savedSessions.findIndex(sess => sess.id == id);
savedSessions.splice(sessionIndex, 1);
setSessionsFile(savedSessions);
io.emit('remove-session', id);
});
// Tambahkan client ke sessions
sessions.push({
id: id,
description: description,
client: client
});
// Menambahkan session ke file
const savedSessions = getSessionsFile();
const sessionIndex = savedSessions.findIndex(sess => sess.id == id);
if (sessionIndex == -1) {
savedSessions.push({
id: id,
description: description,
ready: false,
});
setSessionsFile(savedSessions);
}
}
const init = function(socket) {
const savedSessions = getSessionsFile();
if (savedSessions.length > 0) {
if (socket) {
/**
* At the first time of running (e.g. restarting the server), our client is not ready yet!
* It will need several time to authenticating.
*
* So to make people not confused for the 'ready' status
* We need to make it as FALSE for this condition
*/
savedSessions.forEach((e, i, arr) => {
arr[i].ready = false;
});
socket.emit('init', savedSessions);
} else {
savedSessions.forEach(sess => {
createSession(sess.id, sess.description);
});
}
}
}
init();
// Socket IO
io.on('connection', function(socket) {
init(socket);
socket.on('create-session', function(data) {
console.log('Create session: ' + data.id);
createSession(data.id, data.description);
});
});
// Send message
app.post('/send-message', async (req, res) => {
console.log(req);
const sender = req.body.sender;
const number = phoneNumberFormatter(req.body.number);
const message = req.body.message;
const client = sessions.find(sess => sess.id == sender)?.client;
// Make sure the sender is exists & ready
if (!client) {
return res.status(422).json({
status: false,
message: `The sender: ${sender} is not found!`
})
}
/**
* Check if the number is already registered
* Copied from app.js
*
* Please check app.js for more validations example
* You can add the same here!
*/
const isRegisteredNumber = await client.isRegisteredUser(number);
if (!isRegisteredNumber) {
return res.status(422).json({
status: false,
message: 'The number is not registered'
});
}
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(port, function() {
console.log('App running on *: ' + port);
});