Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
MR414N-ID
GitHub Repository: MR414N-ID/botku2
Path: blob/master/index.js
1113 views
1
/**
2
* Original zets-Morou Dika Ardnt.
3
*/
4
5
require('./config')
6
const { default: zetsConnect, useSingleFileAuthState, DisconnectReason, fetchLatestBaileysVersion, generateForwardMessageContent, prepareWAMessageMedia, generateWAMessageFromContent, generateMessageID, downloadContentFromMessage, makeInMemoryStore, jidDecode, proto } = require("@adiwajshing/baileys")
7
const { state, saveState } = useSingleFileAuthState(`./${sessionName}.json`)
8
const pino = require('pino')
9
const { Boom } = require('@hapi/boom')
10
const fs = require('fs')
11
const yargs = require('yargs/yargs')
12
const chalk = require('chalk')
13
const FileType = require('file-type')
14
const path = require('path')
15
const _ = require('lodash')
16
const PhoneNumber = require('awesome-phonenumber')
17
const { imageToWebp, videoToWebp, writeExifImg, writeExifVid } = require('./lib/exif')
18
const { smsg, isUrl, generateMessageTag, getBuffer, getSizeMedia, fetchJson, await, sleep } = require('./lib/myfunc')
19
20
var low
21
try {
22
low = require('lowdb')
23
} catch (e) {
24
low = require('./lib/lowdb')
25
}
26
27
const { Low, JSONFile } = low
28
const mongoDB = require('./lib/mongoDB')
29
30
global.api = (name, path = '/', query = {}, apikeyqueryname) => (name in global.APIs ? global.APIs[name] : name) + path + (query || apikeyqueryname ? '?' + new URLSearchParams(Object.entries({ ...query, ...(apikeyqueryname ? { [apikeyqueryname]: global.APIKeys[name in global.APIs ? global.APIs[name] : name] } : {}) })) : '')
31
32
const store = makeInMemoryStore({ logger: pino().child({ level: 'silent', stream: 'store' }) })
33
34
global.opts = new Object(yargs(process.argv.slice(2)).exitProcess(false).parse())
35
global.db = new Low(
36
/https?:\/\//.test(opts['db'] || '') ?
37
new cloudDBAdapter(opts['db']) : /mongodb/.test(opts['db']) ?
38
new mongoDB(opts['db']) :
39
new JSONFile(`src/database.json`)
40
)
41
global.DATABASE = global.db // Backwards Compatibility
42
global.loadDatabase = async function loadDatabase() {
43
if (global.db.READ) return new Promise((resolve) => setInterval(function () { (!global.db.READ ? (clearInterval(this), resolve(global.db.data == null ? global.loadDatabase() : global.db.data)) : null) }, 1 * 1000))
44
if (global.db.data !== null) return
45
global.db.READ = true
46
await global.db.read()
47
global.db.READ = false
48
global.db.data = {
49
users: {},
50
chats: {},
51
database: {},
52
game: {},
53
settings: {},
54
others: {},
55
sticker: {},
56
anonymous: {},
57
...(global.db.data || {})
58
}
59
global.db.chain = _.chain(global.db.data)
60
}
61
loadDatabase()
62
63
// save database every 30seconds
64
if (global.db) setInterval(async () => {
65
if (global.db.data) await global.db.write()
66
}, 30 * 1000)
67
68
async function startzets() {
69
const zets = zetsConnect({
70
logger: pino({ level: 'silent' }),
71
printQRInTerminal: true,
72
browser: ['AzzBot•MD','Safari','1.0.0'],
73
auth: state
74
})
75
76
store.bind(zets.ev)
77
78
// Anti Call
79
zets.ev.on('call', async (fatihh) => {
80
let botNumber = await zets.decodeJid(zets.user.id)
81
let ciko = db.data.settings[botNumber].anticall
82
if (!ciko) return
83
console.log(fatihh)
84
for (let tihh of fatihh) {
85
if (tihh.isGroup == false) {
86
if (tihh.status == "offer") {
87
let pa7rick = await zets.sendTextWithMentions(tihh.from, `*${zets.user.name}* tidak bisa menerima panggilan ${tihh.isVideo ? `video` : `suara`}. Maaf @${tihh.from.split('@')[0]} kamu akan diblockir. Jika tidak sengaja silahkan hubungi Owner untuk dibuka !`)
88
zets.sendContact(tihh.from, global.owner, pa7rick)
89
await sleep(8000)
90
await zets.updateBlockStatus(tihh.from, "block")
91
}
92
}
93
}
94
})
95
96
zets.ev.on('messages.upsert', async chatUpdate => {
97
//console.log(JSON.stringify(chatUpdate, undefined, 2))
98
try {
99
mek = chatUpdate.messages[0]
100
if (!mek.message) return
101
mek.message = (Object.keys(mek.message)[0] === 'ephemeralMessage') ? mek.message.ephemeralMessage.message : mek.message
102
if (mek.key && mek.key.remoteJid === 'status@broadcast') return
103
if (!zets.public && !mek.key.fromMe && chatUpdate.type === 'notify') return
104
if (mek.key.id.startsWith('BAE5') && mek.key.id.length === 16) return
105
if (mek.key.id.startsWith('FatihArridho_')) return
106
m = smsg(zets, mek, store)
107
require("./AzzBot")(zets, m, chatUpdate, store)
108
} catch (err) {
109
console.log(err)
110
}
111
})
112
113
// Group Update
114
zets.ev.on('groups.update', async pea => {
115
//console.log(pea)
116
try {
117
for(let ciko of pea) {
118
// Get Profile Picture Group
119
try {
120
ppgc = await zets.profilePictureUrl(ciko.id, 'image')
121
} catch {
122
ppgc = 'https://tinyurl.com/yx93l6da'
123
}
124
let wm_fatih = { url : ppgc }
125
if (ciko.announce == true) {
126
zets.send5ButImg(ciko.id, `「 Group Settings Change 」\n\nGroup telah ditutup oleh admin, Sekarang hanya admin yang dapat mengirim pesan !`, `Group Settings Change Message`, wm_fatih, [])
127
} else if (ciko.announce == false) {
128
zets.send5ButImg(ciko.id, `「 Group Settings Change 」\n\nGroup telah dibuka oleh admin, Sekarang peserta dapat mengirim pesan !`, `Group Settings Change Message`, wm_fatih, [])
129
} else if (ciko.restrict == true) {
130
zets.send5ButImg(ciko.id, `「 Group Settings Change 」\n\nInfo group telah dibatasi, Sekarang hanya admin yang dapat mengedit info group !`, `Group Settings Change Message`, wm_fatih, [])
131
} else if (ciko.restrict == false) {
132
zets.send5ButImg(ciko.id, `「 Group Settings Change 」\n\nInfo group telah dibuka, Sekarang peserta dapat mengedit info group !`, `Group Settings Change Message`, wm_fatih, [])
133
} else {
134
zets.send5ButImg(ciko.id, `「 Group Settings Change 」\n\nGroup Subject telah diganti menjadi *${ciko.subject}*`, `Group Settings Change Message`, wm_fatih, [])
135
}
136
}
137
} catch (err){
138
console.log(err)
139
}
140
})
141
142
zets.ev.on('group-participants.update', async (anu) => {
143
console.log(anu)
144
try {
145
let metadata = await zets.groupMetadata(anu.id)
146
let participants = anu.participants
147
for (let num of participants) {
148
// Get Profile Picture User
149
try {
150
ppuser = await zets.profilePictureUrl(num, 'image')
151
} catch {
152
ppuser = 'https://tinyurl.com/yx93l6da'
153
}
154
155
// Get Profile Picture Group
156
try {
157
ppgroup = await zets.profilePictureUrl(anu.id, 'image')
158
} catch {
159
ppgroup = 'https://tinyurl.com/yx93l6da'
160
}
161
162
if (anu.action == 'add') {
163
zets.sendMessage(anu.id, { image: { url: ppuser }, mentions: [num], caption: `Welcome To ${metadata.subject} @${num.split("@")[0]}` })
164
} else if (anu.action == 'remove') {
165
zets.sendMessage(anu.id, { image: { url: ppuser }, mentions: [num], caption: `@${num.split("@")[0]} Leaving To ${metadata.subject}` })
166
} else if (anu.action == 'promote') {
167
zets.sendMessage(anu.id, { image: { url: ppuser }, mentions: [num], caption: `@${num.split('@')[0]} Promote From ${metadata.subject}` })
168
} else if (anu.action == 'demote') {
169
zets.sendMessage(anu.id, { image: { url: ppuser }, mentions: [num], caption: `@${num.split('@')[0]} Demote From ${metadata.subject}` })
170
}
171
}
172
} catch (err) {
173
console.log(err)
174
}
175
})
176
177
// Setting
178
zets.decodeJid = (jid) => {
179
if (!jid) return jid
180
if (/:\d+@/gi.test(jid)) {
181
let decode = jidDecode(jid) || {}
182
return decode.user && decode.server && decode.user + '@' + decode.server || jid
183
} else return jid
184
}
185
186
zets.ev.on('contacts.update', update => {
187
for (let contact of update) {
188
let id = zets.decodeJid(contact.id)
189
if (store && store.contacts) store.contacts[id] = { id, name: contact.notify }
190
}
191
})
192
193
zets.getName = (jid, withoutContact = false) => {
194
id = zets.decodeJid(jid)
195
withoutContact = zets.withoutContact || withoutContact
196
let v
197
if (id.endsWith("@g.us")) return new Promise(async (resolve) => {
198
v = store.contacts[id] || {}
199
if (!(v.name || v.subject)) v = zets.groupMetadata(id) || {}
200
resolve(v.name || v.subject || PhoneNumber('+' + id.replace('@s.whatsapp.net', '')).getNumber('international'))
201
})
202
else v = id === '[email protected]' ? {
203
id,
204
name: 'WhatsApp'
205
} : id === zets.decodeJid(zets.user.id) ?
206
zets.user :
207
(store.contacts[id] || {})
208
return (withoutContact ? '' : v.name) || v.subject || v.verifiedName || PhoneNumber('+' + jid.replace('@s.whatsapp.net', '')).getNumber('international')
209
}
210
211
zets.sendContact = async (jid, kon, quoted = '', opts = {}) => {
212
let list = []
213
for (let i of kon) {
214
list.push({
215
displayName: await zets.getName(i + '@s.whatsapp.net'),
216
vcard: `BEGIN:VCARD\nVERSION:3.0\nN:${await zets.getName(i + '@s.whatsapp.net')}\nFN:${await zets.getName(i + '@s.whatsapp.net')}\nitem1.TEL;waid=${i}:${i}\nitem1.X-ABLabel:Ponsel\nitem2.EMAIL;type=INTERNET:[email protected]\nitem2.X-ABLabel:Email\nitem3.URL:https://instagram.com/cak_haho\nitem3.X-ABLabel:Instagram\nitem4.ADR:;;Indonesia;;;;\nitem4.X-ABLabel:Region\nEND:VCARD`
217
})
218
}
219
zets.sendMessage(jid, { contacts: { displayName: `${list.length} Kontak`, contacts: list }, ...opts }, { quoted })
220
}
221
222
zets.setStatus = (status) => {
223
zets.query({
224
tag: 'iq',
225
attrs: {
226
to: '@s.whatsapp.net',
227
type: 'set',
228
xmlns: 'status',
229
},
230
content: [{
231
tag: 'status',
232
attrs: {},
233
content: Buffer.from(status, 'utf-8')
234
}]
235
})
236
return status
237
}
238
239
zets.public = true
240
241
zets.serializeM = (m) => smsg(zets, m, store)
242
243
zets.ev.on('connection.update', async (update) => {
244
const { connection, lastDisconnect } = update
245
if (connection === 'close') {
246
let reason = new Boom(lastDisconnect?.error)?.output.statusCode
247
if (reason === DisconnectReason.badSession) { console.log(`Bad Session File, Please Delete Session and Scan Again`); zets.logout(); }
248
else if (reason === DisconnectReason.connectionClosed) { console.log("Connection closed, reconnecting...."); startzets(); }
249
else if (reason === DisconnectReason.connectionLost) { console.log("Connection Lost from Server, reconnecting..."); startzets(); }
250
else if (reason === DisconnectReason.connectionReplaced) { console.log("Connection Replaced, Another New Session Opened, Please Close Current Session First"); zets.logout(); }
251
else if (reason === DisconnectReason.loggedOut) { console.log(`Device Logged Out, Please Scan Again And Run.`); zets.logout(); }
252
else if (reason === DisconnectReason.restartRequired) { console.log("Restart Required, Restarting..."); startzets(); }
253
else if (reason === DisconnectReason.timedOut) { console.log("Connection TimedOut, Reconnecting..."); startzets(); }
254
else if (reason === DisconnectReason.Multidevicemismatch) { console.log("Multi device mismatch, please scan again"); zets.logout(); }
255
else zets.end(`Unknown DisconnectReason: ${reason}|${connection}`)
256
}
257
console.log('Connected...', update)
258
})
259
260
zets.ev.on('creds.update', saveState)
261
262
/** Resize Image
263
*
264
* @param {Buffer} Buffer (Only Image)
265
* @param {Numeric} Width
266
* @param {Numeric} Height
267
*/
268
zets.reSize = async (image, width, height) => {
269
let jimp = require('jimp')
270
var oyy = await jimp.read(image);
271
var kiyomasa = await oyy.resize(width, height).getBufferAsync(jimp.MIME_JPEG)
272
return kiyomasa
273
}
274
// Add Other
275
276
/**
277
*
278
* @param {*} jid
279
* @param {*} url
280
* @param {*} caption
281
* @param {*} quoted
282
* @param {*} options
283
*/
284
zets.sendFileUrl = async (jid, url, caption, quoted, options = {}) => {
285
let mime = '';
286
let res = await axios.head(url)
287
mime = res.headers['content-type']
288
if (mime.split("/")[1] === "gif") {
289
return zets.sendMessage(jid, { video: await getBuffer(url), caption: caption, gifPlayback: true, ...options}, { quoted: quoted, ...options})
290
}
291
let type = mime.split("/")[0]+"Message"
292
if(mime === "application/pdf"){
293
return zets.sendMessage(jid, { document: await getBuffer(url), mimetype: 'application/pdf', caption: caption, ...options}, { quoted: quoted, ...options })
294
}
295
if(mime.split("/")[0] === "image"){
296
return zets.sendMessage(jid, { image: await getBuffer(url), caption: caption, ...options}, { quoted: quoted, ...options})
297
}
298
if(mime.split("/")[0] === "video"){
299
return zets.sendMessage(jid, { video: await getBuffer(url), caption: caption, mimetype: 'video/mp4', ...options}, { quoted: quoted, ...options })
300
}
301
if(mime.split("/")[0] === "audio"){
302
return zets.sendMessage(jid, { audio: await getBuffer(url), caption: caption, mimetype: 'audio/mpeg', ...options}, { quoted: quoted, ...options })
303
}
304
}
305
306
/** Send List Messaage
307
*
308
*@param {*} jid
309
*@param {*} text
310
*@param {*} footer
311
*@param {*} title
312
*@param {*} butText
313
*@param [*] sections
314
*@param {*} quoted
315
*/
316
zets.sendListMsg = (jid, text = '', footer = '', title = '' , butText = '', sects = [], quoted) => {
317
let sections = sects
318
var listMes = {
319
text: text,
320
footer: footer,
321
title: title,
322
buttonText: butText,
323
sections
324
}
325
zets.sendMessage(jid, listMes, { quoted: quoted })
326
}
327
328
/** Send Button 5 Location
329
*
330
* @param {*} jid
331
* @param {*} text
332
* @param {*} footer
333
* @param {*} location
334
* @param [*] button
335
* @param {*} options
336
*/
337
zets.send5ButLoc = async (jid , text = '' , footer = '', lok, but = [], options = {}) =>{
338
let bb = await zets.reSize(lok, 300, 300)
339
zets.sendMessage(jid, { location: { jpegThumbnail: bb }, caption: text, footer: footer, templateButtons: but, ...options })
340
}
341
342
/** Send Button 5 Message
343
*
344
* @param {*} jid
345
* @param {*} text
346
* @param {*} footer
347
* @param {*} button
348
* @returns
349
*/
350
zets.send5ButMsg = (jid, text = '' , footer = '', but = []) =>{
351
let templateButtons = but
352
var templateMessage = {
353
text: text,
354
footer: footer,
355
templateButtons: templateButtons
356
}
357
zets.sendMessage(jid, templateMessage)
358
}
359
360
/** Send Button 5 Image
361
*
362
* @param {*} jid
363
* @param {*} text
364
* @param {*} footer
365
* @param {*} image
366
* @param [*] button
367
* @param {*} options
368
* @returns
369
*/
370
zets.send5ButImg = async (jid , text = '' , footer = '', img, but = [], buff, options = {}) =>{
371
zets.sendMessage(jid, { image: img, caption: text, footer: footer, templateButtons: but, ...options })
372
}
373
374
/** Send Button 5 Video
375
*
376
* @param {*} jid
377
* @param {*} text
378
* @param {*} footer
379
* @param {*} Video
380
* @param [*] button
381
* @param {*} options
382
* @returns
383
*/
384
zets.send5ButVid = async (jid , text = '' , footer = '', vid, but = [], buff, options = {}) =>{
385
let lol = await zets.reSize(buf, 300, 300)
386
zets.sendMessage(jid, { video: vid, jpegThumbnail: lol, caption: text, footer: footer, templateButtons: but, ...options })
387
}
388
389
/** Send Button 5 Gif
390
*
391
* @param {*} jid
392
* @param {*} text
393
* @param {*} footer
394
* @param {*} Gif
395
* @param [*] button
396
* @param {*} options
397
* @returns
398
*/
399
zets.send5ButGif = async (jid , text = '' , footer = '', gif, but = [], buff, options = {}) =>{
400
let ahh = await zets.reSize(buf, 300, 300)
401
let a = [1,2]
402
let b = a[Math.floor(Math.random() * a.length)]
403
zets.sendMessage(jid, { video: gif, gifPlayback: true, gifAttribution: b, caption: text, footer: footer, jpegThumbnail: ahh, templateButtons: but, ...options })
404
}
405
406
/**
407
*
408
* @param {*} jid
409
* @param {*} buttons
410
* @param {*} caption
411
* @param {*} footer
412
* @param {*} quoted
413
* @param {*} options
414
*/
415
zets.sendButtonText = (jid, buttons = [], text, footer, quoted = '', options = {}) => {
416
let buttonMessage = {
417
text,
418
footer,
419
buttons,
420
headerType: 2,
421
...options
422
}
423
zets.sendMessage(jid, buttonMessage, { quoted, ...options })
424
}
425
426
/**
427
*
428
* @param {*} jid
429
* @param {*} text
430
* @param {*} quoted
431
* @param {*} options
432
* @returns
433
*/
434
zets.sendText = (jid, text, quoted = '', options) => zets.sendMessage(jid, { text: text, ...options }, { quoted })
435
436
/**
437
*
438
* @param {*} jid
439
* @param {*} path
440
* @param {*} caption
441
* @param {*} quoted
442
* @param {*} options
443
* @returns
444
*/
445
zets.sendImage = async (jid, path, caption = '', quoted = '', options) => {
446
let buffer = Buffer.isBuffer(path) ? path : /^data:.*?\/.*?;base64,/i.test(path) ? Buffer.from(path.split`,`[1], 'base64') : /^https?:\/\//.test(path) ? await (await getBuffer(path)) : fs.existsSync(path) ? fs.readFileSync(path) : Buffer.alloc(0)
447
return await zets.sendMessage(jid, { image: buffer, caption: caption, ...options }, { quoted })
448
}
449
450
/**
451
*
452
* @param {*} jid
453
* @param {*} path
454
* @param {*} caption
455
* @param {*} quoted
456
* @param {*} options
457
* @returns
458
*/
459
zets.sendVideo = async (jid, path, caption = '', quoted = '', gif = false, options) => {
460
let buffer = Buffer.isBuffer(path) ? path : /^data:.*?\/.*?;base64,/i.test(path) ? Buffer.from(path.split`,`[1], 'base64') : /^https?:\/\//.test(path) ? await (await getBuffer(path)) : fs.existsSync(path) ? fs.readFileSync(path) : Buffer.alloc(0)
461
return await zets.sendMessage(jid, { video: buffer, caption: caption, gifPlayback: gif, ...options }, { quoted })
462
}
463
464
/**
465
*
466
* @param {*} jid
467
* @param {*} path
468
* @param {*} quoted
469
* @param {*} mime
470
* @param {*} options
471
* @returns
472
*/
473
zets.sendAudio = async (jid, path, quoted = '', ptt = false, options) => {
474
let buffer = Buffer.isBuffer(path) ? path : /^data:.*?\/.*?;base64,/i.test(path) ? Buffer.from(path.split`,`[1], 'base64') : /^https?:\/\//.test(path) ? await (await getBuffer(path)) : fs.existsSync(path) ? fs.readFileSync(path) : Buffer.alloc(0)
475
return await zets.sendMessage(jid, { audio: buffer, ptt: ptt, ...options }, { quoted })
476
}
477
478
/**
479
*
480
* @param {*} jid
481
* @param {*} text
482
* @param {*} quoted
483
* @param {*} options
484
* @returns
485
*/
486
zets.sendTextWithMentions = async (jid, text, quoted, options = {}) => zets.sendMessage(jid, { text: text, contextInfo: { mentionedJid: [...text.matchAll(/@(\d{0,16})/g)].map(v => v[1] + '@s.whatsapp.net') }, ...options }, { quoted })
487
488
/**
489
*
490
* @param {*} jid
491
* @param {*} path
492
* @param {*} quoted
493
* @param {*} options
494
* @returns
495
*/
496
zets.sendImageAsSticker = async (jid, path, quoted, options = {}) => {
497
let buff = Buffer.isBuffer(path) ? path : /^data:.*?\/.*?;base64,/i.test(path) ? Buffer.from(path.split`,`[1], 'base64') : /^https?:\/\//.test(path) ? await (await getBuffer(path)) : fs.existsSync(path) ? fs.readFileSync(path) : Buffer.alloc(0)
498
let buffer
499
if (options && (options.packname || options.author)) {
500
buffer = await writeExifImg(buff, options)
501
} else {
502
buffer = await imageToWebp(buff)
503
}
504
505
await zets.sendMessage(jid, { sticker: { url: buffer }, ...options }, { quoted })
506
return buffer
507
}
508
509
/**
510
*
511
* @param {*} jid
512
* @param {*} path
513
* @param {*} quoted
514
* @param {*} options
515
* @returns
516
*/
517
zets.sendVideoAsSticker = async (jid, path, quoted, options = {}) => {
518
let buff = Buffer.isBuffer(path) ? path : /^data:.*?\/.*?;base64,/i.test(path) ? Buffer.from(path.split`,`[1], 'base64') : /^https?:\/\//.test(path) ? await (await getBuffer(path)) : fs.existsSync(path) ? fs.readFileSync(path) : Buffer.alloc(0)
519
let buffer
520
if (options && (options.packname || options.author)) {
521
buffer = await writeExifVid(buff, options)
522
} else {
523
buffer = await videoToWebp(buff)
524
}
525
526
await zets.sendMessage(jid, { sticker: { url: buffer }, ...options }, { quoted })
527
return buffer
528
}
529
530
/**
531
*
532
* @param {*} message
533
* @param {*} filename
534
* @param {*} attachExtension
535
* @returns
536
*/
537
zets.downloadAndSaveMediaMessage = async (message, filename, attachExtension = true) => {
538
let quoted = message.msg ? message.msg : message
539
let mime = (message.msg || message).mimetype || ''
540
let messageType = message.mtype ? message.mtype.replace(/Message/gi, '') : mime.split('/')[0]
541
const stream = await downloadContentFromMessage(quoted, messageType)
542
let buffer = Buffer.from([])
543
for await(const chunk of stream) {
544
buffer = Buffer.concat([buffer, chunk])
545
}
546
let type = await FileType.fromBuffer(buffer)
547
trueFileName = attachExtension ? (filename + '.' + type.ext) : filename
548
// save to file
549
await fs.writeFileSync(trueFileName, buffer)
550
return trueFileName
551
}
552
553
zets.downloadMediaMessage = async (message) => {
554
let mime = (message.msg || message).mimetype || ''
555
let messageType = message.mtype ? message.mtype.replace(/Message/gi, '') : mime.split('/')[0]
556
const stream = await downloadContentFromMessage(message, messageType)
557
let buffer = Buffer.from([])
558
for await(const chunk of stream) {
559
buffer = Buffer.concat([buffer, chunk])
560
}
561
562
return buffer
563
}
564
565
/**
566
*
567
* @param {*} jid
568
* @param {*} path
569
* @param {*} filename
570
* @param {*} caption
571
* @param {*} quoted
572
* @param {*} options
573
* @returns
574
*/
575
zets.sendMedia = async (jid, path, fileName = '', caption = '', quoted = '', options = {}) => {
576
let types = await zets.getFile(path, true)
577
let { mime, ext, res, data, filename } = types
578
if (res && res.status !== 200 || file.length <= 65536) {
579
try { throw { json: JSON.parse(file.toString()) } }
580
catch (e) { if (e.json) throw e.json }
581
}
582
let type = '', mimetype = mime, pathFile = filename
583
if (options.asDocument) type = 'document'
584
if (options.asSticker || /webp/.test(mime)) {
585
let { writeExif } = require('./lib/exif')
586
let media = { mimetype: mime, data }
587
pathFile = await writeExif(media, { packname: options.packname ? options.packname : global.packname, author: options.author ? options.author : global.author, categories: options.categories ? options.categories : [] })
588
await fs.promises.unlink(filename)
589
type = 'sticker'
590
mimetype = 'image/webp'
591
}
592
else if (/image/.test(mime)) type = 'image'
593
else if (/video/.test(mime)) type = 'video'
594
else if (/audio/.test(mime)) type = 'audio'
595
else type = 'document'
596
await zets.sendMessage(jid, { [type]: { url: pathFile }, caption, mimetype, fileName, ...options }, { quoted, ...options })
597
return fs.promises.unlink(pathFile)
598
}
599
600
/**
601
*
602
* @param {*} jid
603
* @param {*} message
604
* @param {*} forceForward
605
* @param {*} options
606
* @returns
607
*/
608
zets.copyNForward = async (jid, message, forceForward = false, options = {}) => {
609
let vtype
610
if (options.readViewOnce) {
611
message.message = message.message && message.message.ephemeralMessage && message.message.ephemeralMessage.message ? message.message.ephemeralMessage.message : (message.message || undefined)
612
vtype = Object.keys(message.message.viewOnceMessage.message)[0]
613
delete(message.message && message.message.ignore ? message.message.ignore : (message.message || undefined))
614
delete message.message.viewOnceMessage.message[vtype].viewOnce
615
message.message = {
616
...message.message.viewOnceMessage.message
617
}
618
}
619
620
let mtype = Object.keys(message.message)[0]
621
let content = await generateForwardMessageContent(message, forceForward)
622
let ctype = Object.keys(content)[0]
623
let context = {}
624
if (mtype != "conversation") context = message.message[mtype].contextInfo
625
content[ctype].contextInfo = {
626
...context,
627
...content[ctype].contextInfo
628
}
629
const waMessage = await generateWAMessageFromContent(jid, content, options ? {
630
...content[ctype],
631
...options,
632
...(options.contextInfo ? {
633
contextInfo: {
634
...content[ctype].contextInfo,
635
...options.contextInfo
636
}
637
} : {})
638
} : {})
639
await zets.relayMessage(jid, waMessage.message, { messageId: waMessage.key.id })
640
return waMessage
641
}
642
643
zets.cMod = (jid, copy, text = '', sender = zets.user.id, options = {}) => {
644
//let copy = message.toJSON()
645
let mtype = Object.keys(copy.message)[0]
646
let isEphemeral = mtype === 'ephemeralMessage'
647
if (isEphemeral) {
648
mtype = Object.keys(copy.message.ephemeralMessage.message)[0]
649
}
650
let msg = isEphemeral ? copy.message.ephemeralMessage.message : copy.message
651
let content = msg[mtype]
652
if (typeof content === 'string') msg[mtype] = text || content
653
else if (content.caption) content.caption = text || content.caption
654
else if (content.text) content.text = text || content.text
655
if (typeof content !== 'string') msg[mtype] = {
656
...content,
657
...options
658
}
659
if (copy.key.participant) sender = copy.key.participant = sender || copy.key.participant
660
else if (copy.key.participant) sender = copy.key.participant = sender || copy.key.participant
661
if (copy.key.remoteJid.includes('@s.whatsapp.net')) sender = sender || copy.key.remoteJid
662
else if (copy.key.remoteJid.includes('@broadcast')) sender = sender || copy.key.remoteJid
663
copy.key.remoteJid = jid
664
copy.key.fromMe = sender === zets.user.id
665
666
return proto.WebMessageInfo.fromObject(copy)
667
}
668
669
670
/**
671
*
672
* @param {*} path
673
* @returns
674
*/
675
zets.getFile = async (PATH, save) => {
676
let res
677
let data = Buffer.isBuffer(PATH) ? PATH : /^data:.*?\/.*?;base64,/i.test(PATH) ? Buffer.from(PATH.split`,`[1], 'base64') : /^https?:\/\//.test(PATH) ? await (res = await getBuffer(PATH)) : fs.existsSync(PATH) ? (filename = PATH, fs.readFileSync(PATH)) : typeof PATH === 'string' ? PATH : Buffer.alloc(0)
678
//if (!Buffer.isBuffer(data)) throw new TypeError('Result is not a buffer')
679
let type = await FileType.fromBuffer(data) || {
680
mime: 'application/octet-stream',
681
ext: '.bin'
682
}
683
filename = path.join(__filename, '../src/' + new Date * 1 + '.' + type.ext)
684
if (data && save) fs.promises.writeFile(filename, data)
685
return {
686
res,
687
filename,
688
size: await getSizeMedia(data),
689
...type,
690
data
691
}
692
693
}
694
695
return zets
696
}
697
698
startzets()
699
700
701
let file = require.resolve(__filename)
702
fs.watchFile(file, () => {
703
fs.unwatchFile(file)
704
console.log(chalk.redBright(`Update ${__filename}`))
705
delete require.cache[file]
706
require(file)
707
})
708
709