-
Notifications
You must be signed in to change notification settings - Fork 0
/
xeon.js
894 lines (826 loc) · 36.1 KB
/
xeon.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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
//
// ___ ___ __________
// | |\ \ | | ____ ________ | | \ \ ____ __ | |___
// | | \ \ | |/ ___ \ | | ___ \ | |_____/ / / / \ \ |__| |__| _______
// | | \ \ | | _____ / | | |_| | | | \ \ | | | | | | / /
// | | \ \| |\ ____ / | |_____ / | |_____/ / \ \___/ / | | /_/____
// | |
// | | A powerful Bot for whatsapp
// | | ___ ___ ________
// | |\ / /| | | | \ \
// | | \/ / | | | | | |
// | | | | | | | |
// | | | | | |______/ /
//
require('./settings')
const { default: NepBotzIncConnect, useSingleFileAuthState, DisconnectReason, fetchLatestBaileysVersion, generateForwardMessageContent, prepareWAMessageMedia, generateWAMessageFromContent, generateMessageID, downloadContentFromMessage, makeInMemoryStore, jidDecode, proto } = require("@adiwajshing/baileys")
const { state, saveState } = useSingleFileAuthState(`./${sessionName}.json`)
const pino = require('pino')
const { Boom } = require('@hapi/boom')
const fs = require('fs')
const yargs = require('yargs/yargs')
const chalk = require('chalk')
const FileType = require('file-type')
const path = require('path')
const PhoneNumber = require('awesome-phonenumber')
const { imageToWebp, videoToWebp, writeExifImg, writeExifVid } = require('./lib/exif')
const { smsg, isUrl, generateMessageTag, getBuffer, getSizeMedia, fetchJson, await, sleep } = require('./lib/myfunc')
const moment = require('moment-timezone')
const { toAudio, toPTT, toVideo } = require('./lib/converter')
var low
try {
low = require('lowdb')
} catch (e) {
low = require('./lib/lowdb')
}
const { Low, JSONFile } = low
const mongoDB = require('./lib/mongoDB')
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] } : {}) })) : '')
const store = makeInMemoryStore({ logger: pino().child({ level: 'silent', stream: 'store' }) })
global.opts = new Object(yargs(process.argv.slice(2)).exitProcess(false).parse())
global.db = new Low(
/https?:\/\//.test(opts['db'] || '') ?
new cloudDBAdapter(opts['db']) : /mongodb/.test(opts['db']) ?
new mongoDB(opts['db']) :
new JSONFile(`database/database.json`)
)
global.db.data = {
users: {},
chats: {},
database: {},
game: {},
settings: {},
others: {},
sticker: {},
...(global.db.data || {})
}
// save database every 30seconds
if (global.db) setInterval(async () => {
if (global.db.data) await global.db.write()
}, 30 * 1000)
async function startNepBotzInc() {
const NepBotzInc = NepBotzIncConnect({
logger: pino({ level: 'silent' }),
printQRInTerminal: true,
browser: ['Subscribe Neptune','Safari','1.0.0'],
auth: state
})
store.bind(NepBotzInc.ev)
// anticall auto block
NepBotzInc.ws.on('CB:call', async (json) => {
const callerId = json.content[0].attrs['call-creator']
if (json.content[0].tag == 'offer') {
let ownnum = await NepBotzInc.sendContact(callerId, global.owner)
NepBotzInc.sendMessage(callerId, { text: `Automatic Block System!\nDon't Call Bot!\nPlease Ask Or Contact The Owner To Unblock You!`}, { quoted : ownnum })
await sleep(8000)
await NepBotzInc.updateBlockStatus(callerId, "block")
}
})
NepBotzInc.ev.on('messages.upsert', async chatUpdate => {
//console.log(JSON.stringify(chatUpdate, undefined, 2))
try {
mek = chatUpdate.messages[0]
if (!mek.message) return
mek.message = (Object.keys(mek.message)[0] === 'ephemeralMessage') ? mek.message.ephemeralMessage.message : mek.message
if (mek.key && mek.key.remoteJid === 'status@broadcast') return
if (!NepBotzInc.public && !mek.key.fromMe && chatUpdate.type === 'notify') return
if (mek.key.id.startsWith('BAE5') && mek.key.id.length === 16) return
m = smsg(NepBotzInc, mek, store)
require("./Nepbotz1")(NepBotzInc, m, chatUpdate, store)
} catch (err) {
console.log(err)
}
})
// Group Update
NepBotzInc.ev.on('groups.update', async pea => {
//console.log(pea)
// Get Profile Picture Group
try {
ppgc = await NepBotzInc.profilePictureUrl(pea[0].id, 'image')
} catch {
ppgc = 'https://shortlink.NepBotzIncarridho.my.id/rg1oT'
}
let lolXeon = { url : ppgc }
if (pea[0].announce == true) {
NepBotzInc.sendMessage(pea[0].id, `「 Group Settings Changed 」\n\nThe Group Has Been Closed By Admin, Now Only Admin Can Send Messages !`, `${botname}`, lolXeon, [])
} else if(pea[0].announce == false) {
NepBotzInc.sendMessage(pea[0].id, `「 Group Settings Changed 」\n\nThe Group Has Been Opened By Admin, Now Participants Can Send Messages !`, `${botname}`, lolXeon, [])
} else if (pea[0].restrict == true) {
NepBotzInc.sendMesaage(pea[0].id, `「 Group Settings Changed 」\n\nGroup Info Has Been Restricted, Now Only Admin Can Edit Group Info !`, `${botname}`, lolXeon, [])
} else if (pea[0].restrict == false) {
NepBotzInc.sendMessage(pea[0].id, `「 Group Settings Changed 」\n\nGroup Info Has Been Opened, Now Participants Can Edit Group Info !`, `${botname}`, lolXeon, [])
} else {
NepBotzInc.sendMessage(pea[0].id, `「 Group Settings Changed 」\n\nGroup Subject Has Been Changed To *${pea[0].subject}*`, `${botname}`, lolXeon, [])
}
})
//randoming function
function pickRandom(list) {
return list[Math.floor(list.length * Math.random())]
}
//document randomizer
let documents = [doc1,doc2,doc3,doc4,doc5,doc6]
let docs = pickRandom(documents)
NepBotzInc.ev.on('group-participants.update', async (anu) => {
console.log(anu)
try {
let metadata = await NepBotzInc.groupMetadata(anu.id)
let participants = anu.participants
for (let num of participants) {
// Get Profile Picture User
try {
ppuser = await NepBotzInc.profilePictureUrl(num, 'image')
} catch {
ppuser = 'https://i0.wp.com/www.gambarunik.id/wp-content/uploads/2019/06/Top-Gambar-Foto-Profil-Kosong-Lucu-Tergokil-.jpg'
}
//Get Profile Picture Group\\
try {
ppgroup = await NepBotzInc.profilePictureUrl(anu.id, 'image')
} catch {
ppgroup = 'https://i0.wp.com/www.gambarunik.id/wp-content/uploads/2019/06/Top-Gambar-Foto-Profil-Kosong-Lucu-Tergokil-.jpg'
}
//welcome\\
let nama = await NepBotzInc.getName(num)
memb = metadata.participants.length
ppusr = await getBuffer(`${encodeURIComponent(ppuser)}`)
if (anu.action == 'add') {
const ppbuffer = await getBuffer(ppuser)
let xeonName = num
const xtime = moment.tz('Asia/Kolkata').format('HH:mm:ss')
const xdate = moment.tz('Asia/Kolkata').format('DD/MM/YYYY')
const xmembers = metadata.participants.length
let unicorndoc = {key: {fromMe: false,"participant":"0@s.whatsapp.net", "remoteJid": "916909137213-1604595598@g.us"}, "message": {orderMessage: {itemCount: 9999999,status: 200, surface: 200, message: `${metadata.subject}`, orderTitle: 'xeon', sellerJid: '0@s.whatsapp.net'}}, contextInfo: {"forwardingScore":999,"isForwarded":true},sendEphemeral: true}
xeonbody = `╭┅═┅❖
┃「 Hi 」
╰┅═┅❖
╭┅═┅═┅═┅═┅═┅═┅ ⪨
┃➣╭━━ ⪩『@${xeonName.split("@")[0]}』
┃➣|〆 Welcome to:
┃➣|〆 ${metadata.subject}
┃➣|〆
┃➣|〆 Member:
┃➣|〆 ${xmembers}th
┃➣|〆
┃➣|〆 Time:
┃➣|〆 ${xdate} ${xtime}
┃么|〆
╰┅═┅═┅═┅═┅═┅═┅ ⪨`
let buttons = [
{buttonId: `rules`, buttonText: {displayText: 'Rules'}, type: 1},
{buttonId: `command`, buttonText: {displayText: 'Menu'}, type: 1}
]
let buttonMessage = {
image: fs.readFileSync('./NepMedia/theme/wc.jpg'),
jpegThumbnail:ppusr,
mentions: [num],
caption: xeonbody,
footer: `${global.footer}`,
buttons: buttons,
headerType: 4,
thumbnail:ppusr,
contextInfo:{externalAdReply:{
mediaType:2
}}
}
NepBotzInc.sendMessage(anu.id, buttonMessage, {quoted:unicorndoc})
} else if (anu.action == 'remove') {
const xeonbuffer = await getBuffer(ppuser)
const xeontime = moment.tz('Asia/Kolkata').format('HH:mm:ss')
const xeondate = moment.tz('Asia/Kolkata').format('DD/MM/YYYY')
let xeonName = num
const xeonmembers = metadata.participants.length
let unicorndoc = {key: {fromMe: false,"participant":"0@s.whatsapp.net", "remoteJid": "916909137213-1604595598@g.us"}, "message": {orderMessage: {itemCount: 9999999,status: 200, surface: 200, message: `${metadata.subject}`, orderTitle: 'xeon', sellerJid: '0@s.whatsapp.net'}}, contextInfo: {"forwardingScore":999,"isForwarded":true},sendEphemeral: true}
xeonbody = `╭┅═┅❖
┃「 Goodbye」
╰┅═┅❖
╭┅═┅═┅═┅═┅═┅═┅ ⪨
┃➣╭━━ ⪩『@${xeonName.split("@")[0]}』
┃➣|〆 Left
┃➣|〆 ${metadata.subject}
┃➣|〆
┃➣|〆 Member
┃➣|〆 ${xeonmembers}th
┃➣|〆
┃➣|〆 Time:
┃➣|〆 ${xeondate} ${xeontime}
┃么|〆
╰┅═┅═┅═┅═┅═┅═┅ ⪨`
let buttons = [
{buttonId: `wkwwk`, buttonText: {displayText: 'Bye'}, type: 1},
{buttonId: `command`, buttonText: {displayText: 'Menu'}, type: 1}
]
let buttonMessage = {
image: fs.readFileSync('./NepMedia/theme/gb.jpg'),
mentions: [num],
caption: xeonbody,
footer: `${global.footer}`,
buttons: buttons,
headerType: 4,
contextInfo:{externalAdReply:{
mediaType:2
}}
}
NepBotzInc.sendMessage(anu.id, buttonMessage, {quoted:unicorndoc})
}
}
} catch (err) {
console.log(err)
}
})
//Setting\\
NepBotzInc.decodeJid = (jid) => {
if (!jid) return jid
if (/:\d+@/gi.test(jid)) {
let decode = jidDecode(jid) || {}
return decode.user && decode.server && decode.user + '@' + decode.server || jid
} else return jid
}
NepBotzInc.ev.on('contacts.update', update => {
for (let contact of update) {
let id = NepBotzInc.decodeJid(contact.id)
if (store && store.contacts) store.contacts[id] = { id, name: contact.notify }
}
})
NepBotzInc.getName = (jid, withoutContact = false) => {
id = NepBotzInc.decodeJid(jid)
withoutContact = NepBotzInc.withoutContact || withoutContact
let v
if (id.endsWith("@g.us")) return new Promise(async (resolve) => {
v = store.contacts[id] || {}
if (!(v.name || v.subject)) v = NepBotzInc.groupMetadata(id) || {}
resolve(v.name || v.subject || PhoneNumber('+' + id.replace('@s.whatsapp.net', '')).getNumber('international'))
})
else v = id === '0@s.whatsapp.net' ? {
id,
name: 'WhatsApp'
} : id === NepBotzInc.decodeJid(NepBotzInc.user.id) ?
NepBotzInc.user :
(store.contacts[id] || {})
return (withoutContact ? '' : v.name) || v.subject || v.verifiedName || PhoneNumber('+' + jid.replace('@s.whatsapp.net', '')).getNumber('international')
}
NepBotzInc.sendContact = async (jid, kon, quoted = '', opts = {}) => {
let list = []
for (let i of kon) {
list.push({
displayName: await NepBotzInc.getName(i + '@s.whatsapp.net'),
vcard: `BEGIN:VCARD\nVERSION:3.0\nN:${await NepBotzInc.getName(i + '@s.whatsapp.net')}\nFN:${global.ownername}\nitem1.TEL;waid=${i}:${i}\nitem1.X-ABLabel:Click here to chat\nitem2.EMAIL;type=INTERNET:${global.ytname}\nitem2.X-ABLabel:YouTube\nitem3.URL:${global.socialm}\nitem3.X-ABLabel:GitHub\nitem4.ADR:;;${global.location};;;;\nitem4.X-ABLabel:Region\nEND:VCARD`
////////////////////////////////////////////////////////////vcard: `BEGIN:VCARD\nVERSION:3.0\nN:${ownername}\nitem1.TEL;waid=${i}:${i}\nitem1.X-ABLabel:Click To Chat\nitem2.EMAIL;type=INTERNET:${botscript}\nitem2.X-ABLabel:Script\nitem3.URL:${websitex}\nitem3.X-ABLabel:Script\nitem4.ADR:;;${location};;;;\nitem4.X-ABLabel:Region\nEND:VCARD`
})
}
NepBotzInc.sendMessage(jid, { contacts: { displayName: `${list.length} Contact`, contacts: list }, ...opts }, { quoted })
}
NepBotzInc.setStatus = (status) => {
NepBotzInc.query({
tag: 'iq',
attrs: {
to: '@s.whatsapp.net',
type: 'set',
xmlns: 'status',
},
content: [{
tag: 'status',
attrs: {},
content: Buffer.from(status, 'utf-8')
}]
})
return status
}
NepBotzInc.public = true
NepBotzInc.serializeM = (m) => smsg(NepBotzInc, m, store)
NepBotzInc.ev.on('connection.update', async (update) => {
const { connection, lastDisconnect } = update
if (connection === 'close') {
let reason = new Boom(lastDisconnect?.error)?.output.statusCode
if (reason === DisconnectReason.badSession) { console.log(`Bad Session File, Please Delete Session and Scan Again`); NepBotzInc.logout(); }
else if (reason === DisconnectReason.connectionClosed) { console.log("Connection closed, reconnecting...."); startNepBotzInc(); }
else if (reason === DisconnectReason.connectionLost) { console.log("Connection Lost from Server, reconnecting..."); startNepBotzInc(); }
else if (reason === DisconnectReason.connectionReplaced) { console.log("Connection Replaced, Another New Session Opened, Please Close Current Session First"); NepBotzInc.logout(); }
else if (reason === DisconnectReason.loggedOut) { console.log(`Device Logged Out, Please Scan Again And Run.`); NepBotzInc.logout(); }
else if (reason === DisconnectReason.restartRequired) { console.log("Restart Required, Restarting..."); startNepBotzInc(); }
else if (reason === DisconnectReason.timedOut) { console.log("Connection TimedOut, Reconnecting..."); startNepBotzInc(); }
else NepBotzInc.end(`Unknown DisconnectReason: ${reason}|${connection}`)
}
console.log('Connected...', update)
})
NepBotzInc.ev.on('creds.update', saveState)
// Add Other
/** Send Button 5 Image
*
* @param {*} jid
* @param {*} text
* @param {*} footer
* @param {*} image
* @param [*] button
* @param {*} options
* @returns
*/
NepBotzInc.send5ButImg = async (jid , text = '' , footer = '', img, but = [], options = {}) =>{
let message = await prepareWAMessageMedia({ image: img }, { upload: NepBotzInc.waUploadToServer })
var template = generateWAMessageFromContent(m.chat, proto.Message.fromObject({
templateMessage: {
hydratedTemplate: {
imageMessage: message.imageMessage,
"hydratedContentText": text,
"hydratedFooterText": footer,
"hydratedButtons": but
}
}
}), options)
NepBotzInc.relayMessage(jid, template.message, { messageId: template.key.id })
}
/**
*
* @param {*} jid
* @param {*} buttons
* @param {*} caption
* @param {*} footer
* @param {*} quoted
* @param {*} options
*/
NepBotzInc.sendButtonText = (jid, buttons = [], text, footer, quoted = '', options = {}) => {
let buttonMessage = {
text,
footer,
buttons,
headerType: 2,
...options
}
NepBotzInc.sendMessage(jid, buttonMessage, { quoted, ...options })
}
/**
*
* @param {*} jid
* @param {*} text
* @param {*} quoted
* @param {*} options
* @returns
*/
NepBotzInc.sendText = (jid, text, quoted = '', options) => NepBotzInc.sendMessage(jid, { text: text, ...options }, { quoted })
/**
*
* @param {*} jid
* @param {*} path
* @param {*} caption
* @param {*} quoted
* @param {*} options
* @returns
*/
NepBotzInc.sendImage = async (jid, path, caption = '', quoted = '', options) => {
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)
return await NepBotzInc.sendMessage(jid, { image: buffer, caption: caption, ...options }, { quoted })
}
/**
*
* @param {*} jid
* @param {*} path
* @param {*} caption
* @param {*} quoted
* @param {*} options
* @returns
*/
NepBotzInc.sendVideo = async (jid, path, caption = '', quoted = '', gif = false, options) => {
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)
return await NepBotzInc.sendMessage(jid, { video: buffer, caption: caption, gifPlayback: gif, ...options }, { quoted })
}
/**
*
* @param {*} jid
* @param {*} path
* @param {*} quoted
* @param {*} mime
* @param {*} options
* @returns
*/
NepBotzInc.sendAudio = async (jid, path, quoted = '', ptt = false, options) => {
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)
return await NepBotzInc.sendMessage(jid, { audio: buffer, ptt: ptt, ...options }, { quoted })
}
/**
*
* @param {*} jid
* @param {*} text
* @param {*} quoted
* @param {*} options
* @returns
*/
NepBotzInc.sendTextWithMentions = async (jid, text, quoted, options = {}) => NepBotzInc.sendMessage(jid, { text: text, contextInfo: { mentionedJid: [...text.matchAll(/@(\d{0,16})/g)].map(v => v[1] + '@s.whatsapp.net') }, ...options }, { quoted })
/**
*
* @param {*} jid
* @param {*} path
* @param {*} quoted
* @param {*} options
* @returns
*/
NepBotzInc.sendImageAsSticker = async (jid, path, quoted, options = {}) => {
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)
let buffer
if (options && (options.packname || options.author)) {
buffer = await writeExifImg(buff, options)
} else {
buffer = await imageToWebp(buff)
}
await NepBotzInc.sendMessage(jid, { sticker: { url: buffer }, ...options }, { quoted })
return buffer
}
/**
*
* @param {*} jid
* @param {*} path
* @param {*} quoted
* @param {*} options
* @returns
*/
NepBotzInc.sendVideoAsSticker = async (jid, path, quoted, options = {}) => {
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)
let buffer
if (options && (options.packname || options.author)) {
buffer = await writeExifVid(buff, options)
} else {
buffer = await videoToWebp(buff)
}
await NepBotzInc.sendMessage(jid, { sticker: { url: buffer }, ...options }, { quoted })
return buffer
}
/**
*
* @param {*} message
* @param {*} filename
* @param {*} attachExtension
* @returns
*/
NepBotzInc.downloadAndSaveMediaMessage = async (message, filename, attachExtension = true) => {
let quoted = message.msg ? message.msg : message
let mime = (message.msg || message).mimetype || ''
let messageType = message.mtype ? message.mtype.replace(/Message/gi, '') : mime.split('/')[0]
const stream = await downloadContentFromMessage(quoted, messageType)
let buffer = Buffer.from([])
for await(const chunk of stream) {
buffer = Buffer.concat([buffer, chunk])
}
let type = await FileType.fromBuffer(buffer)
trueFileName = attachExtension ? (filename + '.' + type.ext) : filename
// save to file
await fs.writeFileSync(trueFileName, buffer)
return trueFileName
}
NepBotzInc.downloadMediaMessage = async (message) => {
let mime = (message.msg || message).mimetype || ''
let messageType = message.mtype ? message.mtype.replace(/Message/gi, '') : mime.split('/')[0]
const stream = await downloadContentFromMessage(message, messageType)
let buffer = Buffer.from([])
for await(const chunk of stream) {
buffer = Buffer.concat([buffer, chunk])
}
return buffer
}
/**
*
* @param {*} jid
* @param {*} path
* @param {*} filename
* @param {*} caption
* @param {*} quoted
* @param {*} options
* @returns
*/
NepBotzInc.sendMedia = async (jid, path, fileName = '', caption = '', quoted = '', options = {}) => {
let types = await NepBotzInc.getFile(path, true)
let { mime, ext, res, data, filename } = types
if (res && res.status !== 200 || file.length <= 65536) {
try { throw { json: JSON.parse(file.toString()) } }
catch (e) { if (e.json) throw e.json }
}
let type = '', mimetype = mime, pathFile = filename
if (options.asDocument) type = 'document'
if (options.asSticker || /webp/.test(mime)) {
let { writeExif } = require('./lib/exif')
let media = { mimetype: mime, data }
pathFile = await writeExif(media, { packname: options.packname ? options.packname : global.packname, author: options.author ? options.author : global.author, categories: options.categories ? options.categories : [] })
await fs.promises.unlink(filename)
type = 'sticker'
mimetype = 'image/webp'
}
else if (/image/.test(mime)) type = 'image'
else if (/video/.test(mime)) type = 'video'
else if (/audio/.test(mime)) type = 'audio'
else type = 'document'
await NepBotzInc.sendMessage(jid, { [type]: { url: pathFile }, caption, mimetype, fileName, ...options }, { quoted, ...options })
return fs.promises.unlink(pathFile)
}
/**
*
* @param {*} jid
* @param {*} message
* @param {*} forceForward
* @param {*} options
* @returns
*/
NepBotzInc.copyNForward = async (jid, message, forceForward = false, options = {}) => {
let vtype
if (options.readViewOnce) {
message.message = message.message && message.message.ephemeralMessage && message.message.ephemeralMessage.message ? message.message.ephemeralMessage.message : (message.message || undefined)
vtype = Object.keys(message.message.viewOnceMessage.message)[0]
delete(message.message && message.message.ignore ? message.message.ignore : (message.message || undefined))
delete message.message.viewOnceMessage.message[vtype].viewOnce
message.message = {
...message.message.viewOnceMessage.message
}
}
let mtype = Object.keys(message.message)[0]
let content = await generateForwardMessageContent(message, forceForward)
let ctype = Object.keys(content)[0]
let context = {}
if (mtype != "conversation") context = message.message[mtype].contextInfo
content[ctype].contextInfo = {
...context,
...content[ctype].contextInfo
}
const waMessage = await generateWAMessageFromContent(jid, content, options ? {
...content[ctype],
...options,
...(options.contextInfo ? {
contextInfo: {
...content[ctype].contextInfo,
...options.contextInfo
}
} : {})
} : {})
await NepBotzInc.relayMessage(jid, waMessage.message, { messageId: waMessage.key.id })
return waMessage
}
NepBotzInc.cMod = (jid, copy, text = '', sender = NepBotzInc.user.id, options = {}) => {
//let copy = message.toJSON()
let mtype = Object.keys(copy.message)[0]
let isEphemeral = mtype === 'ephemeralMessage'
if (isEphemeral) {
mtype = Object.keys(copy.message.ephemeralMessage.message)[0]
}
let msg = isEphemeral ? copy.message.ephemeralMessage.message : copy.message
let content = msg[mtype]
if (typeof content === 'string') msg[mtype] = text || content
else if (content.caption) content.caption = text || content.caption
else if (content.text) content.text = text || content.text
if (typeof content !== 'string') msg[mtype] = {
...content,
...options
}
if (copy.key.participant) sender = copy.key.participant = sender || copy.key.participant
else if (copy.key.participant) sender = copy.key.participant = sender || copy.key.participant
if (copy.key.remoteJid.includes('@s.whatsapp.net')) sender = sender || copy.key.remoteJid
else if (copy.key.remoteJid.includes('@broadcast')) sender = sender || copy.key.remoteJid
copy.key.remoteJid = jid
copy.key.fromMe = sender === NepBotzInc.user.id
return proto.WebMessageInfo.fromObject(copy)
}
//send 5 button image by xeon
NepBotzInc.send5ButImg = async (jid , text = '' , footer = '', img, but = [], thumb, options = {}) =>{
let message = await prepareWAMessageMedia({ image: img, jpegThumbnail:thumb }, { upload: NepBotzInc.waUploadToServer })
var template = generateWAMessageFromContent(m.chat, proto.Message.fromObject({
templateMessage: {
hydratedTemplate: {
imageMessage: message.imageMessage,
"hydratedContentText": text,
"hydratedFooterText": footer,
"hydratedButtons": but
}
}
}), options)
NepBotzInc.relayMessage(jid, template.message, { messageId: template.key.id })
}
//send5butvid by xeon
NepBotzInc.send5ButVid = async (jid , text = '' , footer = '', vid, but = [], options = {}) =>{
let message = await prepareWAMessageMedia({ video: vid }, { upload: NepBotzInc.waUploadToServer })
var template = generateWAMessageFromContent(jid, proto.Message.fromObject({
templateMessage: {
hydratedTemplate: {
videoMessage: message.videoMessage,
"hydratedContentText": text,
"hydratedFooterText": footer,
"hydratedButtons": but
}
}
}), options)
NepBotzInc.relayMessage(jid, template.message, { messageId: template.key.id })
}
//send5butmsg by xeon
NepBotzInc.send5ButMsg = (jid, text = '' , footer = '', but = []) =>{
let templateButtons = but
var templateMessage = {
text: text,
footer: footer,
templateButtons: templateButtons
}
NepBotzInc.sendMessage(jid, templateMessage)
}
//sendlistmsg by xeon
NepBotzInc.sendListMsg = (jid, text = '', footer = '', title = '' , butText = '', sects = [], quoted) => {
let sections = sects
var listMes = {
text: text,
footer: footer,
title: title,
buttonText: butText,
sections
}
NepBotzInc.sendMessage(jid, listMes, { quoted: quoted })
}
//send5butgif by xeon
NepBotzInc.send5ButGif = async (jid , text = '' , footer = '', gif, but = [], options = {}) =>{
let message = await prepareWAMessageMedia({ video: gif, gifPlayback: true }, { upload: NepBotzInc.waUploadToServer })
var template = generateWAMessageFromContent(jid, proto.Message.fromObject({
templateMessage: {
hydratedTemplate: {
videoMessage: message.videoMessage,
"hydratedContentText": text,
"hydratedFooterText": footer,
"hydratedButtons": but
}
}
}), options)
NepBotzInc.relayMessage(jid, template.message, { messageId: template.key.id })
}
//____sendFile by xeon please give credit____//
/**
* Send Media/File with Automatic Type Specifier
* @param {String} jid
* @param {String|Buffer} path
* @param {String} filename
* @param {String} caption
* @param {proto.WebMessageInfo} quoted
* @param {Boolean} ptt
* @param {Object} options
*/
NepBotzInc.sendFile = async (jid, path, filename = '', caption = '', quoted, ptt = false, options = {}) => {
let type = await NepBotzInc.getFile(path, true)
let { res, data: file, filename: pathFile } = type
if (res && res.status !== 200 || file.length <= 65536) {
try { throw { json: JSON.parse(file.toString()) } }
catch (e) { if (e.json) throw e.json }
}
let opt = { filename }
if (quoted) opt.quoted = quoted
if (!type) options.asDocument = true
let mtype = '', mimetype = type.mime, convert
if (/webp/.test(type.mime) || (/image/.test(type.mime) && options.asSticker)) mtype = 'sticker'
else if (/image/.test(type.mime) || (/webp/.test(type.mime) && options.asImage)) mtype = 'image'
else if (/video/.test(type.mime)) mtype = 'video'
else if (/audio/.test(type.mime)) (
convert = await (ptt ? toPTT : toAudio)(file, type.ext),
file = convert.data,
pathFile = convert.filename,
mtype = 'audio',
mimetype = 'audio/ogg; codecs=opus'
)
else mtype = 'document'
if (options.asDocument) mtype = 'document'
delete options.asSticker
delete options.asLocation
delete options.asVideo
delete options.asDocument
delete options.asImage
let message = {
...options,
caption,
ptt,
[mtype]: { url: pathFile },
mimetype
}
let m
try {
m = await NepBotzInc.sendMessage(jid, message, { ...opt, ...options })
} catch (e) {
console.error(e)
m = null
} finally {
if (!m) m = await NepBotzInc.sendMessage(jid, { ...message, [mtype]: file }, { ...opt, ...options })
return m
}
}
//send but 3 image
NepBotzInc.send3ButtonImg = async (jid, buffer, contentText, footerText, button1, id1, button2, id2, button3, id3, quoted, options) => {
let type = await NepBotzInc.getFile(buffer)
let { res, data: file } = type
if (res && res.status !== 200 || file.length <= 65536) {
try { throw { json: JSON.parse(file.toString()) } }
catch (e) { if (e.json) throw e.json }
}
const buttons = [
{ buttonId: id1, buttonText: { displayText: button1 }, type: 1 },
{ buttonId: id2, buttonText: { displayText: button2 }, type: 1 },
{ buttonId: id3, buttonText: { displayText: button3 }, type: 1 }
]
const buttonMessage = {
image: file,
fileLength: 887890909999999,
caption: contentText,
footer: footerText,
mentions: await NepBotzInc.parseMention(contentText + footerText),
...options,
buttons: buttons,
headerType: 4
}
return await NepBotzInc.sendMessage(jid, buttonMessage, { quoted, ephemeralExpiration: 86400, contextInfo: { mentionedJid: conn.parseMention(contentText + footerText) }, ...options })
}
//send but 3
NepBotzInc .send3But = async(jid, content, footer,button1, row1, button2, row2, button3, row3, quoted) => {
const buttons = [
{ buttonId: row1, buttonText: { displayText: button1 }, type: 1 },
{ buttonId: row2, buttonText: { displayText: button2 }, type: 1 },
{ buttonId: row3, buttonText: { displayText: button3 }, type: 1 }
]
const buttonMessage = {
text: content,
footer: footer,
buttons: buttons,
headerType: 1
}
return await NepBotzInc.sendMessage(jid, buttonMessage, {quoted})
}
//sendButton by xeon please give credit
/**
* send Button
* @param {String} jid
* @param {String} contentText
* @param {String} footer
* @param {Buffer|String} buffer
* @param {String[]} buttons
* @param {Object} quoted
* @param {Object} options
*/
NepBotzInc.sendButton = async (jid, contentText, footer, buffer, buttons, quoted, options) => {
if (buffer) try { buffer = (await NepBotzInc.getFile(buffer)).data } catch { buffer = null }
let message = {
...options,
...(buffer ? { caption: contentText || '' } : { text: contentText || '' }),
footer,
buttons: buttons.map(btn => {
return {
buttonId: btn[1] || btn[0] || '',
buttonText: {
displayText: btn[0] || btn[1] || ''
}
}
}),
...(buffer ? { image: buffer } : {})
}
return await NepBotzInc.sendMessage(jid, message, {
quoted,
upload: NepBotzInc.waUploadToServer,
...options
})
}
NepBotzInc.sendButtonImg = async (jid, buffer, contentText, footerText, button1, id1, quoted, options) => {
let type = await NepBotzInc.getFile(buffer)
let { res, data: file } = type
if (res && res.status !== 200 || file.length <= 65536) {
try { throw { json: JSON.parse(file.toString()) } }
catch (e) { if (e.json) throw e.json }
}
const buttons = [
{ buttonId: id1, buttonText: { displayText: button1 }, type: 1 }
]
const buttonMessage = {
image: file,
fileLength: 887890909999999,
caption: contentText,
footer: footerText,
mentions: await NepBotzInc.parseMention(contentText + footerText),
...options,
buttons: buttons,
headerType: 4
}
return await NepBotzInc.sendMessage(jid, buttonMessage, { quoted, ephemeralExpiration: 86400, contextInfo: { mentionedJid: conn.parseMention(contentText + footerText) }, ...options })
}
/**
*
* @param {*} path
* @returns
*/
NepBotzInc.getFile = async (PATH, save) => {
let res
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)
//if (!Buffer.isBuffer(data)) throw new TypeError('Result is not a buffer')
let type = await FileType.fromBuffer(data) || {
mime: 'application/octet-stream',
ext: '.bin'
}
filename = path.join(__filename, '../src/' + new Date * 1 + '.' + type.ext)
if (data && save) fs.promises.writeFile(filename, data)
return {
res,
filename,
size: await getSizeMedia(data),
...type,
data
}
}
return NepBotzInc
}
startNepBotzInc()
let file = require.resolve(__filename)
fs.watchFile(file, () => {
fs.unwatchFile(file)
console.log(chalk.redBright(`Update ${__filename}`))
delete require.cache[file]
require(file)
})