-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy pathUtil.js
3103 lines (2578 loc) · 104 KB
/
Util.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
/*
addCommand\((\[.+?\]), (\w+?), (\w+?), (\w+?), function\([\w, ]+?\) {.*\n\t([\s\S]+?)\n},\n\t(".*?"),\n\t(".*?"),\n\t(".*?")\n\)
module.exports = Cmds.addCommand({
cmds: \1,
requires: {
guild: \4,
loud: false
},
desc: \6,
args: \7,
example: \8,
func: (cmd, args, msgObj, speaker, channel, guild) => {
\5
}
})
*/
const FileSys = index.FileSys;
const DateFormat = index.DateFormat;
const Exec = index.Exec;
const Path = index.Path;
const NodeUtil = index.NodeUtil;
exports.charLimit = 1999;
exports.regexURLPerfect = new RegExp(
'^' +
// protocol identifier
'(?:(?:https?|ftp)://)' +
// user:pass authentication
'(?:\\S+(?::\\S*)?@)?' +
'(?:' +
// IP address exclusion
// private & local networks
'(?!(?:10|127)(?:\\.\\d{1,3}){3})' +
'(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})' +
'(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})' +
// IP address dotted notation octets
// excludes loopback network 0.0.0.0
// excludes reserved space >= 224.0.0.0
// excludes network & broacast addresses
// (first & last IP address of each class)
'(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])' +
'(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}' +
'(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))' +
'|' +
// host name
'(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)' +
// domain name
'(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*' +
// TLD identifier
'(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))' +
// TLD may end with dot
'\\.?' +
')' +
// port number
'(?::\\d{2,5})?' +
// resource path
'(?:[/?#]\\S*)?' +
'$', 'i');
exports.rolePermissions = [
'CREATE_INSTANT_INVITE',
'KICK_MEMBERS',
'BAN_MEMBERS',
'VIEW_AUDIT_LOG',
'ADMINISTRATOR',
'MANAGE_CHANNELS',
'MANAGE_GUILD',
'ADD_REACTIONS', // add reactions to messages
'VIEW_CHANNEL',
'SEND_MESSAGES',
'SEND_TTS_MESSAGES',
'MANAGE_MESSAGES',
'EMBED_LINKS',
'ATTACH_FILES',
'READ_MESSAGE_HISTORY',
'MENTION_EVERYONE',
'USE_EXTERNAL_EMOJIS', // use external emojis
'CONNECT', // connect to voice
'SPEAK', // speak on voice
'MUTE_MEMBERS', // globally mute members on voice
'DEAFEN_MEMBERS', // globally deafen members on voice
'MOVE_MEMBERS', // move member's voice channels
'USE_VAD', // use voice activity detection
'CHANGE_NICKNAME',
'MANAGE_NICKNAMES', // change nicknames of others
'MANAGE_ROLES',
'MANAGE_WEBHOOKS',
'MANAGE_EMOJIS',
];
exports.rolePermissionsObj = {
CREATE_INSTANT_INVITE: true,
KICK_MEMBERS: true,
BAN_MEMBERS: true,
VIEW_AUDIT_LOG: true,
ADMINISTRATOR: true,
MANAGE_CHANNELS: true,
MANAGE_GUILD: true,
ADD_REACTIONS: true, // add reactions to messages
VIEW_CHANNEL: true,
SEND_MESSAGES: true,
SEND_TTS_MESSAGES: true,
MANAGE_MESSAGES: true,
EMBED_LINKS: true,
ATTACH_FILES: true,
READ_MESSAGE_HISTORY: true,
MENTION_EVERYONE: true,
USE_EXTERNAL_EMOJIS: true, // use external emojis
CONNECT: true, // connect to voice
SPEAK: true, // speak on voice
MUTE_MEMBERS: true, // globally mute members on voice
DEAFEN_MEMBERS: true, // globally deafen members on voice
MOVE_MEMBERS: true, // move member's voice channels
USE_VAD: true, // use voice activity detection
CHANGE_NICKNAME: true,
MANAGE_NICKNAMES: true, // change nicknames of others
MANAGE_ROLES: true,
MANAGE_WEBHOOKS: true,
MANAGE_EMOJIS: true,
};
exports.textChannelPermissions = [
'CREATE_INSTANT_INVITE',
'MANAGE_CHANNEL',
'ADD_REACTIONS', // add reactions to messages
'VIEW_CHANNEL',
'SEND_MESSAGES',
'SEND_TTS_MESSAGES',
'MANAGE_MESSAGES',
'EMBED_LINKS',
'ATTACH_FILES',
'READ_MESSAGE_HISTORY',
'MENTION_EVERYONE',
'USE_EXTERNAL_EMOJIS', // use external emojis
'MANAGE_PERMISSIONS',
'MANAGE_WEBHOOKS',
];
exports.textChannelPermissionsObj = {
ADD_REACTIONS: true, // add reactions to messages
VIEW_CHANNEL: true,
SEND_MESSAGES: true,
SEND_TTS_MESSAGES: true,
MANAGE_MESSAGES: true,
EMBED_LINKS: true,
ATTACH_FILES: true,
READ_MESSAGE_HISTORY: true,
MENTION_EVERYONE: true,
USE_EXTERNAL_EMOJIS: true, // use external emojis
CREATE_INSTANT_INVITE: true,
MANAGE_CHANNEL: true,
MANAGE_PERMISSIONS: true,
MANAGE_WEBHOOKS: true,
};
exports.voiceChannelPermissions = [
'CONNECT', // connect to voice
'SPEAK', // speak on voice
'MUTE_MEMBERS', // globally mute members on voice
'DEAFEN_MEMBERS', // globally deafen members on voice
'MOVE_MEMBERS', // move member's voice channels
'USE_VAD', // use voice activity detection
'CREATE_INSTANT_INVITE',
'MANAGE_CHANNEL',
'MANAGE_PERMISSIONS',
'MANAGE_WEBHOOKS',
];
exports.voiceChannelPermissionsObj = {
CONNECT: true, // connect to voice
SPEAK: true, // speak on voice
MUTE_MEMBERS: true, // globally mute members on voice
DEAFEN_MEMBERS: true, // globally deafen members on voice
MOVE_MEMBERS: true, // move member's voice channels
USE_VAD: true, // use voice activity detection
CREATE_INSTANT_INVITE: true,
MANAGE_CHANNEL: true,
MANAGE_PERMISSIONS: true,
MANAGE_WEBHOOKS: true,
};
exports.permissionsOrder = {
ADMINISTRATOR: 27,
MANAGE_GUILD: 26,
MANAGE_ROLES: 25,
MANAGE_CHANNELS: 24,
MANAGE_CHANNEL: 24, // Channel
MANAGE_WEBHOOKS: 23,
MANAGE_EMOJIS: 22,
MANAGE_PERMISSIONS: 22, // Channel
VIEW_AUDIT_LOG: 21,
MENTION_EVERYONE: 20,
BAN_MEMBERS: 19,
KICK_MEMBERS: 18,
MOVE_MEMBERS: 17,
DEAFEN_MEMBERS: 16,
MUTE_MEMBERS: 15,
MANAGE_MESSAGES: 14,
MANAGE_NICKNAMES: 13,
USE_EXTERNAL_EMOJIS: 12,
ATTACH_FILES: 11,
SEND_TTS_MESSAGES: 10,
ADD_REACTIONS: 9,
EMBED_LINKS: 8,
CHANGE_NICKNAME: 7,
USE_VAD: 6,
SPEAK: 5,
CONNECT: 4,
CREATE_INSTANT_INVITE: 3,
SEND_MESSAGES: 2,
READ_MESSAGE_HISTORY: 1,
VIEW_CHANNEL: 0,
};
exports.permRating = [
['ADMINISTRATOR', 100],
['MANAGE_GUILD', 90],
['MANAGE_ROLES', 80],
['MANAGE_CHANNELS', 70],
['MANAGE_EMOJIS', 60],
['MENTION_EVERYONE', 50],
['VIEW_AUDIT_LOG', 50],
['BAN_MEMBERS', 40],
['KICK_MEMBERS', 30],
['MANAGE_MESSAGES', 20],
['MANAGE_NICKNAMES', 20],
['MOVE_MEMBERS', 20],
['ATTACH_FILES', 10],
['ADD_REACTIONS', 10],
['SEND_MESSAGES', 10],
];
exports.replaceAll = (str, search, replacement) => str.split(search).join(replacement);
function getURLChecker() {
const SCHEME = '[a-z\\d.-]+://';
const IPV4 = '(?:(?:[0-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])\\.){3}(?:[0-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])';
const HOSTNAME = "(?:(?:[^\\s!@#$%^&*()_=+[\\]{}\\\\|;:'\",.<>/?]+)\\.)+";
const TLD = `(?:ac|ad|aero|ae|af|ag|ai|al|am|an|ao|aq|arpa|ar|asia|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|biz|bi|bj|bm|bn|bo|br
|bs|bt|bv|bw|by|bz|cat|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|coop|com|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|er|es|et|eu
|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|info|int|in|io|iq
|ir|is|it|je|jm|jobs|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mobi
|mo|mp|mq|mr|ms|mt|museum|mu|mv|mw|mx|my|mz|name|na|nc|net|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|org|pa|pe|pf|pg|ph|pk|place|pl|pm|pn
|pro|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tel|tf|tg|th|tj|tk|tl|tm
|tn|to|tp|trade|travel|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wiki|wf|ws|xn--0zwm56d|xn--11b5bs3a9aj6g|xn--80akhbyknj4f
|xn--9t4b11yi5a|xn--deba0ad|xn--g6w251d|xn--hgbk6aj7f53bba|xn--hlcj6aya9esc7a|xn--jxalpdlp|xn--kgbechtv|xn--zckzah|ye|yt|yu|za|zm|zw)`;
const HOST_OR_IP = `(?:${HOSTNAME}${TLD}|${IPV4})`;
const PATH = '(?:[;/][^#?<>\\s]*)?';
const QUERY_FRAG = '(?:\\?[^#<>\\s]*)?(?:#[^<>\\s]*)?';
const URI1 = `\\b${SCHEME}[^<>\\s]+`;
const URI2 = `\\b${HOST_OR_IP}${PATH}${QUERY_FRAG}(?!\\w)`;
const MAILTO = 'mailto:';
const EMAIL = `(?:${MAILTO})?[a-z0-9!#$%&'*+/=?^_\`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_\`{|}~-]+)*@${HOST_OR_IP}${QUERY_FRAG}(?!\\w)`;
const URI_RE = new RegExp(`(?:${URI1}|${URI2}|${EMAIL})`, 'ig');
const SCHEME_RE = new RegExp(`^${SCHEME}`, 'i');
const quotes = {
"'": '`',
'>': '<',
')': '(',
']': '[',
'}': '{',
'»': '«',
'›': '‹',
};
const defaultOptions = {
callback(text, href) {
return href || null;
},
punct_regexp: /(?:[!?.,:;'"]|(?:&|&)(?:lt|gt|quot|apos|raquo|laquo|rsaquo|lsaquo);)$/,
};
function checkURLs(txtParam, optionsParam) {
let txt = exports.replaceAll(txtParam, '\\', '');
txt = exports.replaceAll(txt, '*', '');
txt = exports.replaceAll(txt, '_', '');
if (txt.includes('roblox')) Util.log(txt);
const options = optionsParam || {};
// Temp variables.
let arr;
let i;
let link;
let href;
// Output HTML.
// const html = '';
// Store text / link parts, in order, for re-combination.
const parts = [];
// Used for keeping track of indices in the text.
let idxPrev;
let idxLast;
let idx;
let linkLast;
// Used for trimming trailing punctuation and quotes from links.
let matchesBegin;
let matchesEnd;
let quoteBegin;
let quoteEnd;
// Initialize options.
for (i of Object.keys(defaultOptions)) {
if (options[i] == null) {
options[i] = defaultOptions[i];
}
}
const inRep = (a) => {
idxLast -= a.length;
return '';
};
// Find links.
while (arr = URI_RE.exec(txt)) {
link = arr[0];
idxLast = URI_RE.lastIndex;
idx = idxLast - link.length;
// Not a link if preceded by certain characters.
if (/[/:]/.test(txt.charAt(idx - 1))) {
continue;
}
// Trim trailing punctuation.
do {
// If no changes are made, we don't want to loop forever!
linkLast = link;
quoteEnd = link.substr(-1);
quoteBegin = quotes[quoteEnd];
// Ending quote character?
if (quoteBegin) {
matchesBegin = link.match(new RegExp(`\\${quoteBegin}(?!$)`, 'g'));
matchesEnd = link.match(new RegExp(`\\${quoteEnd}`, 'g'));
// If quotes are unbalanced, remove trailing quote character.
if ((matchesBegin ? matchesBegin.length : 0) < (matchesEnd ? matchesEnd.length : 0)) {
link = link.substr(0, link.length - 1);
idxLast--;
}
}
// Ending non-quote punctuation character?
if (options.punct_regexp) {
link = link.replace(options.punct_regexp, inRep);
}
} while (link.length && link !== linkLast);
href = link;
// Add appropriate protocol to naked links.
if (!SCHEME_RE.test(href)) {
const origHref = href;
if (href.indexOf('@') != -1) {
if (!href.indexOf(MAILTO)) {
href = '';
} else {
href = MAILTO;
}
} else if (!href.indexOf('irc.')) {
href = 'irc://';
} else if (!href.indexOf('ftp.')) {
href = 'ftp://';
} else {
href = 'http://';
}
href += origHref;
}
// Push preceding non-link text onto the array.
if (idxPrev !== idx) {
parts.push([txt.slice(idxPrev, idx)]);
idxPrev = idxLast;
}
// Push massaged link onto the array
parts.push([link, href]);
}
// Push remaining non-link text onto the array.
parts.push([txt.substr(idxPrev)]);
// Process the array items.
const URLs = [];
for (i = 0; i < parts.length; i++) {
const result = options.callback.apply('nooone', parts[i]);
if (result) {
URLs.push(result);
}
}
return URLs;
}
return checkURLs;
}
exports.checkURLs = getURLChecker();
function forceAddRolesInner(guild, sendRole, iterNum = 1) {
let didError = false;
guild.members.forEach((member) => {
if (!exports.hasRole(member, sendRole)) {
member.addRole(sendRole)
.then(() => Util.log(`Assigned role to ${exports.getName(member)}`))
.catch((error) => {
didError = true;
Util.log(`[E_InitRoles] addRole: ${error}`);
});
}
});
if (!didError || iterNum >= 10) return;
setTimeout(() => {
forceAddRolesInner(guild, sendRole, iterNum + 1);
}, 1000 * 4);
}
function forceAddRoles(guild, sendRole) {
forceAddRolesInner(guild, sendRole);
}
exports.initRoles = async function (sendRole, guild, guildChannel) {
try {
await Promise.all(guild.roles.map(async (role) => {
if (role.name !== 'SendMessages' && role.hasPermission('SEND_MESSAGES', null, false)) {
try {
await role.setPermissions(role.permissions & (~2048));
} catch (err) {
console.log('[RolePermRem]', err);
}
}
}));
await Promise.all(guild.channels.map(async (channel) => {
const deniesMessages = channel.permissionOverwrites.some(channelPerm => channelPerm.type === 'role' && channelPerm.denied.toArray(false).includes('SEND_MESSAGES'));
if (deniesMessages) return;
const newOverwrites = channel.permissionOverwrites.map((channelPerm) => {
// const permObj = channelPerm.type === 'role' ? guild.roles.get(channelPerm.id) : guild.members.get(channelPerm.id);
const allowed = channelPerm.allowed.toArray(false).filter(perm => perm !== 'SEND_MESSAGES');
const denied = channelPerm.denied.toArray(false).filter(perm => perm !== 'SEND_MESSAGES');
return {
allowed,
denied,
id: channelPerm.id,
type: channelPerm.type,
};
});
channel.replacePermissionOverwrites({ overwrites: newOverwrites }).catch((err) => {
console.log('[RepPermOverwrites]', err);
});
}));
if (guildChannel) {
Util.sendDescEmbed(guildChannel, 'Setup VaeBot', 'Server roles and channels have been setup appropriately', null, null, null);
}
} catch (err) {
console.log('InitRolesInner Error:', err);
}
forceAddRoles(guild, sendRole);
};
exports.arrayToObj = function (arr) {
const obj = {};
for (let i = 0; i < arr.length; i++) {
const val = arr[i];
obj[val] = true;
}
return obj;
};
exports.capitalize = function (strParam) {
let str = strParam;
str = String(str);
return str.charAt(0).toUpperCase() + str.slice(1);
};
exports.runLua = function (args, channel) {
// args = "os=nil;io=nil;debug=nil;package=nil;require=nil;loadfile=nil;dofile=nil;collectgarbage=nil;" + args;
const tagNum = Math.floor((new Date()).getTime());
const fileDir = `/tmp/script_${tagNum}.lua`;
FileSys.writeFile(fileDir, args, (err) => {
if (err) {
Util.log(`Script creation error: ${err}`);
Util.print(channel, `Script creation error: ${err}`);
}
Exec(`lua ${fileDir}`, (error, stdoutParam, stderr) => {
let stdout = stdoutParam;
if (!stdout) stdout = '';
const safeOut = Util.safe(stdout);
// var safeErr = Util.safe(stderr);
const outStr = [];
if (error) {
outStr.push('**Execution error:**');
outStr.push('```');
Util.log(`Execution Error: ${stderr}`);
outStr.push(error);
outStr.push('```');
} else {
if (safeOut.length <= 1980) {
outStr.push('**Output:**');
outStr.push('```');
outStr.push(safeOut);
outStr.push('```');
} else {
const options = {
url: 'https://hastebin.com/documents',
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
body: stdout,
};
index.Request(options, (error2, response, bodyParam) => {
const body = JSON.parse(bodyParam);
if (error2 || !body || !body.key) {
Util.print(channel, 'Hastebin upload error:', error2);
} else {
Util.print(channel, 'Output:', `https://hastebin.com/raw/${body.key}`);
}
});
}
if (stderr) {
outStr.push('**Lua Error:**');
outStr.push('```');
Util.log(`Lua Error: ${stderr}`);
outStr.push(stderr);
outStr.push('```');
}
}
Util.print(channel, outStr.join('\n'));
FileSys.unlink(fileDir);
});
});
};
exports.doXOR = function (a, b) {
const result = ((a == 1 || b == 1) && !(a == 1 && b == 1)) ? 1 : 0;
return result;
};
exports.capitalize2 = function (strParam, repUnder) {
let str = String(strParam);
if (repUnder) str = exports.replaceAll(str, '_', ' ');
str = str.replace(/[0-9a-z]+/ig, (txt) => { Util.log(txt); return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
return str;
};
exports.boolToAns = function (bool) {
const result = bool ? 'Yes' : 'No';
return result;
};
exports.safe = function (str) {
if (typeof (str) === 'string') return str.replace(/`/g, '\\`').replace(/@/g, '@');
return undefined;
};
exports.safe2 = function (str) {
if (typeof (str) === 'string') return str.replace(/`/g, '\\`');
return undefined;
};
exports.safeEveryone = function (str) {
if (typeof (str) === 'string') {
const newStr = str.replace(/@everyone/g, '@everyone');
return newStr.replace(/@here/g, '@here');
}
return undefined;
};
exports.fix = str => (`\`${exports.safe(str)}\``);
exports.toFixedCut = (num, decimals) => Number(num.toFixed(decimals)).toString();
exports.grabFiles = function (filePath, filter = () => true) {
const dirFiles = FileSys.readdirSync(filePath);
let fullFiles = [];
dirFiles.forEach((file) => {
const fileData = FileSys.lstatSync(`${filePath}${file}`);
if (fileData.isDirectory()) {
const toAdd = exports.grabFiles(`${filePath}${file}/`, filter);
fullFiles = fullFiles.concat(toAdd);
} else if (filter(file)) {
fullFiles.push(`${filePath}${file}`);
}
});
return fullFiles;
};
exports.bulkRequire = function (filePath) {
const bulkFiles = exports.grabFiles(filePath, file => file.endsWith('.js'));
for (const data of Object.values(bulkFiles)) {
exports.pathRequire(data);
}
};
exports.pathRequire = function (filePath) {
const file = Path.resolve(filePath);
delete require.cache[require.resolve(file)];
const fileData = require(filePath);
const dirName = /(\w+)[/\\]\w+\.js$/.exec(file)[1];
if (dirName && has.call(index.commandTypes, dirName)) {
const cmdTypes = index.commandTypes;
for (const [commandType, commandKey] of Object.entries(cmdTypes)) {
if (commandKey !== 'null') {
if (commandType === dirName) {
fileData[2][commandKey] = true;
} else {
fileData[2][commandKey] = false;
}
}
}
}
};
exports.checkStaff = function (guild, member) {
if (guild == null || member == null) {
Util.log(`>>> CHECK STAFF ISSUE: ${guild} ${member} <<<`);
}
if (member.id === vaebId || member.id === selfId || member.id === guild.ownerID) return true;
if (member.hasPermission('ADMINISTRATOR')) return true;
if (member.id === '126710973737336833') return true;
const speakerRoles = member.roles;
if (!speakerRoles) return false;
// if (exports.getPermRating(guild, member) >= 30) return true;
return speakerRoles.some(role => /\bstaff\b/i.test(role.name) || role.name === 'Owner/Seller' || role.name === 'Bot Admin'
|| role.name === 'Moderator' || role.name.includes('Head Mod') || role.name === 'Trial Moderator' || /OP$/.test(role.name));
};
exports.commandFailed = function (channel, speaker, tag, message) {
if (message == null) {
message = tag;
tag = null;
}
const tagMessage = tag ? `[${tag}] ` : '';
if (channel != null) {
exports.sendEmbed(channel, `${tagMessage}Command Failed`, message, exports.makeEmbedFooter(speaker), null, colGreen, null);
} else {
Util.log(`${tagMessage}[Command_Failed] ${speaker.id}: ${message}`);
}
return false;
};
exports.getRandomInt = function (minParam, maxParam) { // inclusive, exclusive
maxParam++; // inclusive, inclusive
const min = Math.ceil(minParam);
const max = Math.floor(maxParam);
return Math.floor(Math.random() * (max - min)) + min;
};
/* function chunkStringLine(str, size) {
var numChunks = Math.ceil(str.length / size);
var chunks = [];
for (var i = 0, o = 0; i < numChunks; ++i, o += size) {
chunks[i] = str.substr(o, size);
}
var chunkLength = chunks.length;
if (numChunks > 1) {
for (var i = 0; i < chunkLength; i++) {
var nowChunk = chunks[i];
var lastLine = nowChunk.lastIndexOf("\n");
if (lastLine >= 0) {
var nowChunkMsg = nowChunk.substring(0, lastLine);
chunks[i] = nowChunkMsg;
var nextChunkMsg = nowChunk.substring(lastLine+1);
if (chunks[i+1] == null) {
if (nextChunkMsg == "" || nextChunkMsg == "\n" || nextChunkMsg == "```" || nextChunkMsg == "\n```") break;
chunks[i+1] = "";
}
chunks[i+1] = nextChunkMsg + chunks[i+1];
}
}
}
return chunks;
} */
/*
-Chunk string into sets of 2k chars
-For each chunk
-If msg includes newline and first character of next message isn't newline
-Find last newline (unless start of next chunk is newline in which case use the if statement below), where the character before it isn't a codeblock
-Copy everything after the newline to the start of the next chunk
-Set msg to everything before the newline
-If number of code blocks is odd and there are non-whitespace characters after the last codeblock
-Add a codeblock to the end of the chunk
-If number of characters is above 2000
-Find last newline under (or equal) the 2001 character mark, where the character before it isn't a codeblock
-If no newline
-Append a newline as <= 2001st character (not between code blocks if possible)
-Copy everything after the newline (but before the code block), then append it (with an extra newline on the end) to the start of the next chunk
-Cut the chunk to everything before the newline
*/
exports.isObject = function (val) { // Or array
if (val == null) return false;
return (typeof (val) === 'object');
};
exports.cloneObj = function (obj, fixBuffer) {
let copy;
if (obj == null || typeof (obj) !== 'object') return obj;
if (obj instanceof Date) {
copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
if (obj instanceof Array) {
copy = [];
const len = obj.length;
for (let i = 0; i < len; i++) {
copy[i] = exports.cloneObj(obj[i], fixBuffer);
}
return copy;
}
if (fixBuffer && obj instanceof Buffer) {
return obj.readUIntBE(0, 1);
}
if (obj instanceof Object && !(obj instanceof Buffer)) {
copy = {};
for (const [attr, objAttr] of Object.entries(obj)) {
copy[attr] = exports.cloneObj(objAttr, fixBuffer);
}
return copy;
}
console.log("Couldn't clone obj, returning real value");
return obj;
};
exports.cloneObjDepth = function (obj, maxDepth = 1, nowDepth = 0) {
let copy;
if (obj == null || typeof (obj) !== 'object') return obj;
if (obj instanceof Date) {
copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
if (obj instanceof Array) {
const len = obj.length;
if (nowDepth >= maxDepth && len > 0) return '[Array]';
copy = [];
for (let i = 0; i < len; i++) {
copy[i] = exports.cloneObjDepth(obj[i], maxDepth, nowDepth + 1);
}
return copy;
}
if (obj instanceof Object && !(obj instanceof Buffer)) {
const entries = Object.entries(obj);
if (nowDepth >= maxDepth && entries.length > 0) return '[Object]';
copy = {};
for (const [attr, objAttr] of entries) {
copy[attr] = exports.cloneObjDepth(objAttr, maxDepth, nowDepth + 1);
}
return copy;
}
console.log("Couldn't clone obj, returning real value");
return obj;
};
const elapseTimeTags = {};
exports.throwErr = function () {
setTimeout(() => {
throw new Error('err');
}, 1000);
};
exports.getElapsed = function (tag, remove) {
let elapsed;
if (elapseTimeTags[tag] != null) {
const startTimeData = elapseTimeTags[tag];
const elapsedTimeData = process.hrtime(startTimeData); // Seconds, Nanoseconds (Seconds * 1e9)
elapsed = (elapsedTimeData[0] * 1e3) + Number((elapsedTimeData[1] / 1e6).toFixed(3));
}
if (remove) {
elapseTimeTags[tag] = null;
delete elapseTimeTags[tag]; // Remove time storage
} else {
elapseTimeTags[tag] = process.hrtime(); // Mark the start time
}
return elapsed;
};
exports.formatTime = function (time) {
let timeStr;
let formatStr;
const numSeconds = exports.round(time / 1000, 0.1);
const numMinutes = exports.round(time / (1000 * 60), 0.1);
const numHours = exports.round(time / (1000 * 60 * 60), 0.1);
const numDays = exports.round(time / (1000 * 60 * 60 * 24), 0.1);
const numWeeks = exports.round(time / (1000 * 60 * 60 * 24 * 7), 0.1);
const numMonths = exports.round(time / (1000 * 60 * 60 * 24 * 30.42), 0.1);
const numYears = exports.round(time / (1000 * 60 * 60 * 24 * 365.2422), 0.1);
if (numSeconds < 1) {
timeStr = exports.toFixedCut(time, 0);
formatStr = `${timeStr} millisecond`;
} else if (numMinutes < 1) {
timeStr = exports.toFixedCut(numSeconds, 1);
formatStr = `${timeStr} second`;
} else if (numHours < 1) {
timeStr = exports.toFixedCut(numMinutes, 1);
formatStr = `${timeStr} minute`;
} else if (numDays < 1) {
timeStr = exports.toFixedCut(numHours, 1);
formatStr = `${timeStr} hour`;
} else if (numWeeks < 1) {
timeStr = exports.toFixedCut(numDays, 1);
formatStr = `${timeStr} day`;
} else if (numMonths < 1) {
timeStr = exports.toFixedCut(numWeeks, 1);
formatStr = `${timeStr} week`;
} else if (numYears < 1) {
timeStr = exports.toFixedCut(numMonths, 1);
formatStr = `${timeStr} month`;
} else {
timeStr = exports.toFixedCut(numYears, 1);
formatStr = `${timeStr} year`;
}
if (timeStr !== '1') formatStr += 's';
return formatStr;
};
exports.chunkString = function (str, maxChars) {
const iterations = Math.ceil(str.length / maxChars);
const chunks = new Array(iterations);
for (let i = 0, j = 0; i < iterations; ++i, j += maxChars) chunks[i] = str.substr(j, maxChars);
return chunks;
};
exports.cutStringSafe = function (msg, postMsg, lastIsOpener) { // Tries to cut the string along a newline
let lastIndex = msg.lastIndexOf('\n');
if (lastIndex < 0) return [msg, postMsg];
let preCut = msg.substring(0, lastIndex);
let postCut = msg.substring(lastIndex + 1);
const postHasBlock = postCut.includes('```');
if (postHasBlock && !lastIsOpener) { // If postCut is trying to pass over a code block (not allowed) might as well just cut after the code block (as long as it's a closer)
lastIndex = msg.lastIndexOf('```');
preCut = msg.substring(0, lastIndex + 3);
postCut = msg.substring(lastIndex + 3);
} else {
const strEnd1 = preCut.substr(Math.max(preCut.length - 3, 0), 3);
const strEnd2 = preCut.substr(Math.max(preCut.length - 4, 0), 4);
if (postHasBlock || (lastIsOpener && (strEnd1 === '```' || strEnd2 === '``` ' || strEnd2 === '```\n'))) { // If post is triyng to pass over opener or last section of preCut is an opener
return [msg, postMsg];
}
}
return [preCut, postCut + postMsg];
};
exports.fixMessageLengthNew = function (msgParam) {
const argsFixed = exports.chunkString(msgParam, exports.charLimit); // Group string into sets of 2k chars
const minusLimit = exports.charLimit - 4;
// argsFixed.forEach(o => Util.log("---\n" + o));
let totalBlocks = 0; // Total number of *user created* code blocks come across so far (therefore if the number is odd then code block is currently open)
for (let i = 0; i < argsFixed.length; i++) {
let passOver = ''; // String to pass over as the start of the next chunk
let msg = argsFixed[i];
const numBlock = (msg.match(/```/g) || []).length; // Number of user created code blocks in this chunk
if (totalBlocks % 2 == 1) msg = `\`\`\`\n${msg}`; // If code block is currently open then this chunk needs to be formatted
totalBlocks += numBlock; // The user created code blocks may close/open new code block (don't need to include added ones because they just account for separate messages)
let lastIsOpener = totalBlocks % 2 == 1; // Checks whether the last code block is an opener or a closer
if (lastIsOpener && msg.length > minusLimit) { // If the chunk ends with the code block still open then it needs to be auto-closed so the chunk needs to be shortened so it can fit
passOver = msg.substring(minusLimit);
msg = msg.substr(0, minusLimit);
const numPass = (passOver.match(/```/g) || []).length; // If we end up passing over code blocks whilst trying to shorten the string, we need to account for the new amount
totalBlocks -= numPass;
if (numPass % 2 == 1) lastIsOpener = false;
}
const nextMsg = passOver + (argsFixed[i + 1] != null ? argsFixed[i + 1] : ''); // Message for next chunk (or empty string if none)
if (nextMsg !== '' && nextMsg[0] !== '\n' && msg.includes('\n')) { // If start of next chunk is a newline then can just leave the split as it is now (same goes for this chunk having no newlines)
const cutData = exports.cutStringSafe(msg, '', lastIsOpener);
msg = cutData[0];
passOver = cutData[1] + passOver;
}
if (lastIsOpener) msg += '\n```'; // Close any left over code blocks (and re open on next chunk if they continue)
argsFixed[i] = msg;
if (passOver.length > 0) { // Whether any text actually needs to be passed
if (argsFixed[i + 1] == null) argsFixed[i + 1] = ''; // Create new chunk if this is the last one
argsFixed[i + 1] = passOver + argsFixed[i + 1];
}
}
return argsFixed;
};
/* function fixMessageLength(msg) {
var argsFixed = chunkStringLine(msg, 2000);
var argsLength = argsFixed.length;
for (var i = 0; i < argsFixed.length; i++) {
var passOver = "";
var msg = argsFixed[i];
//Util.log("Original message length: " + msg.length);
if (msg.length > 1996) {
passOver = msg.substring(1996);
msg = msg.substring(0, 1996);
//Util.log("passStart orig: " + passOver.length);
var lastLine = msg.lastIndexOf("\n");
if (lastLine >= 5) {
var msgEnd = lastLine;
var passStart = msgEnd+1;
passOver = msg.substring(passStart) + passOver;
msg = msg.substring(0, msgEnd);
//Util.log("passOver: " + passOver.length);
//Util.log("msg: " + msg.length);
//Util.log("lastLine: " + lastLine);
}
}
var numBlock = (msg.match(/```/g) || []).length;
if (numBlock % 2 == 1) {
passOver = "```\n" + passOver;
msg = msg + "\n```";
}
argsFixed[i] = msg;
//Util.log("Message length: " + msg.length);
//Util.log("Pass Over: " + passOver.length);
if (passOver != "" && (argsFixed[i+1] != null || passOver != "```\n")) {
if (argsFixed[i+1] == null) {
//Util.log("Created new print block extender")
argsFixed[i+1] = "";
}
argsFixed[i+1] = passOver + argsFixed[i+1];
}
}
return argsFixed;
} */
exports.splitMessagesOld = function (messages) {
const fixed = exports.fixMessageLengthNew(messages.join(' '));
return fixed;
};
exports.escapeRegExp = function (str) {
return str.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');