forked from DGDEEPAK/Zenitsu-Bot8
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
864 lines (807 loc) · 35.5 KB
/
main.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
//Zenitsu-Bot8
require('./settings')
const pino = require('pino')
const { Boom } = require('@hapi/boom')
const fs = require('fs')
const chalk = require('chalk')
const { color } = require('./lib/color')
const FileType = require('file-type')
const path = require('path')
const axios = require('axios')
const _ = require('lodash')
const { uncache, nocache } = require('./lib/loader')
const yargs = require('yargs/yargs')
const { Low, JSONFile } = require('./lib/lowdb')
const moment = require('moment-timezone')
const PhoneNumber = require('awesome-phonenumber')
const { imageToWebp, videoToWebp, writeExifImg, writeExifVid } = require('./lib/exif')
const { smsg, isUrl, generateMessageTag, getBuffer, getSizeMedia, fetch, await, sleep, reSize } = require('./lib/myfunc')
const { default: DeepakBotIncConnect, delay, PHONENUMBER_MCC, makeCacheableSignalKeyStore, useMultiFileAuthState, DisconnectReason, fetchLatestBaileysVersion, generateForwardMessageContent, prepareWAMessageMedia, generateWAMessageFromContent, generateMessageID, downloadContentFromMessage, makeInMemoryStore, jidDecode, proto, Browsers } = require("@whiskeysockets/baileys")
const NodeCache = require("node-cache")
const Pino = require("pino")
const readline = require("readline")
const { parsePhoneNumber } = require("libphonenumber-js")
const makeWASocket = require("@whiskeysockets/baileys").default
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(new JSONFile(`src/database.json`))
global.DATABASE = global.db
global.loadDatabase = async function loadDatabase() {
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))
if (global.db.data !== null) return
global.db.READ = true
await global.db.read()
global.db.READ = false
global.db.data = {
users: {},
database: {},
chats: {},
game: {},
settings: {},
message: {},
...(global.db.data || {})
}
global.db.chain = _.chain(global.db.data)
}
loadDatabase()
if (global.db) setInterval(async () => {
if (global.db.data) await global.db.write()
}, 30 * 1000)
require('./Zenitsu8.js')
nocache('../Zenitsu8.js', module => console.log(color('[ CHANGE ]', 'green'), color(`'${module}'`, 'green'), 'Updated'))
require('./main.js')
nocache('../main.js', module => console.log(color('[ CHANGE ]', 'green'), color(`'${module}'`, 'green'), 'Updated'))
let phoneNumber = "917029257330"
let owner = JSON.parse(fs.readFileSync('./src/data/role/owner.json'))
const pairingCode = !!phoneNumber || process.argv.includes("--pairing-code")
const useMobile = process.argv.includes("--mobile")
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
const question = (text) => new Promise((resolve) => rl.question(text, resolve))
async function startDeepakBotInc() {
//------------------------------------------------------
let { version, isLatest } = await fetchLatestBaileysVersion()
const { state, saveCreds } =await useMultiFileAuthState(`./session`)
const msgRetryCounterCache = new NodeCache() // for retry message, "waiting message"
const DeepakBotInc = makeWASocket({
logger: pino({ level: 'silent' }),
printQRInTerminal: !pairingCode, // popping up QR in terminal log
browser: Browsers.windows('Firefox'), // for this issues https://github.com/WhiskeySockets/Baileys/issues/328
patchMessageBeforeSending: (message) => {
const requiresPatch = !!(
message.buttonsMessage ||
message.templateMessage ||
message.listMessage
);
if (requiresPatch) {
message = {
viewOnceMessage: {
message: {
messageContextInfo: {
deviceListMetadataVersion: 2,
deviceListMetadata: {},
},
...message,
},
},
};
}
return message;
},
auth: {
creds: state.creds,
keys: makeCacheableSignalKeyStore(state.keys, Pino({ level: "fatal" }).child({ level: "fatal" })),
},
markOnlineOnConnect: true, // set false for offline
generateHighQualityLinkPreview: true, // make high preview link
getMessage: async (key) => {
if (store) {
const msg = await store.loadMessage(key.remoteJid, key.id)
return msg.message || undefined
}
return {
conversation: "Cheems Bot Here!"
}
},
msgRetryCounterCache, // Resolve waiting messages
defaultQueryTimeoutMs: undefined, // for this issues https://github.com/WhiskeySockets/Baileys/issues/276
})
store.bind(DeepakBotInc.ev)
// login use pairing code
// source code https://github.com/WhiskeySockets/Baileys/blob/master/Example/example.ts#L61
if (pairingCode && !DeepakBotInc.authState.creds.registered) {
if (useMobile) throw new Error('Cannot use pairing code with mobile api')
let phoneNumber
if (!!phoneNumber) {
phoneNumber = phoneNumber.replace(/[^0-9]/g, '')
if (!Object.keys(PHONENUMBER_MCC).some(v => phoneNumber.startsWith(v))) {
console.log(chalk.bgBlack(chalk.redBright("Start with country code of your WhatsApp Number, Example : +917029257330")))
process.exit(0)
}
} else {
phoneNumber = await question(chalk.bgBlack(chalk.greenBright(`Please type your WhatsApp number 😍\nFor example: +917029257330 : `)))
phoneNumber = phoneNumber.replace(/[^0-9]/g, '')
// Ask again when entering the wrong number
if (!Object.keys(PHONENUMBER_MCC).some(v => phoneNumber.startsWith(v))) {
console.log(chalk.bgBlack(chalk.redBright("Start with country code of your WhatsApp Number, Example : +917029257330")))
phoneNumber = await question(chalk.bgBlack(chalk.greenBright(`Please type your WhatsApp number 😍\nFor example: +917029257330 : `)))
phoneNumber = phoneNumber.replace(/[^0-9]/g, '')
rl.close()
}
}
setTimeout(async () => {
let code = await DeepakBotInc.requestPairingCode(phoneNumber)
code = code?.match(/.{1,4}/g)?.join("-") || code
console.log(chalk.black(chalk.bgGreen(`Your Pairing Code : `)), chalk.black(chalk.white(code)))
}, 3000)
}
DeepakBotInc.ev.on('connection.update', async (update) => {
const {
connection,
lastDisconnect
} = update
try{
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`);
startDeepakBotInc()
} else if (reason === DisconnectReason.connectionClosed) {
console.log("Connection closed, reconnecting....");
startDeepakBotInc();
} else if (reason === DisconnectReason.connectionLost) {
console.log("Connection Lost from Server, reconnecting...");
startDeepakBotInc();
} else if (reason === DisconnectReason.connectionReplaced) {
console.log("Connection Replaced, Another New Session Opened, Please Close Current Session First");
startDeepakBotInc()
} else if (reason === DisconnectReason.loggedOut) {
console.log(`Device Logged Out, Please Delete Session and Scan Again.`);
startDeepakBotInc();
} else if (reason === DisconnectReason.restartRequired) {
console.log("Restart Required, Restarting...");
startDeepakBotInc();
} else if (reason === DisconnectReason.timedOut) {
console.log("Connection TimedOut, Reconnecting...");
startDeepakBotInc();
} else DeepakBotInc.end(`Unknown DisconnectReason: ${reason}|${connection}`)
}
if (update.connection == "connecting" || update.receivedPendingNotifications == "false") {
console.log(color(`\n🌿Connecting...`, 'yellow'))
}
if (update.connection == "open" || update.receivedPendingNotifications == "true") {
console.log(color(` `,'magenta'))
console.log(color(`🌿Connected to => ` + JSON.stringify(DeepakBotInc.user, null, 2), 'yellow'))
console.log(chalk.yellow(`\n\n ${chalk.bold.blue(`[ ${botname} ]`)}\n\n`))
console.log(color(`< ================================================== >`, 'cyan'))
console.log(color(`\n${themeemoji} YT CHANNEL: Deepak`,'magenta'))
console.log(color(`${themeemoji} GITHUB: DGDEEPAK `,'magenta'))
console.log(color(`${themeemoji} INSTAGRAM: @deepakgupta8931 `,'magenta'))
console.log(color(`${themeemoji} WA NUMBER: ${owner}`,'magenta'))
console.log(color(`${themeemoji} CREDIT: ${wm}\n`,'magenta'))
}
} catch (err) {
console.log('Error in Connection.update '+err)
startDeepakBotInc()
}
})
DeepakBotInc.ev.on('creds.update', saveCreds)
DeepakBotInc.ev.on("messages.upsert", () => { })
//------------------------------------------------------
//farewell/welcome
DeepakBotInc.ev.on('group-participants.update', async (anu) => {
if (global.welcome){
console.log(anu)
try {
let metadata = await DeepakBotInc.groupMetadata(anu.id)
let participants = anu.participants
for (let num of participants) {
try {
ppuser = await DeepakBotInc.profilePictureUrl(num, 'image')
} catch (err) {
ppuser = 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png?q=60'
}
try {
ppgroup = await DeepakBotInc.profilePictureUrl(anu.id, 'image')
} catch (err) {
ppgroup = 'https://i.ibb.co/RBx5SQC/avatar-group-large-v2.png?q=60'
}
//welcome\\
memb = metadata.participants.length
DeepakWlcm = await getBuffer(ppuser)
DeepakLft = await getBuffer(ppuser)
if (anu.action == 'add') {
const deepakbuffer = await getBuffer(ppuser)
let deepakName = 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
deepakbody = `Hello @${deepakName.split("@")[0]},
I am *ZenitsuBot*, Welcome to ${metadata.subject}.
*Group Description:*
${metadata.desc}`
let msgs = generateWAMessageFromContent(anu.id, {
viewOnceMessage: {
message: {
"messageContextInfo": {
"deviceListMetadata": {},
"deviceListMetadataVersion": 2
},
interactiveMessage: proto.Message.InteractiveMessage.create({
body: proto.Message.InteractiveMessage.Body.create({
text: deepakbody
}),
footer: proto.Message.InteractiveMessage.Footer.create({
text: botname
}),
header: proto.Message.InteractiveMessage.Header.create({
hasMediaAttachment: false,
...await prepareWAMessageMedia({ image: DeepakWlcm }, { upload: DeepakBotInc.waUploadToServer })
}),
nativeFlowMessage: proto.Message.InteractiveMessage.NativeFlowMessage.create({
buttons: [{
"name": "quick_reply",
"buttonParamsJson": `{\"display_text\":\"Welcome 💐\",\"id\":\"\"}`
}],
}),
contextInfo: {
mentionedJid: [num],
forwardingScore: 999,
isForwarded: true,
forwardedNewsletterMessageInfo: {
newsletterJid: '120363222395675670@newsletter',
newsletterName: ownername,
serverMessageId: 143
}
}
})
}
}
}, {})
DeepakBotInc.relayMessage(anu.id, msgs.message, {})
} else if (anu.action == 'remove') {
const deepakbuffer = await getBuffer(ppuser)
const deepaktime = moment.tz('Asia/Kolkata').format('HH:mm:ss')
const deepakdate = moment.tz('Asia/Kolkata').format('DD/MM/YYYY')
let deepakName = num
const deepakmembers = metadata.participants.length
deepakbody = `GoodBye 👋, @${deepakName.split("@")[0]}`
let msgs = generateWAMessageFromContent(anu.id, {
viewOnceMessage: {
message: {
"messageContextInfo": {
"deviceListMetadata": {},
"deviceListMetadataVersion": 2
},
interactiveMessage: proto.Message.InteractiveMessage.create({
body: proto.Message.InteractiveMessage.Body.create({
text: deepakbody
}),
footer: proto.Message.InteractiveMessage.Footer.create({
text: botname
}),
header: proto.Message.InteractiveMessage.Header.create({
hasMediaAttachment: false,
...await prepareWAMessageMedia({ image: DeepakLft }, { upload: DeepakBotInc.waUploadToServer })
}),
nativeFlowMessage: proto.Message.InteractiveMessage.NativeFlowMessage.create({
buttons: [{
"name": "quick_reply",
"buttonParamsJson": `{\"display_text\":\"Goodbye 👋\",\"id\":\"\"}`
}],
}),
contextInfo: {
mentionedJid: [num],
forwardingScore: 999,
isForwarded: true,
forwardedNewsletterMessageInfo: {
newsletterJid: '120363222395675670@newsletter',
newsletterName: ownername,
serverMessageId: 143
}
}
})
}
}
}, {})
DeepakBotInc.relayMessage(anu.id, msgs.message, {})
}
}
} catch (err) {
console.log(err)
}
}
})
// Anti Call
DeepakBotInc.ev.on('call', async (DeepakPapa) => {
if (global.anticall){
console.log(DeepakPapa)
for (let DeepakFucks of DeepakPapa) {
if (DeepakFucks.isGroup == false) {
if (DeepakFucks.status == "offer") {
let DeepakBlokMsg = await DeepakBotInc.sendTextWithMentions(DeepakFucks.from, `*${DeepakBotInc.user.name}* can't receive ${DeepakFucks.isVideo ? `video` : `voice` } call. Sorry @${DeepakFucks.from.split('@')[0]} you will be blocked. If called accidentally please contact the owner to be unblocked !`)
DeepakBotInc.sendContact(DeepakFucks.from, owner, DeepakBlokMsg)
await sleep(8000)
await DeepakBotInc.updateBlockStatus(DeepakFucks.from, "block")
}
}
}
}
})
//autostatus view
DeepakBotInc.ev.on('messages.upsert', async chatUpdate => {
if (global.antiswview){
mek = chatUpdate.messages[0]
if (mek.key && mek.key.remoteJid === 'status@broadcast') {
await DeepakBotInc.readMessages([mek.key]) }
}
})
//admin event
DeepakBotInc.ev.on('group-participants.update', async (anu) => {
if (global.adminevent){
console.log(anu)
try {
let participants = anu.participants
for (let num of participants) {
try {
ppuser = await DeepakBotInc.profilePictureUrl(num, 'image')
} catch (err) {
ppuser = 'https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png?q=60'
}
try {
ppgroup = await DeepakBotInc.profilePictureUrl(anu.id, 'image')
} catch (err) {
ppgroup = 'https://i.ibb.co/RBx5SQC/avatar-group-large-v2.png?q=60'
}
if (anu.action == 'promote') {
const deepaktime = moment.tz('Asia/Kolkata').format('HH:mm:ss')
const deepakdate = moment.tz('Asia/Kolkata').format('DD/MM/YYYY')
let deepakName = num
deepakbody = ` 𝗖𝗼𝗻𝗴𝗿𝗮𝘁𝘀🎉 @${deepakName.split("@")[0]}, you have been *promoted* to *admin* 🥳`
DeepakBotInc.sendMessage(anu.id,
{ text: deepakbody,
contextInfo:{
mentionedJid:[num],
"externalAdReply": {"showAdAttribution": true,
"containsAutoReply": true,
"title": ` ${global.botname}`,
"body": `${ownername}`,
"previewType": "PHOTO",
"thumbnailUrl": ``,
"thumbnail": DeepakWlcm,
"sourceUrl": `${wagc}`}}})
} else if (anu.action == 'demote') {
const deepaktime = moment.tz('Asia/Kolkata').format('HH:mm:ss')
const deepakdate = moment.tz('Asia/Kolkata').format('DD/MM/YYYY')
let deepakName = num
deepakbody = `𝗢𝗼𝗽𝘀‼️ @${deepakName.split("@")[0]}, you have been *demoted* from *admin* 😬`
DeepakBotInc.sendMessage(anu.id,
{ text: deepakbody,
contextInfo:{
mentionedJid:[num],
"externalAdReply": {"showAdAttribution": true,
"containsAutoReply": true,
"title": ` ${global.botname}`,
"body": `${ownername}`,
"previewType": "PHOTO",
"thumbnailUrl": ``,
"thumbnail": DeepakLft,
"sourceUrl": `${wagc}`}}})
}
}
} catch (err) {
console.log(err)
}
}
})
// detect group update
DeepakBotInc.ev.on("groups.update", async (json) => {
if (global.groupevent) {
try {
ppgroup = await DeepakBotInc.profilePictureUrl(anu.id, 'image')
} catch (err) {
ppgroup = 'https://i.ibb.co/RBx5SQC/avatar-group-large-v2.png?q=60'
}
console.log(json)
const res = json[0]
if (res.announce == true) {
await sleep(2000)
DeepakBotInc.sendMessage(res.id, {
text: `「 Group Settings Change 」\n\nGroup has been closed by admin, Now only admins can send messages !`,
})
} else if (res.announce == false) {
await sleep(2000)
DeepakBotInc.sendMessage(res.id, {
text: `「 Group Settings Change 」\n\nThe group has been opened by admin, Now participants can send messages !`,
})
} else if (res.restrict == true) {
await sleep(2000)
DeepakBotInc.sendMessage(res.id, {
text: `「 Group Settings Change 」\n\nGroup info has been restricted, Now only admin can edit group info !`,
})
} else if (res.restrict == false) {
await sleep(2000)
DeepakBotInc.sendMessage(res.id, {
text: `「 Group Settings Change 」\n\nGroup info has been opened, Now participants can edit group info !`,
})
} else if(!res.desc == ''){
await sleep(2000)
DeepakBotInc.sendMessage(res.id, {
text: `「 Group Settings Change 」\n\n*Group description has been changed to*\n\n${res.desc}`,
})
} else {
await sleep(2000)
DeepakBotInc.sendMessage(res.id, {
text: `「 Group Settings Change 」\n\n*Group name has been changed to*\n\n*${res.subject}*`,
})
}
}
})
// respon cmd pollMessage
async function getMessage(key){
if (store) {
const msg = await store.loadMessage(key.remoteJid, key.id)
return msg?.message
}
return {
conversation: "Cheems Bot Here!"
}
}
DeepakBotInc.ev.on('messages.update', async chatUpdate => {
for(const { key, update } of chatUpdate) {
if(update.pollUpdates && key.fromMe) {
const pollCreation = await getMessage(key)
if(pollCreation) {
const pollUpdate = await getAggregateVotesInPollMessage({
message: pollCreation,
pollUpdates: update.pollUpdates,
})
var toCmd = pollUpdate.filter(v => v.voters.length !== 0)[0]?.name
if (toCmd == undefined) return
var prefCmd = xprefix+toCmd
DeepakBotInc.appenTextMessage(prefCmd, chatUpdate)
}
}
}
})
DeepakBotInc.ev.on('messages.upsert', async chatUpdate => {
//console.log(JSON.stringify(chatUpdate, undefined, 2))
try {
const 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' )
if (!DeepakBotInc.public && !mek.key.fromMe && chatUpdate.type === 'notify') return
if (mek.key.id.startsWith('BAE5') && mek.key.id.length === 16) return
const m = smsg(DeepakBotInc, mek, store)
require("./Zenitsu8")(DeepakBotInc, m, chatUpdate, store)
} catch (err) {
console.log(err)
}
})
DeepakBotInc.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
}
DeepakBotInc.ev.on('contacts.update', update => {
for (let contact of update) {
let id = DeepakBotInc.decodeJid(contact.id)
if (store && store.contacts) store.contacts[id] = {
id,
name: contact.notify
}
}
})
DeepakBotInc.getName = (jid, withoutContact = false) => {
id = DeepakBotInc.decodeJid(jid)
withoutContact = DeepakBotInc.withoutContact || withoutContact
let v
if (id.endsWith("@g.us")) return new Promise(async (resolve) => {
v = store.contacts[id] || {}
if (!(v.name || v.subject)) v = DeepakBotInc.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 === DeepakBotInc.decodeJid(DeepakBotInc.user.id) ?
DeepakBotInc.user :
(store.contacts[id] || {})
return (withoutContact ? '' : v.name) || v.subject || v.verifiedName || PhoneNumber('+' + jid.replace('@s.whatsapp.net', '')).getNumber('international')
}
DeepakBotInc.sendContact = async (jid, kon, quoted = '', opts = {}) => {
let list = []
for (let i of kon) {
list.push({
displayName: await DeepakBotInc.getName(i),
vcard: `BEGIN:VCARD\nVERSION:3.0\nN:${await DeepakBotInc.getName(i)}\nFN:${await DeepakBotInc.getName(i)}\nitem1.TEL;waid=${i.split('@')[0]}:${i.split('@')[0]}\nitem1.X-ABLabel:Mobile\nEND:VCARD`
})
}
DeepakBotInc.sendMessage(jid, { contacts: { displayName: `${list.length} Contact`, contacts: list }, ...opts }, { quoted })
}
DeepakBotInc.public = true
DeepakBotInc.serializeM = (m) => smsg(DeepakBotInc, m, store)
DeepakBotInc.sendText = (jid, text, quoted = '', options) => DeepakBotInc.sendMessage(jid, {
text: text,
...options
}, {
quoted,
...options
})
DeepakBotInc.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 DeepakBotInc.sendMessage(jid, {
image: buffer,
caption: caption,
...options
}, {
quoted
})
}
DeepakBotInc.sendTextWithMentions = async (jid, text, quoted, options = {}) => DeepakBotInc.sendMessage(jid, {
text: text,
mentions: [...text.matchAll(/@(\d{0,16})/g)].map(v => v[1] + '@s.whatsapp.net'),
...options
}, {
quoted
})
DeepakBotInc.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 DeepakBotInc.sendMessage(jid, { sticker: { url: buffer }, ...options }, { quoted })
.then( response => {
fs.unlinkSync(buffer)
return response
})
}
DeepakBotInc.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 DeepakBotInc.sendMessage(jid, { audio: buffer, ptt: ptt, ...options }, { quoted })
}
DeepakBotInc.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 DeepakBotInc.sendMessage(jid, { video: buffer, caption: caption, gifPlayback: gif, ...options }, { quoted })
}
DeepakBotInc.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 DeepakBotInc.sendMessage(jid, { sticker: { url: buffer }, ...options }, { quoted })
return buffer
}
DeepakBotInc.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
}
DeepakBotInc.sendFileUrl = async (jid, url, caption, quoted, options = {}) => {
let mime = '';
let res = await axios.head(url)
mime = res.headers['content-type']
if (mime.split("/")[1] === "gif") {
return DeepakBotInc.sendMessage(jid, { video: await getBuffer(url), caption: caption, gifPlayback: true, ...options}, { quoted: quoted, ...options})
}
let type = mime.split("/")[0]+"Message"
if(mime === "application/pdf"){
return DeepakBotInc.sendMessage(jid, { document: await getBuffer(url), mimetype: 'application/pdf', caption: caption, ...options}, { quoted: quoted, ...options })
}
if(mime.split("/")[0] === "image"){
return DeepakBotInc.sendMessage(jid, { image: await getBuffer(url), caption: caption, ...options}, { quoted: quoted, ...options})
}
if(mime.split("/")[0] === "video"){
return DeepakBotInc.sendMessage(jid, { video: await getBuffer(url), caption: caption, mimetype: 'video/mp4', ...options}, { quoted: quoted, ...options })
}
if(mime.split("/")[0] === "audio"){
return DeepakBotInc.sendMessage(jid, { audio: await getBuffer(url), caption: caption, mimetype: 'audio/mpeg', ...options}, { quoted: quoted, ...options })
}
}
DeepakBotInc.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
}
}
DeepakBotInc.sendFile = async (jid, path, filename = '', caption = '', quoted, ptt = false, options = {}) => {
let type = await DeepakBotInc.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 DeepakBotInc.sendMessage(jid, message, { ...opt, ...options });
} catch (e) {
//console.error(e)
m = null;
} finally {
if (!m) m = await DeepakBotInc.sendMessage(jid, { ...message, [mtype]: file }, { ...opt, ...options });
file = null;
return m;
}
}
DeepakBotInc.cMod = (jid, copy, text = '', sender = DeepakBotInc.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 === DeepakBotInc.user.id
return proto.WebMessageInfo.fromObject(copy)
}
DeepakBotInc.sendMedia = async (jid, path, fileName = '', caption = '', quoted = '', options = {}) => {
let types = await DeepakBotInc.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 DeepakBotInc.sendMessage(jid, { [type]: { url: pathFile }, caption, mimetype, fileName, ...options }, { quoted, ...options })
return fs.promises.unlink(pathFile)
}
DeepakBotInc.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 DeepakBotInc.relayMessage(jid, waMessage.message, { messageId: waMessage.key.id })
return waMessage
}
DeepakBotInc.sendPoll = (jid, name = '', values = [], selectableCount = 1) => { return DeepakBotInc.sendMessage(jid, { poll: { name, values, selectableCount }}) }
DeepakBotInc.parseMention = (text = '') => {
return [...text.matchAll(/@([0-9]{5,16}|0)/g)].map(v => v[1] + '@s.whatsapp.net')
}
DeepakBotInc.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
}
return DeepakBotInc
}
let file = require.resolve(__filename)
fs.watchFile(file, () => {
fs.unwatchFile(file)
console.log(chalk.redBright(`Update ${__filename}`))
delete require.cache[file]
require(file)
})
startDeepakBotInc()
process.on('uncaughtexception', function (err) {
let e = String(err)
if (e.includes("conflict")) return
if (e.includes("Socket connection timeout")) return
if (e.includes("not-authorized")) return
if (e.includes("already-exists")) return
if (e.includes("rate-overlimit")) return
if (e.includes("Connection Closed")) return
if (e.includes("Timed Out")) return
if (e.includes("Value not found")) return
console.log('Caught exception: ', err)
})