forked from ookamiiixd/baileys-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
whatsapp.js
282 lines (225 loc) · 7.19 KB
/
whatsapp.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
import { rmSync, readdir } from 'fs'
import { join } from 'path'
import pino from 'pino'
import makeWASocket, {
makeWALegacySocket,
useMultiFileAuthState,
useSingleFileLegacyAuthState,
makeInMemoryStore,
Browsers,
DisconnectReason,
delay,
} from '@adiwajshing/baileys'
import { toDataURL } from 'qrcode'
import __dirname from './dirname.js'
import response from './response.js'
const sessions = new Map()
const retries = new Map()
const sessionsDir = (sessionId = '') => {
return join(__dirname, 'sessions', sessionId ? sessionId : '')
}
const isSessionExists = (sessionId) => {
return sessions.has(sessionId)
}
const shouldReconnect = (sessionId) => {
let maxRetries = parseInt(process.env.MAX_RETRIES ?? 0)
let attempts = retries.get(sessionId) ?? 0
maxRetries = maxRetries < 1 ? 1 : maxRetries
if (attempts < maxRetries) {
++attempts
console.log('Reconnecting...', { attempts, sessionId })
retries.set(sessionId, attempts)
return true
}
return false
}
const createSession = async (sessionId, isLegacy = false, res = null) => {
const sessionFile = (isLegacy ? 'legacy_' : 'md_') + sessionId + (isLegacy ? '.json' : '')
const logger = pino({ level: 'warn' })
const store = makeInMemoryStore({ logger })
let state, saveState
if (isLegacy) {
;({ state, saveState } = useSingleFileLegacyAuthState(sessionsDir(sessionFile)))
} else {
;({ state, saveCreds: saveState } = await useMultiFileAuthState(sessionsDir(sessionFile)))
}
/**
* @type {import('@adiwajshing/baileys').CommonSocketConfig}
*/
const waConfig = {
auth: state,
printQRInTerminal: true,
logger,
browser: Browsers.ubuntu('Chrome'),
}
/**
* @type {import('@adiwajshing/baileys').AnyWASocket}
*/
const wa = isLegacy ? makeWALegacySocket(waConfig) : makeWASocket.default(waConfig)
if (!isLegacy) {
store.readFromFile(sessionsDir(`${sessionId}_store.json`))
store.bind(wa.ev)
}
sessions.set(sessionId, { ...wa, store, isLegacy })
wa.ev.on('creds.update', saveState)
wa.ev.on('chats.set', ({ chats }) => {
if (isLegacy) {
store.chats.insertIfAbsent(...chats)
}
})
// Automatically read incoming messages, uncomment below codes to enable this behaviour
/*
wa.ev.on('messages.upsert', async (m) => {
const message = m.messages[0]
if (!message.key.fromMe && m.type === 'notify') {
await delay(1000)
if (isLegacy) {
await wa.chatRead(message.key, 1)
} else {
await wa.sendReadReceipt(message.key.remoteJid, message.key.participant, [message.key.id])
}
}
})
*/
wa.ev.on('connection.update', async (update) => {
const { connection, lastDisconnect } = update
const statusCode = lastDisconnect?.error?.output?.statusCode
if (connection === 'open') {
retries.delete(sessionId)
}
if (connection === 'close') {
if (statusCode === DisconnectReason.loggedOut || !shouldReconnect(sessionId)) {
if (res && !res.headersSent) {
response(res, 500, false, 'Unable to create session.')
}
return deleteSession(sessionId, isLegacy)
}
setTimeout(
() => {
createSession(sessionId, isLegacy, res)
},
statusCode === DisconnectReason.restartRequired ? 0 : parseInt(process.env.RECONNECT_INTERVAL ?? 0)
)
}
if (update.qr) {
if (res && !res.headersSent) {
try {
const qr = await toDataURL(update.qr)
response(res, 200, true, 'QR code received, please scan the QR code.', { qr })
return
} catch {
response(res, 500, false, 'Unable to create QR code.')
}
}
try {
await wa.logout()
} catch {
} finally {
deleteSession(sessionId, isLegacy)
}
}
})
}
/**
* @returns {(import('@adiwajshing/baileys').AnyWASocket|null)}
*/
const getSession = (sessionId) => {
return sessions.get(sessionId) ?? null
}
const deleteSession = (sessionId, isLegacy = false) => {
const sessionFile = (isLegacy ? 'legacy_' : 'md_') + sessionId + (isLegacy ? '.json' : '')
const storeFile = `${sessionId}_store.json`
const rmOptions = { force: true, recursive: true }
rmSync(sessionsDir(sessionFile), rmOptions)
rmSync(sessionsDir(storeFile), rmOptions)
sessions.delete(sessionId)
retries.delete(sessionId)
}
const getChatList = (sessionId, isGroup = false) => {
const filter = isGroup ? '@g.us' : '@s.whatsapp.net'
return getSession(sessionId).store.chats.filter((chat) => {
return chat.id.endsWith(filter)
})
}
/**
* @param {import('@adiwajshing/baileys').AnyWASocket} session
*/
const isExists = async (session, jid, isGroup = false) => {
try {
let result
if (isGroup) {
result = await session.groupMetadata(jid)
return Boolean(result.id)
}
if (session.isLegacy) {
result = await session.onWhatsApp(jid)
} else {
;[result] = await session.onWhatsApp(jid)
}
return result.exists
} catch {
return false
}
}
/**
* @param {import('@adiwajshing/baileys').AnyWASocket} session
*/
const sendMessage = async (session, receiver, message, delayMs = 1000) => {
try {
await delay(parseInt(delayMs))
return session.sendMessage(receiver, message)
} catch {
return Promise.reject(null) // eslint-disable-line prefer-promise-reject-errors
}
}
const formatPhone = (phone) => {
if (phone.endsWith('@s.whatsapp.net')) {
return phone
}
let formatted = phone.replace(/\D/g, '')
return (formatted += '@s.whatsapp.net')
}
const formatGroup = (group) => {
if (group.endsWith('@g.us')) {
return group
}
let formatted = group.replace(/[^\d-]/g, '')
return (formatted += '@g.us')
}
const cleanup = () => {
console.log('Running cleanup before exit.')
sessions.forEach((session, sessionId) => {
if (!session.isLegacy) {
session.store.writeToFile(sessionsDir(`${sessionId}_store.json`))
}
})
}
const init = () => {
readdir(sessionsDir(), (err, files) => {
if (err) {
throw err
}
for (const file of files) {
if ((!file.startsWith('md_') && !file.startsWith('legacy_')) || file.endsWith('_store')) {
continue
}
const filename = file.replace('.json', '')
const isLegacy = filename.split('_', 1)[0] !== 'md'
const sessionId = filename.substring(isLegacy ? 7 : 3)
createSession(sessionId, isLegacy)
}
})
}
export {
isSessionExists,
createSession,
getSession,
deleteSession,
getChatList,
isExists,
sendMessage,
formatPhone,
formatGroup,
cleanup,
init,
}