forked from codigoencasa/bot-whatsapp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
307 lines (255 loc) · 8.24 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
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
/**
* ⚡⚡⚡ DECLARAMOS LAS LIBRERIAS y CONSTANTES A USAR! ⚡⚡⚡
*/
const fs = require('fs');
const mimeDb = require('mime-db')
const express = require('express');
const moment = require('moment');
const ora = require('ora');
const chalk = require('chalk');
const ExcelJS = require('exceljs');
const qrcode = require('qrcode-terminal');
const { flowConversation } = require('./conversation')
const { Client, MessageMedia } = require('whatsapp-web.js');
const app = express();
app.use(express.urlencoded({ extended: true }))
const SESSION_FILE_PATH = './session.json';
let client;
let sessionData;
/**
* Guardamos archivos multimedia que nuestro cliente nos envie!
* @param {*} media
*/
const saveMedia = (media) => {
const extensionProcess = mimeDb[media.mimetype]
const ext = extensionProcess.extensions[0]
fs.writeFile(`./media/${media.filename}.${ext}`, media.data, { encoding: 'base64' }, function (err) {
console.log('** Archivo Media Guardado **');
});
}
/**
* Enviamos archivos multimedia a nuestro cliente
* @param {*} number
* @param {*} fileName
*/
const sendMedia = (number, fileName) => {
number = number.replace('@c.us', '');
number = `${number}@c.us`
const media = MessageMedia.fromFilePath(`./mediaSend/${fileName}`);
client.sendMessage(number, media);
}
/**
* Enviamos un mensaje simple (texto) a nuestro cliente
* @param {*} number
*/
const sendMessage = (number = null, text = null) => {
number = number.replace('@c.us', '');
number = `${number}@c.us`
const message = text || `Hola soy un BOT recuerda https://www.youtube.com/leifermendez`;
client.sendMessage(number, message);
readChat(number, message)
console.log(`${chalk.red('⚡⚡⚡ Enviando mensajes....')}`);
}
/**
* Escuchamos cuando entre un mensaje
*/
const listenMessage = () => {
client.on('message', async msg => {
const { from, to, body } = msg;
//34691015468@c.us
console.log(msg.hasMedia);
if (msg.hasMedia) {
const media = await msg.downloadMedia();
saveMedia(media);
// do something with the media data here
}
await greetCustomer(from);
console.log(body);
await replyAsk(from, body);
// await readChat(from, body)
// console.log(`${chalk.red('⚡⚡⚡ Enviando mensajes....')}`);
// console.log('Guardar este número en tu Base de Datos:', from);
});
}
/**
* Response a pregunta
*/
const replyAsk = (from, answer) => new Promise((resolve, reject) => {
console.log(`---------->`, answer);
if (answer === 'Quieromeme') {
sendMedia(from, 'meme-1.png')
resolve(true)
}
})
/**
* Revisamos si tenemos credenciales guardadas para inciar sessio
* este paso evita volver a escanear el QRCODE
*/
const withSession = () => {
// Si exsite cargamos el archivo con las credenciales
const spinner = ora(`Cargando ${chalk.yellow('Validando session con Whatsapp...')}`);
sessionData = require(SESSION_FILE_PATH);
spinner.start();
client = new Client({
session: sessionData
});
client.on('ready', () => {
console.log('Client is ready!');
spinner.stop();
// sendMessage();
// sendMedia();
connectionReady();
});
client.on('auth_failure', () => {
spinner.stop();
console.log('** Error de autentificacion vuelve a generar el QRCODE (Borrar el archivo session.json) **');
})
client.initialize();
}
/**
* Generamos un QRCODE para iniciar sesion
*/
const withOutSession = () => {
console.log('No tenemos session guardada');
client = new Client();
client.on('qr', qr => {
qrcode.generate(qr, { small: true });
});
client.on('ready', () => {
console.log('Client is ready!');
connectionReady();
});
client.on('auth_failure', () => {
console.log('** Error de autentificacion vuelve a generar el QRCODE **');
})
client.on('authenticated', (session) => {
// Guardamos credenciales de de session para usar luego
sessionData = session;
fs.writeFile(SESSION_FILE_PATH, JSON.stringify(session), function (err) {
if (err) {
console.log(err);
}
});
});
client.initialize();
}
const connectionReady = () => {
listenMessage();
readExcel();
}
/**
* Difundir mensaje a clientes
*/
const readExcel = async () => {
const pathExcel = `./chats/clientes-saludar.xlsx`;
const workbook = new ExcelJS.Workbook();
await workbook.xlsx.readFile(pathExcel);
const worksheet = workbook.getWorksheet(1);
const columnNumbers = worksheet.getColumn('A');
columnNumbers.eachCell((cell, rowNumber) => {
const numberCustomer = cell.value
const columnDate = worksheet.getRow(rowNumber);
let prevDate = columnDate.getCell(2).value;
prevDate = moment.unix(prevDate);
const diffMinutes = moment().diff(prevDate, 'minutes');
// Si ha pasado mas de 60 minuitos podemos enviar nuevamente
if (diffMinutes > 60) {
sendMessage(numberCustomer)
columnDate.getCell(2).value = moment().format('X')
columnDate.commit();
}
});
workbook.xlsx.writeFile(pathExcel);
}
/**
* Guardar historial de conversacion
* @param {*} number
* @param {*} message
*/
const readChat = async (number, message) => {
const pathExcel = `./chats/${number}.xlsx`;
const workbook = new ExcelJS.Workbook();
const today = moment().format('DD-MM-YYYY hh:mm')
if (fs.existsSync(pathExcel)) {
/**
* Si existe el archivo de conversacion lo actualizamos
*/
const workbook = new ExcelJS.Workbook();
workbook.xlsx.readFile(pathExcel)
.then(() => {
const worksheet = workbook.getWorksheet(1);
const lastRow = worksheet.lastRow;
var getRowInsert = worksheet.getRow(++(lastRow.number));
getRowInsert.getCell('A').value = today;
getRowInsert.getCell('B').value = message;
getRowInsert.commit();
workbook.xlsx.writeFile(pathExcel);
});
} else {
/**
* NO existe el archivo de conversacion lo creamos
*/
const worksheet = workbook.addWorksheet('Chats');
worksheet.columns = [
{ header: 'Fecha', key: 'number_customer' },
{ header: 'Mensajes', key: 'message' }
];
worksheet.addRow([today, message]);
workbook.xlsx.writeFile(pathExcel)
.then(() => {
console.log("saved");
})
.catch((err) => {
console.log("err", err);
});
}
}
/**
* Saludos a primera respuesta
* @param {*} req
* @param {*} res
*/
const greetCustomer = (from) => new Promise((resolve, reject) => {
from = from.replace('@c.us', '');
const pathExcel = `./chats/${from}@c.us.xlsx`;
if (!fs.existsSync(pathExcel)) {
const firstMessage = [
'👋 Ey! que pasa bro',
'Recuerda subscribirte a mi canal de YT',
'https://www.youtube.com/leifermendez',
'de regalo te dejo algunos de mis cursos',
'🔴 Aprende ANGULAR desde cero 2021 ⮕ https://bit.ly/367tJ32',
'✅ Aprende NODE desde cero 2021 ⮕ https://bit.ly/3od1Bl6',
'🔵 (Socket.io) NODE (Tutorial) ⮕ https://bit.ly/3pg1Q02',
'------',
'------',
'Veo que es la primera vez que nos escribes ¿Quieres que te envie un MEME?',
'Responde Quieromeme'
].join(' ')
sendMessage(from, firstMessage)
sendMedia(from, 'curso-1-1.png')
sendMedia(from, 'curso-2.png')
sendMedia(from, 'curso-3.png')
}
resolve(true)
})
/**
* Controladores
*/
const sendMessagePost = (req, res) => {
const { message, number } = req.body
console.log(message, number);
sendMessage(number, message)
res.send({ status: 'Enviado!' })
}
/**
* Rutas
*/
app.post('/send', sendMessagePost);
/**
* Revisamos si existe archivo con credenciales!
*/
(fs.existsSync(SESSION_FILE_PATH)) ? withSession() : withOutSession();
app.listen(9000, () => {
console.log('Server ready!');
})