-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
client.js
405 lines (366 loc) · 14.1 KB
/
client.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
/*
terimakasih telah menggunakan source code saya. apabila ada masalah, silahkan hubungi saya
•
Thank you for using my source code. If there is a problem, please contact me
- Facebook: fb.com/amiruldev.ci
- Instagram: instagram.com/amirul.dev
- Telegram: t.me/amiruldev20
- Github: @amiruldev20
- WhatsApp: 085157489446
*/
/* module external */
import pino from "pino"
import fs from "node:fs"
import { Boom } from "@hapi/boom"
import * as baileys from "baileys"
import session from "session"
import readline from "readline"
import path from "path"
import axios from "axios"
import util from "util"
import { pathToFileURL } from "url"
import { createRequire } from "module"
const require = createRequire(import.meta.url)
/* module internal */
const { Client, msg } = await import(`./system/serialize.js?${Date.now()}`)
import * as dbprov from "./system/db/provider.js"
import color from "./system/color.js"
import setting from "./setting.js"
import sch from "./system/db/schema.js"
import * as func from "./system/function.js"
const { default: CommandHandler } = await import(`./system/cmd.js?${Date.now()}`)
const logger = pino({ timestamp: () => `,"time":"${new Date().toJSON()}"` })
logger.level = 'fatal'
let state, saveCreds, clearAll
if (setting.typedb === "mongo") {
({ state, saveCreds, clearAll } = await session.useMongoAuthState(setting.db.mongo))
} else {
({ state, saveCreds } = await baileys.useMultiFileAuthState("./.session"));
}
const mydb = /json/i.test(setting.typedb)
? new dbprov.Local()
: /mongo/i.test(setting.typedb)
? new dbprov.MongoDB(setting.db.mongo, 'db_bot')
: process.exit(1)
let db = await mydb.read()
if (!db || Object.keys(db).length === 0) {
db = {
users: {},
groups: {},
setting: {},
contacts: {},
groupMetadata: {}
}
await mydb.write(db)
console.log(color.green("[ DATABASE ] Database initialized!"))
} else {
console.log(color.yellow("[ DATABASE ] Database loaded."))
}
let phone = db?.setting?.number
const handler = new CommandHandler()
const loadFile = async (filePath) => {
try {
const resolvedPath = path.resolve(filePath)
if (require.cache[resolvedPath]) {
delete require.cache[resolvedPath]
}
let module
const ext = path.extname(filePath)
if (ext === '.cjs') {
const require = createRequire(import.meta.url)
module = require(filePath)
} else if (ext === '.js' || ext === '.mjs') {
const fileUrl = pathToFileURL(filePath).href + `?${Date.now()}`
module = await import(fileUrl)
} else {
return false
}
const commandFunction = module.default || module
if (typeof commandFunction === 'function') {
await commandFunction(handler)
return true
}
return false
} catch (error) {
console.error("[ERROR] Failed to load file:", filePath, error)
return false
}
}
const processDirectory = async (currentDir) => {
try {
const items = fs.readdirSync(currentDir)
for (const item of items) {
const fullPath = path.join(currentDir, item)
const stat = fs.statSync(fullPath)
if (stat.isDirectory()) {
await processDirectory(fullPath)
watchDirectory(fullPath)
} else if (item.endsWith('.js') || item.endsWith('.cjs') || item.endsWith('.mjs')) {
await loadFile(fullPath)
}
}
} catch (error) {
console.error("[ERROR] Error processing directory:", currentDir, error)
}
}
const loadCommands = async (dir) => {
handler.clear()
await processDirectory(dir)
}
const cmdDir = path.join(process.cwd(), 'cmd')
await loadCommands(cmdDir)
let debounceTimeout
const debounceDelay = 100
function watchDirectory(dirPath) {
fs.watch(dirPath, (eventType, filename) => {
if (!filename) return
const filePath = path.join(dirPath, filename)
clearTimeout(debounceTimeout)
debounceTimeout = setTimeout(async () => {
try {
const stats = await fs.promises.stat(filePath)
const isSupportedFile = ['.js', '.cjs', '.mjs'].some(ext => filename.endsWith(ext))
if (stats.isFile() && isSupportedFile) {
console.log(color.cyan(`[INFO] File updated: ${filename}`))
await loadFile(filePath)
} else if (stats.isDirectory()) {
console.log(color.green(`[INFO] Directory added: ${filename}`))
await processDirectory(filePath)
watchDirectory(filePath)
}
} catch (err) {
if (err.code === 'ENOENT') {
console.log(color.red(`[INFO] File or directory removed: ${filename}`))
handler.clear()
await loadCommands(cmdDir)
} else {
console.error(`[ERROR] Could not access ${filePath}:`, err)
}
}
}, debounceDelay)
})
fs.readdirSync(dirPath).forEach((item) => {
const fullPath = path.join(dirPath, item)
if (fs.statSync(fullPath).isDirectory()) {
watchDirectory(fullPath)
}
})
}
watchDirectory(cmdDir)
async function connectWA() {
process.on("uncaughtException", error => {
console.error("Uncaught Exception:", error.message)
})
async function getPhoneNumber() {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
return new Promise((resolve) => {
rl.question('[+] WhatsApp: ', async (number) => {
db.setting.number = number.replace(/[^0-9]/g, '')
db.setting.owner = setting.owner
await mydb.write(db)
rl.close()
resolve(number.replace(/[^0-9]/g, ''))
})
})
}
console.log(color.yellow("[+] STARTING WHATSAPP BOT..."))
const { version, isLatest } = await baileys.fetchLatestBaileysVersion()
console.log(color.cyan(`[+] Using WA v${version.join(".")}, isLatest: ${isLatest}`))
if (!phone) {
phone = await getPhoneNumber()
}
console.log(color.cyan(`[+] Request Pairing: ${phone}`))
const sock = Client(db, {
version,
logger,
auth: {
creds: state.creds,
keys: baileys.makeCacheableSignalKeyStore(state.keys, logger)
},
mobile: false,
printQRInTerminal: true,
browser: baileys.Browsers.ubuntu("Chrome"),
markOnlineOnConnect: false,
generateHighQualityLinkPreview: true,
syncFullHistory: false,
retryRequestDelayMs: 10,
transactionOpts: { maxCommitRetries: 10, delayBetweenTriesMs: 10 },
maxMsgRetryCount: 15,
appStateMacVerification: {
patch: true,
snapshot: true
},
})
if (!sock.authState.creds.registered) {
setTimeout(async () => {
const code = (await sock.requestPairingCode(phone))
?.match(/.{1,4}/g)
?.join("-") || ""
console.log(`Your Pairing Code: `, color.green(code))
}, 3000)
}
sock.ev.on("connection.update", async update => {
const { lastDisconnect, connection, receivedPendingNotifications } = update
if (receivedPendingNotifications && !sock.authState.creds?.myAppStateKeyId) {
sock.ev.flush()
}
if (connection) {
console.log(color.yellow(`[+] Connection Status : ${connection}`))
}
if (connection === 'close') {
let reason = new Boom(lastDisconnect?.error)?.output.statusCode
// console.log('reason: ', reason)
//console.log('dis ', baileys.DisconnectReason)
switch (reason) {
case 408:
console.log(color.red('[+] Connection timed out. restarting...'))
await connectWA()
break
case 503:
console.log(color.red('[+] Unavailable service. restarting...'))
await connectWA()
break
case 428:
console.log(color.cyan('[+] Connection closed, restarting...'))
await connectWA()
break
case 515:
console.log(color.cyan('[+] Need to restart, restarting...'))
await connectWA()
break
case 401:
try {
console.log(color.cyan('[+] Session Logged Out.. Recreate session...'))
if (setting.typedb === "mongo") {
await clearAll()
} else {
fs.rmSync('.session', { recursive: true, force: true })
}
console.log(color.green('[+] Session removed!!'))
process.send('reset')
} catch {
console.log(color.cyan('[+] Session not found!!'))
}
break
case 403:
console.log(color.red(`[+] Your WhatsApp Has Been Baned :D`))
if (setting.typedb === "mongo") {
await clearAll()
} else {
fs.rmSync('.session', { recursive: true, force: true })
}
process.send('reset')
break
case 405:
try {
console.log(color.cyan('[+] Session Not Logged In.. Recreate session...'))
if (setting.typedb === "mongo") {
await clearAll()
} else {
fs.rmSync('.session', { recursive: true, force: true })
}
console.log(color.green('[+] Session removed!!'))
process.send('reset')
} catch {
console.log(color.cyan('[+] Session not found!!'))
}
break
default:
}
}
if (connection === "open") {
const conn = await func.loads("amiruldev/conn.js")
conn(color, sock, axios)
if (!fs.existsSync("./temp")) {
fs.mkdirSync("./temp")
console.log(color.cyan('[+] Folder "temp" successfully created.'))
}
await mydb.write(db)
}
})
sock.ev.on("creds.update", saveCreds)
sock.ev.on("messages.upsert", async ({ type, messages }) => {
if (type === "notify" && messages.length) {
let m = messages[0]
if (m.message) {
m.message = m.message?.ephemeralMessage
? m.message.ephemeralMessage.message
: m.message
const mes = await msg(sock, m, db)
sch.schema(mes, sock, db)
await handler.execute(mes, sock, db, func, color, util)
}
}
})
sock.ev.on("contacts.update", update => {
for (const contact of update) {
const id = baileys.jidNormalizedUser(contact.id)
if (db.contacts) {
db.contacts[id] = {
...(db.contacts[id] || {}),
...(contact || {})
}
}
}
})
sock.ev.on("contacts.upsert", update => {
for (const contact of update) {
const id = baileys.jidNormalizedUser(contact.id)
if (db.contacts) {
db.contacts[id] = { ...(contact || {}), isContact: true }
}
}
})
sock.ev.on("groups.update", updates => {
for (const update of updates) {
const id = update.id
if (db.groupMetadata[id]) {
console.log(color.green('[+] Group Metadata Updated!!'))
db.groupMetadata[id] = {
...(db.groupMetadata[id] || {}),
...(update || {})
}
}
}
})
sock.ev.on("group-participants.update", ({ id, participants, action }) => {
const metadata = db.groupMetadata[id]
if (metadata) {
switch (action) {
case "add":
case "revoked_membership_requests":
metadata.participants.push(
...participants.map(id => ({
id: baileys.jidNormalizedUser(id),
admin: null
}))
)
break
case "demote":
case "promote":
for (const participant of metadata.participants) {
const id = baileys.jidNormalizedUser(participant.id)
if (participants.includes(id)) {
console.log(`${color.green(`[ ${action} ]`)} ${id.split("@")[0]} in group ${color.cyan(metadata.subject)}`)
participant.admin =
action === "promote" ? "admin" : null
}
}
break
case "remove":
metadata.participants = metadata.participants.filter(
p => !participants.includes(baileys.jidNormalizedUser(p.id))
)
break
}
}
})
// interval save db
setInterval(async () => {
await mydb.write(db)
}, 3000)
}
connectWA()