-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathapp.js
188 lines (162 loc) · 5.18 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
/**
* ⚡⚡⚡ DECLARAMOS LAS LIBRERIAS y CONSTANTES A USAR! ⚡⚡⚡
* https://dashboard.heroku.com/new?button-url=https%3A%2F%2Fgithub.heygears.com%2Fdiegomorales91%2Fbot-whatsapp&template=https%3A%2F%2Fgithub.heygears.com%2Fleifermendez%2Fbot-whatsapp
*/
require('dotenv').config()
const fs = require('fs');
const express = require('express');
const qrcode = require('qrcode-terminal');
const { Client } = require('whatsapp-web.js');
const mysqlConnection = require('./config/mysql')
const { middlewareClient } = require('./middleware/client')
const { generateImage } = require('./controllers/handle')
const { connectionReady, connectionLost } = require('./controllers/connection')
const { saveMedia } = require('./controllers/save')
const { getMessages, responseMessages, bothResponse } = require('./controllers/flows')
const { sendMedia, sendMessage, lastTrigger } = require('./controllers/send')
const app = express();
app.use(express.json())
app.use('/',require('./routes/web'))
const port = process.env.PORT || 3000
const SESSION_FILE_PATH = './session.json';
var client;
var sessionData;
/**
* Escuchamos cuando entre un mensaje
*/
const listenMessage = () => client.on('message', async msg => {
const { from, body, hasMedia } = msg;
// Este bug lo reporto Lucas Aldeco Brescia para evitar que se publiquen estados
if(from === 'status@broadcast'){
return
}
message = body.toLowerCase();
/**
* Guardamos el archivo multimedia que envia
*/
if (process.env.SAVE_MEDIA && hasMedia) {
const media = await msg.downloadMedia();
saveMedia(media);
}
/**
* Si estas usando dialogflow solo manejamos una funcion todo es IA
*/
if (process.env.DATABASE === 'dialogflow') {
const response = await bothResponse(message);
await sendMessage(client, from, response.replyMessage);
if(response.media){
sendMedia(client, from, response.media);
}
return
}
/**
* Ver si viene de un paso anterior
* Aqui podemos ir agregando más pasos
* a tu gusto!
*/
const lastStep = await lastTrigger(from) || null;
console.log({lastStep})
if (lastStep) {
const response = await responseMessages(lastStep)
await sendMessage(client, from, response.replyMessage);
}
/**
* Respondemos al primero paso si encuentra palabras clave
*/
const step = await getMessages(message);
console.log({step})
if (step) {
const response = await responseMessages(step)
await sendMessage(client, from, response.replyMessage, response.trigger);
if(!response.delay && response.media){
sendMedia(client, from, response.media);
}
if(response.delay && response.media){
setTimeout(() => {
sendMedia(client, from, response.media);
},response.delay)
}
return
}
if(process.env.DEFAULT_MESSAGE === 'true'){
console.log('hehehe',(process.env.DEFAULT_MESSAGE) , step)
const response = await responseMessages('DEFAULT')
await sendMessage(client, from, response.replyMessage, response.trigger);
return
}
});
/**
* 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
console.log(`Validando session con Whatsapp...`)
sessionData = require(SESSION_FILE_PATH);
client = new Client({
session: sessionData,
puppeteer: {
args: [
'--no-sandbox'
],
}
});
client.on('ready', () => {
connectionReady()
listenMessage()
loadRoutes(client);
});
client.on('auth_failure', () => connectionLost())
client.initialize();
}
/**
* Generamos un QRCODE para iniciar sesion
*/
const withOutSession = () => {
console.log('No tenemos session guardada');
client = new Client({
puppeteer: {
args: [
'--no-sandbox'
],
}
});
client.on('qr', qr => generateImage(qr, () => {
qrcode.generate(qr, { small: true });
console.log(`Ver QR http://localhost:${port}/qr`)
}))
client.on('ready', () => {
connectionReady()
listenMessage()
loadRoutes(client);
});
client.on('auth_failure', () => connectionLost());
client.on('authenticated', (session) => {
sessionData = session;
fs.writeFile(SESSION_FILE_PATH, JSON.stringify(session), function (err) {
if (err) {
console.log(`Ocurrio un error con el archivo: `, err);
}
});
});
client.initialize();
}
/**
* Cargamos rutas de express
*/
const loadRoutes = (client) => {
app.use('/api/', middlewareClient(client), require('./routes/api'))
}
/**
* Revisamos si existe archivo con credenciales!
*/
(fs.existsSync(SESSION_FILE_PATH)) ? withSession() : withOutSession();
/**
* Verificamos si tienes un gesto de db
*/
if(process.env.DATABASE === 'mysql'){
mysqlConnection.connect()
}
app.listen(port, () => {
console.log(`El server esta listo por el puerto ${port}`);
})