-
Notifications
You must be signed in to change notification settings - Fork 417
/
Command.js
550 lines (528 loc) · 32.3 KB
/
Command.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
"use strict";
const Base = require("../structures/Base");
/**
* Represents an command framework command
* @prop {Array<String>} aliases An array of command aliases
* @prop {Boolean} argsRequired If arguments are required or not
* @prop {Boolean} caseInsensitive Whether the command label (and aliases) is case insensitive or not
* @prop {Number} cooldown The cooldown between command usage in milliseconds
* @prop {Object} cooldownExclusions A set of factors that limit where cooldowns are active
* @prop {Function | String} cooldownMessage A string or a function that returns a string to show when the command is on cooldown.
* @prop {Number} cooldownReturns Number of times to return a message when the command is used during it's cooldown.
* @prop {Object} defaultSubcommandOptions Default subcommand options.
* @prop {Boolean} deleteCommand Whether to delete the user command message or not
* @prop {String} description A short description of the command
* @prop {Boolean} dmOnly Whether the command is prevented from being used in guilds or not
* @prop {Function | String} errorMessage A string or a function that returns a string to show if the execution of the command handler somehow fails. The function is passed the Message object as a parameter.
* @prop {String} fullDescription A detailed description of the command
* @prop {String} fullLabel The full command label
* @prop {Boolean} guildOnly Whether the command is prevented from being used in Direct Messages or not
* @prop {Boolean} hidden Whether or not the command is hidden from the default help command list.
* @prop {Object} hooks A set of functions to be executed at different times throughout the command's processing
* @prop {Function | String} invalidUsageMessage A string or a function that returns a string to show when a command was improperly used.
* @prop {String} label The command label
* @prop {Command?} parentCommand If this command is also a subcommand, this will refer to its parent Command
* @prop {Function | String} permissionMessage A string or a function that returns a string to show when the user doesn't have permissions to use the command.
* @prop {Object?} reactionButtons An array of objects specifying reaction buttons, or null if no reaction buttons.
* @prop {Number} reactionButtonTimeout Time (in milliseconds) to wait before invalidating the command's reaction buttons
* @prop {Object} requirements A set of factors that limit who can call the command
* @prop {Boolean} restartCooldown Whether or not to restart a command's cooldown every time it's used
* @prop {Object} subcommands Object mapping subcommand labels to Command objects
* @prop {Object} subcommandAliases Object mapping subcommand aliases to their respective subcommand label
* @prop {String} usage Details on how to call the command to show in the default help command
*/
class Command {
/**
* Register a command
* @arg {String} label The command label
* @arg {Function | String | Array<Function | String>} generator A response string, array of functions or strings, or function that generates a string or array of strings when called.
* If a function is passed, the function will be passed a Message object and an array of command arguments. The Message object will have an additional property `prefix`, which is the prefix used in the command.
* `generator(msg, args)`
* @arg {Object} [options] Command options
* @arg {Array<String>} [options.aliases] An array of command aliases
* @arg {Boolean} [options.argsRequired=false] If arguments are required or not
* @arg {Boolean} [options.caseInsensitive=false] Whether the command label (and aliases) is case insensitive or not
* @arg {Number} [options.cooldown] The cooldown between command usage in milliseconds
* @arg {Object} [options.cooldownExclusions={}] A set of factors that limit where cooldowns are active
* @arg {Array<String>} [options.cooldownExclusions.userIDs] An array of user IDs representing users that are not affected by cooldowns.
* @arg {Array<String>} [options.cooldownExclusions.guildIDs] An array of guild IDs representing guilds that are not affected by cooldowns.
* @arg {Array<String>} [options.cooldownExclusions.channelIDs] An array of channel IDs representing channels that are not affected by cooldowns.
* @arg {Function | String | Object} [options.cooldownMessage] A string or `createMessage()` content object, or a function that returns either of those, to show when the command is on cooldown. The function is passed the Message object as a parameter.
* @arg {Number} [option.cooldownReturns=0] Number of times to return a message when the command is used during it's cooldown. Once the cooldown expires this is reset. Set this to 0 to always return a message.
* @arg {Object} [options.defaultSubcommandOptions={}] Default subcommand options. This object takes the same options as a normal Command
* @arg {Boolean} [options.deleteCommand=false] Whether to delete the user command message or not
* @arg {String} [options.description="No description"] A short description of the command to show in the default help command
* @arg {Boolean} [options.dmOnly=false] Whether to prevent the command from being used in guilds or not
* @arg {Function | String | Object} [options.errorMessage] A string or `createMessage()` content object, or a function that returns either of those, to show if the execution of the command handler somehow fails. The function is passed the Message object as a parameter.
* @arg {String} [options.fullDescription="No full description"] A detailed description of the command to show in the default help command
* @arg {Boolean} [options.guildOnly=false] Whether to prevent the command from being used in Direct Messages or not
* @arg {Boolean} [options.hidden=false] Whether or not the command should be hidden from the default help command list.
* @arg {Object} [options.hooks] A set of functions to be executed at different times throughout the command's processing
* @arg {Function} [options.hooks.preCommand] A function that is executed before any permission or cooldown checks is made. The function is passed the command message and arguments as parameters.
* @arg {Function} [options.hooks.postCheck] A function that is executed after all checks have cleared, but before the command is executed. The function is passed the command message, arguments, and if command checks were passed as parameters.
* @arg {Function} [options.hooks.postExecution] A function that is executed after the command is executed, regardless of the final failed state of the command. The function is passed the command message, arguments, and if execution succeeded as parameters.
* @arg {Function} [options.hooks.postCommand] A function that is executed after a response has been posted, and the command has finished processing. The function is passed the command message, arguments, and the response message (if applicable) as parameters.
* @arg {Function | String | Object} [options.invalidUsageMessage] A string or `createMessage()` content object, or a function that returns either of those, to show when a command was improperly used. The function is passed the Message object as a parameter.
* @arg {Function | String | Object} [options.permissionMessage] A string or `createMessage()` content object, or a function that returns either of those, to show when the user doesn't have permissions to use the command. The function is passed the Message object as a parameter.
* @arg {Array<{emoji: String, type: String, response: (Function | String | Array<Function | String>), filter: Function}>} [options.reactionButtons] An array of objects specifying reaction buttons
* `emoji` specifies the button emoji. Custom emojis should be in format `emojiName:emojiID`
* `type` specifies the type of the reaction button, either "edit" or "cancel"
* `response` specifies the content to edit the message to when the reaction button is pressed. This accepts the same arguments as the `generator` parameter of this function, but with an extra userID parameter for generator functions (`function(msg, args, userID)`) describing the user that made the reaction
* `filter` specifies a function (`function(msg, emoji, userID)`) that filters message reactions. If the function returns false, the reaction is not treated as a valid reaction button response
* @arg {Number} [options.reactionButtonTimeout=60000] Time (in milliseconds) to wait before invalidating the command's reaction buttons
* @arg {Object} [options.requirements] A set of factors that limit who can call the command
* @arg {Function | Array<String>} [options.requirements.userIDs] An array or a function that returns an array of user IDs representing users that can call the command. The function is passed the Message object as a parameter.
* @arg {Function | Object} [options.requirements.permissions] An object or a function that returns an object containing permission keys the user must match to use the command. The function is passed the Message object as a parameter.
* i.e.:
* ```
* {
* "administrator": false,
* "manageMessages": true
* }
* ```
* In the above example, the user must not have administrator permissions, but must have manageMessages to use the command
* @arg {Function | Array<String>} [options.requirements.roleIDs] An array or a function that returns an array of role IDs that would allow a user to use the command. The function is passed the Message object as a parameter.
* @arg {Function | Array<String>} [options.requirements.roleNames] An array or a function that returns an array of role names that would allow a user to use the command. The function is passed the Message object as a parameter.
* @arg {Function} [options.requirements.custom] A function that accepts a message and returns true if the command should be run
* @arg {Boolean} [option.restartCooldown=false] Whether or not to restart a command's cooldown every time it's used.
* @arg {String} [options.usage] Details on how to call the command to show in the default help command
*/
constructor(label, generator, options, parentCommand) {
this.parentCommand = parentCommand;
this.label = label;
this.description = options.description || "No description";
this.fullDescription = options.fullDescription || "No full description";
this.usage = options.usage || "";
this.aliases = options.aliases || [];
this.caseInsensitive = !!options.caseInsensitive;
this.hooks = options.hooks || {};
this.requirements = options.requirements || {};
if(!this.requirements.userIDs) {
this.requirements.userIDs = [];
}
if(!this.requirements.permissions) {
this.requirements.permissions = {};
}
this.deleteCommand = !!options.deleteCommand;
this.argsRequired = !!options.argsRequired;
this.guildOnly = !!options.guildOnly;
this.dmOnly = !!options.dmOnly;
this.cooldown = options.cooldown || 0;
this.cooldownExclusions = options.cooldownExclusions || {};
if(!this.cooldownExclusions.userIDs) {
this.cooldownExclusions.userIDs = [];
}
if(!this.cooldownExclusions.guildIDs) {
this.cooldownExclusions.guildIDs = [];
}
if(!this.cooldownExclusions.channelIDs) {
this.cooldownExclusions.channelIDs = [];
}
this.restartCooldown = !!options.restartCooldown;
this.cooldownReturns = options.cooldownReturns || 0;
this.cooldownMessage = options.cooldownMessage || false;
this.invalidUsageMessage = options.invalidUsageMessage || false;
this.permissionMessage = options.permissionMessage || false;
this.errorMessage = options.errorMessage || "";
this.reactionButtons = options.reactionButtons ? options.reactionButtons.map((button, index) => {
if(typeof button.response === "string") {
button.execute = () => button.response;
return button;
} else if(Array.isArray(button.response)) {
button.responses = button.response.map((item, otherIndex) => {
if(typeof item === "string") {
return () => item;
} else if(typeof item === "function") {
return item;
} else {
throw new Error(`Invalid reaction button response generator (index ${index}:${otherIndex})`);
}
});
button.execute = () => button.responses[Math.floor(Math.random() * button.responses.length)]();
return button;
} else if(typeof button.response === "function") {
button.execute = button.response;
return button;
} else if(button.type === "cancel") {
return button;
} else {
throw new Error(`Invalid reaction button response generator (index ${index})`);
}
}) : null;
this.reactionButtonTimeout = options.reactionButtonTimeout || 60000;
if(this.cooldown !== 0) {
this.usersOnCooldown = new Set();
if(this.restartCooldown) {
this.cooldownTimeouts = {};
}
if(this.cooldownReturns) {
this.cooldownAmounts = {};
}
}
if(typeof generator === "string") {
this.response = generator;
this.execute = () => this.response;
} else if(Array.isArray(generator)) {
this.responses = generator.map((item, index) => {
if(typeof item === "string") {
return () => item;
} else if(typeof item === "function") {
return item;
} else {
throw new Error(`Invalid command response generator (index ${index})`);
}
});
this.execute = () => this.responses[Math.floor(Math.random() * this.responses.length)]();
} else if(typeof generator === "function") {
this.execute = generator;
} else {
throw new Error("Invalid command response generator");
}
this.defaultSubcommandOptions = options.defaultSubcommandOptions || {};
this.subcommands = {};
this.subcommandAliases = {};
this.hidden = !!options.hidden;
}
get fullLabel() {
return `${this.parentCommand ? this.parentCommand.fullLabel + " " : ""}${this.label}`;
}
cooldownCheck(msg) {
// Verify the msg isn't excluded from cooldown checks
if(this.cooldownExclusionCheck(msg)) {
return true;
}
const userID = msg.author.id;
if(this.usersOnCooldown.has(userID)) {
if(this.cooldownReturns) {
this.cooldownAmounts[userID]++;
}
if(this.restartCooldown) {
clearTimeout(this.cooldownTimeouts[userID]);
this.cooldownTimeouts[userID] = setTimeout(() => {
this.usersOnCooldown.delete(userID);
}, this.cooldown);
}
return false;
}
if(this.cooldownReturns) {
this.cooldownAmounts[userID] = 0;
}
this.usersOnCooldown.add(userID);
if(this.restartCooldown) {
this.cooldownTimeouts[userID] = setTimeout(() => {
this.usersOnCooldown.delete(userID);
}, this.cooldown);
} else {
setTimeout(() => {
this.usersOnCooldown.delete(userID);
}, this.cooldown);
}
return true;
}
cooldownExclusionCheck(msg) {
return this.cooldownExclusions.channelIDs.includes(msg.channel.id) || this.cooldownExclusions.userIDs.includes(msg.author.id) || (msg.channel.guild && this.cooldownExclusions.guildIDs.includes(msg.channel.guild.id));
}
async executeCommand(msg, args) {
if(this.hooks.postCheck) {
const response = await this.hooks.postCheck(msg, args, true);
if(response) {
msg = response.msg || msg;
args = response.args || args;
}
}
const ret = this.execute(msg, args);
if(this.hooks.postExecution) {
this.hooks.postExecution(msg, args, true);
}
return ret;
}
async permissionCheck(msg) {
if(this.requirements.custom) {
if(typeof this.requirements.custom !== "function") {
throw new Error("Custom requirement is not a function");
}
if(!(await this.requirements.custom(msg))) {
return false;
}
}
if(this.requirements.userIDs) {
const userIDs = typeof this.requirements.userIDs === "function" ? await this.requirements.userIDs(msg) : this.requirements.userIDs;
if(!Array.isArray(userIDs)) {
throw new Error("User IDs requirement is not an array");
}
if(userIDs.length > 0 && !userIDs.includes(msg.author.id)) {
return false;
}
}
if(msg.channel.guild) {
if(this.dmOnly) {
return false;
}
if(this.requirements.permissions) {
const requiredPermissions = Object.keys(typeof this.requirements.permissions === "function" ? await this.requirements.permissions(msg) : this.requirements.permissions);
if(requiredPermissions.length > 0) {
const permissions = msg.channel.permissionsOf(msg.author.id);
for(const permission of requiredPermissions) {
if(!permissions.has(permission)) {
return false;
}
}
}
}
const roleIDs = msg.member.roles || [];
if(this.requirements.roleIDs) {
const requiredRoleIDs = typeof this.requirements.roleIDs === "function" ? await this.requirements.roleIDs(msg) : this.requirements.roleIDs;
if(!Array.isArray(requiredRoleIDs)) {
throw new Error("Role IDs requirement is not an array");
}
for(const roleID of requiredRoleIDs) {
if(!roleIDs.includes(roleID)) {
return false;
}
}
}
if(this.requirements.roleNames) {
const roleNames = roleIDs.map((roleID) => msg.channel.guild.roles.get(roleID).name);
const requiredRoleNames = typeof this.requirements.roleNames === "function" ? await this.requirements.roleNames(msg) : this.requirements.roleNames;
if(!Array.isArray(roleNames)) {
throw new Error("Role names requirement is not an array");
}
for(const roleName of requiredRoleNames) {
if(!roleNames.includes(roleName)) {
return false;
}
}
}
} else if(this.guildOnly) {
return false;
}
return true;
}
async process(args, msg) {
const shouldDelete = this.deleteCommand && msg.channel.guild && msg.channel.permissionsOf(msg._client.user.id).has("manageMessages");
if(this.hooks.preCommand) {
const response = await this.hooks.preCommand(msg, args);
if(response) {
msg = response.msg || msg;
args = response.args || args;
}
}
let reply;
if(this.cooldown !== 0 && !this.cooldownCheck(msg)) {
if(this.hooks.postCheck) {
const response = await this.hooks.postCheck(msg, args, true);
if(response) {
msg = response.msg || msg;
args = response.args || args;
}
}
if(this.cooldownMessage && (!this.cooldownReturns || this.cooldownAmounts[msg.author.id] <= this.cooldownReturns)) {
reply = typeof this.cooldownMessage === "function" ? await this.cooldownMessage(msg) : this.cooldownMessage;
if(reply) {
msg.channel.createMessage(reply);
}
}
return;
}
if(!await this.permissionCheck(msg)) {
if(this.hooks.postCheck) {
const response = await this.hooks.postCheck(msg, args, false);
if(response) {
msg = response.msg || msg;
args = response.args || args;
}
}
if(shouldDelete) {
msg.delete();
}
reply = typeof this.permissionMessage === "function" ? await this.permissionMessage(msg) : this.permissionMessage;
if(reply) {
msg.channel.createMessage(reply);
}
return;
}
if(args.length === 0) {
if(shouldDelete) {
msg.delete();
}
if(this.argsRequired) {
if(this.hooks.postCheck) {
const response = await this.hooks.postCheck(msg, args, true);
if(response) {
msg = response.msg || msg;
args = response.args || args;
}
}
reply = typeof this.invalidUsageMessage === "function" ? await this.invalidUsageMessage(msg) : this.invalidUsageMessage;
if(reply) {
if(typeof reply === "string") {
reply = {
content: reply
};
}
if(reply.content) {
reply.content = reply.content.replace(/%prefix%/g, msg.prefix).replace(/%label%/g, this.fullLabel);
}
msg.channel.createMessage(reply);
}
return;
}
return this.executeCommand(msg, args);
}
const label = this.subcommandAliases[args[0]] || args[0];
let subcommand;
if((subcommand = this.subcommands[label]) !== undefined || ((subcommand = this.subcommands[label.toLowerCase()]) !== undefined && subcommand.caseInsensitive)) {
msg.command = subcommand; // eslint-disable-line require-atomic-updates
return subcommand.process(args.slice(1), msg);
} else {
if(shouldDelete) {
msg.delete();
}
return this.executeCommand(msg, args);
}
}
/**
* Register a subcommand
* @arg {String} label The subcommand label
* @arg {Function | String | Array<Function | String>} generator A response string, array of functions or strings, or function that generates a string or array of strings when called.
* If a function is passed, the function will be passed a Message object and an array of subcommand arguments. The Message object will have an additional property `prefix`, which is the prefix used in the subcommand.
* `generator(msg, args)`
* @arg {Object} [options] Command options
* @arg {Array<String>} [options.aliases] An array of command aliases
* @arg {Boolean} [options.argsRequired=false] If arguments are required or not
* @arg {Boolean} [options.caseInsensitive=false] Whether the command label (and aliases) is case insensitive or not
* @arg {Number} [options.cooldown] The cooldown between command usage in milliseconds
* @arg {Object} [options.cooldownExclusions={}] A set of factors that limit where cooldowns are active
* @arg {Array<String>} [options.cooldownExclusions.userIDs] An array of user IDs representing users that are not affected by cooldowns.
* @arg {Array<String>} [options.cooldownExclusions.guildIDs] An array of guild IDs representing guilds that are not affected by cooldowns.
* @arg {Array<String>} [options.cooldownExclusions.channelIDs] An array of channel IDs representing channels that are not affected by cooldowns.
* @arg {Function | String | Object} [options.cooldownMessage] A string or `createMessage()` content object, or a function that returns either of those, to show when the command is on cooldown
* @arg {Number} [option.cooldownReturns=0] Number of times to return a message when the command is used during it's cooldown. Once the cooldown expires this is reset. Set this to 0 to always return a message.
* @arg {Object} [options.defaultSubcommandOptions={}] Default subcommand options. This object takes the same options as a normal Command
* @arg {Boolean} [options.deleteCommand=false] Whether to delete the user command message or not
* @arg {String} [options.description="No description"] A short description of the command to show in the default help command
* @arg {Boolean} [options.dmOnly=false] Whether to prevent the command from being used in guilds or not
* @arg {Function | String | Object} [options.errorMessage] A string or `createMessage()` content object, or a function that returns either of those, to show if the execution of the command handler somehow fails.
* @arg {String} [options.fullDescription="No full description"] A detailed description of the command to show in the default help command
* @arg {Boolean} [options.guildOnly=false] Whether to prevent the command from being used in Direct Messages or not
* @arg {Boolean} [options.hidden=false] Whether or not the command should be hidden from the default help command list
* @arg {Object} [options.hooks] A set of functions to be executed at different times throughout the command's processing
* @arg {Function} [options.hooks.preCommand] A function that is executed before any permission or cooldown checks is made. The function is passed the command message and arguments as parameters.
* @arg {Function} [options.hooks.postCheck] A function that is executed after all checks have cleared, but before the command is executed. The function is passed the command message, arguments, and if command checks were passed as parameters.
* @arg {Function} [options.hooks.postExecution] A function that is executed after the command is executed, regardless of the final failed state of the command. The function is passed the command message, arguments, and if execution succeeded as parameters.
* @arg {Function} [options.hooks.postCommand] A function that is executed after a response has been posted, and the command has finished processing. The function is passed the command message, arguments, and the response message (if applicable) as parameters.
* @arg {Function | String | Object} [options.invalidUsageMessage] A string or `createMessage()` content object, or a function that returns either of those, to show when a command was improperly used
* @arg {Function | String | Object} [options.permissionMessage] A string or `createMessage()` content object, or a function that returns either of those, to show when the user doesn't have permissions to use the command
* @arg {Array<{emoji: String, type: String, response: (Function | String | Array<Function | String>)}>} [options.reactionButtons] An array of objects specifying reaction buttons
* `emoji` specifies the button emoji. Custom emojis should be in format `emojiName:emojiID`
* `type` specifies the type of the reaction button, either "edit" or "cancel"
* `response` specifies the content to edit the message to when the reaction button is pressed. This accepts the same arguments as the `generator` parameter of this function, but with an extra userID parameter for generator functions (`function(msg, args, userID)`) describing the user that made the reaction
* `filter` specifies a function (`function(msg, emoji, userID)`) that filters message reactions. If the function returns false, the reaction is not treated as a valid reaction button response
* @arg {Number} [options.reactionButtonTimeout=60000] Time (in milliseconds) to wait before invalidating the command's reaction buttons
* @arg {Object} [options.requirements] A set of factors that limit who can call the command
* @arg {Function | Array<String>} [options.requirements.userIDs] An array or a function that returns an array of user IDs representing users that can call the command
* @arg {Function | Object} [options.requirements.permissions] An object or a function that returns an object containing permission keys the user must match to use the command
* i.e.:
* ```
* {
* "administrator": false,
* "manageMessages": true
* }
* ```
* In the above example, the user must not have administrator permissions, but must have manageMessages to use the command
* @arg {Function | Array<String>} [options.requirements.roleIDs] An array or a function that returns an array of role IDs that would allow a user to use the command
* @arg {Function | Array<String>} [options.requirements.roleNames] An array or a function that returns an array of role names that would allow a user to use the command
* @arg {Function} [options.requirements.custom] A function that accepts a message and returns true if the command should be run
* @arg {Boolean} [option.restartCooldown=false] Whether or not to restart a command's cooldown every time it's used.
* @arg {String} [options.usage] Details on how to call the command to show in the default help command
* @returns {Command}
*/
registerSubcommand(label, generator, options = {}) {
if(label.includes(" ")) {
throw new Error("Subcommand label may not have spaces");
}
if(this.subcommands[label]) {
throw new Error("You have already registered a subcommand for " + label);
}
options.defaultSubcommandOptions = options.defaultSubcommandOptions || {};
for(const key in this.defaultSubcommandOptions) {
if(this.defaultSubcommandOptions.hasOwnProperty(key) && options[key] === undefined) {
options[key] = this.defaultSubcommandOptions[key];
options.defaultSubcommandOptions[key] = this.defaultSubcommandOptions[key];
}
}
label = options.caseInsensitive === true ? label.toLowerCase() : label;
this.subcommands[label] = new Command(label, generator, options, this);
if(options.aliases) {
options.aliases.forEach((alias) => {
this.subcommandAliases[alias] = label;
});
}
return this.subcommands[label];
}
/**
* Register an alias for a subcommand
* @arg {String} alias The alias
* @arg {String} label The original subcommand label
*/
registerSubcommandAlias(alias, label) {
if(!this.subcommands[label]) {
throw new Error("No subcommand registered for " + label);
}
if(this.subcommandAliases[alias]) {
throw new Error(`Alias ${label} already registered`);
}
this.subcommandAliases[alias] = label;
this.subcommands[label].aliases.push(alias);
}
/**
* Unregister a subcommand
* @arg {String} label The subcommand label
*/
unregisterSubcommand(label) {
const original = this.subcommandAliases[label];
if(original) {
this.subcommands[original].aliases.splice(this.subcommands[original].aliases.indexOf(label), 1);
delete this.subcommandAliases[label];
} else {
delete this.subcommands[label];
}
}
toString() {
return `[Command ${this.label}]`;
}
toJSON(props = []) {
return Base.prototype.toJSON.call(this, [
"parentCommand",
"label",
"description",
"fullDescription",
"usage",
"aliases",
"caseInsensitive",
"hooks",
"requirements",
"deleteCommand",
"argsRequired",
"guildOnly",
"dmOnly",
"cooldown",
"cooldownExclusions",
"restartCooldown",
"cooldownReturns",
"cooldownMessage",
"invalidUsageMessage",
"permissionMessage",
"errorMessage",
"reactionButtons",
"reactionButtonTimeout",
"execute",
"defaultSubcommandOptions",
"subcommands",
"subcommandAliases",
"hidden",
...props
]);
}
}
module.exports = Command;