-
Notifications
You must be signed in to change notification settings - Fork 13
/
Command.ts
402 lines (353 loc) · 13 KB
/
Command.ts
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
/* eslint-disable complexity */
import { PermissionResolvable, Permissions, MessageOptions } from 'discord.js';
import { ArgOpts } from '../types/ArgOpts';
import { Client } from '../client/Client';
import { CommandInfo } from '../types/CommandInfo';
import { CommandLock } from './CommandLock';
import { CompactModeHelper } from './CompactModeHelper';
import { Message } from '../types/Message';
import { MiddlewareFunction } from '../types/MiddlewareFunction';
import { RespondOptions } from '../types/RespondOptions';
import { Util } from '../util/Util';
/**
* Action to be executed when the command is called. The following parameters
* are what command actions will be passed by the {@link CommandDispatcher} whenever
* a command is called. Be sure to receive these in proper order when writing
* new commands
* @abstract
* @method Command#action
* @param {external:Message} message Discord.js message object
* @param {any[]} args An array containing the args parsed from the command calling message.<br>
* Will contain strings unless middleware is used to transform the args
* @returns {any}
*/
/**
* Command class to extend to create commands users can execute
* @abstract
* @param {CommandInfo} info - Object containing required command properties
*/
export abstract class Command<T extends Client = Client>
{
private _disabled!: boolean;
private _ratelimit!: string;
public client!: T;
public name!: string;
public desc!: string;
public usage!: string;
public info!: string;
public group!: string;
public aliases!: string[];
public guildOnly!: boolean;
public hidden!: boolean;
public argOpts!: ArgOpts;
public callerPermissions!: PermissionResolvable[];
public clientPermissions!: PermissionResolvable[];
public roles!: string[];
public ownerOnly!: boolean;
public external!: boolean;
public lock!: CommandLock;
public lockTimeout!: number;
// Internals
public readonly middleware: MiddlewareFunction[];
public classloc!: string;
public initialized: boolean;
public constructor(info?: CommandInfo)
{
/**
* YAMDBF Client instance
* @name Command#client
* @type {Client}
*/
/**
* The name of the command, used by the dispatcher
* to determine the command being executed
* @name Command#name
* @type {string}
*/
/**
* A brief description of the command, displayed
* in the commands list via the Help command
* @name Command#desc
* @type {string}
*/
/**
* An example of command usage. The token `<prefix>` will
* be replaced by the guild-specific command prefix in the Help command when
* `help <command>` is called
* @name Command#usage
* @type {string}
*/
/**
* Extra information about the command to be displayed
* by the Help command when `help <command>` is called
* @name Command#info
* @type {string}
*/
/**
* The command group that the command belongs to. Allows commands to be
* grouped for disabling. The group 'base' cannot be disabled.
* @name Command#group
* @type {string}
*/
/**
* Aliases the command can be called by other than its name
* @name Command#aliases
* @type {string[]}
*/
/**
* Whether or not a command can only be used within a
* guild text channel
* @name Command#guildOnly
* @type {boolean}
*/
/**
* Whether or not the command is to be hidden from the
* commands list via the default help command
* @name Command#hidden
* @type {boolean}
*/
/**
* Options for how arguments should be parsed.<br>
* **See:** {@link ArgOpts}
* @name Command#argOpts
* @type {ArgOpts}
*/
/**
* Array of permissions required by the command
* caller to be able to execute the command in
* the guild the command is called in.
*
* If any permissions are provided the command's `guildOnly`
* property will be automatically overridden to true
* @name Command#callerPermissions
* @type {external:PermissionResolvable[]}
*/
/**
* Array of permissions required by the client
* to be able to execute the command in the guild
* the command is called in.
*
* If any permissions are provided the command's `guildOnly`
* property will be automatically overridden to true
* @name Command#clientPermissions
* @type {external:PermissionResolvable[]}
*/
/**
* Array of specific {@link external:Role} names required to use the command.
* If the command caller has any (even just one) of the roles in the array,
* they will be able to use the command.
*
* If any roles are provided the command's `guildOnly` property will be
* automatically set to `true`
*
* >**Note:** This is far inferior to {@link Command#callerPermissions},
* using the base `limit` command's role-limiting system, or really even
* a custom-engineered solution to control who can use a command. Forcing
* servers to create Roles with specific names makes your bot that much
* less configurable on a per-guild basis, and configurability is what
* YAMDBF is all about. But, for the sake of simplicity, this is available
* @name Command#roles
* @type {string[]}
*/
/**
* Whether or not the command can be used only by the client/bot owner(s).<br>
* **See:** [Client#config.owner]{@link Client#config}
* @name Command#ownerOnly
* @type {boolean}
*/
/**
* Whether or not this command was registered via {@link CommandRegistry#registerExternal}
* by some means other than the command loader like a Plugin
* @name Command#external
* @type {boolean}
*/
/**
* The CommmandLock this command uses. Must be assigned manually if
* locking functionality is desired
* @name Command#lock
* @type {CommandLock}
*/
/**
* Time until command locks will be cancelled if a command
* does not finish in time
* @name Command#lockTimeout
* @type {number}
*/
// Middleware function storage for the Command instance
this.middleware = [];
this.initialized = false;
if (info) Object.assign(this, info);
}
// Docs above class
public abstract action(message: Message, args: any[]): any;
/**
* The ratelimit for this command per user
* @type {string}
*/
public get ratelimit(): string { return this._ratelimit; }
public set ratelimit(value: string)
{
Util.parseRateLimit(value);
this._ratelimit = value;
}
/**
* Can be included in a command to initlialize any resources a command
* needs at runtime that require things that are not available within
* a command's constructor like the client instance or client/guild storages.
*
* Will be called after all commands are loaded (including those from
* any loaded plugins) and after all base framework storages (client and guild)
* are ready for use.
*
* >**Note:** Can be async if needed
* @abstract
* @returns {Promise<void>}
*/
public init(): void {}
/**
* Make necessary asserts for Command validity.
* Called internally by the command loader
* @private
*/
public register(client: T): void
{
this.client = client;
// Set defaults if not present
if (typeof this.aliases === 'undefined') this.aliases = [];
if (typeof this.group === 'undefined') this.group = 'base';
if (typeof this.guildOnly === 'undefined') this.guildOnly = false;
if (typeof this.hidden === 'undefined') this.hidden = false;
if (typeof this.argOpts === 'undefined') this.argOpts = {};
if (typeof this.argOpts.separator === 'undefined') this.argOpts.separator = ' ';
if (typeof this.callerPermissions === 'undefined') this.callerPermissions = [];
if (typeof this.clientPermissions === 'undefined') this.clientPermissions = [];
if (typeof this.roles === 'undefined') this.roles = [];
if (typeof this.ownerOnly === 'undefined') this.ownerOnly = false;
if (typeof this.external === 'undefined') this.external = false;
if (typeof this._disabled === 'undefined') this._disabled = false;
if (typeof this.classloc === 'undefined') this.classloc = '<External Command>';
if (typeof this.lockTimeout === 'undefined') this.lockTimeout = 30e3;
// Make necessary asserts
if (!this.name) throw new Error(`A command is missing a name:\n${this.classloc}`);
if (!this.desc) throw new Error(`A description must be provided for Command: ${this.name}`);
if (!this.usage) throw new Error(`Usage information must be provided for Command: ${this.name}`);
if (this.aliases && !Array.isArray(this.aliases))
throw new TypeError(`Aliases for Command "${this.name}" must be an array of alias strings`);
if (this.callerPermissions && !Array.isArray(this.callerPermissions))
throw new TypeError(`\`callerPermissions\` for Command "${this.name}" must be an array`);
if (this.clientPermissions && !Array.isArray(this.clientPermissions))
throw new TypeError(`\`clientPermissions\` for Command "${this.name}" must be an array`);
if (this.callerPermissions && this.callerPermissions.length)
this._validatePermissions('callerPermissions', this.callerPermissions);
if (this.clientPermissions && this.clientPermissions.length)
this._validatePermissions('clientPermissions', this.clientPermissions);
if (this.roles && !Array.isArray(this.roles))
throw new TypeError(`\`roles\` for Command "${this.name}" must be an array`);
if (typeof this.lockTimeout !== 'undefined' && typeof this.lockTimeout !== 'number')
throw new TypeError(`\`lockTimeout\` for Command "${this.name}" must be a number`);
if (typeof this.action === 'undefined' || !(this.action instanceof Function))
throw new TypeError(`Command "${this.name}".action: expected Function, got: ${typeof this.action}`);
// Default guildOnly to true if permissions/roles are given
if (!this.guildOnly
&& (this.callerPermissions.length
|| this.clientPermissions.length
|| this.roles.length))
this.guildOnly = true;
if (typeof this.lock !== 'undefined' && !this.guildOnly)
throw new Error(`Command "${this.name} has a defined lock but is not guildOnly`);
}
/**
* Whether or not this command is disabled
* @type {boolean}
*/
public get disabled(): boolean
{
return this._disabled;
}
/**
* Enable this command if it is disabled
* @returns {void}
*/
public enable(): void
{
this._disabled = false;
}
/**
* Disable this command if it is enabled
* @returns {void}
*/
public disable(): void
{
this._disabled = true;
}
/**
* Adds a middleware function to be used when the command is called
* to make modifications to args, determine if the command can
* be run, or anything else you want to do whenever this command
* is called.
*
* See {@link MiddlewareFunction} for information on how a middleware
* function should be represented
*
* Usage example:
* ```
* <Client>.use((message, args) => [message, args.map(a => a.toUpperCase())]);
* ```
* This will add a middleware function to this command that will attempt
* to transform all args to uppercase. This will of course fail if any
* of the args are not a string.
*
* >**Note:** Middleware functions should only be added to a command one
* time each and thus should not be added within any sort of event or loop.
* Multiple separate middleware functions can be added to the via multiple
* separate calls to this method
* @param {MiddlewareFunction} func The middleware function to use
* @returns {Command}
*/
public use(func: MiddlewareFunction): this
{
this.middleware.push(func);
return this;
}
protected async respond(message: Message, response: string, options?: MessageOptions): Promise<Message | Message[]>;
protected async respond(message: Message, response: string, options?: RespondOptions): Promise<void>;
/**
* Send provided response to the provided message's channel,
* leveraging compact mode mechanics if enabled
* @protected
* @param {external:Message} message Discord.js Message object
* @param {string} response String to send
* @param {RespondOptions} [options] Optional options for the response
* @returns {Promise<external:Message | external:Message[] | undefined>}
*/
protected async respond(...args: any[]): Promise<any>
{
const [message, response, options]: [Message, string, RespondOptions] = args as any;
if (typeof options !== 'undefined'
&& typeof options.button !== 'undefined'
&& (await message.guild.storage!.settings.get('compact') || this.client.compact))
{
if (message.reactions.cache.size > 0) await message.reactions.removeAll();
CompactModeHelper.registerButton(
message,
this.client.buttons[options.button] || options.button,
async () => message.channel.send(response, options)
);
return;
}
return message.channel.send(response, options);
}
/**
* Validate PermissionResolvables in the given array, throwing an error
* for any that are invalid
* @private
*/
private _validatePermissions(field: string, perms: PermissionResolvable[]): void
{
const errString: (i: number, err: any) => string = (i, err) =>
`Command "${this.name}" permission "${perms[i]}" in ${field}[${i}] is not a valid permission.\n\n${err}`;
for (const [index, perm] of perms.entries())
try { Permissions.resolve(perm); }
catch (err) { throw new TypeError(errString(index, err)); }
}
}