This repository was archived by the owner on Apr 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
1182 lines (1106 loc) · 40.5 KB
/
index.js
File metadata and controls
1182 lines (1106 loc) · 40.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
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
const Eris = require('eris');
const _ = require('lodash');
const assert = require('assert');
const fs = require('fs');
const fuzzy = require('fuzzy');
const childProcess = require('child_process');
const path = require('path');
const mimimist = require('minimist')
const util = require('util');
const vm = require('vm2');
const _config = require('./_config.json');
const _util = {
truthy: new Set(['true', 't', 'yes', 'y', 'on', 'enable', 'enabled', '1', '+']),
// null: ['null', 'nil', 'wat', '-1'],
falsy: new Set(['false', 'f', 'no', 'n', 'off', 'disable', 'disabled', '0', '-']),
200: ":heavy_check_mark: **[`200`] OK**",
401: ":x: **[`401`] Unauthorized**",
403: ":x: **[`403`] Forbidden**",
404: ":x: **[`404`] Not found**",
501: ":x: **[`501`] Not implemented.**",
stringify(data) {
return JSON.stringify(data, null, 2);
},
random(arr) {
return arr[Math.floor(Math.random() * arr.length)];
},
saveUser(id, data) {
userData.set(id, data);
fs.writeFileSync(`./userData/${id}.json`, this.stringify(data));
},
getUser(id) {
return userData.get(id) || {
isAdmin: false,
isBanned: false,
favorites: [],
spaces: []
}
},
resolveBoolean(val) {
val = val.toLowerCase();
if (this.truthy.has(val)) return true;
else if (this.falsy.has(val)) return false;
else return null;
},
isAdmin(id) {
let uData = this.getUser(id);
return uData.isAdmin;
},
isBanned(id) {
let uData = this.getUser(id);
return uData.isBanned;
},
forbiddenNames: ['_meta', 'random'],
forbiddenChars: ['/', '@', '\\', '[', ']', '\n', '\t'],
tagRegex: /\[>[^\s]*\/[^\s]*\]/g,
SYSTEM: {
username: "SYSTEM",
discriminator: "0000",
id: "-1"
},
tagsPerPage: 50
}
const _code = `\`\`\``; //`
class Space {
/**
*
* @param {String} name
*/
constructor(name) {
/**
* @type {String}
*/
this.name = name;
/**
* @type {Map<String, Tag>}
*/
this.tags = new Map();
/**
* @type {String[]}
*/
this.rawTags = [];
this.load();
}
/**
*
* @param {String} name
* @param {external:Eris.User|_util.SYSTEM} author
* @param {Object} [options={}]
* @param {Boolean} [options.private=false]
* @param {String[]} [options.contributors=[]]
* @param {Boolean} [options.limited=false]
*/
static create(name, author, options = {}) {
options = _.merge({
private: false,
limited: false,
contributors: []
}, options);
if (spaces.has(name)) return this;
let data = {
author: author.id,
contributors: [author.id, ...(options.contributors || [])],
tags: [],
lastModified: new Date().toISOString(),
private: options.private,
limited: options.limited
};
fs.mkdirSync(`./_/${name}`);
fs.writeFileSync(`./_/${name}/_meta.json`, _util.stringify(data));
let uData = _util.getUser(author.id);
uData.spaces.push(name);
_util.saveUser(author.id, uData);
console.log(`{${new Date().toISOString()}} [Space | Create]: ${name} by ${author.username}#${author.discriminator} (${author.id})`);
return new Space(name);
}
delete() {
this.tags.forEach(t => t.delete());
fs.unlinkSync(`./_/${this.name}/_meta.json`);
fs.rmdirSync(`./_/${this.name}`);
spaces.delete(this.name);
let uData = _util.getUser(this.author.id);
uData.spaces.splice(uData.spaces.findIndex(s => s === this.name), 1);
_util.saveUser(this.author.id, uData);
console.log(`{${new Date().toISOString()}} [Space | Delete]: ${this.name} by ${this.author.username}#${this.author.discriminator} (${this.author.id})`);
return undefined;
}
createTag([space, name], author, content, options = {}) {
let newTag = Tag.create([space, name], author, content, options);
this.addTag(newTag);
return newTag;
}
save(update = true) {
if (update) this.lastModified = new Date();
let data = this.toJSON();
delete data.name;
fs.writeFileSync(`./_/${this.name}/_meta.json`, _util.stringify(data));
return this;
}
load() {
let data = JSON.parse(fs.readFileSync(`./_/${this.name}/_meta.json`).toString());
this.author = data.author === "-1" ? _util.SYSTEM : (client.users.get(data.author) || _util.SYSTEM);
this.rawTags = Array.from(new Set(_(fs.readdirSync(`./_/${this.name}`)).map(t => t.slice(0, -5)).without('_meta').value()));
this.contributors = data.contributors.map(u => client.users.get(u) || _util.SYSTEM) || [];
this.lastModified = new Date(data.lastModified) || new Date();
this.private = data.private || false;
this.limited = data.limited || false;
console.log(`{${new Date().toISOString()}} [Space | Load]: ${this.name} by ${this.author.username}#${this.author.discriminator} (${this.author.id}) with ${this.rawTags.length} tags`);
this.loadTags();
return this;
}
get random() {
let _tag = _util.random(this.rawTags);
return this.getTag(_tag);
}
/**
*
* @param {Tag} tag
*/
addTag(tag) {
if (this.tags.has(tag.name)) return false;
this.tags.set(tag.name, tag);
if (!this.rawTags.includes(tag.name)) this.rawTags.push(tag.name);
return this;
}
/**
* @param {String} id
*/
addContributor(id) {
if (client.users.has(id)) {
if (!this.isContributor(id)) {
let user = client.users.get(id);
this.contributors.push(user);
console.log(`{${new Date().toISOString()}} [Space | Edit]: ${user.username}#${user.discriminator} was added to ${this.name}`);
this.save(false);
} else {
return null;
}
} else if (id === _util.SYSTEM.id) {
if (!this.contributors.includes(_util.SYSTEM)) this.contributors.push(_util.SYSTEM);
console.log(`{${new Date().toISOString()}} [Space | Edit]: SYSTEM#0000 was added to ${this.name}`);
this.save(false);
} else {
return null;
}
return this;
}
/**
* @param {String} id
*/
isContributor(id) {
return this.contributors.some(u => u.id === id);
}
/**
* @param {String} id
*/
removeContributor(id) {
if (this.isContributor(id) && client.users.has(id)) {
let user = client.users.get(id);
this.contributors.splice(this.contributors.findIndex(u => u.id === id), 1);
console.log(`{${new Date().toISOString()}} [Space | Edit]: ${user.username}#${user.discriminator} was removed from ${this.name}.`);
this.save(false);
} else if (this.isContributor(id) && id === _util.SYSTEM.id) {
this.contributors.splice(this.contributors.findIndex(u => u.id === id), 1);
console.log(`{${new Date().toISOString()}} [Space | Edit]: ${user.username}#${user.discriminator} was removed from ${this.name}.`);
this.save(false);
} else {
return null;
}
return this;
}
clearContributors() {
this.contributors.forEach(c => this.removeContributor(c.id));
}
transfer(target, keepContributors = false) {
let prevOwner = client.users.get(this.author.id);
let prevOwnerData = _util.getUser(this.author.id);
if (client.users.has(target.id)) {
let nextOwner = client.users.get(target.id);
let nextOwnerData = _util.getUser(target.id);
if (uData.spaces.length <= 5 || _util.isAdmin(id)) {
// Old Owner
if (!keepContributors) this.clearContributors();
this.author = null;
prevOwnerData.spaces.splice(prevOwnerData.spaces.indexOf(this.name), 1);
// Log Action
console.log(`{${new Date().toISOString()}} [Space | Edit]: ${this.name} was transfered from ${prevOwner.username}#${prevOwner.discriminator} to ${nextOwner.username}#${nextOwner.discriminator}`);
// New Owner
this.author = nextOwner;
this.addContributor(nextOwner.id);
nextOwnerData.spaces.push(this.name);
this.save(false);
return true;
} else {
return false;
}
} else if (_.isEqual(target, _util.SYSTEM)) {
// Old Owner
if (!keepContributors) this.clearContributors();
this.author = _util.SYSTEM;
this.private = false;
this.limited = true;
prevOwnerData.spaces.splice(prevOwnerData.spaces.indexOf(this.name), 1);
// Log Action
console.log(`{${new Date().toISOString()}} [Space | Edit]: ${this.name} was transfered from ${prevOwner.username}#${prevOwner.discriminator} to SYSTEM#0000`);
// New Owner - SYSTEM
this.author = _util.SYSTEM;
this.addContributor(this.author.id);
// Save it
this.save(true);
return true;
} else {
return null;
}
}
/**
*
* @param {String} _t
*/
getTag(_t) {
if (!this.hasTag(_t)) return null;
let tag = new Tag(_t, this);
this.tags.set(_t, tag);
return tag;
}
hasTag(t) {
return this.tags.has(t) || this.rawTags.includes(t);
}
deleteTag(_t) {
if (!this.hasTag(_t)) return false;
let tag = this.getTag(_t);
if (this.tags.has(_t)) this.tags.delete(_t);
if (this.rawTags.includes(_t)) this.rawTags.splice(this.rawTags.indexOf(_t), 1);
if(fs.existsSync(`./_/${this.name}/${_t}.json`)) fs.unlinkSync(`./_/${this.name}/${_t}.json`);
console.log(`{${new Date().toISOString()}} [(Space) Tag | Delete]: ${this.name}/${tag.name} by ${tag.author.username}#${tag.author.discriminator}`)
return true;
}
loadTags() {
this.rawTags.forEach(t => {
this.tags.set(t, new Tag(t, this));
})
return this;
}
rename(name) {
if (spaces.has(name)) return false;
let uData = _util.getUser(this.author.id);
fs.renameSync(`./_/${this.name}`, `./_/${name}`);
spaces.delete(this.name);
spaces.set(name, this);
uData.spaces.splice(uData.spaces.indexOf(this.name), 1, name);
console.log(`{${new Date().toISOString()}} [Space | Edit]: ${this.name} renamed to ${name}`);
this.name = name;
_util.saveUser(this.author.id, uData);
return this;
}
toString() {
return `<Space name=${this.name} tags=${this.rawTags.length} private=${this.private} limited=${this.limited} lastModified=${this.lastModified.toISOString()}>`;
}
toJSON() {
return {
name: this.name,
author: this.author.id,
private: this.private,
limted: this.limited,
contributors: this.contributors.map(u => u.id || u).filter(u => !u instanceof String),
lastModified: this.lastModified.toISOString()
}
}
}
class Tag {
/**
*
* @param {String} name
* @param {Space} space
*/
constructor(name, space) {
/**
* @type {String}
*/
this.name = name;
/**
* @type {Space}
*/
this.space = space;
this.load();
}
static create([space, name], author, content, options = {}) {
if (!spaces.has(space)) return undefined;
let data = _util.stringify({
author: author.id,
content: content,
lastModified: Date.now(),
uses: 0,
favorites: 0
});
fs.writeFileSync(`./_/${space}/${name}.json`, data);
console.log(`{${new Date().toISOString()}} [Tag | Create]: ${space}/${name} by ${author.username}#${author.discriminator} (${author.id})`);
return new Tag(name, spaces.get(space));
}
save(update = true) {
if (update) {
this.lastModified = new Date()
};
let data = this.toJSON();
delete data.name;
fs.writeFileSync(`./_/${this.space.name}/${this.name}.json`, _util.stringify(data));
this.space.tags.set(this.name, this);
return this;
}
use(user) {
this.uses++;
this.save(false);
console.log(`{${new Date().toISOString()}} [Tag | Use]: ${this.space.name}/${this.name} by ${user.username}#${user.discriminator} (${user.id})`);
return this;
}
favorite(user) {
let data = _util.getUser(user.id);
if (data.favorites.includes(`${this.space.name}/${this.name}`)) {
let index = data.favorites.findIndex(fav => fav === `${this.space.name}/${this.name}`);
data.favorites.splice(index, 1);
this.favorites--;
console.log(`{${new Date().toISOString()}} [Tag | Unfavorite]: ${user.username}#${user.discriminator} removed ${this.space.name}/${this.name} from their favorites.`);
} else {
data.favorites.push(`${this.space.name}/${this.name}`);
this.favorites++;
console.log(`{${new Date().toISOString()}} [Tag | Favorite]: ${user.username}#${user.discriminator} added ${this.space.name}/${this.name} to their favorites.`);
}
_util.saveUser(user.id, data);
this.save(false);
return this;
}
load() {
let data = JSON.parse(fs.readFileSync(`./_/${this.space.name}/${this.name}.json`).toString());
this.author = data.author === "-1" ? _util.SYSTEM : (client.users.get(data.author) || _util.SYSTEM);
this.content = data.content || _util["404"];
this.lastModified = new Date(data.lastModified) || new Date();
this.uses = data.uses || 0;
this.favorites = data.favorites || 0;
return this;
}
rename(name) {
if (this.space.hasTag(name)) return `${_util["403"]} | Name already exists`
fs.renameSync(`./_/${this.toString()}`, `./_/${this.space.name}/${name}`);
this.space.tags.delete(this.name);
this.space.rawTags.splice(this.space.rawTags.findIndex(t => t === this.name));
this.name = name;
this.space.tags.set(this.name, this);
this.space.rawTags.push(this.name);
this.save();
console.log(`{${new Date().toISOString()}} [Tag | Edit]: ${this.space.name}/${this.name} renamed to ${this.space.name}/${name}`);
return this;
}
toString() {
return `<Tag spaceName=${this.space.name} name=${this.name} lastModified=${this.lastModified.toISOString()} uses=${this.uses} favorites=${this.favorites}>`;
}
toJSON() {
return {
name: this.name,
author: this.author.id,
content: this.content,
lastModified: this.lastModified.toISOString(),
uses: this.uses,
favorites: this.favorites
}
}
transfer(target) {
let prevOwner = client.users.get(this.author.id);
if (client.users.has(target.id)) {
let nextOwner = client.users.get(target.id);
} else if (_.isEqual(target, _util.SYSTEM)) {
this.author = _util.SYSTEM;
console.log(`{${new Date().toISOString()}} [Tag | Edit]: ${this.name} was transfered from ${prevOwner.username}#${prevOwner.discriminator} to SYSTEM#0000`);
this.save(true);
return true;
} else {
return null;
}
}
}
const client = new Eris.CommandClient(_config.token, {
autoreconnect: true,
disableEveryone: true
}, {
defaultHelpCommand: true,
ignoreSelf: true,
ignoreBots: true,
name: "Tag[ ]Space",
description: "A tagbot, nothing more.",
owner: "PlayTheFallen#8318",
prefix: ["[T]", "@mention "]
});
/**
* @type {Map<String, Space>}
*/
let spaces = new Map();
/**
* @type {Map<String, Object>}
*/
let userData = new Map();
client.registerCommand('eval', async (msg, args) => {
try {
let start = msg.createdAt;
let ev = eval(args.join(" "));
let end = Date.now();
if (ev instanceof Promise) await ev;
if (typeof ev !== 'string')
ev = util.inspect(ev, {
depth: 2,
showHidden: true
})
ev = ev.replace(client.token, '1n-r1sk-w3-tru5t');
if (ev.length > 1000) {
msg.channel.createMessage('**Output:** Success *with file upload*\nTime: ' + (end - start) / 1000, {
file: ev,
name: "evalresult.log"
});
} else {
msg.channel.createMessage('**Output:**\n```js\n' + ev + '```\nTime: ' + (end - start) / 1000);
}
} catch (err) {
if (err.stack.length > 1000) {
msg.channel.createMessage('**Output:** Failure *with file upload*', {
file: err.stack,
name: "evalerror.log"
});
} else {
msg.channel.createMessage('**Output:** Failure\n```js\n' + err.stack + '```');
}
}
}, {
hidden: true,
requirements: {
userIDs: ['133659993768591360']
}
})
client.registerCommand('exec', (msg, args) => {
let result = childProcess.execSync(args.join(' '));
msg.channel.createMessage(`**Output:**\n\`\`\`${result}\`\`\``);
childProcess.exec(args.join(' '), (err, stdout, stderr) => {
if (err)
return msg.channel.createMessage(`**Failure:**\n${_code}\n${err}\n${_code}`);
else if (stderr)
return msg.channel.createMessage(`**Failure:**\n${_code}\n${stderr}\n${_code}`);
else
return msg.channel.createMessage(`**Output:**\n${_code}\n${stdout}\n${_code}`);
})
}, {
hidden: true,
requirements: {
userIDs: ['133659993768591360']
}
})
client.registerCommand('limits', "`304`: Moved to `system/limits`.", {
description: "**MOVED**: Run the command to see the limits of this service."
});
let spaceCommand = client.registerCommand('space', (msg, args) => client.commands['help'].execute(msg, ['space']), {
aliases: ['s'],
description: "m8 gimme some space of yours",
fullDescription: "you have way to much"
})
spaceCommand.registerSubcommand('create', (msg, args) => {
let spaceName = args.shift();
let uData = _util.getUser(msg.author.id);
if (spaces.has(spaceName)) return `${_util["403"]} | Space already exists.`;
if (uData.spaces.length >= 5) return `${_util["403"]} | You already have 5 spaces.`;
let options = mimimist(args, {
boolean: ['private', 'limited'],
alias: {
p: 'private',
c: 'contributors',
l: 'limited'
},
default: {
private: false,
contributors: "",
limited: false
}
});
options.contributors = options.contributors.split(',').filter(c => client.users.has(c));
let newSpace = Space.create(spaceName, msg.author, options);
spaces.set(newSpace.name, newSpace);
uData.spaces.push(newSpace.name);
_util.saveUser(msg.author.id, uData);
return `${_util["200"]} | Space \`${newSpace.name}\` created.
**Space Options:**
> Private: ${newSpace.private ? 'Yes' : 'No'}
> Contributors: ${options.contributors.length > 0 ? formatArray(options.contributors.map(c => {let u = client.users.get(c); return `${u.username}#${u.discriminator}`}).filter(u => !util.isNullOrUndefined(u))) : 'No contributors'}
> Limited: ${newSpace.limited ? 'Yes' : 'No'}`;
}, {
description: "Create your own space.",
fullDescription: [
"**[`Usage Explained:`]**",
"",
"**Optional Arguments:**",
"> `p|private`: Whether or not the space should be hidden from searches. (WIP)",
"> `c|contributors`: Space contributors to add from the start. (WIP)",
"> `l|limited`: Limited access meaning that only contributors can interact with this space, others can still read what is inside. (WIP)",
"",
"**Examples:**",
"> -p -c 359353569478049792,329729588206764041 -l",
"> --private --contributors 359353569478049792,329729588206764041 --limited",
"",
"**Notes:**",
"> Extra arguments intended to be part of the name will be discarded in the creation of the space.",
"> IDs unknown to the bot will be filtered out of the creation process."
].join('\n'),
usage: "<name> [(-(-)<key> [value])]"
});
spaceCommand.registerSubcommand('delete', (msg, args) => {
let _space = args.shift();
let uData = _util.getUser(msg.author.id);
if (!spaces.has(_space))
return _util["404"];
let space = spaces.get(_space);
if (!(_util.isAdmin(msg.author.id) || space.author.id === msg.author.id))
return `${_util["403"]}`;
space.delete();
return _util["200"];
}, {
description: "Delete a space of yours.",
fullDescription: "You need to be the author of the space. \n**(WARNING: There is no confirm action ...yet)**\nPlease take care when using this.",
usage: "<space>"
});
spaceCommand.registerSubcommand('edit', (msg, args) => {
let [_space, action, ...extra] = args;
// [Checks]
if (!spaces.has(_space))
return `${_util["404"]} (Space)`;
let space = spaces.get(_space);
if (!(space.author.id === msg.author.id ||
_util.isAdmin(msg.author.id)))
return `${_util["403"]} (Permissions)`;
// [Actions]
switch (action) {
case "n":
case "name":
// <name>
{
let newName = extra.shift();
space.rename(newName);
return `${_util["200"]} | Space renamed to \`${newName}\``;
//return _util["501"];
}
case "t":
case "transfer":
// @target|targetid|SYSTEM
{
let target = (msg.mentions[0] ? msg.mentions[0] :
client.users.has(args[0]) ? client.users.get(args[0]) : null) || _util.SYSTEM;
if (!target && target !== _util.SYSTEM)
return `${_util["404"]} (User)`;
space.transfer(target);
return `${_util["200"]} | Transfered \`${_space}\` to ${target.username}#${target.discriminator}`;
}
case "c":
case "contributors":
{
let targets = msg.mentions;
if (!targets.length === 0) return `${_util["401"]}\n> Invaild targets / Targets not found`;
switch (args.shift()) {
case "a":
case "add":
case "+":
{
targets = _.filter(targets, (target) => !space.isContributor(target.id));
_.each(targets, (target) => space.addContributor(target.id));
return `${_util["200"]}\n> Added ${formatArray(targets)} as contributors of ${_space}`;
}
case "r":
case "remove":
case "-":
{
targets = _.filter(targets, (target) => space.isContributor(target.id));
_.each(targets, (target) => space.removeContributor(target.id));
return `${_util["200"]}\n> Added ${formatArray(targets)} as contributors of ${_space}.`;
}
default:
return `${_util["404"]}`;
}
}
case "p":
case "private":
{
let newValue = _util.resolveBoolean(args.shift());
if (newValue) return `${_util["404"]}`;
space.private = newValue;
space.save()
return `${_util["200"]} (Set \`private\` to ${space.limited ? 'Yes': 'No'}`;
}
case "l":
case "limited":
{
let newValue = _util.resolveBoolean(args.shift());
if (newValue) return `${_util["404"]}`;
space.limited = newValue;
space.save()
return `${_util["200"]} (Set \`limited\` to ${space.limited ? 'Yes': 'No'}`;
}
default:
return _util["404"];
}
}, {
description: "Change your space up. Make it your own.",
fullDescription: [
"**[`Usage Explained`]**",
"",
"**Resolvers:**",
"> `true`: `t|true`, `y|yes`, `0`, `+`",
"> `false`: `f|false`, `n|no`, `1`, `-`",
// TODO: Transfer resolvers
//"See `system/resolvers`",
"",
"**Action Types:**",
"> `n|name <newName>` - Change the name of your space. That is if your new one isn't already taken.",
"> `t|transfer <@target|SYSTEM>` - Is it that time? I'm sure this person will take good care of it.",
"> `c|contributors <(a|add|+)|(r|remove|-)> <...@target>` - Allow others to help manage the space. (content only, not the space itself).",
"> `p|private {resolver}` - Should others be allowed to access the content.",
"> `l|limited {resolver}` - Should others be allowed to contribute their own content to this space? (contributors and existing tag authors will be able to no matter what)",
"",
"**Examples:**",
"None yet...",
"",
"**Notes:**",
"> `t|transfer` will failback to you if the `@target` does not exist or does not have enough space slots in their own profile. (WIP)",
" > You can also `t|transfer` it to the system by providing 'SYSTEM' as the transfer target instead. But once it's gone, to someone else, the contributors will be wiped *including SYSTEM*.",
"> `c|contributors` will be able to access the space no matter the setting for `l|limited` or `p|private`"
].join('\n'),
usage: "<space> <{action}> (<...extra>)"
});
spaceCommand.registerSubcommand('info', (msg, args) => {
return _util["501"];
}, {
usage: "<space>"
})
client.registerCommand('quote', async (msg, args) => {
if(msg.author.id !== '133659993768591360') return _util["501"];
let msgID = args.shift();
let argv = mimimist(args, {
alias: {
c: "channel",
e: "embed"
},
default: {
channel: msg.channel.id,
embed: false
}
})
if (!hasPermissions(msg, ['EMBED_LINKS'])) argv.e = argv.embed = false;
if (!msg.channel.guild.channels.has(argv.c)) argv.c = argv.channel = msg.channel.id;
let channel = msg.channel.guild.channels.get(argv.c);
let targetMessage = await channel.getMessage(msgID);
if (util.isNullOrUndefined(targetMessage)) return `${_util["404"]} (Message ID)`;
if (argv.e) {
msg.channel.createMessage({
embed: {
author: {
name: `${targetMessage.author.username}#${targetMessage.author.discriminator}`,
icon_url: targetMessage.author.avatarURL || targetMessage.author.defaultAvatarURL
},
description: targetMessage.content,
timestamp: targetMessage.timestamp,
color: Math.floor(Math.random() * 0xFFFFFF),
}
})
} else {
msg.channel.createMessage([
`${(a => `**${a.username}#${a.discriminator} (${a.id})**`)(targetMessage.author)} once said:`,
'-'.repeat(20),
targetMessage.content.substring(0, 1000),
'-'.repeat(20)
].join('\n'))
}
}, {
description: "Recall a message?",
fullDescription: [
"**[`Usage Explained`]**",
"",
"**Options:**",
"> `<message>` - Your target. (Message ID)",
"> `c|channel <id>` - Channel to target. (Channel ID)",
"> `e|embed` - Embed the quote.",
"",
"**Todo:**",
"> Add a `color` option for the embed.",
"> Add a feature to detect and add message attachments to the embed.",
"> Add a feature to recognise game application messages / system messages / etc.",
"> Add a feature to add the quote as a tag in a given space.",
"",
"**Notes:**",
"> This command is guild only.",
"> `<message>` will fallback to 404, if the target cannot be found.",
"> `c|channel` will fallback to the current channel, if the target cannot be found.",
"> `e|embed` will fallback to the default message format."
].join('\n'),
guildOnly: true,
usage: "<message> [-(-)<key> [value]]"
})
let tagCommand = client.registerCommand('tag', (msg, args) => client.commands['help'].execute(msg, ['tag']), {
aliases: ['t'],
description: "i want a share of your space"
});
tagCommand.registerSubcommand('create', (msg, args) => {
let [_space, name] = args.shift().split('\/');
let content = args.join(' '); //.replace(/[\n\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
if (_util.forbiddenNames.includes(name))
return _util["403"] + ' | (Name)';
if (_util.forbiddenChars.some(c => (name || "").includes(c)))
return _util["403"] + ' | (Chars)';
if (!spaces.has(_space))
return `${_util["404"]} | (Space).`;
let space = spaces.get(_space);
if ((space.private || space.limited) &&
!(space.isContributor(msg.author.id) ||
space.author.id === msg.author.id ||
_util.isAdmin(msg.author.id)))
return `${_util["403"]} (Permissions)`;
if (space.hasTag(name))
return `${_util["403"]} | Tag \`${name}\` already exists.`;
if (content.length < 20 && !_util.isAdmin(msg.author.id))
return `${_util["403"]} | Tag content is too short (${content.length} of 20)`;
if (content.length > 1500 && !_util.isAdmin(msg.author.id))
return `${_util["403"]} | Tag content is too long (${content.length}/1500)`;
space.createTag([_space, name], msg.author, content);
return `${_util["200"]} | Tag \`${_space}/${name}\` created.`;
}, {
fullDescription: "**DO NOT ADD A NEW LINE DIRECTLY AFTER THE INTENDED TAG NAME, IT HAS TO BE A SPACE (\\u0020)**",
usage: "<{space}/{newTag}> <...content>"
});
tagCommand.registerSubcommand('search', (msg, args) => {
let [_space, ...query] = args;
if (!spaces.has(_space)) return `${_util["404"]} (Space)`;
let space = spaces.get(_space);
if (space.private && !(
_util.isAdmin(msg.author.id) ||
space.author.id === msg.author.id ||
space.isContributor(msg.author.id)))
return `${_util["403"]} (Permissions)`;
let tags = [...space.tags.keys()];
let searchResult = _.chunk(fuzzy.filter(query.join(' '), tags), 50)[0].map(val => val.string);
msg.channel.createMessage(`**Search results for \`${query.join(' ')}\` in ${_space}:**\n${_code}fix\n${searchResult.join(', ')}\n${_code}`);
}, {
description: "Shows first 50 tags from search query.",
usage: "<space> <...query>"
});
tagCommand.registerSubcommand('raw', (msg, args) => {
let [_space, _tag] = args.shift().split('\/');
if (!spaces.has(_space)) return `${_util["404"]} | (Space)`;
let space = spaces.get(_space);
if (!space.hasTag(_tag)) return `${_util["404"]} | (Tag)`;
let tag = space.getTag(_tag);
if (!(_util.isAdmin(msg.author.id) ||
space.author.id === msg.author.id ||
space.isContributor(msg.author.id) ||
tag.author.id === msg.author.id))
return `${_util["403"]} | (Permissions)`;
msg.channel.createMessage([
`**${tag.space.name}/${tag.name}** by **${tag.author.username}#${tag.author.discriminator}**`,
`**${"-".repeat(20)}`,
`${_code}js`,
`${tag.content}`,
_code,
`**${"-".repeat(20)}`
].join('\n'))
}, {
description: "Useful for editing. (copying is not prefered)",
fullDescription: "This is restricted to space owners, space contributors and the tag owner.",
usage: "<{space}/{tag}>"
});
tagCommand.registerSubcommand('list', async (msg, args) => {
let [_space, page = 1] = args;
if (page < 1) page = 1;
if (!spaces.has(_space)) return _util["404"];
let space = spaces.get(_space);
if (space.private && !(
_util.isAdmin(msg.author.id) ||
space.author.id !== msg.author.id ||
space.isContributor(msg.author.id)))
return _util["403"];
let tags = [...space.tags.keys()];
let tagPage = _.chunk(tags, 50)[0];
msg.channel.createMessage(`**Tag[ ]Space \`${_space}\`**\n\`\`\`fix\n${tagPage.join(', ')}\`\`\``); //[\`${page % tagPages.length}\` of \`${tagPages.length}\`]
}, {
usage: "<{space}>"
});
tagCommand.registerSubcommand('delete', (msg, args) => {
let [_space, _tag] = args.shift().split('/');
let uData = _util.getUser(msg.author.id);
if (!spaces.has(_space)) return _util["404"];
let space = spaces.get(_space);
if (!space.hasTag(_tag)) return _util["404"];
let tag = space.getTag(_tag);
if (!(tag.author.id === msg.author.id || space.isContributor(msg.author.id) || space.author.id === msg.author.id || _util.isAdmin(msg.author.id))) return `${_util["403"]}`
space.deleteTag(_tag);
return `${_util["200"]} | \`${_space}/${_tag}\` was deleted.`
}, {
usage: "<({space}/{tag})>"
});
tagCommand.registerSubcommand('edit', (msg, args) => {
let [_space, _tag] = args.shift().split('/');
let content = args.join(' ');
if (!spaces.has(_space)) return `${_util["404"]} | TagSpace \`${_space}\` not found.`;
let space = spaces.get(_space);
if (!space.hasTag(_tag)) return `${_util["404"]} | Tag \`${_space}/${_tag}\` not found.`;
let tag = space.getTag(_tag);
if (!(tag.author.id === msg.author.id ||
space.isContributor(id) ||
space.author.id === msg.author.id ||
_util.isAdmin(msg.author.id)))
return _util["403"];
if (content.length < 20 && !_util.isAdmin(msg.author.id))
return `${_util["403"]} | Tag content is too short (${content.length} of 20)`;
if (content.length > 1500 && !_util.isAdmin(msg.author.id))
return `${_util["403"]} | Tag content is too long (${content.length}/1500)`;
tag.content = content;
tag.save();
return `${_util["200"]} | Tag \`${_space}/${_tag}\` edited.`;
}, {
usage: "<({space}/{tag})> <...content>"
});
tagCommand.registerSubcommand('transfer', (msg, args) => {
let [_space, _tag] = args.shift('/');
let target = args[0] === 'SYSTEM' ? null : (msg.mentions[0] ? msg.mentions[0] : null) || _util.SYSTEM;
if (!spaces.has(_space)) return `${_util["404"]} | TagSpace \`${_space}\` not found.`;
let space = spaces.get(_space);
if (!space.hasTag(_tag)) return `${_util["404"]} | Tag \`${_space}/${_tag}\` not found.`;
let tag = space.getTag(_tag);
if (!(tag.author.id === msg.author.id ||
space.isContributor(id) ||
space.author.id === msg.author.id ||
_util.isAdmin(msg.author.id)))
return _util["403"];
tag.transfer(target);
return `${_util["200"]} | \`${_space}/${_tag}\` was given to ${tag.author.username}#${tag.author.discriminator}`;
}, {
description: "Pass the mantel of responsibility to one that may be worthy of your chosen tag.",
usage: "<{space}/{tag}> <@target|SYSTEM>"
})
tagCommand.registerSubcommand('info', (msg, args) => {
let [_space, _tag] = args.shift().split('/');
if (!spaces.has(_space)) return _util["404"];
let space = spaces.get(_space);
if (!space.hasTag(_tag)) return _util["404"];
let tag = space.getTag(_tag);
if (!(tag.author.id === msg.author.id ||
space.isContributor(msg.author.id) ||
space.author.id === msg.author.id) &&
space.private) return _util["403"];
return `Tag info for \`${space}/${tag}\` would be here.`;
}, {
usage: "<({space}/{tag})>"
});
tagCommand.registerSubcommand('favorite', (msg, [action = 'add', ...tags] /* args */ ) => {
tags = tags.map(t => {
let [_space, _tag] = t.split('/');
if (!spaces.has(_space)) return null;
let space = spaces.get(_space);
if (!space.hasTag(_tag)) return null;
return space.getTag(_tag);
}).filter(t => !util.isNullOrUndefined(t));
if (['a', 'add', '+'].includes(action)) {
tags.forEach(t =>
t.favorite(msg.author));
return `${_util["200"]} | You added ${tags.length} tags to your favorites.\n> ${tags.map(t => `\`${t.space.name}/${t.name}\``).join(', ')}`;
} else if (['r', 'remove', '-'].includes(action)) {
tags.forEach(t =>
t.favorite(msg.author));
return `${_util["200"]} | You removed ${tags.length} tags from your favorites\n> ${tags.map(t => `\`${t.space.name}/${t.name}\``).join(', ')}`;
} else {
return `${_util["404"]} | Please provide a valid action.`;
}
}, {
aliases: ['favourite'],
description: "(Un)favorite some of your \"good finds\".",
usage: "<(a|add|+)|(r|remove|-)> <{space}/{tag}> [{space}/{tag}] ..."
});
let myCommand = client.registerCommand('my', (msg) => client.commands['help'].execute(msg, ["my"]), {
description: "This one doesn't do anything."
})
myCommand.registerSubcommand('favorites', (msg, args) => {
let uData = _util.getUser(msg.author.id);
return `**Your favorites (${uData.favorites.length}):**\n${_.chunk(uData.favorites.slice(0, 50), 10).map(arr => `> ${arr.map(t => `\`${t}\``).join(', ')}`).join('\n')}`;
}, {
aliases: ['favourites'],
description: "Get all your favorites in one place. (pages soon:tm:, will only show first 50 at best)",
//usage: ""
});
myCommand.registerSubcommand('spaces', (msg, args) => {
let uData = _util.getUser(msg.author.id);
return `**Your spaces (${uData.spaces.length}):**\n${uData.spaces.map(s => `> \`${s}\``).join('\n')}`;
}, {
description: "Get all your spaces in one place.",
//usage: "[page]"
});
myCommand.registerSubcommand('tags', (msg, args) => {
let uData = _util.getUser(msg.author.id);
let _spaceCount = 0;
let tags = _([...[...spaces.values()].map(space => [...space.tags.values()])].map(tags => tags.filter(t => t.author.id === msg.author.id))).flatten().chunk(50).value()[0].map(t => `${t.space.name}/${t.name}`);
return `**Your tags (${tags.length} across ${_spaceCount}):**\n${_code}fix\n${tags.join(', ')}\n${_code}`;
}, {
description: "not yet, sorry... (will only show first 50 at best)",