-
Notifications
You must be signed in to change notification settings - Fork 1
/
gateway.js
3450 lines (3120 loc) · 137 KB
/
gateway.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
var WebSocket = require("ws").WebSocket;
var https = require("https");
var fs = require("fs");
var identify = {"op":2,"d":{"intents":37619,"properties":{"$os":process.platform,"$browser":"node","$device":"firework_gateway"},"token":(JSON.parse(fs.readFileSync("gateway_static/token.json").toString())).token}};
var currentGatewayUrl = 'wss://gateway.discord.gg';
var heartbeatThreadingInterval = 500;
var reconnectInterval = 4000;
var occasionalSaveSize = 100000;
var lastSaveSize = 0;
var userMap = new Map(); // user_id -> user_obj
var activityMap = new Map(); // user_id -> map<timestamp,customStatus/Activity>
var memberMap = new Map(); // guild_id -> map<member_id,members> (contains roles+nick+boost+mute)
var channelMap = new Map(); // channel_id -> channel_obj
var threadMap = new Map(); // thread_id -> thread_obj
var channelToGuildMap = new Map(); // channel_id -> guild_id
var guildNameMap = new Map(); // guild_id -> string
var guildOwnerMap = new Map() // guild_id -> user_id
var rolePositions = new Map();// role_id -> number (used to sort role orders when user leaves)
var userXpMap = new Map(); // guild_id -> map<member_id,xpobj>
// xpobj := {xp:int,lvl:int,lastxptime:time,message_count:int}
var userDmMap = new Map(); // user_id -> channel_id
var sents = [];
var SAVECRASHCATCHDUMP = null;
var FORCE_OCCASIONAL_SAVE = false;
var beta = false; // sets which set of modules to use (prevents spam when debugging)
var version = (beta?'β':'v')+'1.40.';
// privilaged intents codes:
// w/o w/
// 32509 53608447
// avatars: https://cdn.discordapp.com/avatars/{uid}/{avatar_hash}.png?size=4096
var g_wofcs= "713127035156955276"
var g_anp ="1186141783856513024"
var c_dm = "870868315793391686"
var c_fire = "870500800613470248" // firework-playground
var c_audit = "750509276707160126" // wofcs audit
var c_anp_audit = "1186187875189018634"
var u_selk = "163718745888522241"
var r_mod = "724461190897729596"
var r_modling = "739602680653021274"
var r_botwing = "713510512150839347"
var SNOWFLAKE_ONE_MONTH = "11234023833600000" // 17 digits starts with 11
// oldest: "49230618424246272" // 17 digits starts with 49
// me: "163718745888522241" // 18 digits starts with 16
// 2022: "1000000000000000000" // 19 digits
// 2024: ~12
var dispatchTypes = [ // GUILDS (1 << 0)
"GUILD_CREATE", "GUILD_UPDATE", "GUILD_DELETE", "GUILD_ROLE_CREATE", "GUILD_ROLE_UPDATE", "GUILD_ROLE_DELETE",
"CHANNEL_CREATE", "CHANNEL_UPDATE", "CHANNEL_DELETE", "CHANNEL_PINS_UPDATE", "THREAD_CREATE", "THREAD_UPDATE",
"THREAD_DELETE", "THREAD_LIST_SYNC", "THREAD_MEMBER_UPDATE", "THREAD_MEMBERS_UPDATE"/* * */, "STAGE_INSTANCE_CREATE",
"STAGE_INSTANCE_UPDATE", "STAGE_INSTANCE_DELETE",
// GUILD_MEMBERS (1 << 1)
"GUILD_MEMBER_ADD", "GUILD_MEMBER_UPDATE", "GUILD_MEMBER_REMOVE", "THREAD_MEMBERS_UPDATE"/* * */,
// GUILD_BANS (1 << 2)
"GUILD_BAN_ADD", "GUILD_BAN_REMOVE",
// GUILD_EMOJIS_AND_STICKERS (1 << 3)
"GUILD_EMOJIS_UPDATE", "GUILD_STICKERS_UPDATE",
// GUILD_INTEGRATIONS (1 << 4)
"GUILD_INTEGRATIONS_UPDATE", "INTEGRATION_CREATE", "INTEGRATION_UPDATE", "INTEGRATION_DELETE",
// GUILD_WEBHOOKS (1 << 5)
"WEBHOOKS_UPDATE",
// GUILD_INVITES (1 << 6)
"INVITE_CREATE", "INVITE_DELETE",
// GUILD_VOICE_STATES (1 << 7)
"VOICE_STATE_UPDATE",
// GUILD_PRESENCES (1 << 8)
"PRESENCE_UPDATE",
// GUILD_MESSAGES (1 << 9)
"MESSAGE_CREATE", "MESSAGE_UPDATE", "MESSAGE_DELETE", "MESSAGE_DELETE_BULK",
// GUILD_MESSAGE_REACTIONS (1 << 10)
"MESSAGE_REACTION_ADD", "MESSAGE_REACTION_REMOVE", "MESSAGE_REACTION_REMOVE_ALL", "MESSAGE_REACTION_REMOVE_EMOJI",
// GUILD_MESSAGE_TYPING (1 << 11)
"TYPING_START",
// DIRECT_MESSAGES (1 << 12)
"MESSAGE_CREATE", "MESSAGE_UPDATE", "MESSAGE_DELETE", "CHANNEL_PINS_UPDATE",
// DIRECT_MESSAGE_REACTIONS (1 << 13)
"MESSAGE_REACTION_ADD", "MESSAGE_REACTION_REMOVE", "MESSAGE_REACTION_REMOVE_ALL", "MESSAGE_REACTION_REMOVE_EMOJI",
// DIRECT_MESSAGE_TYPING (1 << 14)
"TYPING_START",
// GUILD_SCHEDULED_EVENTS (1 << 16)
"GUILD_SCHEDULED_EVENT_CREATE", "GUILD_SCHEDULED_EVENT_UPDATE", "GUILD_SCHEDULED_EVENT_DELETE",
"GUILD_SCHEDULED_EVENT_USER_ADD", "GUILD_SCHEDULED_EVENT_USER_REMOVE"
]
// Guild Tags: CLYDE_EXPERIMENT_ENABLED COMMUNITY SUMMARIES_ENABLED_GA SUMMARIES_ENABLED SHARED_CANVAS_FRIENDS_AND_FAMILY_TEST PARTNERED INTERNAL_EMPLOYEE_ONLY
// if (!console.isChangedBySelkie) {
const oldlog = console.log;
console.log=(a,b,c,d)=>{
if (d!==undefined) oldlog("INF["+new Date().toISOString().substring(11,19)+"]",a,b,c,d);
else if (c!==undefined) oldlog("INF["+new Date().toISOString().substring(11,19)+"]",a,b,c);
else if (b!==undefined) oldlog("INF["+new Date().toISOString().substring(11,19)+"]",a,b);
else oldlog("INF["+new Date().toISOString().substring(11,19)+"]",a);}
const olderr = console.error;
console.error=(a,b,c,d)=>{
if (d!==undefined) olderr("ERR["+new Date().toISOString().substring(11,19)+"]",a,b,c,d);
else if (d!==undefined) olderr("ERR["+new Date().toISOString().substring(11,19)+"]",a,b,c);
else if (d!==undefined) olderr("ERR["+new Date().toISOString().substring(11,19)+"]",a,b);
else olderr("ERR["+new Date().toISOString().substring(11,19)+"]",a);}
console.isChangedBySelkie = true;
// }
const isArray = a=>a instanceof Array;
const isBool = a=>(typeof a) == "boolean";
const isNumber = a=>!isNaN(a);
const isNumGE1 = a=>isNumber(a)&& a>=1;
const isInteger = a=>isNumber(a) && a%1===0;
const isDuration = a=>isNumber(a) && a>=0;
const isIntegerGE_1 = a=> isInteger(a) && a>=-1;
const isEnum=(allowedTypes) => (a)=>allowedTypes.includes(a);
const enforceSnowflakeArray = [isArray, a=>a.map(a=>BigInt(a)).filter(a=>a>SNOWFLAKE_ONE_MONTH).map(a=>a.toString())];
const enforceBool = [isBool, a=>!!a];
const enforceNonNegative = [isNumber, a=>a<0?0:a];
const enforceNullableNatural = [a=>a===null||(isNumber(a)&&(a%1==0)&&(a>=-1)), a=>a==-1?null:a];
const enforceDuration = [isNumber, a=>a-(a%1)];
const enforceEnumBuilder=(allowedTypes)=> [a=>allowedTypes.includes(a), a=>a];
var config = null;
load = function(path = "gateway_data") {
// Typically Unchanging
config = JSON.parse(fs.readFileSync(path+"/config.json"));
config.threadAlive = new Set(config.threadAlive);
console.log("Config loaded.")
// Load data that typically changes
if (fs.existsSync(path+"/threadMap.json")) {
let data = JSON.parse(fs.readFileSync(path+"/threadMap.json"));
Object.entries(data).forEach(a=>threadMap.set(a[0],a[1]));
console.log("Thread Map loaded.")
} else console.error("Data 'threadMap' JSON doesnt exist! Cannot read the Data That Typically Changes!");
if (fs.existsSync(path+"/userXpMap.json")) {
let data = JSON.parse(fs.readFileSync(path+"/userXpMap.json"));
userXpMap.clear();
Object.entries(data).forEach(a=>userXpMap.set(a[0],new Map(Object.entries(a[1]))));
console.log("Old XP Map loaded.")
} else console.error("Data 'userXpMap' JSON doesnt exist! Cannot read the Data That Typically Changes!");
if (fs.existsSync(path+"/userDmMap.json")) {
let data = JSON.parse(fs.readFileSync(path+"/userDmMap.json"));
userDmMap.clear();
Object.entries(data).forEach(a=>userDmMap.set(a[0],a[1]));
console.log("DM Map loaded.")
} else console.error("Data 'userDmMap' JSON doesnt exist! Cannot read the Data That Typically Changes!");
if (fs.existsSync(path+"/subscribed.json")) {
modules.disboardReminder.subscriptions = new Set([u_selk]);
let data = JSON.parse(fs.readFileSync(path+"/subscribed.json"));
modules.disboardReminder.subscriptions = new Set(data);
modules.disboardReminder.dests = [...modules.disboardReminder.subscriptions].map(a=>userDmMap.get(a)).filter(a=>a);
console.log("Subscriptions list loaded.")
} else console.error("Data 'subscribed' JSON doesnt exist! Cannot read the Data That Typically Changes!");
const newSave = new Set(["newxp", "floatMessage"]);
bot.modules.filter(m=>newSave.has(m.name)).forEach(m=>{
try{
m.load(m,path);
console.log(`Loaded: ${m.name}`);
} catch (e) {console.error(`Module ${m.name}:`,e)}
});
}
save = function(path = "gateway_data") {
// Typically Unchanging
try {
config.threadAlive = [...config.threadAlive].sort();
fs.writeFileSync(path+"/config.json", JSON.stringify(config,null,2));
config.threadAlive = new Set(config.threadAlive);
console.log("Config saved.");
} catch (e) {console.error(e)}
// Data that typically changes
try {
fs.writeFileSync(path+"/threadMap.json",JSON.stringify((
Object.fromEntries([...threadMap.entries()].sort()) // sort by thread id oldest to newest
),null,2));
console.log("Thread Map saved.");
} catch (e) {console.error(e)}
try {
fs.writeFileSync(path+"/userXpMap.json",JSON.stringify((
Object.fromEntries([...userXpMap.entries()].map(a=>[a[0],Object.fromEntries(a[1])]))
),null,2));
console.log("Old XP Map saved.");
} catch (e) {console.error(e)}
try {
fs.writeFileSync(path+"/userDmMap.json",JSON.stringify((
Object.fromEntries([...userDmMap.entries()].sort((a,b)=>Number(a)-Number(b)))
),null,2));
console.log("DM Map saved.");
} catch (e) {console.error(e)}
try {
fs.writeFileSync(path+"/subscribed.json",JSON.stringify((
[...modules.disboardReminder.subscriptions].sort((a,b)=>Number(a)-Number(b))
),null,2));
console.log("Subscriptions list saved.");
} catch (e) {console.error(e)}
const newSave = new Set(["newxp", "floatMessage"]);
bot.modules.filter(m=>newSave.has(m.name)).forEach(m=>{
try{
m.save(m,path);
console.log(`Saved: ${m.name}`);
} catch (e) {console.error(`Module ${m.name}:`,e)}
});
}
// Discord requests queued to update various caches without breaking ratelimit.
var cq = {
high: "HIGH",
medium: "MEDIUM",
low: "LOW",
priorities: ["HIGH","MEDIUM","LOW"],
lastSent: 0, // in millis
maxRate: 500, // in ms
add: (priority, func) => cq.queue.get(priority).push(func),
pop: () => cq.priorities.map(a=>cq.queue.get(a)).find(a=>a.length>0)?.shift(),
attempt: () => cq.lastSent+cq.maxRate<=new Date()?cq.pop()?.(cq.lastSent=+new Date()):undefined
};
cq.queue = new Map(cq.priorities.map(a=>[a,[]]));
// if (!console.boxClassCreated) {
class Bot {
constructor() {
this.ws = null;
this.lastSequence = null;
this.heartbeatRequested = false;
this.heartbeatTimestamp = 0;
this.heartbeatShouldBeRunning = false;
this.types = new Map(); // dispatch_type -> count
this.contacts = []; // TODO: Crashes on outputting more than 500mb. Split into 100k segments on output?
// var sents = []; // global cuz refactoring is pain
this.print = false; // print all dispatch to logs
// this.send = true; // false to disable sending messages via sendMessage method
// this.heartbeatThread = 0;
this.connectionAlive = false;
this.interval = null;
this.sessionID = null;
this.self = null; // the user object for this bot.
this.modules = []; // Normal modules to run
this.modulesPre = []; // Modules to run before the others; updates the states of things.
this.modulesPost = []; // Modules to run after the others; clears the states of things.
this.plannedMessages = []; // heap of messages to be sent; tags of when to send and if late messages okay.
this.timeStart = Date.now();
this.timeLastReconnect = null;
this.isSaving = false; // If currently in the saving loop (prevent multiple heartbeat threads from saving at the same time)
this.lastSavedChunk = 0; // Keep track of last set of contacts saved to prevent writing gigabytes at a time.
// If true, do not send messages.
this.silent = false;
try {
let data = fs.readFileSync("gateway_data/firework_config.json").toString();
data = JSON.parse(data);
this.config = data;
} catch (err) {}
try {
let data = fs.readFileSync("gateway_data/firework_plannedactions.json").toString();
data = JSON.parse(data);
this.plannedMessages = data;
} catch (err) {}
}
wsSend = function(websocketPacket) {
console.log("Sending:")
console.log(JSON.stringify(websocketPacket,null,2))
if (this.connectionAlive)
this.ws.send(JSON.stringify(websocketPacket));
else
console.log("Failed to send. Connection is dead.")
}
heartbeatForce = function() {
this.heartbeatRequested = true;
this.heartbeat();
}
heartbeat = function(id) {
let now = +Date.now();
if (!this.connectionAlive) {
console.log(`[hb-${id}] Planned heartbeat cancelled. Connection is dead.`);
this.heartbeatShouldBeRunning = false;
return;
}
if (!this.heartbeatShouldBeRunning) {
console.log(`[hb-${id}] Heartbeat should not be running. Stopping heartbeat.`);
this.heartbeatShouldBeRunning = false;
return;
}
if (!id) {
id = Math.floor(Math.random()*(1<<24)).toString(16).padStart(6,'0');
console.log(`[hb-${id}] New heartbeat thread created: "${id}"`);
}
// Send an actual heartbeat
if (this.heartbeatRequested || (this.heartbeatTimestamp && now>=this.heartbeatTimestamp+this.interval)) {
console.log(`[hb-${id}]`,JSON.stringify({heartbeatRequested:this.heartbeatRequested,msToScheduled:(this.heartbeatTimestamp+this.interval-now),now,scheduledTime:(this.heartbeatTimestamp+this.interval)}));
let heartbeatObject = {"op":1,"d": this.lastSequence};
console.log(`[hb-${id}] Ba-Bum. Heartbeat sent for message ${this.lastSequence}.`);
console.log("~>",heartbeatObject);
this.ws.send(JSON.stringify(heartbeatObject));
this.heartbeatTimestamp = +Date.now();
this.heartbeatRequested = false;
}
// Run the cache-queue
try{cq.attempt()}catch{}
// save on occasion (every ${occasionalSaveSize} disbatches)
if (FORCE_OCCASIONAL_SAVE || this.contacts.length%occasionalSaveSize == 0 && (lastSaveSize-this.contacts.length)>0 && !this.isSaving) {
bot.saveOnOccasion();
// check if another hb is needed right away.
this.heartbeat(id);
} else {
setTimeout(()=>this.heartbeat(id),heartbeatThreadingInterval);
}
}
saveOnOccasion = function() {
try {
this.isSaving = true;
FORCE_OCCASIONAL_SAVE = false;
sendMessage([/*"870500800613470248",*/"883172908418084954"],
`Starting occasional save #${this.contacts.length/occasionalSaveSize}...`
);
bot.heartbeatRequested = true;
lastSaveSize = this.contacts.length;
this.cleanup();
sendMessage([/*"870500800613470248",*/"883172908418084954"],
"Occasional save complete."
);
this.isSaving = false;
} catch (e) {
sendMessage([/*"870500800613470248",*/"883172908418084954"],
"Try-Catch catch ran in scheduled save. Crash prevented, and error stored in global variable `SAVECRASHCATCHDUMP`..."
);
SAVECRASHCATCHDUMP = e;
this.isSaving = false;
}
}
hasInterest = function(string) {
let ret = [];
if (this.self && string.includes(this.self.id)) ret.push("FIREWORK");
if (string.includes("163718745888522241")) ret.push("SELKIE");
if (ret.length==0) return "";
let retstr = " [";
for (let i=0; i<ret.length-1; i++)
retstr+=ret[i]+",";
return retstr+ret[ret.length-1]+"]"
}
online = function() {
// Update Presence
this.wsSend({"op":3,"d":{"status":"online","afk":false,"activities":[],"since":null}});
}
dnd = function() {
// Update Presence
this.wsSend({"op":3,"d":{"status":"dnd","afk":false,"activities":[],"since":null}});
}
invis = function() {
// Update Presence
this.wsSend({"op":3,"d":{"status":"invisible","afk":false,"activities":[],"since":null}});
}
idle = function() {
// Update Presence
this.wsSend({"op":3,"d":{"status":"idle","afk":true,"activities":[],"since":null}});
}
// "Ice Selkie ✿#4064 code the Firework Bot!"
setStatus = function(string) {
this.wsSend({"op":3,"d":{"since":91879201,"activities":[{"name":string,"type":3}],"status":"online","afk":false}});
}
addModule = function(module) {
this.modules.push(module);
}
start = function(sid=null, last=null) {
this.ws = new WebSocket(currentGatewayUrl+'/?v=10&encoding=json');
if (sid!=null) this.timeLastReconnect = Date.now();
this.ws.on('open', () => this.wsOnOpen(this, sid, last));
this.ws.on('close', (errcode, buffer) => this.wsOnClose(this, errcode, buffer));
this.ws.on('message', (message) => this.wsOnMessage(this, message));
}
wsOnOpen = function(thiss, sid, last) {
thiss.connectionAlive = true;
if (sid === null)
thiss.wsSend(identify)
else {
if (last !== null)
thiss.lastSequence = last;
thiss.wsSend({"op":6,"d":{"token":identify.d.token,"session_id":sid,"seq":thiss.lastSequence}})
}
// ["870500800613470248","883172908418084954"]
// WOFCS embed playgr hyec firework logs
if (sid)
sendMessage([/*"870500800613470248",*/"883172908418084954"],`Firework bot is reconnecting. (${version})`);
else
sendMessage(["870500800613470248","883172908418084954"],`Firework bot has connected. (${version})`);
}
wsOnClose = function(thiss, errcode, buffer) {
thiss.connectionAlive = false;
console.log('disconnected:');
console.log(errcode);
console.log('"'+buffer.toString()+'"');
sendMessage([/*"870500800613470248",*/"883172908418084954"],
`Firework bot has lost connection: ${errcode} (${version})\n> "${buffer.toString()}"`);
if (errcode === 1001) {
if (buffer.toString() === "Discord WebSocket requesting client reconnect.")
console.log("Discord server load balancing... Reconnecting...");
else if (buffer.toString() === "CloudFlare WebSocket proxy restarting")
console.log("CloudFlare proxy load balancing... Reconnecting...");
else
console.log("Unknown 1001... Reconnecting...");
thiss.start(thiss.sessionID);
}
if (errcode === 1006) {
console.log("Unexpected client side disconnect... Reconnecting in 4 seconds...");
setTimeout(()=>thiss.start(thiss.sessionID), reconnectInterval);
}
}
wsOnMessage = function(thiss, message) {
let message_time = Date.now();
// console.log('received:');
message = JSON.parse(message);
message.time = message_time;
let messagestr = JSON.stringify(message,null,2);
if (thiss.print) console.log(messagestr);
if (message.op!==0 || message.s===null || message.t==='RESUMED') {
const OPNAMES = {'1': "HEARTBEAT_REQUESTED", '7': "RECONNECT_IMMEDIATELY", '9': "INVALID_SESSION", '10': "HELLO", '11': "HEARTBEAT_ACK"};
// console.log("Received message (none/heartbeat-ack)");
console.log(message.op, `(${OPNAMES[message.op]})`, "<~", message);
}
if (message.s!=null) {
while (thiss.contacts.length<message.s-1)
thiss.contacts.push(null);
thiss.contacts[message.s-1] = message;
// console.log("Received message #"+message.s + hasInterest(messagestr));
thiss.lastSequence = message.s;
}
// Hello -> Set Heartbeat Interval
if (message.op === 10) {
console.log("Received message (none/hello)");
console.log(message)
thiss.interval = message.d.heartbeat_interval;
if (thiss.heartbeatShouldBeRunning)
console.error("[hb] A heartbeat thread already exists, and yet one is about to be started! This should never happen!");
thiss.heartbeatShouldBeRunning = true;
// trigger the heartbeat after waiting long enough.
// Dont set last heartbeat to Date.now()-interval*random;
// if hb is called now, it would send heartbeat on a multiple of the update interval.
thiss.heartbeatRequested = false;
console.log("[hb] Starting new Heartbeat thread. This should be the only place to do so, outside of manual heartbeat thread restart.")
// First heartbeat should run after a jitter:
thiss.heartbeat() // Start heartbeat thread
// set to "run now" after jitter has passed.
setTimeout(()=>{thiss.heartbeatRequested=true;}, thiss.interval*Math.random());
} else
// Send Heartbeat ASAP
if (message.op === 1) {
console.log("[hb] Early heartbeat requested. Should trigger in the next half second.")
thiss.heartbeatRequested = true;
} else
// Resume Successful
if (message.op === 7) {
console.log("Successful reconnection!")
} else
// Resume Failed
if (message.op === 9) {
console.error("Reconnect failed. Please start a new session.")
sendMessage(["870500800613470248","883172908418084954"],
"Reconnect failed with op code 9. Will **_not_** attempt to reconnect. Bot has effectively died; Manual restart required.\n\n> "+version+"\n\n<@163718745888522241>");
thiss.dc();
setTimeout(()=>thiss.cleanup(),5000);
} else
// Standard Dipatch
if (message.op === 0) {
if (!thiss.types.has(message.t))
thiss.types.set(message.t,0);
thiss.types.set(message.t,thiss.types.get(message.t)+1);
if (message.t === "READY") {
thiss.sessionID = message.d.session_id;
thiss.self = message.d.user;
let newGatewayUrl = message.d.resume_gateway_url || currentGatewayUrl;
if (newGatewayUrl != currentGatewayUrl) {
console.log(`Reconnect URL updated to "${message.d.resume_gateway_url}" from "${currentGatewayUrl}"`);
currentGatewayUrl = newGatewayUrl;
}
console.log("Connection READY: Logged in as "+thiss.self.username+"#"+thiss.self.discriminator+" <@"+thiss.self.id+"> "+(thiss.self.bot?"[bot]":"<<selfbot>>") + " -> "+thiss.sessionID);
}
console.log("Dispatch received: "+message.t+" #"+thiss.types.get(message.t) + " id="+message.s + thiss.hasInterest(messagestr))
thiss.modulesPre.forEach(a => thiss.runModule(thiss,a,message));
thiss.modules.forEach(a => thiss.runModule(thiss,a,message));
thiss.modulesPost.forEach(a => thiss.runModule(thiss,a,message));
}
}
runModule = function(thiss, currentModule, message) {
try {
if (currentModule.onDispatch) currentModule.onDispatch(thiss, message, currentModule);
} catch (err) {
console.error(err);
// Complain if the module exists and it crashed
if (currentModule?.onDispatch)
sendMessage(["883172908418084954","870500800613470248"],`Module "${currentModule?.name}" (index ${thiss.modules.indexOf(currentModule)}) crashed with error: ${err.toString()}`);
// Log but dont spam discord if it is somehow null/doesnt exist
else
console.log("Existing Modules:",thiss.modules.map((m,i)=>[i,m?.name]));
}
}
cleanup = function() {
oldlog(timeDuration(this.timeStart,this.contacts[this.contacts.length-1].time));
oldlog(new Date(this.contacts[this.contacts.length-1].time));
oldlog(this.contacts.length/1000);
save()
oldlog(version);
let division_size = 500e3;
let strlen = (this.contacts.length).toString().length;
let dir = beta?"contactsbeta/":"contacts/";
fs.mkdirSync(dir, {recursive:true});
// Write sents:
fs.writeFileSync(dir+this.contacts[0].time+"-"+this.contacts.length+"-sents.json",JSON.stringify(sents));
// Write contacts:
if (this.contacts.length <= division_size)
fs.writeFileSync(dir+this.contacts[0].time+"-"+this.contacts.length+".json",JSON.stringify(this.contacts));
else {
for (let i=0; i<this.contacts.length; i+=division_size) {
// don't repeat old chunks that have already been saved.
if (i>=this.lastSavedChunk) {
fs.writeFileSync(
dir+this.contacts[0].time+"-"+this.contacts.length
+"-part"+((i).toString().padStart(strlen,"0"))+".json",
JSON.stringify(this.contacts.slice(i,i+division_size)));
// lastSavedChunk will be a multiple of 500e3, will only increment if saving past the 500e3 block.
this.lastSavedChunk = i;
}
}
}
oldlog("Saving logs done.");
}
term = function() {
// this.ws.terminate()
this.ws.close(4321)
this.heartbeatShouldBeRunning = false;
}
dc = function() {
this.heartbeatShouldBeRunning = false;
this.ws.close(1000)
setTimeout(()=>this.cleanup(),5000);
}
// reconnect
rc = function() {
if (this.connectionAlive) {
this.term();
setTimeout(()=>this.start(this.sessionID), 2*heartbeatThreadingInterval);
} else
this.start(this.sessionID);
}
go = function() {
bot.start();
setTimeout(()=>{bot.setStatus("Ice Selkie ✿#4064 code the Firework Bot!");}, 2000);
}
}
// console.boxClassCreated = true;
bot = new Bot();
// }
var multipartboundary = "boundary" + (Buffer.from("("+ +new Date()+")",'utf-8').toString("base64"))
function discordRequest(path, data=null, method=null, attachments=null, isText=true, useToken=true) {
if (path == undefined) {
return 'function discordRequest(path, data=null, method=null="GET", attachments=null, isText=true, useToken=true)\n'+
'path="channels/####" or "https://discord.com/api/v9/channels/####"\n'+
'data={json:"payload",or:"object to cast to json"}\n'+
'method="null/GET/POST/PUT/DELETE/etc"\n'+
'attachments="../firework_pfp.png"\n'+
' or {filename?:"unknown.txt",mime?:"text/plain",path:"/path/to/file"}\n'+
' or {filename?:"pfp.png",mime?:"image/png",data:<raw-bytes>}\n'+
' or array of above (up to 10)\n'+
'isText=true -> utf8 text -> returned.res will be string\n'+
' otherwise, isText=false -> returned.res will be Buffer of raw bytes\n'+
'useToken=true -> uses authorization header or not in request. Discord API needs. Everywhere else will leak bot token.\n'+
'\n'+
'var multipartboundary = '+JSON.stringify(multipartboundary)+' for "multipart/form-data" boundaries.\n'+
' If "--boundary" will occur in payload, change this var.';
}
// console.log("Discord Request called with path of:")
// console.log(path)
// console.log("Discord Request called with data of:")
// console.log(data)
return new Promise((resolve,reject)=>{
let hasPayload = data!=null;
let multipart = attachments!=null;
if (useToken === null)
useToken = true;
if (isText === null)
isText = true;
if (method == null && (hasPayload||multipart))
method = "POST";
if (method == null)
method = "GET";
if (attachments && !(attachments instanceof Array))
attachments = [attachments]
if (attachments && attachments.length>=10)
throw 'At most 10 attachments per message.'
if (path.startsWith('https://')){
host = path.substring(8) // "https://discord.com/api..." -> "discord.com/api..."
host = host.substring(0,host.indexOf('/')) // "discord.com/api..." -> "discord.com"
if (!host.includes("discord") || !host.includes("api"))
useToken = false;
} else
host = "discord.com"
let headers = {"content-type":"application/json"};
if (useToken)
headers.authorization=identify.d.token;
if (multipart)
headers["content-type"] = 'multipart/form-data;boundary="'+multipartboundary+'"';
let opts = {"hostname": host,"port": 443,"headers":headers,
"path": (path.startsWith("https://")?path:"/api/v9/"+path),
"method": method
}
if (data!=null && typeof data !== "string")
data = JSON.stringify(data);
let multipartdata = []
if (multipart) {
multipart = "";
if (data) {
multipart += '--'+multipartboundary+'\n'
multipart += 'Content-Disposition: form-data; name="payload_json"\n';
multipart += 'Content-Type: application/json\n';
multipart += '\n';
multipartdata.push(multipart);
multipartdata.push(data);
multipart = '\n';
data = null;
}
attachments.forEach((att,i)=> {
// att can be file name -> get file and upload it
// "/path/to/file"
// or raw data -> upload the data
// {filename:"file.txt",mime:"text/plain",data:<raw-data>||file:"/path/to/file"}
// URL to reupload not accepted, since that would require this to be async.
if (typeof att === "string") {
att = {file:att}
}
if ((!!att.data) + (!!att.file) != 1)
throw 'Attachment expected one of: rawdata (attachment.data) or filepath (attachment.file). Received neither or both.'
if (att.file && !fs.existsSync(att.file))
throw 'Attachment expected to find a file, but instead '+JSON.stringify(att.file)+' didnt exist.';
let buffer;
if (att.file) {
if (!att.filename)
att.filename = att.file.substring(att.file.lastIndexOf('/')+1);
if (!att.mime)
att.mime = mimelookup(att.file.substring(att.file.lastIndexOf('.')+1));
buffer = fs.readFileSync(att.file);
}
if (att.data) {
if (!att.filename)
att.filename = "unknown"
if (!att.mime)
att.mime = "text/plain"
buffer = att.data
if (buffer.data && buffer.type === "Buffer")
buffer = Buffer.from(buffer)
}
// if (att.url) {
// if (!att.filename) {
// att.filename = att.url;
// if (att.filename.includes('?'))
// att.filename = att.filename.substring(0,att.filename.indexOf('?'));
// if (att.filename.includes('#'))
// att.filename = att.filename.substring(0,att.filename.indexOf('#'));
// att.filename = att.filename.substring(att.filename.lastIndexOf('/')+1);
// }
// if (!att.mime)
// att.mime = mimelookup(att.file.substring(att.file.lastIndexOf('.')+1));
// buffer = await discordRequest(att.url).res
// }
multipart += '--'+multipartboundary+'\n'
multipart += 'Content-Disposition: form-data; name="files['+i+']"; filename="'+att.filename+'"\n'
multipart += 'Content-Type: '+att.mime+'\n';
multipart += '\n';
multipartdata.push(multipart);
multipartdata.push(buffer);
multipart = '\n';
});
multipart += '--'+multipartboundary+'--\n';
multipartdata.push(multipart);
multipart = true;
data = multipartdata.join("");
}
let encoding = isText?'utf8':null;
let saveObject = {
method:opts.method,
path:opts.path,
timeSend:Date.now(),
data,
isMultipart:multipart,
encoding
};
sents.push(saveObject);
console.log(JSON.stringify(saveObject));
// fs.appendFileSync("contacts"+(beta?"beta/":"/")+"latest.log",JSON.stringify(saveObject)+"\n")
let logDirectory = beta?"contactsbeta/":"contacts/";
fs.mkdirSync(logDirectory, {recursive:true});
let req = https.request(opts,
res=>{
let dataReturned = [];
if (encoding) res.setEncoding(encoding);
res.on('data',part=>dataReturned.push(part));
// TODO: remember ratelimit data
res.on('end',()=>{
if (isText)
dataReturned = dataReturned.join("");
else
dataReturned = Buffer.concat(dataReturned);
saveObject.timeDone = Date.now();
saveObject.ret = res.statusCode;
saveObject.res = dataReturned;
saveObject.ratelimit_data = JSON.stringify(res.headers,null,2);
fs.appendFileSync(logDirectory+"latest.log",JSON.stringify(saveObject)+"\n");
// Notify if something goes wrong
if (res.statusCode>=400 && !path.includes("883172908418084954")) { // prevent spam on retrying send message failures.
let msg = ""+dataReturned;
sendMessage("883172908418084954", {"embeds":[{
"author":{"name":method+" Failed"},
"title":"http error "+res.statusCode,
"description":msg.substring(0,4001),
"footer":{"text":path},
"timestamp":new Date().toISOString()}]});
}
resolve(saveObject);
});
}).on('error',err=>{
saveObject.timeDone = Date.now();
saveObject.err = err;
fs.appendFileSync(logDirectory+"latest.log",JSON.stringify(saveObject)+"\n");
console.error(err);
if (!path.includes("883172908418084954")) // prevent spam on retrying send message failures.
sendMessage("883172908418084954",err.toString().substring(0,4000));
reject(err);
});
if (data != null) {
req.write(data);
}
req.end();
});
}
async function sendMessage(channel_id, message_object) {
// TODO:
// - check ratelimit
// - if ratelimit hit; wait and try again.
// - message send queue, bucketed by channel
if (typeof message_object === "string")
message_object = {"content":message_object};
if (channel_id == null)
return "channel_id was null or undefined.";
let type = typeof channel_id;
if (type !== 'string' && type !== 'bigint' && type !== 'number') {
let ret = [];
for (let i=0; i<channel_id.length; i++) {
let temp = await sendMessage(channel_id[i],message_object);
ret.push(temp);
}
return ret;
}
else {
if (!bot.silent)
return discordRequest("channels/"+channel_id+"/messages",JSON.stringify(message_object));
return new Promise((resolve,reject)=>resolve({res:null,ret:"silent"}));
}
}
replyToMessage = async function(original, message_object) {
if (typeof message_object === "string")
message_object = {"content":message_object};
if (!original.channel_id && original.d.channel_id)
original = original.d;
message_object.message_reference = {channel_id:original.channel_id, message_id:original.id};
return sendMessage(original.channel_id,message_object);
}
var mimetypes = new Map(JSON.parse(fs.readFileSync('gateway_static/mimetypes.json')))
function mimelookup(ext) {
if (mimetypes.has(ext))
return mimetypes.get(ext);
if (mimetypes.has("."+ext))
return mimetypes.get("."+ext);
// Arbitrary Binary. The default.
return 'application/octet-stream'
// Text only. No binary.
return 'text/plain'
}
/**
* Discord CDN uri -> buffer
*/
function downloadFile(uri) {
return new Promise((resolve,reject)=>{
discordRequest(uri,null,"GET",null,false,false).then(a=>resolve(a.res),e=>reject(e))
})
// /**
// * Downloads a file from a discord cdn, returning the path to the file as a string.
// * Buckets specify where to retain the files. Null or undefined implies temp file.
// * Files in the temp folder will be cleared on occasion, after some time has passed.
// * Buckets only allow alphanumeric, dash, underscore, and / for subfolders.
// *
// * eg downloadFile("url/to/avatar.png", "avatars", "163718745888522241_3bb5bfa826fa59167533f6380127d59e.png")
// */
// // If already downloaded, return that path
// bucket = "./"+(("/"+(bucket||"temp")+"/").replaceAll(/[^-/_a-zA-Z0-9]/g,"").replaceAll(/\/+/g,"/").toLowerCase().substring(1)||"temp/")
// fs.mkdirSync(bucket, { recursive: true })
// // if (fs.existsSync(bucket+hash(uri)))
// // return hash(uri)
// // Else, ensure destination exists
// // download it
// // return the path to it
// return;
}
function downloadFiles(uris) {
return new Promise((resolve,reject)=>{
let ret = uris.map(a=>undefined);
uris.forEach((uri,i)=>downloadFile(uri).then(dat=>{
ret[i]=dat;
if (ret.filter(a=>!a).length===0)
resolve(ret);
}));
if (uris.length==0)
resolve(ret)
})
}
var parseCommandRegex = null
function parseCommandToArgs(input) {
if (!parseCommandRegex) {
let stringGrouping = '"[^"\\\\]*(?:\\\\[\\S\\s][^"\\\\]*)*"'
let allStrings =
"(?:"+ // NCG Open ━━━━━━━━━━━━━━━━━━━━━━━━┓
([ // ┃
stringGrouping, // ┃
stringGrouping.replaceAll('"',"'"), // ┃
stringGrouping.replaceAll('"','`') // ┃
].join('|'))+ // ┃
")" // NCG Close ━━━━━━━━━━━━━━━━━━━━━━━━━━┛
let weirdThingIdk = '(?:\\/[^\\/\\\\]*(?:\\\\[\\S\\s][^\\/\\\\]*)*\\/[gimy]*(?=\\s|$))'
// Note: CG = capturing group; NCG = non-caputuring group
let regex =
'('+ // CG 1 Open ━━━━━━━━━━━━━━━━━━━━━┓
'(?:'+ // NCG 2 Open ━━━━━━━━━━━━━━━━━━━┓ ┃
allStrings+ // ══════════════════════╡ ┃ ┃
'|'+ // or ┃ ┃
// weirdThingIdk+ // ═══════════════════╡ ┃ ┃
// '|'+ // or ┃ ┃
'(?:'+ // NCG 3 Open ━━━━━━━━━━━━━━━━┓ ┃ ┃
'\\\\\\\\'+ // escaped backslash ┃ ┃ ┃ // wait shouldnt escaped any
'|'+ // or ┃ ┃ ┃ // include escaped backslash?
'\\\\[\\s\\S]'+ // escaped any ┃ ┃ ┃
'|'+ // or ┃ ┃ ┃
'[^\\s\\\\]'+ // anything else ┃ ┃ ┃
')'+ // NCG 3 Close ━━━━━━━━━━━━━━━━┛ ┃ ┃
')'+ // NCG 2 Close ━━━━━━━━━━━━━━━━━━━━┛ ┃
'+'+ // NCG 2 Repeat 1 or more ┃
')'+ // CG 1 Close ━━━━━━━━━━━━━━━━━━━━━━━━━┛
'(?=\\s|$)'; // Lookahead to ensure whitespace/end follows
console.log(regex)
// convert to a regex object
parseCommandRegex = RegExp(regex,"g");
}
return [...input.matchAll(parseCommandRegex)].map(a=>a[0])
}
function commandAndPrefix(content) {
let argv = parseCommandToArgs(content)
if (/<@!?870750872504786944>/.test(argv.shift())) {
return argv;
}
return false;
}
function isStaff(uid, gid) {
if (!gid) // dm
return false;
if (guildOwnerMap.get(gid)==uid)
return true;
let member = memberMap.get(gid).get(uid);
if (!member)
return false;
return (
member.roles.includes(r_mod)
|| member.roles.includes(r_modling)
);
}
function isDev(uid) {
if (uid === "163718745888522241" || uid === "488383281935548436")
return true;
}
/**
* timeDuration
* Takes in a duration or a start time and end time in milliseconds, and finds
* the duration between them, outputting it in a human readable format.
*
* - Correctly pluralizes time units
* - If two or more time unit terms, joins the last two with "and"
* - negative duration puts "negative" in front
* - If one zero term between two non-zeros, will display.
* - If two or more concecutive zeros, don't display them.
* - no commas.
*/
function timeDuration (start, end) {
if (start==null)
return null;
let duration = start;
if (end!=null)
duration = end-start;
if (duration==0)
return "0.000 seconds";
let isNeg = duration<0;
if (isNeg)
duration = -duration;
let ms = duration%1000;
duration = Math.floor(duration/1000);
let sec = duration%60;