-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhandler.js
More file actions
796 lines (699 loc) · 20.6 KB
/
handler.js
File metadata and controls
796 lines (699 loc) · 20.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
const util = require('util');
const moment = require('moment-timezone');
const { smsg } = require('./lib/simple');
const fs = require('fs');
const chalk = require('chalk');
const print = require('./lib/print');
const defaultUserData = {
exp: 0,
limit: 80,
lastLimitReset: 0,
atm: 0,
lastpractice: 0,
pickaxe: 0,
banteng: 0,
bosbattle: 0,
lastberburu: 0,
lastbossbattle: 0,
lastRestCommand: 0,
harimau: 0,
restActive: false,
lastRest: 0,
maxStamina: 100,
fishingrod: 0,
babihutan: 0,
sworddurability: 0,
pickaxedurability: 0,
fishingroddurability: 0,
armordurability: 0,
lasthunt: 0,
gajah: 0,
kambing: 0,
panda: 0,
buaya: 0,
kerbau: 0,
sapi: 0,
monyet: 0,
babi: 0,
ayam: 0,
anjing: 0,
gelas: 0,
plastik: 0,
lastclaim: 0,
lastkerja: 0,
lastjb: 0,
lastngojek: 0,
ojekk: 0,
registered: false,
name: "User",
usertag: "user",
age: -1,
regTime: -1,
afk: -1,
afkReason: '',
bank: 0,
berlian: 0,
banned: false,
cat: 0,
coal: 0,
level: 0,
lastnambang: 0,
lastnsmbang: 0,
lastrob: 0,
role: 'Beginner',
autolevelup: true,
premium: false,
paus: 0,
kepiting: 0,
gurita: 0,
cumi: 0,
buntal: 0,
dory: 0,
lumba: 0,
lobster: 0,
hiu: 0,
udang: 0,
ikan: 0,
orca: 0,
premiumTime: 0,
money: 0,
potion: 0,
diamond: 0,
common: 0,
uncommon: 0,
mythic: 0,
legendary: 0,
sampah: 0,
armor: 0,
string: 0,
iron: 0,
sword: 0,
batu: 0,
botol: 0,
kaleng: 0,
kardus: 0,
kayu: 0,
emas: 0,
emasbatang: 0,
bensin: 0,
weapon: 0,
obat: 0,
pisang: 0,
anggur: 0,
mangga: 0,
jeruk: 0,
apel: 0,
bibitpisang: 0,
bibitanggur: 0,
bibitmangga: 0,
bibitjeruk: 0,
bibitapel: 0,
gardenboxs: 0,
makananpet: 0,
makanannaga: 0,
makanankyubi: 0,
makanangriffin: 0,
makananphonix: 0,
makanancentaur: 0,
aqua: 0,
pancingan: 0,
umpan: 0,
pet: 0,
phonix: 0,
anakphonix: 0,
phonixlastclaim: 0,
griffin: 0,
anakgriffin: 0,
griffinlastclaim: 0,
kyubi: 0,
anakkyubi: 0,
kyubilastclaim: 0,
naga: 0,
anaknaga: 0,
nagalastclaim: 0,
centaur: 0,
anakcentaur: 0,
centaurlastclaim: 0,
kuda: 0,
anakkuda: 0,
kudalastclaim: 0,
rubah: 0,
anakrubah: 0,
rubahlastclaim: 0,
kucing: 0,
anakkucing: 0,
kucinglastclaim: 0,
serigala: 0,
anakserigala: 0,
serigalalastclaim: 0,
hero: 0,
exphero: 0,
health: 100,
monster: null,
stamina: 100,
energyCooldown: 0,
cupon: 0,
expg: 0,
healtmonster: 0,
tiketcoin: 0,
boxs: 0,
ramuan: 0,
lastadventure: 0,
healt: 100,
ayambakar: 0,
ayamgoreng: 0,
rendang: 0,
steak: 0,
babipanggang: 0,
gulaiayam: 0,
oporayam: 0,
vodka: 0,
sushi: 0,
bandage: 0,
ganja: 0,
soda: 0,
roti: 0,
ikanbakar: 0,
lelebakar: 0,
nilabakar: 0,
bawalbakar: 0,
udangbakar: 0,
pausbakar: 0,
kepitingbakar: 0,
ojek: false,
pedagang: false,
dokter: false,
petani: false,
montir: false,
kuli: false
};
const defaultChatData = {
isBanned: false,
welcome: true,
sWelcome: '',
sLeave: '',
sPromote: '',
sDemote: '',
antiLink: false,
antiBot: false,
antiChannel: false,
antiVideo: false,
antiToxic: false,
antiNSFW: false,
detect: false,
desc: true,
delete: true,
autoDL: false,
viewonce: false,
autotr: false,
ngetik: true,
expired: 0,
allakses: true,
autokick: false,
participants: []
};
async function handleCallback(bot, ctx) {
for (let name in global.plugins) {
let plugin = global.plugins[name];
if (!plugin) continue;
if (plugin.disabled) continue;
if (typeof plugin.callback === 'function') {
try {
const result = await plugin.callback(ctx, bot);
if (result === true) {
return true;
}
} catch (e) {
console.error(`Error in ${name}.callback:`, e);
}
}
}
return false;
}
async function handleWelcome(bot, ctx) {
try {
const chatId = ctx.chat.id;
if (!global.db.data.chats[chatId]) {
global.db.data.chats[chatId] = { ...defaultChatData };
}
const chat = global.db.data.chats[chatId];
for (const member of ctx.message.new_chat_members) {
if (member.id === ctx.botInfo.id) continue;
if (!chat.participants) {
chat.participants = [];
}
if (!chat.participants.includes(member.id)) {
chat.participants.push(member.id);
}
}
if (chat && chat.welcome) {
const newMembers = ctx.message.new_chat_members;
const groupMetadata = await bot.groupMetadata(chatId);
for (const member of newMembers) {
if (member.id === ctx.botInfo.id) continue;
const userName = member.first_name + (member.last_name ? ' ' + member.last_name : '');
const userMention = member.username ? `@${member.username}` : `[${userName}](tg://user?id=${member.id})`;
const groupName = groupMetadata.subject;
const groupDesc = groupMetadata.desc || 'Tidak ada deskripsi';
let welcomeMessage;
if (chat.sWelcome) {
welcomeMessage = chat.sWelcome
.replace(/@user/gi, userMention)
.replace(/@subject/gi, groupName)
.replace(/@desc/gi, groupDesc);
} else {
welcomeMessage = `Selamat Datang!\n\nHalo ${userMention}!\nSelamat datang di ${groupName}\n\nSemoga betah dan jangan lupa baca deskripsi grup ya!`;
}
try {
if (groupMetadata.photo) {
await ctx.replyWithPhoto({ source: groupMetadata.photo }, {
caption: welcomeMessage,
reply_to_message_id: ctx.message.message_id,
parse_mode: 'Markdown'
});
} else {
await ctx.reply(welcomeMessage, {
reply_to_message_id: ctx.message.message_id,
parse_mode: 'Markdown'
});
}
} catch (e) {
await ctx.reply(welcomeMessage, { parse_mode: 'Markdown' });
}
}
}
} catch (error) {
console.error('Error in welcome handler:', error);
}
}
async function handleGoodbye(bot, ctx) {
try {
const chatId = ctx.chat.id;
if (!global.db.data.chats[chatId]) {
global.db.data.chats[chatId] = { ...defaultChatData };
}
const chat = global.db.data.chats[chatId];
const leftMember = ctx.message.left_chat_member;
if (chat.participants) {
const index = chat.participants.indexOf(leftMember.id);
if (index > -1) {
chat.participants.splice(index, 1);
}
}
if (chat && chat.welcome) {
if (leftMember.id !== ctx.botInfo.id) {
const userName = leftMember.first_name + (leftMember.last_name ? ' ' + leftMember.last_name : '');
const userMention = leftMember.username ? `@${leftMember.username}` : `[${userName}](tg://user?id=${leftMember.id})`;
const groupMetadata = await bot.groupMetadata(chatId);
const groupName = groupMetadata.subject;
let goodbyeMessage;
if (chat.sLeave) {
goodbyeMessage = chat.sLeave
.replace(/@user/gi, userMention)
.replace(/@subject/gi, groupName);
} else {
goodbyeMessage = `Sampai Jumpa!\n\n${userMention} telah meninggalkan grup ${groupName}\n\nSemoga sukses selalu!`;
}
try {
await ctx.reply(goodbyeMessage, { parse_mode: 'Markdown' });
} catch (e) {
await ctx.reply(goodbyeMessage, { parse_mode: 'Markdown' });
}
}
}
} catch (error) {
console.error('Error in goodbye handler:', error);
}
}
function initializeUserData(userId, m) {
if (!global.db.data.users) {
global.db.data.users = {};
}
if (!global.db.data.users[userId]) {
global.db.data.users[userId] = { ...defaultUserData };
global.db.data.users[userId].name = m.from.first_name || 'User';
global.db.data.users[userId].usertag = m.from.username ? '@' + m.from.username : 'user';
}
let user = global.db.data.users[userId];
for (let key in defaultUserData) {
if (user[key] === undefined || user[key] === null || (typeof user[key] === 'number' && isNaN(user[key]))) {
user[key] = defaultUserData[key];
}
}
const now = Date.now();
const lastReset = user.lastLimitReset || 0;
const jakartaTime = moment.tz('Asia/Jakarta');
const lastResetTime = moment(lastReset).tz('Asia/Jakarta');
if (lastReset === 0 || !jakartaTime.isSame(lastResetTime, 'day') || (jakartaTime.hour() === 0 && lastResetTime.hour() !== 0)) {
user.limit = 80;
user.lastLimitReset = now;
}
if (user.name === 'User' && m.from.first_name) {
user.name = m.from.first_name + (m.from.last_name ? ' ' + m.from.last_name : '');
}
if (user.usertag === 'user' && m.from.username) {
user.usertag = '@' + m.from.username;
}
return user;
}
function initializeChatData(chatId, userId, isGroup) {
if (!global.db.data.chats) {
global.db.data.chats = {};
}
if (!global.db.data.chats[chatId]) {
global.db.data.chats[chatId] = { ...defaultChatData };
}
let chat = global.db.data.chats[chatId];
for (let key in defaultChatData) {
if (chat[key] === undefined || chat[key] === null) {
chat[key] = defaultChatData[key];
}
}
if (isGroup) {
if (!chat.participants) {
chat.participants = [];
}
if (!chat.participants.includes(userId)) {
chat.participants.push(userId);
}
}
return chat;
}
async function checkPermissions(bot, ctx, chatId, userId, isGroup) {
const ownerNumbers = global.owner.map(v => v.replace(/[^0-9]/g, ''));
const isOwner = ownerNumbers.includes(String(userId));
const isMods = global.mods.includes(String(userId));
let user = global.db.data.users[userId];
const isPrems = global.prems.includes(String(userId)) || user.premium;
let isAdmin = false;
let isBotAdmin = false;
if (isGroup) {
try {
const chatMember = await bot.telegram.getChatMember(chatId, userId);
isAdmin = ['creator', 'administrator'].includes(chatMember.status);
const botMember = await bot.telegram.getChatMember(chatId, ctx.botInfo.id);
isBotAdmin = ['administrator'].includes(botMember.status);
} catch (e) {
console.error('Error checking admin status:', e);
}
}
return { isOwner, isMods, isPrems, isAdmin, isBotAdmin };
}
async function executePluginBefore(m, extra) {
for (let name in global.plugins) {
let plugin = global.plugins[name];
if (!plugin) continue;
if (plugin.disabled) continue;
if (typeof plugin.before === 'function') {
try {
const result = await plugin.before(m, extra);
if (result === true) {
return true;
}
} catch (e) {
console.error(`Error in ${name}.before:`, e);
}
}
}
return false;
}
async function processCommand(bot, ctx, m, text, chatId, userId, isGroup, user, chat, permissions) {
for (let name in global.plugins) {
let plugin = global.plugins[name];
if (!plugin) continue;
if (plugin.disabled) continue;
const _prefix = plugin.customPrefix ? plugin.customPrefix : global.prefix;
let match = (_prefix instanceof RegExp ?
[[_prefix.exec(text), _prefix]] :
Array.isArray(_prefix) ?
_prefix.map(p => {
let re = p instanceof RegExp ? p : new RegExp(p.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&'));
return [re.exec(text), re];
}) :
typeof _prefix === 'string' ?
[[new RegExp(_prefix.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')).exec(text), new RegExp(_prefix.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&'))]] :
[[[], new RegExp]]
).find(p => p[1]);
if (typeof plugin !== 'function') continue;
let usedPrefix;
if ((usedPrefix = (match[0] || '')[0])) {
let noPrefix = text.replace(usedPrefix, '');
let [command, ...args] = noPrefix.trim().split(/\s+/).filter(v => v);
args = args || [];
let _args = noPrefix.trim().split(/\s+/).slice(1);
let cmdText = _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;
bot.sendChatAction(chatId, 'typing').catch(() => {});
if (plugin.owner && !permissions.isOwner) {
fail('owner', m, ctx);
continue;
}
if (plugin.mods && !permissions.isMods) {
fail('mods', m, ctx);
continue;
}
if (plugin.premium && !permissions.isPrems) {
fail('premium', m, ctx);
continue;
}
if (plugin.group && !isGroup) {
fail('group', m, ctx);
continue;
}
if (plugin.private && isGroup) {
fail('private', m, ctx);
continue;
}
if (plugin.admin && !permissions.isAdmin) {
fail('admin', m, ctx);
continue;
}
if (plugin.botAdmin && !permissions.isBotAdmin) {
fail('botAdmin', m, ctx);
continue;
}
if (plugin.register && !user.registered) {
fail('register', m, ctx);
continue;
}
if (plugin.limit) {
const limitCost = typeof plugin.limit === 'number' ? plugin.limit : 1;
if (!permissions.isOwner) {
if (user.limit < limitCost) {
fail('limit', m, ctx, limitCost);
continue;
}
}
}
let extra = {
match,
usedPrefix,
noPrefix,
_args,
args,
command,
text: cmdText,
bot,
ctx,
chatId,
userId,
isGroup,
...permissions,
user,
chat,
m,
conn: bot
};
plugin.call(ctx, m, extra).then(() => {
if (plugin.limit && !permissions.isOwner) {
const limitCost = typeof plugin.limit === 'number' ? plugin.limit : 1;
user.limit -= limitCost;
}
user.exp += plugin.exp || 0;
if (!global.db.data.stats) {
global.db.data.stats = {};
}
let stats = global.db.data.stats;
if (plugin && plugin.command) {
let cmdName = typeof plugin.command === 'string' ? plugin.command : 'unknown';
if (!stats[cmdName]) {
stats[cmdName] = {
total: 0,
success: 0,
last: Date.now(),
lastSuccess: Date.now()
};
}
stats[cmdName].total += 1;
stats[cmdName].success += 1;
stats[cmdName].last = Date.now();
stats[cmdName].lastSuccess = Date.now();
}
}).catch((e) => {
console.error(e);
if (typeof e === 'string') {
ctx.reply(e).catch(err => console.error('Reply error:', err));
} else if (e instanceof Error) {
ctx.reply(e.message || 'Terjadi kesalahan saat menjalankan perintah').catch(err => console.error('Reply error:', err));
let errorText = util.format(e);
let errorStack = e.stack || errorText;
let errorReport = `ERROR REPORT\n\n`;
errorReport += `Plugin: ${name}\n`;
errorReport += `User: ${m.pushName || m.from.first_name} (${userId})\n`;
errorReport += `Chat: ${chatId}\n`;
errorReport += `Command: ${usedPrefix}${command} ${args.join(' ')}\n`;
errorReport += `Time: ${moment().tz('Asia/Jakarta').format('DD/MM/YY HH:mm:ss')}\n\n`;
errorReport += `Error Message:\n${e.message}\n\n`;
errorReport += `Stack Trace:\n${errorStack.substring(0, 500)}`;
for (let ownerId of global.owner) {
ctx.telegram.sendMessage(ownerId, errorReport).catch(sendErr => console.error('Failed to send error report to owner:', sendErr));
}
}
});
break;
}
}
}
module.exports = {
async handler(bot, ctx) {
if (ctx.callbackQuery) {
const callbackData = ctx.callbackQuery.data;
if (callbackData && callbackData.startsWith('cmd_')) {
const command = callbackData.replace('cmd_', '');
const fakeMessage = {
message_id: ctx.callbackQuery.message.message_id,
from: ctx.callbackQuery.from,
chat: ctx.callbackQuery.message.chat,
text: command,
date: Math.floor(Date.now() / 1000)
};
const fakeCtx = {
message: fakeMessage,
update: {
message: fakeMessage
},
botInfo: ctx.botInfo,
telegram: ctx.telegram,
chat: ctx.callbackQuery.message.chat,
from: ctx.callbackQuery.from,
reply: async (text, options = {}) => {
return await ctx.telegram.sendMessage(ctx.callbackQuery.message.chat.id, text, {
parse_mode: 'Markdown',
...options
});
},
replyWithPhoto: ctx.replyWithPhoto.bind(ctx),
replyWithVideo: ctx.replyWithVideo.bind(ctx),
replyWithAudio: ctx.replyWithAudio.bind(ctx),
replyWithDocument: ctx.replyWithDocument.bind(ctx),
replyWithSticker: ctx.replyWithSticker.bind(ctx),
deleteMessage: ctx.deleteMessage.bind(ctx)
};
await ctx.answerCbQuery().catch(() => {});
return await require('./handler').handler(bot, fakeCtx);
}
let handled = false;
for (let name in global.plugins) {
let plugin = global.plugins[name];
if (!plugin) continue;
if (plugin.disabled) continue;
if (typeof plugin.handleCallback === 'function') {
try {
const result = await plugin.handleCallback(bot, ctx.callbackQuery);
if (result === true) {
handled = true;
break;
}
} catch (e) {
console.error(`Error in ${name}.handleCallback:`, e);
}
}
}
if (handled) return;
return await handleCallback(bot, ctx);
}
if (ctx.message?.new_chat_members) {
await handleWelcome(bot, ctx);
return;
}
if (ctx.message?.left_chat_member) {
await handleGoodbye(bot, ctx);
return;
}
let m = await smsg(bot, ctx);
if (!m.text) return;
await print(m, ctx, bot);
const chatId = m.chat;
const userId = m.from.id;
let text = m.text;
const isGroup = m.isGroup;
if (global.waitingForAnswer && global.waitingForAnswer.has(chatId)) {
const session = global.waitingForAnswer.get(chatId);
if (session && session.resolve && !m.fromMe) {
clearTimeout(session.timeout);
session.resolve(text);
return;
}
}
const botUsername = bot.botInfo?.username;
if (botUsername && text.includes(`@${botUsername}`)) {
text = text.replace(new RegExp(`@${botUsername}`, 'gi'), '').trim();
m.text = text;
}
const user = initializeUserData(userId, m);
const chat = initializeChatData(chatId, userId, isGroup);
const permissions = await checkPermissions(bot, ctx, chatId, userId, isGroup);
const extra = {
bot,
ctx,
chatId,
userId,
isGroup,
...permissions,
user,
chat,
conn: bot
};
executePluginBefore(m, extra).then(beforeResult => {
if (beforeResult === true) {
return;
}
}).catch(err => {
console.error('Error in plugin before:', err);
});
await processCommand(bot, ctx, m, text, chatId, userId, isGroup, user, chat, permissions);
}
};
global.dfail = (type, m, ctx, extra) => {
let messages = {
owner: 'This command only available for Developer!',
mods: 'This command only available for bot mods',
premium: 'This command only for premium users!',
group: 'This command only available on group!',
private: 'This command only available on private chat!',
admin: 'This command only available for group admins!',
botAdmin: 'Bot must be admin to use this command!',
register: 'You are not registered yet!\nPlease register first, example:\n/register nama.umur',
limit: `Your limit is insufficient to use this command!`,
restrict: 'This feature is not available right now!'
}[type];
if (messages) {
ctx.reply(messages);
}
};
let file = require.resolve(__filename);
fs.watchFile(file, () => {
fs.unwatchFile(file);
console.log(chalk.redBright("Update 'handler.js'"));
delete require.cache[file];
if (global.reloadHandler) global.reloadHandler();
});