forked from feliscatusmeows/robot-chicken
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chicken-bot.js
2780 lines (2594 loc) · 94.7 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 { 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)
// })
process.on('SIGTERM', () => {
log('Got SIGTERM')
while(savingDatabase || savingBlacklist) {
log('Waiting for file writes to shut down')
saveDatabase()
saveBlacklist()
sleeps(1)
}
process.exit(0)
})
/* END OF ERROR HANDLING OR LACK THEREOF */
/* START OF CONSTANTS */
const START_TIME = moment()
const BED_POS = new Vec3(...process.env.BED.match(/(\S+),(\S+),(\S+)/).slice(1).map(Number))
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 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 here: `" + OUR_WEBSITE,
",Need to send someone items? Just &mail them!",
]
const COMMAND_PREFIXES = ['!', '&', '$', '?', '*', '%', '>', ':']
const WEBHOOK = new WebhookClient({ url: `http://discord.com/api/webhooks/1131047779817500793/${process.env.WEBHOOK_ID}` }) // thanks Cody4687
const VIP = [ // cooldown removed, more kits!
'antonymph',
'antonymphs',
'AstolfoIsKing',
'prljav',
'_Nether_Chicken',
'PayTheParrot',
'lilkitkat1',
'Primooctopus33',
'vaporii'
]
const VVIP = [ // reset priviledges!!
'antonymph',
'antonymphs',
'_Nether_Chicken'
]
const VVVIP = [ // tp and whisper command priviledge!!!
'_Nether_Chicken'
]
const DOUBLE_KITS = ['mapart']
const EXCLUSIVE_KITS = ['lava', 'obsidian', 'tnt', 'grief']
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
}
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
'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)
return commandClass
}
matchCommand(commandMessage) {
let commandIds = this.commands.map(command => command.prototype.id)
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 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 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
/* 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() {
const client = new Client({ intents: [Guilds, GuildMessages, MessageContent, GuildMembers] })
client.login(process.env.DISCORD_BOT_KEY)
client.once('ready', c => {
log(`Discord bot logged in as ${c.user.tag}`)
bridgeChannel = client.channels.cache.get(BRIDGE_CHANNEL_ID)
sourceChannel = client.channels.cache.get(SOURCE_CHANNEL_ID)
randomChannel = client.channels.cache.get(RANDOM_CHANNEL_ID)
playerChannel = client.channels.cache.get(PLAYER_CHANNEL_ID)
logsChannel = client.channels.cache.get(LOGS_CHANNEL_ID)
kitRestockChannel = client.channels.cache.get(KIT_RESTOCK_CHANNEL_ID)
bridgeChannel.guild.members.fetch()
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)
}
})
client.on('error', error => {
console.error('A websocket connection encountered an error:', error)
})
client.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.startsWith('&ban') && author == '_nether_chicken#0') {
ban(content.substring(4).trim())
return
}
if(content.startsWith('&unban') && author == '_nether_chicken#0') {
unban(content.substring(6).trim())
return
}
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)
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()
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]
}).then(() => {
for(let i=0; i < existingMessages.size; i++) {
existingMessages.at(i).delete()
.then(()=>{})
.catch(()=>{})
}
})
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)
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)
}
})
.then(() => {
log('Database file created.')
})
.catch((err) => {
console.error(err)
process.exit(1)
})
}
async function ban(username) {
if(blacklist.includes(username))
return
blacklist.push(username)
saveBlacklist()
}
async function unban(username) {
blacklist = blacklist.filter((user) => user !== username)
saveBlacklist()
}
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
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(typeof message !== 'string')
message = message.toString()
if(!DISPLAY_CHAT && chat)
return
console.log(`[${timestamp()}][${chat ? 'CHAT' : 'SELF'}]: ${message}`)
if(logsChannel && !chat)
if(message)
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) {
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) {
return function (commandClass) {
commandClass.prototype.id = id
commandClass.prototype.args = args
commandClass.prototype.description = description
commandHandler.register(commandClass)
return commandClass
}
}
@registeredCommand("&help", "[command]", "shows a command's description")
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`)
}
}
}
@registeredCommand("&bible", "<query>", "shows a bible verse containing the queried string")
class BibleCommand extends Command {
constructor(username, query) {
super(username)
this.query = query
}
async execute() {
if(!this.query) {
speak(`&bible requires a query`)
return
}
const url = 'http://bible-go-api.rkeplin.com/v1/search'
axios.get(url, {
params: {
query: this.query
}
}).then((response) => {
const items = response.data.items
if(!items) {
speak(`${this.query} is not contained in this bible`)
return
}
let verseIx = Math.floor(Math.random() * items.length)
let blocks = splitStringIntoBlocks(items[verseIx].verse.replaceAll(/<.+?>/g, ''), 99)
for(const block of blocks)
speak(block)
})
.catch((error) => {
speak('The Bible is unavailable at this moment. Surely the work of the Devil.')
log(`Error: ${error.message}`)
})
}
}
@registeredCommand("&github", "", "shows the github url")
class GitHubCommand extends Command {
execute() {
speak("This is my github repo: https://github.com/nether-chicken/robot-chicken.")
speak("Remember that I may or may not be currently running the github repo code, but &source is always up to date")
}
}
@registeredCommand("&endportal", "", "shows the closest endportal to spawn")
class EndPortalCommand extends Command {
execute() {
speak("X: 1888 Z: -30 is the closest end portal to spawn! Going to the end allows you to tpa to anyone, and is quicker then escaping.")
}
}
@registeredCommand("&godsword", "", "Terry Davis' gw program")
class GwCommand extends Command {
async execute() {
const url = 'http://raw.githubusercontent.com/orhun/godsays/master/Happy.TXT'
axios.get(url)
.then(response => {
const data = response.data
const lines = data.split('\n')
const randomLines = lines
.sort(() => 0.5 - Math.random())
.slice(0, 16)
.join(' ')
let blocks = splitStringIntoBlocks(randomLines, 99)
for(const block of blocks)
speak(block)
})
.catch(error => {
console.error(`Error: ${error.message}`)
})
}
}
@registeredCommand("&afk", "[reason]", "sets you as AFK and warns anyone who tries to contact you in chat")
class AfkCommand extends Command {
static afkPlayers = {}
constructor(username, reason) {
super(username)
this.reason = reason
}
execute() {
log(`Setting ${this.username} as AFK`)
let afkMessage = `${this.username} is now set as AFK`
if(this.reason)
afkMessage += `: ${this.reason}`
speak(afkMessage)
AfkCommand.afkPlayers[this.username] = [moment(), this.reason]
}
}
@registeredCommand("&howdupe", "", "shows Aspect's video on how to dupe")
class HowDupeCommand extends Command {
execute() {
speak(`Here's how to dupe: https://www.youtube.com/watch?v=TdoypGpkcz0`)
}
}
@registeredCommand("&topfslur", "<hard|soft>", "shows the fslur leaderboard")
class TopFslurCommand extends Command {
constructor(username, args) {
super(username)
this.args = args
}
execute() {
let [, degree] = this.args?.match(/^(hard|soft)?$/) || []
if(!degree) {
speak(`Invalid args, use &topfslur <hard|soft>`)
return
}
const entries = Object.entries(database.fagCounter)
let sortedEntries = null
if(degree == 'hard') {
sortedEntries = entries.sort((a, b) => b[1][0] - a[1][0])
} else if(degree == 'soft'){
sortedEntries = entries.sort((a, b) => b[1][1] - a[1][1])
}
const top3FCallers = sortedEntries.slice(0, 3)
let ix = 1
let scoreboard = []
top3FCallers.forEach(([user, count]) => {
scoreboard.push(`#${ix++}: ${user} - ${count[degree == 'hard' ? 0 : 1]}`)
})
speak(scoreboard.join(' | '))
}
}
@registeredCommand("&fslur", "[username]", "shows fslur count of the player")
class FslurCommand extends Command {
constructor(username, args) {
super(username)
this.args = args
}
execute() {
let user = this.args?.trim()
if(!user)
user = this.username
if(!database.hasOwnProperty('fagCounter'))
database.fagCounter = {}
if(database.fagCounter?.hasOwnProperty(user)) {
let hardCount = database.fagCounter[user][0]
let softCount = database.fagCounter[user][1]
if(hardCount == 0 && softCount == 0)
speak(`> ${user} has not said the f slur YET.`)
else
speak(`> ${user}: Hard T: ${hardCount}, Normal: ${softCount}`)
} else {
speak(`> ${user} has not said the f slur YET.`)
}
}
}
@registeredCommand("&uptime", "", "shows the bot's current uptime")
class UptimeCommand extends Command {
execute() {
const duration = moment.duration(moment().diff(START_TIME))
speak(`I have been up for ${duration.humanize()}`)
}
}
@registeredCommand("&kits", "", "shows the kit menu")
class KitsCommand extends Command {
execute() {
speak(`You can check the list of kits and their IDs here: \`${OUR_WEBSITE}`)
}
}
@registeredCommand("&kitCount", "[username]", "shows the amount of kits the user got out of me")
class KitCount extends Command {
constructor(username, kitCountPlayer) {
super(username)
this.kitCountPlayer = kitCountPlayer
}
execute() {
if(this.kitCountPlayer) {
if(database.kitCount.hasOwnProperty(this.kitCountPlayer)) {
let kitsCount = database.kitCount[this.kitCountPlayer]
speak(`I have given ${kitsCount} kits to ${this.kitCountPlayer}`)
} else {
speak(`I have never given ${this.kitCountPlayer} a kit`)