-
-
Notifications
You must be signed in to change notification settings - Fork 748
/
index.js
408 lines (345 loc) 路 13.3 KB
/
index.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
const { ProviderClass } = require('@bot-whatsapp/bot')
const { Sticker } = require('wa-sticker-formatter')
const pino = require('pino')
const rimraf = require('rimraf')
const mime = require('mime-types')
const { join } = require('path')
const { createWriteStream, readFileSync } = require('fs')
const { Console } = require('console')
const { default: makeWASocket, useMultiFileAuthState, Browsers, DisconnectReason } = require('@adiwajshing/baileys')
const { baileyGenerateImage, baileyCleanNumber, baileyIsValidNumber } = require('./utils')
const { generalDownload } = require('../../common/download')
const { generateRefprovider } = require('../../common/hash')
const { convertAudio } = require('../utils/convertAudio')
const logger = new Console({
stdout: createWriteStream(`${process.cwd()}/baileys.log`),
})
/**
* 鈿欙笍 BaileysProvider: Es una clase tipo adaptor
* que extiende clases de ProviderClass (la cual es como interfaz para sber que funciones rqueridas)
* https://github.com/whiskeysockets/Baileys
*/
class BaileysProvider extends ProviderClass {
globalVendorArgs = { name: `bot`, gifPlayback: false }
vendor
saveCredsGlobal = null
constructor(args) {
super()
this.globalVendorArgs = { ...this.globalVendorArgs, ...args }
this.initBailey().then()
}
/**
* Iniciar todo Bailey
*/
initBailey = async () => {
const NAME_DIR_SESSION = `${this.globalVendorArgs.name}_sessions`
const { state, saveCreds } = await useMultiFileAuthState(NAME_DIR_SESSION)
this.saveCredsGlobal = saveCreds
try {
const sock = makeWASocket({
printQRInTerminal: false,
auth: state,
browser: Browsers.macOS('Desktop'),
syncFullHistory: false,
logger: pino({ level: 'fatal' }),
})
sock.ev.on('connection.update', async (update) => {
const { connection, lastDisconnect, qr } = update
const statusCode = lastDisconnect?.error?.output?.statusCode
/** Conexion cerrada por diferentes motivos */
if (connection === 'close') {
if (statusCode !== DisconnectReason.loggedOut) {
this.initBailey()
}
if (statusCode === DisconnectReason.loggedOut) {
const PATH_BASE = join(process.cwd(), NAME_DIR_SESSION)
rimraf(PATH_BASE, (err) => {
if (err) return
})
this.initBailey()
}
}
/** Conexion abierta correctamente */
if (connection === 'open') {
this.emit('ready', true)
this.initBusEvents(sock)
}
/** QR Code */
if (qr) {
this.emit('require_action', {
instructions: [
`Debes escanear el QR Code 馃憣 ${this.globalVendorArgs.name}.qr.png`,
`Recuerda que el QR se actualiza cada minuto `,
`Necesitas ayuda: https://link.codigoencasa.com/DISCORD`,
],
})
await baileyGenerateImage(qr, `${this.globalVendorArgs.name}.qr.png`)
}
})
sock.ev.on('creds.update', async () => {
await saveCreds()
})
} catch (e) {
logger.log(e)
this.emit('auth_failure', [
`Algo inesperado ha ocurrido NO entres en p谩nico`,
`Reinicia el BOT`,
`Tambien puedes mirar un log que se ha creado baileys.log`,
`Necesitas ayuda: https://link.codigoencasa.com/DISCORD`,
`(Puedes abrir un ISSUE) https://github.com/codigoencasa/bot-whatsapp/issues/new/choose`,
])
}
}
/**
* Mapeamos los eventos nativos a los que la clase Provider espera
* para tener un standar de eventos
* @returns
*/
busEvents = () => [
{
event: 'messages.upsert',
func: ({ messages, type }) => {
if (type !== 'notify') return
const [messageCtx] = messages
let payload = {
...messageCtx,
body: messageCtx?.message?.extendedTextMessage?.text ?? messageCtx?.message?.conversation,
from: messageCtx?.key?.remoteJid,
}
//Detectar location
if (messageCtx.message?.locationMessage) {
const { degreesLatitude, degreesLongitude } = messageCtx.message.locationMessage
if (typeof degreesLatitude === 'number' && typeof degreesLongitude === 'number') {
payload = { ...payload, body: generateRefprovider('_event_location_') }
}
}
//Detectar media
if (messageCtx.message?.imageMessage) {
payload = { ...payload, body: generateRefprovider('_event_media_') }
}
//Detectar file
if (messageCtx.message?.documentMessage) {
payload = { ...payload, body: generateRefprovider('_event_document_') }
}
//Detectar voice note
if (messageCtx.message?.audioMessage) {
payload = { ...payload, body: generateRefprovider('_event_voice_note_') }
}
if (payload.from === 'status@broadcast') return
if (payload?.key?.fromMe) return
if (!baileyIsValidNumber(payload.from)) {
return
}
const btnCtx = payload?.message?.buttonsResponseMessage?.selectedDisplayText
if (btnCtx) payload.body = btnCtx
const listRowId = payload?.message?.listResponseMessage?.title
if (listRowId) payload.body = listRowId
payload.from = baileyCleanNumber(payload.from, true)
this.emit('message', payload)
},
},
]
initBusEvents = (_sock) => {
this.vendor = _sock
const listEvents = this.busEvents()
for (const { event, func } of listEvents) {
this.vendor.ev.on(event, func)
}
}
/**
* Funcion SendRaw envia opciones directamente del proveedor
* @example await sendMessage('+XXXXXXXXXXX', 'Hello World')
*/
/**
* @alpha
* @param {string} number
* @param {string} message
* @example await sendMessage('+XXXXXXXXXXX', 'https://dominio.com/imagen.jpg' | 'img/imagen.jpg')
*/
sendMedia = async (number, imageUrl, text) => {
const fileDownloaded = await generalDownload(imageUrl)
const mimeType = mime.lookup(fileDownloaded)
if (mimeType.includes('image')) return this.sendImage(number, fileDownloaded, text)
if (mimeType.includes('video')) return this.sendVideo(number, fileDownloaded, text)
if (mimeType.includes('audio')) {
const fileOpus = await convertAudio(fileDownloaded)
return this.sendAudio(number, fileOpus, text)
}
return this.sendFile(number, fileDownloaded)
}
/**
* Enviar imagen
* @param {*} number
* @param {*} imageUrl
* @param {*} text
* @returns
*/
sendImage = async (number, filePath, text) => {
return this.vendor.sendMessage(number, {
image: readFileSync(filePath),
caption: text,
})
}
/**
* Enviar video
* @param {*} number
* @param {*} imageUrl
* @param {*} text
* @returns
*/
sendVideo = async (number, filePath, text) => {
return this.vendor.sendMessage(number, {
video: readFileSync(filePath),
caption: text,
gifPlayback: this.globalVendorArgs.gifPlayback,
})
}
/**
* Enviar audio
* @alpha
* @param {string} number
* @param {string} message
* @param {boolean} voiceNote optional
* @example await sendMessage('+XXXXXXXXXXX', 'audio.mp3')
*/
sendAudio = async (number, audioUrl) => {
return this.vendor.sendMessage(number, {
audio: { url: audioUrl },
ptt: true,
})
}
/**
*
* @param {string} number
* @param {string} message
* @returns
*/
sendText = async (number, message) => {
return this.vendor.sendMessage(number, { text: message })
}
/**
*
* @param {string} number
* @param {string} filePath
* @example await sendMessage('+XXXXXXXXXXX', './document/file.pdf')
*/
sendFile = async (number, filePath) => {
const mimeType = mime.lookup(filePath)
const fileName = filePath.split('/').pop()
return this.vendor.sendMessage(number, {
document: { url: filePath },
mimetype: mimeType,
fileName: fileName,
})
}
/**
*
* @param {string} number
* @param {string} text
* @param {string} footer
* @param {Array} buttons
* @example await sendMessage("+XXXXXXXXXXX", "Your Text", "Your Footer", [{"buttonId": "id", "buttonText": {"displayText": "Button"}, "type": 1}])
*/
sendButtons = async (number, text, buttons) => {
const numberClean = baileyCleanNumber(number)
const templateButtons = buttons.map((btn, i) => ({
buttonId: `id-btn-${i}`,
buttonText: { displayText: btn.body },
type: 1,
}))
const buttonMessage = {
text,
footer: '',
buttons: templateButtons,
headerType: 1,
}
return this.vendor.sendMessage(numberClean, buttonMessage)
}
/**
* TODO: Necesita terminar de implementar el sendMedia y sendButton guiarse:
* https://github.com/leifermendez/bot-whatsapp/blob/4e0fcbd8347f8a430adb43351b5415098a5d10df/packages/provider/src/web-whatsapp/index.js#L165
* @param {string} number
* @param {string} message
* @example await sendMessage('+XXXXXXXXXXX', 'Hello World')
*/
sendMessage = async (numberIn, message, { options }) => {
const number = baileyCleanNumber(numberIn)
if (options?.buttons?.length) return this.sendButtons(number, message, options.buttons)
if (options?.media) return this.sendMedia(number, options.media, message)
return this.sendText(number, message)
}
/**
* @param {string} remoteJid
* @param {string} latitude
* @param {string} longitude
* @param {any} messages
* @example await sendLocation("xxxxxxxxxxx@c.us" || "xxxxxxxxxxxxxxxxxx@g.us", "xx.xxxx", "xx.xxxx", messages)
*/
sendLocation = async (remoteJid, latitude, longitude, messages = null) => {
await this.vendor.sendMessage(
remoteJid,
{
location: {
degreesLatitude: latitude,
degreesLongitude: longitude,
},
},
{ quoted: messages }
)
return { status: 'success' }
}
/**
* @param {string} remoteJid
* @param {string} contactNumber
* @param {string} displayName
* @param {any} messages - optional
* @example await sendContact("xxxxxxxxxxx@c.us" || "xxxxxxxxxxxxxxxxxx@g.us", "+xxxxxxxxxxx", "Robin Smith", messages)
*/
sendContact = async (remoteJid, contactNumber, displayName, messages = null) => {
const cleanContactNumber = contactNumber.replaceAll(' ', '')
const waid = cleanContactNumber.replace('+', '')
const vcard =
'BEGIN:VCARD\n' +
'VERSION:3.0\n' +
`FN:${displayName}\n` +
'ORG:Ashoka Uni;\n' +
`TEL;type=CELL;type=VOICE;waid=${waid}:${cleanContactNumber}\n` +
'END:VCARD'
await this.client.sendMessage(
remoteJid,
{
contacts: {
displayName: 'XD',
contacts: [{ vcard }],
},
},
{ quoted: messages }
)
return { status: 'success' }
}
/**
* @param {string} remoteJid
* @param {string} WAPresence
* @example await sendPresenceUpdate("xxxxxxxxxxx@c.us" || "xxxxxxxxxxxxxxxxxx@g.us", "recording")
*/
sendPresenceUpdate = async (remoteJid, WAPresence) => {
await this.client.sendPresenceUpdate(WAPresence, remoteJid)
}
/**
* @param {string} remoteJid
* @param {string} url
* @param {object} stickerOptions
* @param {any} messages - optional
* @example await sendSticker("xxxxxxxxxxx@c.us" || "xxxxxxxxxxxxxxxxxx@g.us", "https://dn/image.png" || "https://dn/image.gif" || "https://dn/image.mp4", {pack: 'User', author: 'Me'} messages)
*/
sendSticker = async (remoteJid, url, stickerOptions, messages = null) => {
const sticker = new Sticker(url, {
...stickerOptions,
quality: 50,
type: 'crop',
})
const buffer = await sticker.toMessage()
await this.client.sendMessage(remoteJid, buffer, { quoted: messages })
}
}
module.exports = BaileysProvider