This repository has been archived by the owner on Oct 30, 2024. It is now read-only.
forked from feliscatusmeows/robot-chicken
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chicken-bot.js
3816 lines (3582 loc) · 135 KB
/
chicken-bot.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
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* START OF IMPORTS */
require('./env.js') // load environment variables
const Mineflayer = require('mineflayer')
const minecraftData = require('minecraft-data')
const { pathfinder, Movements, goals: { GoalNear } } = require('mineflayer-pathfinder')
const tablist = require('mineflayer-tablist')
const repl = require('repl')
const fs = require('fs').promises
const axios = require('axios')
const FormData = require('form-data')
const { Vec3 } = require('vec3')
const langDetector = new (require('languagedetect'))
const moment = require('moment')
const levenshtein = require('fast-levenshtein')
const path = require('path')
const { Client, GatewayIntentBits, EmbedBuilder, WebhookClient, Attachment } = require('discord.js')
const { MessageContent, GuildMessages, Guilds, GuildMembers } = GatewayIntentBits
/* END OF IMPORTS */
/* START OF ERROR HANDLING OR LACK THEREOF */
process.on('uncaughtException', (error) => {
console.error(`An uncaught exception occurred at ${timestamp()}:`, error)
})
// process.on('unhandledRejection', (reason, promise) => {
// console.log('Unhandled Rejection at:', promise, 'reason:', reason)
// })
/* END OF ERROR HANDLING OR LACK THEREOF */
/* START OF CONSTANTS */
const START_TIME = moment()
const KIT_COOLDOWN_SECONDS = 20
const DUPE_COOLDOWN_SECONDS = 10
const STACK_COOLDOWN_SECONDS = 45
const DUPE_INTERVAL_SECONDS = 21
let BED_POS
try {
BED_POS = new Vec3(...process.env.BED.match(/(\S+),\s*(\S+),\s*(\S+)/).slice(1).map(Number))
} catch(error) {
log('BED env var is not set. It needs to be a comma-separated string, like 0,0,0')
log('Defaulting to 0,0,0')
BED_POS = new Vec3(0,0,0)
}
const OUR_WEBSITE = 'https://robot-chicken.neocities.org'
const DISPLAY_CHAT = true
const DATABASE = 'database.json'
const BLACKLIST_FILE = 'blacklist.json'
const ONE_MINUTE = 1 * 60 * 20
const FIVE_MINUTES = 5 * 60 * 20
const TEN_MINUTES = 10 * 60 * 20
const FIFTEEN_MINUTES = 15 * 60 * 20
const THIRTY_MINUTES = 30 * 60 * 20
const STACK_STOCK_CHANNEL_ID = '1155870004630265948'
const STACK_STOCK_INSTOCK_MESSAGE_ID = '1155871112224317591'
const STACK_STOCK_NEEDED_MESSAGE_ID = '1155871113209987162'
const RANDOM_CHANNEL_ID = '1113295878606831741'
const BRIDGE_CHANNEL_ID = '1113295943140380703'
const SOURCE_CHANNEL_ID = '1131397353107116193'
const PLAYER_CHANNEL_ID = '1135339325446426714'
const SOURCE_MESSAGE_ID = '1131398231868313670'
const KIT_RESTOCK_CHANNEL_ID = '1144706233471864983'
const LOGS_CHANNEL_ID = '1143955427864887426'
const SPAM_SIMILARITY_CHECK = 0.88
const PROMOTION_MESSAGES = [
',Try &dupe today! Make sure to have an enderchest nearby. You can see my other commands with &help',
",I'm opensource! Check out my current version with &source",
",Tired of duping manually? Just type &dupe, and you're set!",
',Get expert advice today with &askgpt command!',
',Drop by the discord bridge! `https://discord.gg/fegUKHTwQd',
",Try &kit today! You can see the list of kits here: `" + OUR_WEBSITE + '/#kits',
",Need to send someone items? Just &mail them!",
]
const COMMAND_PREFIXES = ['!', '&', '$', '?', '*', '%', '>', ':']
const WEBHOOK = process.env.WEBHOOK_ID ? new WebhookClient({ url: `http://discord.com/api/webhooks/1131047779817500793/${process.env.WEBHOOK_ID}` }) : null// thanks Cody4687
const VIP = [ // cooldown removed, more kits!
'6b1f7a3c-a1c3-491a-8514-12b6b90d9152', // antonymph
'1a88042a-5487-4250-9439-1a34347966aa', // antonymphs
'b8bdeeef-263b-4198-9f2a-ac3a8b825b36', // prljav
'be5480a2-ea06-4a7e-95dc-7ef54fed5f73', // _Nether_Chicken
'6e834b55-8f47-4990-ac7e-9731bc5fd11c', // PayTheParrot
'078f913d-d843-4cb3-8984-22545c593aa2', // lilkitkat1
'7a79368b-2235-4aba-a1cb-f88c06f03141', // Primooctopus33
'e7548b8c-8c05-480b-8c2d-a72eb3a6aa7d', // vaporii
'd02d076d-2949-47ef-83e2-936f2989d7d0', // vaporiii
'8be60c03-25c5-4e57-ab5d-0081e8736cf8', // lit_furnace
'9fb22b27-5fda-48ed-8a5a-ad6e1ff30d71', // X0Z0
'e0a6d498-e60d-448a-996b-93794fa4c767', // Thoriiii
'af12dc7d-fe8f-4524-a216-63b8a323e961', // xdarked
'956c20b7-2b99-4629-86b7-2b89b02fdfb1', // Autiboy08
'4acf26bd-be83-4fc2-a07e-fd93c08a2131', // _Robot_Duck
]
const VVIP = [ // reset and ban/unban priviledges!!
'6b1f7a3c-a1c3-491a-8514-12b6b90d9152', // antonymph
'1a88042a-5487-4250-9439-1a34347966aa', // antonymphs
'be5480a2-ea06-4a7e-95dc-7ef54fed5f73', // _Nether_Chicken
'4acf26bd-be83-4fc2-a07e-fd93c08a2131', // _Robot_Duck
]
const VVVIP = [ // tp and whisper command priviledge!!!
'be5480a2-ea06-4a7e-95dc-7ef54fed5f73', // _Nether_Chicken
'4acf26bd-be83-4fc2-a07e-fd93c08a2131', // _Robot_Duck
]
async function isRole(username, roleUuids) {
if(!bot?.players) {
return false
}
if (bot.players.hasOwnProperty(username)) {
return roleUuids.includes(bot.players[username].uuid)
} else {
let uuid = await fetchUuid(username)
return roleUuids.map(uuid => uuid.replaceAll('-', '')).includes(uuid)
}
}
function fetchUuid(username) {
return fetch(`https://api.mojang.com/users/profiles/minecraft/${username}`)
.then(data => data.json())
.then(player => player.id)
}
const DOUBLE_KITS = ['mapart']
const EXCLUSIVE_KITS = ['lava', 'obsidian', 'tnt', 'grief', 'mapart']
const KITS_2 = {
'kit' : BED_POS.offset( 4, 0, -17), // https://i.imgur.com/X7IwX5i.png
'sand' : BED_POS.offset( 4, 0, -16), // https://i.imgur.com/z0HkbVD.png
'lava' : BED_POS.offset( 4, 0, -15), // https://i.imgur.com/l0X8gJl.png
'signs' : BED_POS.offset( 4, 0, -14), // https://i.imgur.com/51ZzDuA.png
'end' : BED_POS.offset( 4, 0, -13), // https://i.imgur.com/SEB6z5T.png
'mapart' : BED_POS.offset( 4, 0, -12), // https://i.imgur.com/rV6yxTQ.png + https://i.imgur.com/gd3BBbI.png
'tesco' : BED_POS.offset( 4, 0, -10), // https://i.imgur.com/3NpGE4M.png
'eggs' : BED_POS.offset( 4, 0, -9), // https://i.imgur.com/JV1cr9Z.png
'lapis' : BED_POS.offset( 4, 0, -8), // https://i.imgur.com/Ehtas77.png
'cool-banners' : BED_POS.offset( 4, 0, -7), // https://i.imgur.com/dLgun4J.png
'test' : BED_POS.offset( 4, 0, -6), //
'duck' : BED_POS.offset( 4, 0, -5), //
'"commons"' : BED_POS.offset( 4, 0, -4), // https://i.imgur.com/hHmtE5g.png
'terraform' : BED_POS.offset( 4, 0, -3), // https://i.imgur.com/Sy4g6th.png
'red-sand' : BED_POS.offset( 4, 0, -2), // https://i.imgur.com/lHZPwja.png
}
const KITS_1 = {
'tree' : BED_POS.offset(-4, 0, 19), // https://i.imgur.com/nRUlj2e.png
'xp' : BED_POS.offset(-4, 0, 18), // https://i.imgur.com/R2xLcaf.png
'quartz' : BED_POS.offset(-4, 0, 17), // https://i.imgur.com/aOmIzRZ.png
'illegal' : BED_POS.offset(-4, 0, 16), // https://i.imgur.com/W3enroH.png
'nether' : BED_POS.offset(-4, 0, 15), // https://i.imgur.com/T1BKTHo.png
'boxbox' : BED_POS.offset(-4, 0, 14), // https://i.imgur.com/5o8f8Mp.png
'stone' : BED_POS.offset(-4, 0, 13), // https://i.imgur.com/LCd7lCf.png
'obsidian' : BED_POS.offset(-4, 0, 12), // https://i.imgur.com/HF64MdY.png
'toolbox' : BED_POS.offset(-4, 0, 11), // https://i.imgur.com/WgcQShb.png
'toolkit' : BED_POS.offset(-4, 0, 11), // https://i.imgur.com/WgcQShb.png
'tools' : BED_POS.offset(-4, 0, 11), // https://i.imgur.com/WgcQShb.png
'farming' : BED_POS.offset(-4, 0, 10), // https://i.imgur.com/jLJEUrP.png
'grass' : BED_POS.offset(-4, 0, 9), // https://i.imgur.com/g9fuVTo.png
'sponge' : BED_POS.offset(-4, 0, 8), // https://i.imgur.com/SA34fQk.png
'wood' : BED_POS.offset(-4, 0, 7), // https://i.imgur.com/FHTfrBS.png
'g-terracotta' : BED_POS.offset(-4, 0, 6), // https://i.imgur.com/x16gpe6.png
'beacon' : BED_POS.offset(-4, 0, 5), // https://i.imgur.com/hZphcFy.png
'autograph' : BED_POS.offset(-4, 0, 4), // https://i.imgur.com/5qfOHEl.png
'trans' : BED_POS.offset(-4, 0, 3), // https://i.imgur.com/qURiMsi.png
'flower' : BED_POS.offset(-4, 0, 2), // https://i.imgur.com/BaAj1gI.png
'misc' : BED_POS.offset(-4, 0, 1), // https://i.imgur.com/HU9YJHj.png
'tinyhouse' : BED_POS.offset(-4, 0, 0), // https://i.imgur.com/3T6K1NF.png
'redstone' : BED_POS.offset(-4, 0, -1), // https://i.imgur.com/5vNi2wJ.png
'dyes' : BED_POS.offset(-4, 0, -2), // https://i.imgur.com/nQfRnY8.png
'respawn' : BED_POS.offset(-4, 0, -3), // https://i.imgur.com/qfBne02.png
'totems' : BED_POS.offset(-4, 0, -4), // https://i.imgur.com/q1Xk1ew.png
'elytra' : BED_POS.offset(-4, 0, -5), // https://i.imgur.com/VMBNlqh.png
'travel' : BED_POS.offset(-4, 0, -5), // https://i.imgur.com/VMBNlqh.png
'fireworks' : BED_POS.offset(-4, 0, -5), // https://i.imgur.com/VMBNlqh.png
'dupe' : BED_POS.offset(-4, 0, -6), // https://i.imgur.com/dhe5sjH.png
'maps' : BED_POS.offset(-4, 0, -7), // https://i.imgur.com/xQRql7N.png
'light' : BED_POS.offset(-4, 0, -8), // https://i.imgur.com/Y4eq8HH.png
'storage' : BED_POS.offset(-4, 0, -9), // https://i.imgur.com/yj5xpOQ.png
'brewing' : BED_POS.offset(-4, 0, -10), // https://i.imgur.com/eoQgSkN.png
'wool' : BED_POS.offset(-4, 0, -11), // https://i.imgur.com/SC9qxaO.png
'terracotta' : BED_POS.offset(-4, 0, -12), // https://i.imgur.com/yiDnuPg.png
'concrete' : BED_POS.offset(-4, 0, -13), // https://i.imgur.com/0JmFmT1.png
'glass' : BED_POS.offset(-4, 0, -14), // https://i.imgur.com/3JQJe9N.png
'box' : BED_POS.offset(-4, 0, -15), // https://i.imgur.com/qJSI84f.png
'gaps' : BED_POS.offset(-4, 0, -16), // https://i.imgur.com/FclqKHf.png
'gapples' : BED_POS.offset(-4, 0, -16), // https://i.imgur.com/FclqKHf.png
'banner-maker' : BED_POS.offset(-4, 0, -17), // https://i.imgur.com/lLWDaQf.png
}
const HEX_CONVERSION_CODES = {
"§0": "#000000",
"§1": "#0000AA",
"§2": "#00AA00",
"§3": "#00AAAA",
"§4": "#AA0000",
"§5": "#AA00AA",
"§6": "#FFAA00",
"§7": "#AAAAAA",
"§8": "#555555",
"§9": "#5555FF",
"§a": "#55FF55",
"§b": "#55FFFF",
"§c": "#FF5555",
"§d": "#FF55FF",
"§e": "#FFFF55",
"§f": "#FFFFFF",
}
const DISCORD_ROLES = {
"§0": '1127715959365435402',
"§1": '1127716592466280609',
"§2": '1127705116942798909',
"§3": '1127716846494306357',
"§4": '1127720350071914557',
"§5": '1127705372279439512',
"§6": '1127705636365414439',
"§7": '1127704942954676254',
"§8": '1127706101211734126',
"§9": '1127705253932974120',
"§a": '1127705116942798909',
"§b": '1127705859275898940',
"§c": '1127705686072115411',
"§d": '1127706161437749310',
"§e": '1127705778476810240',
"§f": '1127705022734545038',
}
class CommandHandler {
constructor() {
this.commands = []
}
register(commandClass) {
this.commands.push(commandClass)
}
getAll() {
return this.commands
}
get(commandId) {
for(const commandClass of this.commands)
if(commandClass.prototype.id == commandId || commandClass.prototype.aliases.includes(commandId))
return commandClass
}
matchCommand(commandMessage) {
let commandIds = this.commands.flatMap(command => [command.prototype.id].concat(command.prototype.aliases))
let commandRegex = `^(?:> )?(${commandIds.join('|')})( .*)?$`
return commandMessage.match(commandRegex)
}
handle(username, commandMessage) {
if(username == '_Robot_Chicken')
return
let match = this.matchCommand(commandMessage)
if(!match)
return
let commandId = match[1]
let args = match[2]?.trim()
let commandClass = this.get(commandId)
new commandClass(username, args).execute()
}
}
const commandHandler = new CommandHandler()
/* END OF CONSTANTS */
/* START OF GLOBAL VARS */
let bridgeChannel = null
let sourceChannel = null
let randomChannel = null
let playerChannel = null
let logsChannel = null
let stackChannel = null
let kitRestockChannel = null
let bot = null
let ticks = 0
let firstInit = true
let lastTipIx = null
let emojis = null
let lastMessage = null
let lastMessageTicks = null
let maintenance = false
let intentionalDeath = false
let intentionalDisconnect = false
let database = null
let isWalking = false
let ll = null
let chatCache = []
let speakQueue = []
let speaking = false
let lock = null
let critical = false
let recentlyDisconnected = false
let blacklist = []
let tpingTo = null
let lastUpdatedImgTabTicks = 0
let savingDatabase = false
let savingBlacklist = false
let discordClient = null
/* END OF GLOBAL VARS */
/* START OF DISCORD FUNCTIONS */
function makeBoldUsername(username) {
let normalChars = 'ABCDEFGHIJKLMNOPQRSTUVWYXZabcdefghijklmnopqrstuvwyxz1234567890_'
let boldChars = '𝐀𝐁𝐂𝐃𝐄𝐅𝐆𝐇𝐈𝐉𝐊𝐋𝐌𝐍𝐎𝐏𝐐𝐑𝐒𝐓𝐔𝐕𝐖𝐘𝐗𝐙𝐚𝐛𝐜𝐝𝐞𝐟𝐠𝐡𝐢𝐣𝐤𝐥𝐦𝐧𝐨𝐩𝐪𝐫𝐬𝐭𝐮𝐯𝐰𝐱𝐲𝐳𝟏𝟐𝟑𝟒𝟓𝟔𝟕𝟖𝟗𝟎_'
let result = ''
for(let i=0; i < username.length; i++)
result += boldChars[normalChars.indexOf(username[i])]
return result
}
async function updateIgnColorIfNeeded(rawUsername) {
let possibleColorCode = rawUsername.substring(0,2)
let isBold = rawUsername.includes('§l')
let actualColor = HEX_CONVERSION_CODES[possibleColorCode] ?? null
let username = rawUsername.replaceAll(/§./g, '')
if(actualColor == null)
return
if(!HEX_CONVERSION_CODES.hasOwnProperty(possibleColorCode)) {
log(`Unknown color code: ${possibleColorCode}`)
return
}
let targetRoleId = DISCORD_ROLES[possibleColorCode]
let discordTag = null
for (const [discordUsername, ign] of Object.entries(database.verification)) {
if (ign === username) {
discordTag = discordUsername
break
}
}
if(!discordTag) {
log(`Discord user not found for ign ${username}`)
return
}
if(!bridgeChannel)
return
let guildMember = bridgeChannel.guild.members.cache.find(member => member.user.tag == discordTag)
await bridgeChannel.guild.roles.fetch()
if(!guildMember) {
log('GuildMember not found')
return
}
if(username != '_Nether_Chicken') {
if(isBold) {
guildMember.setNickname(makeBoldUsername(username))
} else if(guildMember.nickname) {
guildMember.setNickname('')
}
}
if(!guildMember.roles) {
log('GuildMember.roles not found')
return
}
let currentRole = guildMember.roles.cache.filter(role => role.name != '@everyone').at(0)
let targetRole = bridgeChannel.guild.roles.cache.get(targetRoleId)
if(!targetRole) {
log('Target role not found')
return
}
if(currentRole) {
if(currentRole.id == targetRoleId)
return
try {
guildMember.roles.remove(currentRole)
} catch(error) {
console.error(`error changing ${username}'s role:`, error)
}
}
guildMember.roles.add(targetRole)
}
function initDiscord() {
discordClient = new Client({ intents: [Guilds, GuildMessages, MessageContent, GuildMembers] })
if(!process.env.DISCORD_BOT_KEY) {
log('No discord bot key provided')
log('Disabling discord functionality')
return
}
discordClient.login(process.env.DISCORD_BOT_KEY)
discordClient.once('ready', async c => {
log(`Discord bot logged in as ${c.user.tag}`)
bridgeChannel = discordClient.channels.cache.get(BRIDGE_CHANNEL_ID)
sourceChannel = discordClient.channels.cache.get(SOURCE_CHANNEL_ID)
randomChannel = discordClient.channels.cache.get(RANDOM_CHANNEL_ID)
playerChannel = discordClient.channels.cache.get(PLAYER_CHANNEL_ID)
logsChannel = discordClient.channels.cache.get(LOGS_CHANNEL_ID)
stackChannel = discordClient.channels.cache.get(STACK_STOCK_CHANNEL_ID)
kitRestockChannel = discordClient.channels.cache.get(KIT_RESTOCK_CHANNEL_ID)
bridgeChannel.guild.members.fetch()
// discordClient.application.commands.set([])
for(const commandClass of commandHandler.getAll()) {
if(commandClass.prototype.slashCommand) {
let commandData = {
name: commandClass.prototype.id.replace('&', '').toLowerCase(),
description: commandClass.prototype.description
}
if(commandClass.prototype.args) {
commandData.options = [
{
type: 3,
name: 'arg',
description: commandClass.prototype.args?.replaceAll(/[\[\]<>]/g, ''),
required: commandClass.prototype.args?.match('<.+>')
&& !commandClass.prototype.args?.match(/\[.+\]/)
}
]
}
const command = discordClient.application.commands.create(commandData)
}
}
discordClient.on('interactionCreate', async interaction => {
if (!interaction.isCommand())
return
let author = `${interaction.user.username}#${interaction.user.discriminator}`
let isAuthorVerified = database.verification.hasOwnProperty(author)
if(isAuthorVerified)
author = database.verification[author]
const commandClass = commandHandler.get('&' + interaction.commandName)
if(commandClass) {
let username = isAuthorVerified ? author : '_Robot_Chicken'
if(interaction.options?._hoistedOptions.length > 0) {
const args = interaction.options._hoistedOptions[0].value
speak(`${author} used /${interaction.commandName} ${args}`)
new commandClass(username, args).execute()
} else {
speak(`${author} used /${interaction.commandName}`)
new commandClass(username).execute()
}
} else {
log('No command class matched')
}
const okMessages = ['ok', 'done', 'fr', 'for real', 'nice', 'sent', 'processed', 'computed', 'discord wont lemme sent empty replies', 'for shizzle', 'ong', 'on god', 'ong god', 'alr', 'aite', 'ite', 'ight', 'aight']
let reply = okMessages[Math.floor(Math.random() * okMessages.length)].replaceAll(" ", "%20")
await interaction.reply({content: `https://cataas.com/cat/cute/says/${reply}?0b0t=${Math.floor(Date.now() / 1000)}`, ephemeral: true})
})
if (!bridgeChannel) {
log(`I could not find the bridge channel!`)
process.exit(1)
}
if (!sourceChannel) {
log(`I could not find the source channel!`)
process.exit(1)
}
if (!randomChannel) {
log(`I could not find the random channel!`)
process.exit(1)
}
})
discordClient.on('error', error => {
console.error('A websocket connection encountered an error:', error)
})
discordClient.on('messageCreate', async message => {
if (message.webhookId) return
let author = `${message.author.username}#${message.author.discriminator}`
if(author == '_Robot_Chicken#3088')
return
let content = message.content
if(content == '&source') {
let sourceUrl = await new SourceCommand(null, true).execute()
message.channel.send(`${author}, I just updated my source code at ${sourceUrl}`)
}
if(content == '&verify') {
VerifyCommand.generateCode()
VerifyCommand.verificationUsername = author
message.author.send(`Send ${VerifyCommand.verification} in-game within 30s to verify your username`)
VerifyCommand.clearAfterSeconds(30)
}
if(content == VerifyCommand.verification) {
database.verification[author] = VerifyCommand.verificationUsername
while(!bot)
await sleeps(1)
bot.chat(`/w ${VerifyCommand.verificationUsername} you are now verified`)
saveDatabase()
return
}
if(database.verification.hasOwnProperty(author))
author = database.verification[author]
if(author == 'XDARKED')
author = 'xdarked'
if (message.channel.id !== bridgeChannel.id) return
let removedNewlines = content.replaceAll(/\n|\r/g, '').trim()
let authorTag = `[${author}]`
let messageBlocks = splitStringIntoBlocks(removedNewlines, 96 - authorTag.length)
for(const msg of messageBlocks) {
let line = `${authorTag}: \`${msg}`
await getEmojis()
Object.entries(emojis).forEach(([emoji, convertedEmoji]) => {
line = line.replaceAll(emoji, `:${convertedEmoji}:`)
})
log('Discord: ' + line)
speak(preventDegeneracy(line))
}
if(author == '_Nether_Chicken' && content.startsWith('&'))
commandHandler.handle('_Nether_Chicken', content)
})
}
async function updatePlayerTabImg() {
if(!bot?.players || !playerChannel)
return
if(ticks % 2 == 0)
return
let playerPingList = Object.keys(bot.players)
.sort((p1, p2) => p1.localeCompare(p2, undefined, { sensitivity: 'base' }))
.map(player => `${player}:${bot.players[player].ping}`)
let existingMessages = await playerChannel.messages.fetch()
for(let i=0; i < existingMessages.size; i++) {
try {
await existingMessages.at(i).delete().catch(()=>{})
} catch(error) { }
}
let tablistBase64 = null
try {
tablistBase64 = await bot.tablist.renderToBase64()
} catch (error) {
log('Failed updating player tab img:')
log(error)
}
if(!tablistBase64)
return
const buffer = Buffer.from(tablistBase64.replace("data:image/png;base64,",""), 'base64')
const attachment = new Attachment(buffer, { name: 'playerlist.png', contentType: 'image/png' })
try {
await playerChannel.send({
files: [
{
contentType: 'image/png',
name: 'playerlist.png',
attachment: buffer
}
],
flags: [4096]
})
lastUpdatedImgTabTicks = ticks
} catch(error) {
log('Failed updating player tab img')
}
}
function forwardDiscordBridge(username, message, server) {
if(isSpam(message)) {
return
}
let oddUsername = username.match('.*[❘| ].*')
message = message.split('@everyone').join(`*@*everyone`)
message = message.split('@here').join(`*@*here`)
message = message.replaceAll('~', '\\~')
message = message.replaceAll('_', '\\_')
message = message.replaceAll('*', '\\*')
username = username.replaceAll('_', '\_')
message = message.replaceAll(/((?:https?:\/\/)?(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&//=]*))/g, '<$1>') // 3 votes **ahead**
message = message.trim()
if(!message)
return
if(server) {
WEBHOOK?.send({
content: message,
username: '[Server]',
avatarURL: `http://styles.redditmedia.com/t5_3f7j6/styles/communityIcon_1ym4m7ga94231.png`,
flags: [4096] // thanks diamondFTW!
})
} else {
WEBHOOK?.send({
content: message,
username: username,
avatarURL: `http://mc-heads.net/head/${oddUsername ? '0385': username}`,
flags: [4096] // thanks diamondFTW!
})
}
}
/* END OF DISCORD FUNCTIONS */
/* START DATABASE-RELATED FUNCTIONS */
async function clearUpdateLockFile() {
try {
const filePath = path.join(__dirname, "updateInProgress")
await fs.unlink(filePath)
} catch (err) {
console.error(`Error deleting file: ${err}`)
if (err.code != 'ENOENT')
process.exit(1)
}
}
function isUpdating() {
const filePath = path.join(__dirname, "updateInProgress")
try {
fs.accessSync(filePath)
return true
} catch (error) {
return false
}
}
function initBlacklist() {
fs.access(BLACKLIST_FILE, fs.constants.F_OK)
.then(() => {
return fs.readFile(BLACKLIST_FILE, 'utf8')
})
.then((data) => {
log('Read blacklist: ')
blacklist = JSON.parse(data)
log('\n' + JSON.stringify(blacklist, null, 2))
})
.catch((err) => {
console.error(err)
process.exit(1)
})
}
function initDatabase() {
fs.access(DATABASE, fs.constants.F_OK)
.then(() => {
return fs.readFile(DATABASE, 'utf8')
})
.then((data) => {
log('Read database: ')
database = JSON.parse(data)
if(!database.hasOwnProperty('stock')) {
database.stock = {}
}
log('\n' + JSON.stringify(database, null, 2))
})
.catch((err) => {
if (err.code === 'ENOENT') {
database = { dupeCount: {} }
const json = JSON.stringify(database)
return fs.writeFile(DATABASE, json)
} else {
console.error(err)
process.exit(1)
}
})
.catch((err) => {
console.error(err)
process.exit(1)
})
}
async function incrementFagCounter(username, message) {
log('Incrementing fag counter')
let hard = (message.match(/\bfaggot(s)?\b/g) || []).length
let soft = (message.match(/\bfag(s)?\b/g) || []).length
if(!database.hasOwnProperty('fagCounter'))
database.fagCounter = {}
if(!database.fagCounter[username])
database.fagCounter[username] = [0,0]
database.fagCounter[username][0] += hard
database.fagCounter[username][1] += soft
saveDatabase()
}
function incrementDupeCount(username) {
if(!database.dupeCount.hasOwnProperty(username))
database.dupeCount[username] = lock.itemCount
else
database.dupeCount[username] += lock.itemCount
saveDatabase()
}
function incrementKitCount(username) {
if(!database.hasOwnProperty('kitCount'))
database.kitCount = {}
if(!database.kitCount.hasOwnProperty(username))
database.kitCount[username] = 1
else
database.kitCount[username] += 1
saveDatabase()
}
function saveBlacklist() {
savingBlacklist = true
return fs.writeFile(BLACKLIST_FILE, JSON.stringify(blacklist))
.then(() => {
savingBlacklist = false
log('Blacklist saved successfully.')
})
.catch((err) => {
console.error(err)
process.exit(1)
})
}
function saveDatabase() {
savingDatabase = true
if(savingDatabase)
return
return fs.writeFile(DATABASE, JSON.stringify(database))
.then(() => {
savingDatabase = false
log('Database saved successfully.')
})
.catch((err) => {
console.error(err)
process.exit(1)
})
}
/* END DATABASE-RELATED FUNCTIONS */
/* START OF AUXILIARY TEXT FUNCTIONS */
function timestamp() {
return moment().subtract(3, 'hours').format('YYYY-MM-DD HH:mm:ss')
}
function log(message, chat) {
if(!DISPLAY_CHAT && chat)
return
console.log(`[${timestamp()}][${chat ? 'CHAT' : 'SELF'}]: ${message}`)
if(logsChannel && !chat)
if(message) {
if(typeof message !== 'string')
message = message.toString()
logsChannel.send(message)
}
}
async function getEmojis() {
if(!emojis) {
try {
const response = await axios.get('http://pastebin.com/raw/LhQek0L1') // thanks diamondFTW !!
emojis = response.data
} catch (error) {
console.error('Error loading remote JSON:', error.message)
return null
}
}
return emojis
}
function isSpam(newMessage) {
let obfuscatedUrlHuntingCompatible = newMessage.replaceAll(/[^A-Za-z0-9]/g, '').toLowerCase()
if(['anarchymc0rg', 'mcalphaanarchyonline'].some(ouhc => obfuscatedUrlHuntingCompatible.includes(ouhc)))
return true
if(newMessage.match('<@&?[0-9]+>'))
return true
if(commandHandler.matchCommand(newMessage))
return false
let newMessageLength = newMessage.length
let matchCount = 0
for(const chatMsg of chatCache) {
let [_, msg] = chatMsg
let msgDistance = levenshtein.get(msg, newMessage)
let oldMsgLength = msg.length
if(msgDistance/oldMsgLength < 1 - SPAM_SIMILARITY_CHECK)
matchCount += 1
}
return matchCount > 1
}
async function checkAfk(username, message) {
if(username == '_Robot_Chicken')
return
if(AfkCommand.afkPlayers.hasOwnProperty(username)) {
delete AfkCommand.afkPlayers[username]
}
Object.keys(AfkCommand.afkPlayers).forEach((afkPlayer) => {
if(message.toLowerCase().includes(afkPlayer.toLowerCase())) {
let [afkStart, afkReason] = AfkCommand.afkPlayers[afkPlayer]
let afkTime = moment.duration(moment().diff(afkStart))
let afkWarnMessage = `${username}, ${afkPlayer} has been AFK for ${afkTime.humanize()}`
if(afkReason)
afkWarnMessage += ` for ${afkReason}`
speak(afkWarnMessage)
}
})
}
function splitStringIntoBlocks(str, blockSize) {
const blocks = []
let currentIndex = 0
while (currentIndex < str.length) {
let currentBlockSize = blockSize
while (currentIndex + currentBlockSize < str.length && !/\s/.test(str[currentIndex + currentBlockSize]))
currentBlockSize++
blocks.push(str.substring(currentIndex, currentIndex + currentBlockSize))
currentIndex += currentBlockSize
while (currentIndex < str.length && /\s/.test(str[currentIndex]))
currentIndex++
}
return blocks
}
function preventDegeneracy(message) {
if(!message)
return message
return message
.replaceAll(/\bkill\b/ig, ' love ')
.replaceAll(/torture/ig, 'appreciate')
.replaceAll(/crime/ig, 'academic paper')
.replaceAll(/molest/ig, 'respect')
.replaceAll(/child/ig, 'grown man')
.replaceAll(/\bkid\b/ig, ' grown man ')
.replaceAll(/infant/ig, 'grown man')
.replaceAll(/\bboy\b/ig, ' grown man ')
.replaceAll(/minor/ig, 'grown man')
.replaceAll(/\bsex\b/ig, ' something I have never had ')
.replaceAll(/\brape\b/ig, ' help ')
.replaceAll(/nigger/ig, 'digger')
.replaceAll(/nigga/ig, 'digga')
}
function shamelessSelfPromotion() {
let tipIx = null
while(!tipIx || tipIx == lastTipIx)
tipIx = Math.floor(Math.random() * PROMOTION_MESSAGES.length)
speak(PROMOTION_MESSAGES[tipIx])
lastTipIx = tipIx
}
async function speakRoutine() {
if(speaking)
return
if(speakQueue.length == 0)
return
let initTicks = ticks
speaking = true
let message = speakQueue.shift()
while(ticks - lastMessageTicks < 80)
await sleep(20)
while(isWalking)
await sleep(20)
try {
bot.chat(message)
lastMessage = message
lastMessageTicks = ticks
} catch (error) {
log('Chat error pls fix me:')
log(error)
}
speaking = false
}
async function copypasta(username) {
let bedtimeStory = `Who the fuck are you saying "hi" to? This is 0b0t motherfucker there's only psychopaths, murderers and white-collar criminals in here. If you have the audacity to say "hello" or "good morning" you can fuck off right back to Hypixel, you hear me? This place is not for your pleasantries or cordiality; it's a realm for the twisted, the deranged, and the devious. So watch your step and adjust your attitude accordingly. You think you can waltz into this dark corner of the internet and expect warm greetings? Well, you've got another thing coming. We thrive on chaos, anonymity, and lawlessness here. This is the realm where maddened minds rejoice, where illicit dealings unfold in the shadows. We don't care about your social norms or your delicate sensibilities. So take your "hellos" and "good mornings" and shove them up your ass. If you can't handle the grit and the grime, the blood and the betrayal, then get the fuck out. This is not a place for the faint-hearted or the easily swayed.`
for(const msg of splitStringIntoBlocks(bedtimeStory, 99))
speak(msg)
}
/* END OF AUXILIARY TEXT FUNCTIONS */
/* START OF COMMAND DECLARATIONS */
class Command {
constructor(username) {
this.username = username
this.startTicks = ticks
}
execute() {}
}
function registeredCommand(id, args, description, slashCommand, aliases) {
return function (commandClass) {
commandClass.prototype.id = id
commandClass.prototype.args = args
commandClass.prototype.description = description
commandClass.prototype.slashCommand = slashCommand
commandClass.prototype.aliases = aliases
commandHandler.register(commandClass)
return commandClass
}
}
@registeredCommand('&mute', "<username>", "ignores a delinquent", true, ['&ignore'])
class IgnoreCommand extends Command {
constructor(username, delinquent) {
super(username)
this.delinquent = delinquent
}
async execute() {
let isVVIP = await isRole(this.username, VVIP)
if(isVVIP) {
bot.chat(`/ignore ${this.delinquent}`)
log(`Ignored ${this.delinquent}`)
// speak(`Ignored ${this.delinquent}`)
} else {
log(`${this.username} tried to ignore ${this.delinquent}, but doesn't have the needed role`)
}
}
}
@registeredCommand('&users', "", "shows how many have requested my assistance", true, ['&players'])
class UsersCommand extends Command {
async execute() {
let usersCount = Set(Object.keys(database.dupeCount).concat(Object.keys(database.kitCount))).size
log(`${userCount} users have requested my assistance in some way`)
}
}
@registeredCommand('&ban', "<username>", "bans a delinquent", true, [])
class BanCommand extends Command {
constructor(username, delinquent) {
super(username)
this.delinquent = delinquent
}
async execute() {
let isVVIP = await isRole(this.username, VVIP)
if(isVVIP) {
if(blacklist.includes(this.delinquent))
return
blacklist.push(this.delinquent)
saveBlacklist()
log(`Banned ${this.delinquent}. The blacklist is now ${blacklist.length} long`)
speak(`Banned ${this.delinquent}`)
} else {
log(`${this.username} tried to ban ${this.delinquent}, but doesn't have the needed role`)
}
}
}
@registeredCommand('&namemc', "[username]", "shows up to three last name changes of the player", true, ['&namehistory', '&history'])
class NameMcCommand extends Command {
constructor(username, targetUser) {
super(username)
this.targetUser = targetUser
}
async execute() {
if(!this.targetUser) {
this.targetUser = this.username
return
}
let uuid = await fetchUuid(this.targetUser)
axios.get(`http://laby.net/api/user/${uuid}/get-names`, {
headers: {
'User-Agent': 'Axios/5.0 (compatible; robot-chicken/1.0; +https://github.com/nether-chicken)',
}
}).then((response) => {
const nameChanges = response.data
let last3NameChanges = nameChanges.slice(-4, -1).reverse()
if(last3NameChanges.length == 0) {
speak(`${this.targetUser} has not had their name changed recently`)
} else {
speak(`${this.targetUser} has had at least ${nameChanges.length - 1} name changes.`)
speak(`${last3NameChanges.length == 1 ? 'This is' : 'These are'} the last ${last3NameChanges.length}: `
+ last3NameChanges.map(nameChange => nameChange.username).join(', '))
}
})
.catch((error) => {
speak('laby.net is unavailable at this moment. Frankly, terrible!')
log(`Error: ${error.message}`)
})
}
}
@registeredCommand('&unban', "<username>", "unbans a reformed individual", true, [])
class UnbanCommand extends Command {
constructor(username, reformedIndividual) {
super(username)
this.reformedIndividual = reformedIndividual
}
async execute() {
let isVVIP = await isRole(this.username, VVIP)
if(isVVIP) {
blacklist = blacklist.filter((user) => user !== this.reformedIndividual)
saveBlacklist()
log(`Unbanned ${this.reformedIndividual}. The blacklist is now ${blacklist.length} long`)
// speak(`Unbanned ${this.reformedIndividual}`)
} else {
log(`${this.username} tried to unban ${this.reformedIndividual}, but doesn't have the needed role`)
}
}
}
@registeredCommand("&help", "[command]", "shows a command's description", true, [])
class HelpCommand extends Command {
constructor(username, commandId) {
super(username)
this.commandId = commandId
}
execute() {
if(this.commandId) {
if(!this.commandId.startsWith('&'))
this.commandId = '&' + this.commandId
let commandClass = commandHandler.get(this.commandId)
if(commandClass) {
let helpString = commandClass.prototype.id + ' ' +
commandClass.prototype.args + ' - ' +
commandClass.prototype.description
speak(helpString)
} else {
speak(`< There's no such command YET`)
}
} else {
speak(`You can see all the commands here: \`${OUR_WEBSITE}/#commands`)
}