forked from realvare/varebot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.js
More file actions
859 lines (780 loc) · 37.6 KB
/
handler.js
File metadata and controls
859 lines (780 loc) · 37.6 KB
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
import { smsg } from './lib/simple.js'
import { format } from 'util'
import { fileURLToPath } from 'url'
import path, { join } from 'path'
import { unwatchFile, watchFile } from 'fs'
import chalk from 'chalk'
import NodeCache from 'node-cache'
import { getAggregateVotesInPollMessage, toJid } from '@realvare/baileys'
global.ignoredUsersGlobal = new Set()
global.ignoredUsersGroup = {}
global.groupSpam = {}
if (!global.groupCache) {
global.groupCache = new NodeCache({ stdTTL: 5 * 60, useClones: false })
}
if (!global.jidCache) {
global.jidCache = new NodeCache({ stdTTL: 600, useClones: false })
}
if (!global.nameCache) {
global.nameCache = new NodeCache({ stdTTL: 600, useClones: false });
}
export const fetchMetadata = async (conn, chatId) => await conn.groupMetadata(chatId)
const fetchGroupMetadataWithRetry = async (conn, chatId, retries = 3, delay = 1000) => {
for (let i = 0; i < retries; i++) {
try {
return await conn.groupMetadata(chatId);
} catch (e) {
if (i === retries - 1) throw e;
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
if (!global.cacheListenersSet) {
const conn = global.conn
if (conn) {
conn.ev.on('groups.update', async (updates) => {
for (const update of updates) {
if (!update || !update.id) {
continue;
}
try {
const metadata = await fetchGroupMetadataWithRetry(conn, update.id)
if (!metadata) {
continue
}
global.groupCache.set(update.id, metadata, { ttl: 300 })
} catch (e) {
if (!e.message?.includes('not authorized') && !e.message?.includes('chat not found') && !e.message?.includes('not in group')) {
console.error(`[ERRORE] Errore nell'aggiornamento cache su groups.update per ${update.id}:`, e)
}
}
}
})
global.cacheListenersSet = true
}
}
if (!global.pollListenerSet) {
const conn = global.conn
if (conn) {
conn.ev.on('messages.update', async (chatUpdate) => {
for (const { key, update } of chatUpdate) {
if (update.pollUpdates) {
try {
const pollCreation = await global.store.getMessage(key)
if (pollCreation) {
await getAggregateVotesInPollMessage({
message: pollCreation,
pollUpdates: update.pollUpdates,
})
}
} catch (e) {
console.error('[ERRORE] Errore nel gestire poll update:', e)
}
}
}
})
global.pollListenerSet = true
}
}
const isNumber = x => typeof x === 'number' && !isNaN(x)
const delay = ms => isNumber(ms) && new Promise(resolve => setTimeout(resolve, ms))
const responseHandlers = new Map()
function initResponseHandler(conn) {
if (!conn.waitForResponse) {
conn.waitForResponse = async (chat, sender, options = {}) => {
const {
timeout = 30000,
validResponses = null,
onTimeout = null,
filter = null
} = options
return new Promise((resolve) => {
const key = chat + sender
const timeoutId = setTimeout(() => {
responseHandlers.delete(key)
if (onTimeout) onTimeout()
resolve(null)
}, timeout)
responseHandlers.set(key, {
resolve,
timeoutId,
validResponses,
filter
})
})
}
}
}
global.processedCalls = global.processedCalls || new Map()
if (global.conn && global.conn.ws) {
global.conn.ws.on('CB:call', async (json) => {
try {
if (!json?.tag || json.tag !== 'call' || !json.attrs?.from) {
return
}
const callerId = global.conn.decodeJid(json.attrs.from)
const isOwner = global.owner.some(([num]) => num === callerId.split('@')[0])
if (isOwner) return
const eventId = json.attrs.id
let actualCallId = null
if (json.content?.length > 0) {
for (const item of json.content) {
if (item.attrs && item.attrs['call-id']) {
actualCallId = item.attrs['call-id']
break
}
}
}
const uniqueCallId = actualCallId || eventId
if (json.content?.length > 0) {
const contentTags = json.content.map(item => item.tag)
if (contentTags.includes('terminate')) {
global.processedCalls.delete(uniqueCallId)
return
}
if (contentTags.includes('relaylatency')) {
if (global.processedCalls.has(uniqueCallId)) {
return
}
global.processedCalls.set(uniqueCallId, true)
const numero = callerId.split('@')[0]
let nome = global.nameCache.get(callerId);
if (!nome) {
nome = global.conn.getName(callerId) || 'Sconosciuto'
global.nameCache.set(callerId, nome);
}
console.log(`[📞] chiamata in arrivo da ${numero} - ${nome}`)
if (!global.db.data) await global.loadDatabase()
let settings = global.db.data?.settings?.[global.conn.user.jid]
if (!settings) {
settings = global.db.data.settings[global.conn.user.jid] = {
jadibotmd: false,
antiPrivate: true,
soloCreatore: false,
anticall: true,
status: 0
}
}
if (!settings.anticall) return
let user = global.db.data.users[callerId] || (global.db.data.users[callerId] = { callCount: 0, banned: false })
if (user.banned) {
await global.conn.rejectCall(uniqueCallId, callerId)
return
}
user.callCount = (user.callCount || 0) + 1
try {
await global.conn.rejectCall(uniqueCallId, callerId)
console.log(`[📞] chiamata di ${numero} - ${nome} rifiutata`)
if (user.callCount >= 3) {
user.banned = true
user.bannedReason = 'Troppi tentativi di chiamata'
const msg = `🚫 Quanto puoi essere sfigato per spammare di call smh.`
await global.conn.sendMessage(toJid(callerId), { text: msg })
} else {
const msg = `🚫 Chiamata rifiutata automaticamente, non chiamare il bot.`
await global.conn.sendMessage(toJid(callerId), { text: msg })
}
} catch (err) {
console.error('[ERRORE] Errore nel gestire la chiamata:', err)
global.processedCalls.delete(uniqueCallId)
}
}
}
} catch (e) {
console.error('[ERRORE] Errore generale gestione chiamata:', e)
}
})
}
setInterval(() => {
if (global.processedCalls.size > 10) {
global.processedCalls.clear()
}
}, 180000)
export async function participantsUpdate({ id, participants, action }) {
if (global.db.data.chats[id]?.rileva === false) return
try {
let metadata = global.groupCache.get(id) || await fetchMetadata(this, id)
if (!metadata) return
global.groupCache.set(id, metadata, { ttl: 300 })
for (const user of participants) {
const normalizedUser = this.decodeJid(user)
let userName = global.nameCache.get(normalizedUser);
if (!userName) {
userName = (await this.getName(normalizedUser)) || normalizedUser.split('@')[0] || 'Sconosciuto'
global.nameCache.set(normalizedUser, userName);
}
switch (action) {
case 'add':
break
case 'remove':
break
case 'promote':
break
case 'demote':
break
}
}
} catch (e) {
console.error(`[ERRORE] Errore in participantsUpdate per ${id}:`, e)
}
}
export async function handler(chatUpdate) {
this.msgqueque = this.msgqueque || []
this.uptime = this.uptime || Date.now()
if (!chatUpdate) return
this.pushMessage(chatUpdate.messages).catch(console.error)
let m = chatUpdate.messages[chatUpdate.messages.length - 1]
if (!m) return
if (m.message?.protocolMessage?.type === 'MESSAGE_EDIT') {
const key = m.message.protocolMessage.key;
const editedMessage = m.message.protocolMessage.editedMessage;
m.key = key;
m.message = editedMessage;
m.text = editedMessage.conversation || editedMessage.extendedTextMessage?.text || '';
m.mtype = Object.keys(editedMessage)[0];
console.log(`[EDIT] Messaggio ${key.id} modificato in ${key.remoteJid}`);
}
m = smsg(this, m, global.store)
if (!m || !m.key || !m.chat || !m.sender) return
if (m.fromMe) return
if (m.key.participant && m.key.participant.includes(':') && m.key.participant.split(':')[1]?.includes('@')) return
if (m.key) {
m.key.remoteJid = this.decodeJid(m.key.remoteJid)
if (m.key.participant) m.key.participant = this.decodeJid(m.key.participant)
}
if (!m.key.remoteJid) return
if (!this.originalGroupParticipantsUpdate) {
this.originalGroupParticipantsUpdate = this.groupParticipantsUpdate
this.groupParticipantsUpdate = async function(chatId, users, action) {
try {
let metadata = global.groupCache.get(chatId)
if (!metadata) {
metadata = await fetchMetadata(this, chatId)
if (metadata) global.groupCache.set(chatId, metadata, { ttl: 300 })
}
if (!metadata) {
console.error('[ERRORE] Nessun metadato del gruppo disponibile per un aggiornamento sicuro')
return this.originalGroupParticipantsUpdate.call(this, chatId, users, action)
}
const correctedUsers = users.map(userJid => {
const decoded = this.decodeJid(userJid)
const phone = decoded.split('@')[0].replace(/:\d+$/, '')
const participant = metadata.participants.find(p => {
const pId = this.decodeJid(p.id)
const pPhone = pId.split('@')[0].replace(/:\d+$/, '')
return pPhone === phone
})
return participant ? participant.id : userJid
})
return this.originalGroupParticipantsUpdate.call(this, chatId, correctedUsers, action)
} catch (e) {
console.error('[ERRORE] Errore in safeGroupParticipantsUpdate:', e)
throw e
}
}
}
initResponseHandler(this)
let user = null
let chat = null
let usedPrefix = null
let normalizedSender = null
let normalizedBot = null
try {
let eventHandled = false
if (m.message?.eventResponseMessage) {
const { eventId, response } = m.message.eventResponseMessage
const jid = this.decodeJid(m.key.remoteJid)
const userId = this.decodeJid(m.key.participant || m.key.remoteJid)
const action = response === 'going' ? 'join' : 'leave'
try {
if (!global.activeEvents) global.activeEvents = new Map()
if (!global.activeGiveaways) global.activeGiveaways = new Map()
let eventData = global.activeEvents.get(eventId) || global.activeGiveaways.get(jid)
if (eventData) {
if (!eventData.participants) eventData.participants = new Set()
if (action === 'join') {
eventData.participants.add(userId)
} else {
eventData.participants.delete(userId)
}
eventHandled = true
}
} catch (e) {
console.error('[ERRORE] Errore nel gestire eventResponseMessage:', e)
}
}
if (m.message?.interactiveResponseMessage) {
const interactiveResponse = m.message.interactiveResponseMessage
if (interactiveResponse.nativeFlowResponseMessage?.paramsJson) {
try {
const params = JSON.parse(interactiveResponse.nativeFlowResponseMessage.paramsJson)
if (params.id) {
const fakeMessage = {
key: m.key,
message: { conversation: params.id },
messageTimestamp: m.messageTimestamp,
pushName: m.pushName,
broadcast: m.broadcast
}
const processedMsg = smsg(this, fakeMessage)
if (processedMsg) {
processedMsg.text = params.id
return handler.call(this, { messages: [processedMsg] })
}
}
} catch (e) {
console.error('❌ Errore parsing nativeFlowResponse:', e)
}
}
}
if (!global.db.data) await global.loadDatabase()
m.exp = 0
m.euro = false
m.isCommand = false
normalizedSender = this.decodeJid(m.sender)
normalizedBot = this.decodeJid(this.user.jid)
if (!normalizedSender) return;
user = global.db.data.users[normalizedSender] || (global.db.data.users[normalizedSender] = {
exp: 0,
euro: 10,
muto: false,
registered: false,
name: m.pushName || '?',
age: -1,
regTime: -1,
banned: false,
bank: 0,
level: 0,
firstTime: Date.now(),
spam: 0
})
chat = global.db.data.chats[m.chat] || (global.db.data.chats[m.chat] = {
isBanned: false,
welcome: false,
goodbye: false,
ai: false,
vocali: false,
antiporno: false,
antioneview: false,
autolevelup: false,
antivoip: false,
rileva: false,
modoadmin: false,
antiLink: false,
antiLink2: false,
reaction: false,
antispam: false,
expired: 0,
users: {}
})
let settings = global.db.data.settings[this.user.jid] || (global.db.data.settings[this.user.jid] = {
autoread: false,
jadibotmd: false,
antiPrivate: true,
soloCreatore: false,
status: 0
})
if (m.mtype === 'pollUpdateMessage') return
if (m.mtype === 'reactionMessage') return
let groupMetadata = m.isGroup ? global.groupCache.get(m.chat) : null
let participants = null
let normalizedParticipants = null
let isBotAdmin = false
let isAdmin = false
let isRAdmin = false
let isSam = global.owner.some(([num]) => num + '@s.whatsapp.net' === normalizedSender)
let isROwner = isSam || global.owner.some(([num]) => num + '@s.whatsapp.net' === normalizedSender)
let isOwner = isROwner || m.fromMe
let isMods = isOwner || global.mods?.map(v => v.replace(/[^0-9]/g, '') + '@s.whatsapp.net').includes(normalizedSender) || false
let isPrems = isROwner || global.prems?.map(v => v.replace(/[^0-9]/g, '') + '@s.whatsapp.net').includes(normalizedSender) || false
if (m.isGroup) {
if (!groupMetadata) {
groupMetadata = await fetchGroupMetadataWithRetry(this, m.chat)
if (groupMetadata) {
groupMetadata.fetchTime = Date.now()
global.groupCache.set(m.chat, groupMetadata, { ttl: 300 })
}
}
if (groupMetadata) {
participants = groupMetadata.participants
normalizedParticipants = participants.map(u => {
const normalizedId = this.decodeJid(u.id)
return { ...u, id: normalizedId, jid: u.jid || normalizedId }
})
const normalizedOwner = groupMetadata.owner ? this.decodeJid(groupMetadata.owner) : null
const normalizedOwnerLid = groupMetadata.ownerLid ? this.decodeJid(groupMetadata.ownerLid) : null
isAdmin = participants.some(u => {
const participantIds = [
this.decodeJid(u.id),
u.jid ? this.decodeJid(u.jid) : null,
u.lid ? this.decodeJid(u.lid) : null
].filter(Boolean)
const isMatch = participantIds.includes(normalizedSender)
return isMatch && (u.admin === 'admin' || u.admin === 'superadmin' || u.isAdmin === true || u.admin === true)
})
isBotAdmin = participants.some(u => {
const participantIds = [
this.decodeJid(u.id),
u.jid ? this.decodeJid(u.jid) : null,
u.lid ? this.decodeJid(u.lid) : null
].filter(Boolean)
const isMatch = participantIds.includes(normalizedBot)
return isMatch && (u.admin === 'admin' || u.admin === 'superadmin' || u.isAdmin === true || u.admin === true)
}) || (normalizedBot === normalizedOwner || normalizedBot === normalizedOwnerLid)
isRAdmin = isAdmin && (normalizedSender === normalizedOwner || normalizedSender === normalizedOwnerLid)
if (m.isGroup && !isAdmin) {
const secondMetadata = await fetchGroupMetadataWithRetry(this, m.chat)
if (secondMetadata) {
secondMetadata.fetchTime = Date.now()
global.groupCache.set(m.chat, secondMetadata, { ttl: 300 })
participants = secondMetadata.participants
normalizedParticipants = participants.map(u => {
const normalizedId = this.decodeJid(u.id)
return { ...u, id: normalizedId, jid: u.jid || normalizedId }
})
isAdmin = participants.some(u => {
const participantIds = [
this.decodeJid(u.id),
u.jid ? this.decodeJid(u.jid) : null,
u.lid ? this.decodeJid(u.lid) : null
].filter(Boolean)
const isMatch = participantIds.includes(normalizedSender)
return isMatch && (u.admin === 'admin' || u.admin === 'superadmin' || u.isAdmin === true || u.admin === true)
})
isBotAdmin = participants.some(u => {
const participantIds = [
this.decodeJid(u.id),
u.jid ? this.decodeJid(u.jid) : null,
u.lid ? this.decodeJid(u.lid) : null
].filter(Boolean)
const isMatch = participantIds.includes(normalizedBot)
return isMatch && (u.admin === 'admin' || u.admin === 'superadmin' || u.isAdmin === true || u.admin === true)
}) || (normalizedBot === normalizedOwner || normalizedBot === normalizedOwnerLid)
}
}
}
}
const ___dirname = join(path.dirname(fileURLToPath(import.meta.url)), './plugins')
for (let name in global.plugins) {
let plugin = global.plugins[name]
if (!plugin) continue
const __filename = join(___dirname, name)
if (typeof plugin.all === 'function') {
try {
await plugin.all.call(this, m, {
chatUpdate,
__dirname: ___dirname,
__filename
})
} catch (e) {
console.error('[ERRORE] Errore in plugin.all:', e)
}
}
const str2Regex = str => str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
let _prefix = plugin.customPrefix || global.prefix || '.'
let match = (_prefix instanceof RegExp ? [[_prefix.exec(m.text), _prefix]] :
Array.isArray(_prefix) ? _prefix.map(p => [p instanceof RegExp ? p : new RegExp(str2Regex(p)).exec(m.text), p]) :
typeof _prefix === 'string' ? [[new RegExp(str2Regex(_prefix)).exec(m.text), _prefix]] :
[[[], new RegExp]]).find(p => p[1])
if (typeof plugin.before === 'function') {
if (await plugin.before.call(this, m, {
match,
conn: this,
participants: normalizedParticipants,
groupMetadata,
user: { admin: isAdmin ? 'admin' : null },
bot: { admin: isBotAdmin ? 'admin' : null },
isSam,
isROwner,
isOwner,
isRAdmin,
isAdmin,
isBotAdmin,
isPrems,
chatUpdate,
__dirname: ___dirname,
__filename
})) continue
}
if (typeof plugin !== 'function') continue
if (!match || !match[0]) continue
usedPrefix = (match[0] || '')[0]
if (usedPrefix) {
let noPrefix = m.text.replace(usedPrefix, '')
let [command, ...args] = noPrefix.trim().split` `.filter(v => v)
args = args || []
let _args = noPrefix.trim().split` `.slice(1)
let text = _args.join` `
command = command?.toLowerCase() || ''
let fail = plugin.fail || global.dfail
let isAccept = plugin.command instanceof RegExp ? plugin.command.test(command) :
Array.isArray(plugin.command) ? plugin.command.some(cmd => cmd instanceof RegExp ? cmd.test(command) : cmd === command) :
typeof plugin.command === 'string' ? plugin.command === command : false
if (!isAccept) continue
if (m.isGroup && (plugin.admin || plugin.botAdmin)) {
const freshMetadata = global.groupCache.get(m.chat) || await fetchGroupMetadataWithRetry(this, m.chat)
if (freshMetadata) {
freshMetadata.fetchTime = Date.now()
global.groupCache.set(m.chat, freshMetadata, { ttl: 300 })
groupMetadata = freshMetadata
participants = groupMetadata.participants
normalizedParticipants = participants.map(u => {
const normalizedId = this.decodeJid(u.id)
return { ...u, id: normalizedId, jid: u.jid || normalizedId }
})
const normalizedOwner = groupMetadata.owner ? this.decodeJid(groupMetadata.owner) : null
const normalizedOwnerLid = groupMetadata.ownerLid ? this.decodeJid(groupMetadata.ownerLid) : null
isAdmin = participants.some(u => {
const participantIds = [
this.decodeJid(u.id),
u.jid ? this.decodeJid(u.jid) : null,
u.lid ? this.decodeJid(u.lid) : null
].filter(Boolean)
const isMatch = participantIds.includes(normalizedSender)
return isMatch && (u.admin === 'admin' || u.admin === 'superadmin' || u.isAdmin === true || u.admin === true)
})
isBotAdmin = participants.some(u => {
const participantIds = [
this.decodeJid(u.id),
u.jid ? this.decodeJid(u.jid) : null,
u.lid ? this.decodeJid(u.lid) : null
].filter(Boolean)
const isMatch = participantIds.includes(normalizedBot)
return isMatch && (u.admin === 'admin' || u.admin === 'superadmin' || u.isAdmin === true || u.admin === true)
}) || (normalizedBot === normalizedOwner || normalizedBot === normalizedOwnerLid)
isRAdmin = isAdmin && (normalizedSender === normalizedOwner || normalizedSender === normalizedOwnerLid)
}
}
if (plugin.disabled && !isOwner) {
fail('disabled', m, this)
continue
}
if (user.muto && !isROwner && !isOwner) {
await this.sendMessage(m.chat, { text: `🚫 Sei stato mutato, non puoi usare i comandi.` }, { quoted: m }).catch(e => console.error('[ERRORE] Errore nell\'invio del messaggio:', e))
return
}
const ignoredGlobally = global.ignoredUsersGlobal.has(normalizedSender)
const ignoredInGroup = m.isGroup && global.ignoredUsersGroup[m.chat]?.has(normalizedSender)
if ((ignoredGlobally || ignoredInGroup) && !isROwner) {
await this.sendMessage(m.chat, { text: `🚫 Non sei autorizzato a usare comandi.` }, { quoted: m }).catch(e => console.error('[ERRORE] Errore nell\'invio del messaggio:', e))
return
}
m.plugin = name
if (chat.isBanned && !isROwner && !['gp-sbanchat.js', 'creatore-exec.js', 'gp-delete.js'].includes(name)) return
if (user.banned && !isROwner && name !== 'creatore-banuser.js') {
if (user.antispam > 2) return
await this.sendMessage(m.chat, {
text: `🚫 *Sei stato bannato/a dall'utilizzo del bot*.\n\n${user.bannedReason ? `🥀 Motivo: ${user.bannedReason}` : `🥀 Motivo: Non specificato ma meritato`}\n\n⚠️ Contatta il creatore con *${usedPrefix}segnala* per problemi.`
}, { quoted: m }).catch(e => console.error('[ERRORE] Errore nell\'invio del messaggio:', e))
user.antispam++
return
}
if (m.isGroup && !isOwner && !isROwner && !isAdmin && chat.antispam) {
const groupData = global.groupSpam[m.chat] || (global.groupSpam[m.chat] = {
count: 0,
firstCommandTimestamp: 0,
isSuspended: false
})
const now = Date.now()
if (groupData.isSuspended) return
if (now - groupData.firstCommandTimestamp > 60000) {
groupData.count = 1
groupData.firstCommandTimestamp = now
} else {
groupData.count++
}
if (groupData.count > 8) {
groupData.isSuspended = true
await this.reply(m.chat, `『 ⚠️ 』 \`Anti-spam comandi\`\n\n> Rilevati troppi comandi in un minuto, aspettate \`15 secondi\` prima di riutilizzare i comandi.\n\n*ℹ️ Gli admin del gruppo sono esenti da questo limite.*`, m).catch(e => console.error('[ERRORE] Errore nell\'invio della risposta:', e))
setTimeout(() => {
delete global.groupSpam[m.chat]
console.log(`[Anti-Spam] Comandi riattivati per il gruppo: ${m.chat}`)
}, 15000)
return
}
}
if (chat.modoadmin && !isOwner && !isROwner && m.isGroup && !isAdmin && !user.premium) return
if (settings.soloCreatore && !isROwner) return
if (plugin.sam && !isSam) {
fail('sam', m, this)
continue
}
if (plugin.rowner && !isROwner) {
fail('rowner', m, this)
continue
}
if (plugin.owner && !isOwner) {
fail('owner', m, this)
continue
}
if (plugin.mods && !isMods) {
fail('mods', m, this)
continue
}
if (plugin.premium && !isPrems) {
fail('premium', m, this)
continue
}
if (plugin.group && !m.isGroup) {
fail('group', m, this)
continue
}
if (plugin.botAdmin && !isBotAdmin) {
fail('botAdmin', m, this)
continue
}
if (plugin.admin && !isAdmin) {
fail('admin', m, this)
continue
}
if (plugin.private && m.isGroup) {
fail('private', m, this)
continue
}
if (plugin.register && !user.registered) {
fail('unreg', m, this)
continue
}
m.isCommand = true
let xp = 'exp' in plugin ? parseInt(plugin.exp) : 17
if (xp > 200) {
await this.reply(m.chat, 'bzzzzz', m).catch(e => console.error('[ERRORE] Errore nella risposta:', e))
} else {
m.exp += xp
}
if (!isPrems && plugin.euro && user.euro < plugin.euro) {
await this.reply(m.chat, `Niente più soldini, stupido poraccio`, m, null, global.fake).catch(e => console.error('[ERRORE] Errore nella risposta:', e))
continue
}
let extra = {
match,
usedPrefix,
noPrefix,
_args,
args,
command,
text,
conn: this,
participants: normalizedParticipants,
groupMetadata,
user: { admin: isAdmin ? 'admin' : null },
bot: { admin: isBotAdmin ? 'admin' : null },
isSam,
isROwner,
isOwner,
isRAdmin,
isAdmin,
isBotAdmin,
isPrems,
chatUpdate,
__dirname: ___dirname,
__filename
}
try {
await plugin.call(this, m, extra)
if (!isPrems) m.euro = plugin.euro || false
} catch (e) {
m.error = e
console.error(`[ERRORE] Errore nell'esecuzione del plugin per la chat ${m.chat}, mittente ${m.sender}:`, e)
if (e.message.includes('rate-overlimit')) {
console.warn('[AVVISO] Rate limit raggiunto, ritento dopo 2 secondi...')
await delay(2000)
}
let text = format(e)
await this.reply(m.chat, text, m).catch(e => console.error('[ERRORE] Errore nella risposta:', e))
} finally {
if (typeof plugin.after === 'function') {
try {
await plugin.after.call(this, m, extra)
} catch (e) {
console.error('[ERRORE] Errore in plugin.after:', e)
}
}
if (m.euro) {
await this.reply(m.chat, `\`Hai utilizzato *${+m.euro}*\``, m, null, global.rcanal).catch(e => console.error('[ERRORE] Errore nell\'invio della risposta:', e))
}
}
break
}
}
} catch (e) {
console.error(`[ERRORE] Errore nel handler per la chat ${m.chat}, mittente ${m.sender}:`, e)
} finally {
if (m && user && user.muto && !m.fromMe) {
await this.sendMessage(m.chat, { delete: m.key }).catch(e => console.error('[ERRORE] Errore nell\'eliminazione del messaggio:', e))
}
if (m && user) {
user.exp += m.exp || 0
user.euro -= m.euro * 1 || 0
if (!user.messages) user.messages = 0;
user.messages++;
if (m.isGroup) {
if (!chat.users) chat.users = {};
const senderId = normalizedSender;
if (!chat.users[senderId]) {
chat.users[senderId] = { messages: 0 };
}
chat.users[senderId].messages++;
}
if (m.plugin) {
let stats = global.db.data.stats || (global.db.data.stats = {})
let stat = stats[m.plugin] || (stats[m.plugin] = {
total: 0,
success: 0,
last: 0,
lastSuccess: 0
})
const now = +new Date
stat.total += 1
stat.last = now
if (!m.error) {
stat.success += 1
stat.lastSuccess = now
}
}
}
try {
if (!global.opts['noprint'] && m) await (await import(`./lib/print.js`)).default(m, this)
} catch (e) {
console.error('[ERRORE] Errore in print:', e)
}
let settingsREAD = global.db.data.settings[this.user.jid] || {}
if ((global.opts['autoread'] || settingsREAD.autoread2) && m) {
await this.readMessages([m.key]).catch(e => console.error('[ERRORE] Errore nella lettura del messaggio:', e))
}
if (chat && chat.reaction && m?.text?.match(/(mente|zione|tà|ivo|osa|issimo|ma|però|eppure|anche|ma|no|se|ai|ciao|si)/gi) && !m.fromMe) {
const emot = pickRandom([
"🍟", "😃", "😄", "😁", "😆", "🍓", "😅", "😂", "🤣", "🥲", "☺️", "😊", "😇", "🙂", "🙃", "😉", "😌", "😍", "🥰"
])
await this.sendMessage(m.chat, { react: { text: emot, key: m.key } }).catch(e => console.error('[ERRORE] Errore nell\'invio della reazione:', e))
}
}
}
global.dfail = async (type, m, conn) => {
const nome = m.pushName || 'sam'
const etarandom = Math.floor(Math.random() * 21) + 13
const msg = {
sam: '🔐 𝐂𝐎𝐌𝐀𝐍𝐃𝐎 𝐑𝐈𝐒𝐄𝐑𝐕𝐀𝐓𝐎\n╰➤ ✦ Accesso consentito esclusivamente al Creatore',
rowner: '👑 𝐂𝐎𝐌𝐀𝐍𝐃𝐎 𝐂𝐑𝐄𝐀𝐓𝐎𝐑𝐄\n╰➤ ✦ Solo il Creatore del bot può utilizzare questa funzione',
owner: '🛡️ 𝐀𝐂𝐂𝐄𝐒𝐒𝐎 𝐎𝐖𝐍𝐄𝐑\n╰➤ ✦ Funzione disponibile solo agli Owner autorizzati',
mods: '⚙️ 𝐀𝐂𝐂𝐄𝐒𝐒𝐎 𝐌𝐎𝐃𝐄𝐑𝐀𝐓𝐎𝐑𝐈\n╰➤ ✦ Comando riservato ai Moderatori del bot',
premium: '💎 𝐔𝐓𝐄𝐍𝐓𝐄 𝐏𝐑𝐄𝐌𝐈𝐔𝐌\n╰➤ ✦ Questa funzione è disponibile solo per utenti Premium',
group: '👥 𝐒𝐎𝐋𝐎 𝐆𝐑𝐔𝐏𝐏𝐈\n╰➤ ✦ Questo comando può essere utilizzato esclusivamente nei gruppi',
private: '📩 𝐒𝐎𝐋𝐎 𝐏𝐑𝐈𝐕𝐀𝐓𝐎\n╰➤ ✦ Questa funzione è disponibile solo in chat privata',
admin: '🛠️ 𝐒𝐎𝐋𝐎 𝐀𝐃𝐌𝐈𝐍\n╰➤ ✦ Comando utilizzabile solo dagli Admin del gruppo',
botAdmin: '🤖 𝐁𝐎𝐓 𝐍𝐎𝐍 𝐀𝐃𝐌𝐈𝐍\n╰➤ ✦ Devo essere Admin del gruppo per eseguire questo comando',
restrict: '🚫 𝐅𝐔𝐍𝐙𝐈𝐎𝐍𝐄 𝐃𝐈𝐒𝐀𝐓𝐓𝐈𝐕𝐀𝐓𝐀\n╰➤ ✦ Questa funzione è attualmente disattivata',
disabled: '⛔ 𝐂𝐎𝐌𝐀𝐍𝐃𝐎 𝐃𝐈𝐒𝐀𝐁𝐈𝐋𝐈𝐓𝐀𝐓𝐎\n╰➤ ✦ Questo comando non è attivo al momento'
}[type]
if (msg) {
conn.reply(m.chat, msg, m, global.rcanal).catch(e => console.error('[ERRORE] Errore in dfail:', e))
}
}
function pickRandom(list) {
return list[Math.floor(Math.random() * list.length)]
}
let file = global.__filename(import.meta.url, true)
watchFile(file, async () => {
unwatchFile(file)
console.log(chalk.bgHex('#3b0d95')(chalk.white.bold("File: 'handler.js' Aggiornato")))
})