@zygout/eris 0.19.0 → 0.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/LICENSE +20 -20
  2. package/README.md +71 -80
  3. package/esm.mjs +72 -72
  4. package/index.d.ts +4407 -4397
  5. package/index.js +75 -75
  6. package/lib/Client.js +4708 -4683
  7. package/lib/Constants.d.ts +990 -988
  8. package/lib/Constants.js +1163 -1161
  9. package/lib/command/Command.js +552 -552
  10. package/lib/command/CommandClient.js +460 -460
  11. package/lib/errors/DiscordHTTPError.js +63 -63
  12. package/lib/errors/DiscordRESTError.js +77 -77
  13. package/lib/gateway/Shard.js +3029 -3029
  14. package/lib/gateway/ShardManager.js +164 -164
  15. package/lib/rest/Endpoints.js +172 -172
  16. package/lib/rest/RequestHandler.js +459 -459
  17. package/lib/structures/ApplicationCommand.js +125 -125
  18. package/lib/structures/AutoModerationRule.js +143 -143
  19. package/lib/structures/AutocompleteInteraction.js +80 -80
  20. package/lib/structures/Base.js +81 -81
  21. package/lib/structures/CategoryChannel.js +77 -77
  22. package/lib/structures/Channel.js +98 -98
  23. package/lib/structures/CommandInteraction.js +473 -473
  24. package/lib/structures/ComponentInteraction.js +538 -538
  25. package/lib/structures/DMChannel.js +278 -278
  26. package/lib/structures/Entitlement.js +77 -77
  27. package/lib/structures/ExtendedUser.js +46 -46
  28. package/lib/structures/ForumChannel.js +24 -24
  29. package/lib/structures/GroupChannel.js +106 -106
  30. package/lib/structures/Guild.js +1677 -1677
  31. package/lib/structures/GuildAuditLogEntry.js +190 -190
  32. package/lib/structures/GuildChannel.js +128 -128
  33. package/lib/structures/GuildIntegration.js +99 -99
  34. package/lib/structures/GuildPreview.js +97 -97
  35. package/lib/structures/GuildScheduledEvent.js +176 -176
  36. package/lib/structures/GuildTemplate.js +76 -76
  37. package/lib/structures/GuildTextableChannel.js +260 -260
  38. package/lib/structures/Interaction.js +133 -133
  39. package/lib/structures/Invite.js +143 -143
  40. package/lib/structures/Lobby.js +108 -108
  41. package/lib/structures/LobbyMember.js +59 -59
  42. package/lib/structures/MediaChannel.js +216 -216
  43. package/lib/structures/Member.js +371 -371
  44. package/lib/structures/Message.js +708 -708
  45. package/lib/structures/ModalSubmitInteraction.js +478 -478
  46. package/lib/structures/NewsChannel.js +34 -34
  47. package/lib/structures/NewsThreadChannel.js +12 -12
  48. package/lib/structures/Permission.js +80 -80
  49. package/lib/structures/PermissionOverwrite.js +32 -32
  50. package/lib/structures/PingInteraction.js +39 -39
  51. package/lib/structures/PrivateThreadChannel.js +25 -25
  52. package/lib/structures/PublicThreadChannel.js +26 -26
  53. package/lib/structures/Role.js +163 -163
  54. package/lib/structures/SKU.js +80 -80
  55. package/lib/structures/SoundboardSound.js +79 -79
  56. package/lib/structures/StageChannel.js +59 -59
  57. package/lib/structures/StageInstance.js +55 -55
  58. package/lib/structures/Subscription.js +69 -69
  59. package/lib/structures/TextChannel.js +202 -202
  60. package/lib/structures/ThreadChannel.js +143 -143
  61. package/lib/structures/ThreadMember.js +59 -59
  62. package/lib/structures/UnavailableGuild.js +26 -26
  63. package/lib/structures/UnknownInteraction.js +502 -502
  64. package/lib/structures/User.js +296 -296
  65. package/lib/structures/VoiceChannel.js +166 -166
  66. package/lib/structures/VoiceState.js +84 -84
  67. package/lib/util/BrowserWebSocket.js +76 -76
  68. package/lib/util/Bucket.js +89 -89
  69. package/lib/util/Collection.js +202 -202
  70. package/lib/util/MultipartData.js +70 -70
  71. package/lib/util/Opus.js +33 -33
  72. package/lib/util/SequentialBucket.js +83 -83
  73. package/lib/util/emitDeprecation.js +26 -26
  74. package/lib/voice/Piper.js +300 -300
  75. package/lib/voice/SharedStream.js +238 -238
  76. package/lib/voice/VoiceConnection.js +1440 -1440
  77. package/lib/voice/VoiceConnectionManager.js +151 -151
  78. package/lib/voice/VoiceDataStream.js +22 -22
  79. package/lib/voice/streams/BaseTransformer.js +40 -40
  80. package/lib/voice/streams/DCAOpusTransformer.js +78 -78
  81. package/lib/voice/streams/FFmpegDuplex.js +192 -192
  82. package/lib/voice/streams/FFmpegOggTransformer.js +35 -35
  83. package/lib/voice/streams/FFmpegPCMTransformer.js +26 -26
  84. package/lib/voice/streams/OggOpusTransformer.js +108 -108
  85. package/lib/voice/streams/PCMOpusTransformer.js +61 -61
  86. package/lib/voice/streams/VolumeTransformer.js +50 -50
  87. package/lib/voice/streams/WebmOpusTransformer.js +258 -258
  88. package/package.json +83 -82
@@ -1,460 +1,460 @@
1
- "use strict";
2
-
3
- const Client = require("../Client");
4
- const Command = require("./Command");
5
- const Message = require("../structures/Message");
6
-
7
- /**
8
- * Represents an Eris client with the command framework
9
- * @extends Client
10
- * @prop {Object} commands Object mapping command labels to Command objects
11
- * @prop {Object} commandAliases Object mapping command label aliases to command labels
12
- * @prop {Object} commandOptions Command options
13
- * @prop {Object} guildPrefixes Object mapping guild IDs to guild specific prefix or arrays of guild-specific prefixes
14
- */
15
- class CommandClient extends Client {
16
- /**
17
- * Create a CommandClient
18
- * @arg {String} token Bot token
19
- * @arg {Object} options Eris options (same as Client)
20
- * @arg {Object} [commandOptions] Command options
21
- * @arg {Function} [commandOptions.argsSplitter] The function used to split args. The function is given a string with the contents of the command message (without the prefix) and should return an array of strings. By default, args are split by consecutive whitespace
22
- * @arg {Object} [commandOptions.defaultCommandOptions={}] Default command options. This object takes the same options as a normal Command
23
- * @arg {Boolean} [commandOptions.defaultHelpCommand=true] Whether to register the default help command or not
24
- * @arg {String} [commandOptions.description="An Eris-based Discord bot"] The description to show in the default help command
25
- * @arg {Boolean} [commandOptions.ignoreBots=true] Whether to ignore bot accounts or not
26
- * @arg {Boolean} [commandOptions.ignoreSelf=true] Whether to ignore the bot's own account or not
27
- * @arg {String} [commandOptions.name="<Bot username>"] The bot name to show in the default help command
28
- * @arg {String} [commandOptions.owner="an unknown user"] The owner to show in the default help command
29
- * @arg {String | Array<String>} [commandOptions.prefix="@mention "] The bot prefix. Can be either an array of prefixes or a single prefix. "@mention" will be automatically replaced with the bot's actual mention
30
- */
31
- constructor(token, options, commandOptions) {
32
- super(token, options);
33
- this.commandOptions = Object.assign({
34
- argsSplitter: (str) => str.split(/\s+/g),
35
- defaultHelpCommand: true,
36
- description: "An Eris-based Discord bot",
37
- ignoreBots: true,
38
- ignoreSelf: true,
39
- name: null,
40
- owner: "an unknown user",
41
- prefix: "@mention ",
42
- defaultCommandOptions: {},
43
- }, commandOptions);
44
- this.guildPrefixes = {};
45
- this.commands = {};
46
- this.commandAliases = {};
47
- this.activeMessages = {};
48
-
49
- this.once("shardPreReady", () => {
50
- this.preReady = true;
51
- if (!this.commandOptions.name) {
52
- this.commandOptions.name = `**${this.user.username}**`;
53
- }
54
- if (Array.isArray(this.commandOptions.prefix)) {
55
- for (let i = 0; i < this.commandOptions.prefix.length; ++i) {
56
- this.commandOptions.prefix[i] = this.commandOptions.prefix[i].replace(/@mention/g, this.user.mention);
57
- }
58
- } else {
59
- this.commandOptions.prefix = this.commandOptions.prefix.replace(/@mention/g, this.user.mention);
60
- }
61
- for (const key of Object.keys(this.guildPrefixes)) {
62
- if (Array.isArray(this.guildPrefixes[key])) {
63
- for (let i = 0; i < this.guildPrefixes[key].length; ++i) {
64
- this.guildPrefixes[key][i] = this.guildPrefixes[key][i].replace(/@mention/g, this.user.mention);
65
- }
66
- } else {
67
- this.guildPrefixes[key] = this.guildPrefixes[key].replace(/@mention/g, this.user.mention);
68
- }
69
- }
70
- });
71
-
72
- this.on("messageCreate", this.onMessageCreate);
73
-
74
- this.on("messageReactionAdd", this.onMessageReactionEvent);
75
- this.on("messageReactionRemove", this.onMessageReactionEvent);
76
-
77
- if (this.commandOptions.defaultHelpCommand) {
78
- this.registerCommand("help", async (msg, args) => {
79
- let result = "";
80
- if (args.length > 0) {
81
- let cur = this.commands[this.commandAliases[args[0]] || args[0]];
82
- if (!cur) {
83
- return "Command not found";
84
- }
85
- let { label } = cur;
86
- for (let i = 1; i < args.length; ++i) {
87
- cur = cur.subcommands[cur.subcommandAliases[args[i]] || args[i]];
88
- if (!cur) {
89
- return "Command not found";
90
- }
91
- label += ` ${cur.label}`;
92
- }
93
- result += `**${msg.prefix}${label}** ${cur.usage}\n${cur.fullDescription}`;
94
- if (cur.aliases.length > 0) {
95
- result += `\n\n**Aliases:** ${cur.aliases.join(", ")}`;
96
- }
97
- const subcommands = Object.keys(cur.subcommands);
98
- if (subcommands.length > 0) {
99
- result += "\n\n**Subcommands:**";
100
- for (const subLabel of subcommands) {
101
- if (cur.subcommands.hasOwnProperty(subLabel) && await cur.subcommands[subLabel].permissionCheck(msg)) {
102
- result += `\n **${subLabel}** - ${cur.subcommands[subLabel].description}`;
103
- }
104
- }
105
- }
106
- } else {
107
- result += `${this.commandOptions.name} - ${this.commandOptions.description}\n`;
108
- if (this.commandOptions.owner) {
109
- result += `by ${this.commandOptions.owner}\n`;
110
- }
111
- result += "\n**Commands:**\n";
112
- for (const label in this.commands) {
113
- if (this.commands.hasOwnProperty(label) && this.commands[label] && await this.commands[label].permissionCheck(msg) && !this.commands[label].hidden) {
114
- result += ` **${msg.prefix}${label}** - ${this.commands[label].description}\n`;
115
- }
116
- }
117
- result += `\nType ${msg.prefix}help <command> for more info on a command.`;
118
- }
119
- return result;
120
- }, {
121
- description: "This help text",
122
- fullDescription: "This command is used to view information of different bot commands, including this one.",
123
- });
124
- if (!this.commandOptions.defaultCommandOptions.invalidUsageMessage) {
125
- this.commandOptions.defaultCommandOptions.invalidUsageMessage = "Invalid usage. Do `%prefix%help %label%` to view proper usage.";
126
- }
127
- } else if (!this.commandOptions.defaultCommandOptions.invalidUsageMessage) {
128
- this.commandOptions.defaultCommandOptions.invalidUsageMessage = "Invalid usage.";
129
- }
130
- }
131
-
132
- checkPrefix(msg) {
133
- let prefixes = this.commandOptions.prefix;
134
- if (msg.channel.guild !== undefined && this.guildPrefixes[msg.channel.guild.id] !== undefined) {
135
- prefixes = this.guildPrefixes[msg.channel.guild.id];
136
- }
137
- if (typeof prefixes === "string") {
138
- return msg.content.replace(/<@!/g, "<@").startsWith(prefixes) && prefixes;
139
- } else if (Array.isArray(prefixes)) {
140
- return prefixes.find((prefix) => msg.content.replace(/<@!/g, "<@").startsWith(prefix));
141
- }
142
- throw new Error(`Unsupported prefix format | ${prefixes}`);
143
- }
144
-
145
- /**
146
- * Checks the command client for a command based on the provided message
147
- * @arg {Message} msg The message object from the message create event
148
- */
149
- async onMessageCreate(msg) {
150
- if (!this.ready) {
151
- return;
152
- }
153
- if (!msg.author) {
154
- this.emit("warn", `Message ${msg.id} has author=${msg.author} | Channel ${msg.channel.id}, timestamp ${Date.now()}`);
155
- return;
156
- }
157
-
158
- msg.command = false;
159
- if ((!this.commandOptions.ignoreSelf || msg.author.id !== this.user.id) && (!this.commandOptions.ignoreBots || !msg.author.bot) && (msg.prefix = this.checkPrefix(msg))) {
160
- const args = this.commandOptions.argsSplitter(msg.content.replace(/<@!/g, "<@").substring(msg.prefix.length).trim());
161
- const label = args.shift();
162
- const command = this.resolveCommand(label);
163
- if (command !== undefined) {
164
- msg.command = command;
165
- try {
166
- let resp = await msg.command.process(args, msg);
167
- if (resp != null) {
168
- if (!(resp instanceof Message)) {
169
- resp = await this.createMessage(msg.channel.id, resp); // eslint-disable-line require-atomic-updates
170
- }
171
- if (msg.command.reactionButtons) {
172
- msg.command.reactionButtons.forEach((button) => resp.addReaction(button.emoji));
173
- this.activeMessages[resp.id] = {
174
- args: args,
175
- command: msg.command,
176
- message: resp,
177
- timeout: setTimeout(() => {
178
- this.unwatchMessage(resp.id, resp.channel.id);
179
- }, msg.command.reactionButtonTimeout),
180
- };
181
- }
182
- }
183
- if (msg.command.hooks.postCommand) {
184
- msg.command.hooks.postCommand(msg, args, resp);
185
- }
186
- } catch (err) {
187
- this.emit("error", err);
188
- if (msg.command.hooks.postExecution) {
189
- msg.command.hooks.postExecution(msg, args, false);
190
- }
191
- let newMsg;
192
- if (msg.command.errorMessage) {
193
- try {
194
- if (typeof msg.command.errorMessage === "function") {
195
- const reply = await msg.command.errorMessage(msg, err);
196
- if (reply !== undefined) {
197
- newMsg = await this.createMessage(msg.channel.id, reply);
198
- }
199
- } else {
200
- newMsg = await this.createMessage(msg.channel.id, msg.command.errorMessage);
201
- }
202
- } catch (err) {
203
- this.emit("error", err);
204
- }
205
- }
206
- if (msg.command.hooks.postCommand) {
207
- msg.command.hooks.postCommand(msg, args, newMsg);
208
- }
209
- }
210
- }
211
- }
212
- }
213
-
214
- async onMessageReactionEvent(msg, emoji, reactor) {
215
- const userID = typeof reactor === "object" ? reactor.id : reactor;
216
- const activeMessage = this.activeMessages[msg.id];
217
- if (!this.ready || userID === this.user.id || !activeMessage) {
218
- return;
219
- }
220
- // Messages in uncached channels, like DMs, only come with their ID: use the response as last sent
221
- if (!(msg.content || msg.embeds || msg.attachments)) {
222
- msg = activeMessage.message;
223
- }
224
-
225
- emoji = emoji.id ? `${emoji.name}:${emoji.id}` : emoji.name;
226
-
227
- if (activeMessage.command.reactionButtons) {
228
- const action = activeMessage.command.reactionButtons.find((button) => button.emoji === emoji);
229
- if (!action) {
230
- return;
231
- }
232
-
233
- if (action.filter && !action.filter(msg, emoji, userID)) {
234
- return;
235
- }
236
-
237
- switch (action.type) {
238
- case "cancel": {
239
- this.unwatchMessage(msg.id, msg.channel.guild && msg.channel.id);
240
- try {
241
- const resp = await action.execute(msg, activeMessage.args, userID);
242
- if (resp != null) {
243
- await this.editMessage(msg.channel.id, msg.id, resp);
244
- }
245
- } catch {} // eslint-disable-line no-empty
246
- break;
247
- }
248
- case "edit":
249
- default: {
250
- try {
251
- const resp = await action.execute(msg, activeMessage.args, userID);
252
- if (resp != null) {
253
- activeMessage.message = await this.editMessage(msg.channel.id, msg.id, resp);
254
- }
255
- } catch {} // eslint-disable-line no-empty
256
- break;
257
- }
258
- }
259
- }
260
- }
261
-
262
- /**
263
- * Register a command
264
- * @arg {String} label The command label
265
- * @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.
266
- * 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.
267
- * `generator(msg, args)`
268
- * @arg {Object} [options] Command options
269
- * @arg {Array<String>} [options.aliases] An array of command aliases
270
- * @arg {Boolean} [options.argsRequired=false] If arguments are required or not
271
- * @arg {Boolean} [options.caseInsensitive=false] Whether the command label (and aliases) is case insensitive or not
272
- * @arg {Number} [options.cooldown] The cooldown between command usage in milliseconds
273
- * @arg {Object} [options.cooldownExclusions={}] A set of factors that limit where cooldowns are active
274
- * @arg {Array<String>} [options.cooldownExclusions.channelIDs] An array of channel IDs representing channels that are not affected by cooldowns.
275
- * @arg {Array<String>} [options.cooldownExclusions.guildIDs] An array of guild IDs representing guilds that are not affected by cooldowns.
276
- * @arg {Array<String>} [options.cooldownExclusions.userIDs] An array of user IDs representing users that are not affected by cooldowns.
277
- * @arg {Function | String} [options.cooldownMessage] A string or a function that returns a string to show when the command is on cooldown
278
- * @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.
279
- * @arg {Object} [options.defaultSubcommandOptions={}] Default subcommand options. This object takes the same options as a normal Command
280
- * @arg {Boolean} [options.deleteCommand=false] Whether to delete the user command message or not
281
- * @arg {String} [options.description="No description"] A short description of the command to show in the default help command
282
- * @arg {Boolean} [options.dmOnly=false] Whether to prevent the command from being used in guilds or not
283
- * @arg {Function | String} [options.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 command message and the error as parameters.
284
- * @arg {String} [options.fullDescription="No full description"] A detailed description of the command to show in the default help command
285
- * @arg {Boolean} [options.guildOnly=false] Whether to prevent the command from being used in Direct Messages or not
286
- * @arg {Boolean} [options.hidden=false] Whether or not the command should be hidden from the default help command list
287
- * @arg {Object} [options.hooks] A set of functions to be executed at different times throughout the command's processing
288
- * @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.
289
- * @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.
290
- * @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.
291
- * @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.
292
- * @arg {Function | String} [options.invalidUsageMessage] A string or a function that returns a string to show when a command was improperly used
293
- * @arg {Function | String} [options.permissionMessage] A string or a function that returns a string to show when the user doesn't have permissions to use the command
294
- * @arg {Array<{emoji: String, type: String, response: (Function | String | Array<Function | String>)}>} [options.reactionButtons] An array of objects specifying reaction buttons
295
- * `emoji` specifies the button emoji. Custom emojis should be in format `emojiName:emojiID`
296
- * `type` specifies the type of the reaction button, either "edit" or "cancel"
297
- * `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
298
- * `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
299
- * @arg {Number} [options.reactionButtonTimeout=60000] Time (in milliseconds) to wait before invalidating the command's reaction buttons
300
- * @arg {Object} [options.requirements] A set of factors that limit who can call the command
301
- * @arg {Function} [options.requirements.custom] A function that accepts a message and returns true if the command should be run
302
- * @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
303
- * i.e.:
304
- * ```
305
- * {
306
- * "administrator": false,
307
- * "manageMessages": true
308
- * }
309
- * ```
310
- * In the above example, the user must not have administrator permissions, but must have manageMessages to use the command
311
- * @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
312
- * @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
313
- * @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
314
- * @arg {Boolean} [option.restartCooldown=false] Whether or not to restart a command's cooldown every time it's used.
315
- * @arg {String} [options.usage] Details on how to call the command to show in the default help command
316
- * @returns {Command}
317
- */
318
- registerCommand(label, generator, options = {}) {
319
- if (label.includes(" ")) {
320
- throw new Error("Command label may not have spaces");
321
- }
322
- let lowercaseCommand = label.toLowerCase();
323
- if (this.commands[label] || (this.commands[lowercaseCommand] && this.commands[lowercaseCommand].caseInsensitive)) {
324
- throw new Error(`You have already registered a command for ${label}`);
325
- }
326
- // Aliases are not deleted when deleting commands
327
- let command = this.commandAliases[label]; // Just to make the following if statement less messy
328
- lowercaseCommand = this.commandAliases[label.toLowerCase()];
329
- if (this.commands[command] || (this.commands[lowercaseCommand] && this.commands[lowercaseCommand].caseInsensitive)) {
330
- throw new Error(`Alias ${label} already registered`);
331
- }
332
- options.defaultSubcommandOptions = options.defaultSubcommandOptions || {};
333
- for (const key in this.commandOptions.defaultCommandOptions) {
334
- if (this.commandOptions.defaultCommandOptions.hasOwnProperty(key) && options[key] === undefined) {
335
- options[key] = this.commandOptions.defaultCommandOptions[key];
336
- options.defaultSubcommandOptions[key] = this.commandOptions.defaultCommandOptions[key];
337
- }
338
- }
339
- label = options.caseInsensitive === true ? label.toLowerCase() : label;
340
- if (this.commands[label]) {
341
- throw new Error(`You have already registered a command for ${label}`);
342
- }
343
- command = this.commandAliases[label];
344
- if (this.commands[command]) {
345
- throw new Error(`Alias ${command} already registered`);
346
- }
347
- if (options.aliases) {
348
- options.aliases.forEach((alias) => {
349
- lowercaseCommand = alias.toLowerCase();
350
- if (this.commands[alias] || (this.commands[lowercaseCommand] && this.commands[lowercaseCommand].caseInsensitive)) {
351
- throw new Error(`You have already registered a command for alias ${alias}`);
352
- }
353
- command = this.commandAliases[alias];
354
- lowercaseCommand = this.commandAliases[alias.toLowerCase()];
355
- if (this.commands[command] || (this.commands[lowercaseCommand] && this.commands[lowercaseCommand].caseInsensitive)) {
356
- throw new Error(`Alias ${alias} already registered`);
357
- }
358
- alias = options.caseInsensitive === true ? alias.toLowerCase() : alias;
359
- if (this.commands[alias]) {
360
- throw new Error(`You have already registered a command for alias ${alias}`);
361
- }
362
- command = this.commandAliases[alias];
363
- if (this.commands[command]) {
364
- throw new Error(`Alias ${alias} already registered`);
365
- }
366
- this.commandAliases[alias] = label;
367
- });
368
- }
369
- this.commands[label] = new Command(label, generator, options);
370
- return this.commands[label];
371
- }
372
-
373
- /**
374
- * Register an alias for a command
375
- * @arg {String} alias The alias
376
- * @arg {String} label The original command label
377
- */
378
- registerCommandAlias(alias, label) {
379
- let caseInsensitiveLabel = false;
380
- if (!this.commands[label] && !(this.commands[(label = label.toLowerCase())] && (caseInsensitiveLabel = this.commands[label.toLowerCase()].caseInsensitive))) {
381
- throw new Error(`No command registered for ${label}`);
382
- }
383
- alias = caseInsensitiveLabel === true ? alias.toLowerCase() : alias;
384
- if (this.commandAliases[alias]) {
385
- throw new Error(`Alias ${alias} already registered`);
386
- }
387
- this.commandAliases[alias] = label;
388
- this.commands[label].aliases.push(alias);
389
- }
390
-
391
- /**
392
- * Register a prefix override for a specific guild
393
- * @arg {String} guildID The ID of the guild to override prefixes for
394
- * @arg {String | Array} prefix The bot prefix. Can be either an array of prefixes or a single prefix. "@mention" will be automatically replaced with the bot's actual mention
395
- */
396
- registerGuildPrefix(guildID, prefix) {
397
- if (!this.preReady) {
398
- this.guildPrefixes[guildID] = prefix;
399
- } else if (Array.isArray(prefix)) {
400
- for (let i = 0; i < prefix.length; ++i) {
401
- prefix[i] = prefix[i].replace(/@mention/g, this.user.mention);
402
- }
403
- this.guildPrefixes[guildID] = prefix;
404
- } else {
405
- this.guildPrefixes[guildID] = prefix.replace(/@mention/g, this.user.mention);
406
- }
407
- }
408
-
409
- resolveCommand(label) {
410
- label = this.commandAliases[label] || label;
411
- let command = this.commands[label];
412
- if (command) {
413
- return command;
414
- }
415
- label = label.toLowerCase();
416
- label = this.commandAliases[label] || label;
417
- command = this.commands[label];
418
- if (command && command.caseInsensitive) {
419
- return command;
420
- }
421
- }
422
-
423
- /**
424
- * Unregister a command
425
- * @arg {String} label The command label
426
- */
427
- unregisterCommand(label) {
428
- const original = this.commandAliases[label];
429
- if (original) {
430
- this.commands[original].aliases.splice(this.commands[original].aliases.indexOf(label), 1);
431
- delete this.commandAliases[label];
432
- } else {
433
- delete this.commands[label];
434
- }
435
- }
436
-
437
- unwatchMessage(id, channelID) {
438
- delete this.activeMessages[id];
439
- if (channelID) {
440
- this.removeMessageReactions(channelID, id).catch(() => {});
441
- }
442
- }
443
-
444
- toString() {
445
- return `[CommandClient ${this.user.id}]`;
446
- }
447
-
448
- toJSON(props = []) {
449
- return super.toJSON([
450
- "activeMessages",
451
- "commandAliases",
452
- "commandOptions",
453
- "commands",
454
- "guildPrefixes",
455
- ...props,
456
- ]);
457
- }
458
- }
459
-
460
- module.exports = CommandClient;
1
+ "use strict";
2
+
3
+ const Client = require("../Client");
4
+ const Command = require("./Command");
5
+ const Message = require("../structures/Message");
6
+
7
+ /**
8
+ * Represents an Eris client with the command framework
9
+ * @extends Client
10
+ * @prop {Object} commands Object mapping command labels to Command objects
11
+ * @prop {Object} commandAliases Object mapping command label aliases to command labels
12
+ * @prop {Object} commandOptions Command options
13
+ * @prop {Object} guildPrefixes Object mapping guild IDs to guild specific prefix or arrays of guild-specific prefixes
14
+ */
15
+ class CommandClient extends Client {
16
+ /**
17
+ * Create a CommandClient
18
+ * @arg {String} token Bot token
19
+ * @arg {Object} options Eris options (same as Client)
20
+ * @arg {Object} [commandOptions] Command options
21
+ * @arg {Function} [commandOptions.argsSplitter] The function used to split args. The function is given a string with the contents of the command message (without the prefix) and should return an array of strings. By default, args are split by consecutive whitespace
22
+ * @arg {Object} [commandOptions.defaultCommandOptions={}] Default command options. This object takes the same options as a normal Command
23
+ * @arg {Boolean} [commandOptions.defaultHelpCommand=true] Whether to register the default help command or not
24
+ * @arg {String} [commandOptions.description="An Eris-based Discord bot"] The description to show in the default help command
25
+ * @arg {Boolean} [commandOptions.ignoreBots=true] Whether to ignore bot accounts or not
26
+ * @arg {Boolean} [commandOptions.ignoreSelf=true] Whether to ignore the bot's own account or not
27
+ * @arg {String} [commandOptions.name="<Bot username>"] The bot name to show in the default help command
28
+ * @arg {String} [commandOptions.owner="an unknown user"] The owner to show in the default help command
29
+ * @arg {String | Array<String>} [commandOptions.prefix="@mention "] The bot prefix. Can be either an array of prefixes or a single prefix. "@mention" will be automatically replaced with the bot's actual mention
30
+ */
31
+ constructor(token, options, commandOptions) {
32
+ super(token, options);
33
+ this.commandOptions = Object.assign({
34
+ argsSplitter: (str) => str.split(/\s+/g),
35
+ defaultHelpCommand: true,
36
+ description: "An Eris-based Discord bot",
37
+ ignoreBots: true,
38
+ ignoreSelf: true,
39
+ name: null,
40
+ owner: "an unknown user",
41
+ prefix: "@mention ",
42
+ defaultCommandOptions: {},
43
+ }, commandOptions);
44
+ this.guildPrefixes = {};
45
+ this.commands = {};
46
+ this.commandAliases = {};
47
+ this.activeMessages = {};
48
+
49
+ this.once("shardPreReady", () => {
50
+ this.preReady = true;
51
+ if (!this.commandOptions.name) {
52
+ this.commandOptions.name = `**${this.user.username}**`;
53
+ }
54
+ if (Array.isArray(this.commandOptions.prefix)) {
55
+ for (let i = 0; i < this.commandOptions.prefix.length; ++i) {
56
+ this.commandOptions.prefix[i] = this.commandOptions.prefix[i].replace(/@mention/g, this.user.mention);
57
+ }
58
+ } else {
59
+ this.commandOptions.prefix = this.commandOptions.prefix.replace(/@mention/g, this.user.mention);
60
+ }
61
+ for (const key of Object.keys(this.guildPrefixes)) {
62
+ if (Array.isArray(this.guildPrefixes[key])) {
63
+ for (let i = 0; i < this.guildPrefixes[key].length; ++i) {
64
+ this.guildPrefixes[key][i] = this.guildPrefixes[key][i].replace(/@mention/g, this.user.mention);
65
+ }
66
+ } else {
67
+ this.guildPrefixes[key] = this.guildPrefixes[key].replace(/@mention/g, this.user.mention);
68
+ }
69
+ }
70
+ });
71
+
72
+ this.on("messageCreate", this.onMessageCreate);
73
+
74
+ this.on("messageReactionAdd", this.onMessageReactionEvent);
75
+ this.on("messageReactionRemove", this.onMessageReactionEvent);
76
+
77
+ if (this.commandOptions.defaultHelpCommand) {
78
+ this.registerCommand("help", async (msg, args) => {
79
+ let result = "";
80
+ if (args.length > 0) {
81
+ let cur = this.commands[this.commandAliases[args[0]] || args[0]];
82
+ if (!cur) {
83
+ return "Command not found";
84
+ }
85
+ let { label } = cur;
86
+ for (let i = 1; i < args.length; ++i) {
87
+ cur = cur.subcommands[cur.subcommandAliases[args[i]] || args[i]];
88
+ if (!cur) {
89
+ return "Command not found";
90
+ }
91
+ label += ` ${cur.label}`;
92
+ }
93
+ result += `**${msg.prefix}${label}** ${cur.usage}\n${cur.fullDescription}`;
94
+ if (cur.aliases.length > 0) {
95
+ result += `\n\n**Aliases:** ${cur.aliases.join(", ")}`;
96
+ }
97
+ const subcommands = Object.keys(cur.subcommands);
98
+ if (subcommands.length > 0) {
99
+ result += "\n\n**Subcommands:**";
100
+ for (const subLabel of subcommands) {
101
+ if (cur.subcommands.hasOwnProperty(subLabel) && await cur.subcommands[subLabel].permissionCheck(msg)) {
102
+ result += `\n **${subLabel}** - ${cur.subcommands[subLabel].description}`;
103
+ }
104
+ }
105
+ }
106
+ } else {
107
+ result += `${this.commandOptions.name} - ${this.commandOptions.description}\n`;
108
+ if (this.commandOptions.owner) {
109
+ result += `by ${this.commandOptions.owner}\n`;
110
+ }
111
+ result += "\n**Commands:**\n";
112
+ for (const label in this.commands) {
113
+ if (this.commands.hasOwnProperty(label) && this.commands[label] && await this.commands[label].permissionCheck(msg) && !this.commands[label].hidden) {
114
+ result += ` **${msg.prefix}${label}** - ${this.commands[label].description}\n`;
115
+ }
116
+ }
117
+ result += `\nType ${msg.prefix}help <command> for more info on a command.`;
118
+ }
119
+ return result;
120
+ }, {
121
+ description: "This help text",
122
+ fullDescription: "This command is used to view information of different bot commands, including this one.",
123
+ });
124
+ if (!this.commandOptions.defaultCommandOptions.invalidUsageMessage) {
125
+ this.commandOptions.defaultCommandOptions.invalidUsageMessage = "Invalid usage. Do `%prefix%help %label%` to view proper usage.";
126
+ }
127
+ } else if (!this.commandOptions.defaultCommandOptions.invalidUsageMessage) {
128
+ this.commandOptions.defaultCommandOptions.invalidUsageMessage = "Invalid usage.";
129
+ }
130
+ }
131
+
132
+ checkPrefix(msg) {
133
+ let prefixes = this.commandOptions.prefix;
134
+ if (msg.channel.guild !== undefined && this.guildPrefixes[msg.channel.guild.id] !== undefined) {
135
+ prefixes = this.guildPrefixes[msg.channel.guild.id];
136
+ }
137
+ if (typeof prefixes === "string") {
138
+ return msg.content.replace(/<@!/g, "<@").startsWith(prefixes) && prefixes;
139
+ } else if (Array.isArray(prefixes)) {
140
+ return prefixes.find((prefix) => msg.content.replace(/<@!/g, "<@").startsWith(prefix));
141
+ }
142
+ throw new Error(`Unsupported prefix format | ${prefixes}`);
143
+ }
144
+
145
+ /**
146
+ * Checks the command client for a command based on the provided message
147
+ * @arg {Message} msg The message object from the message create event
148
+ */
149
+ async onMessageCreate(msg) {
150
+ if (!this.ready) {
151
+ return;
152
+ }
153
+ if (!msg.author) {
154
+ this.emit("warn", `Message ${msg.id} has author=${msg.author} | Channel ${msg.channel.id}, timestamp ${Date.now()}`);
155
+ return;
156
+ }
157
+
158
+ msg.command = false;
159
+ if ((!this.commandOptions.ignoreSelf || msg.author.id !== this.user.id) && (!this.commandOptions.ignoreBots || !msg.author.bot) && (msg.prefix = this.checkPrefix(msg))) {
160
+ const args = this.commandOptions.argsSplitter(msg.content.replace(/<@!/g, "<@").substring(msg.prefix.length).trim());
161
+ const label = args.shift();
162
+ const command = this.resolveCommand(label);
163
+ if (command !== undefined) {
164
+ msg.command = command;
165
+ try {
166
+ let resp = await msg.command.process(args, msg);
167
+ if (resp != null) {
168
+ if (!(resp instanceof Message)) {
169
+ resp = await this.createMessage(msg.channel.id, resp); // eslint-disable-line require-atomic-updates
170
+ }
171
+ if (msg.command.reactionButtons) {
172
+ msg.command.reactionButtons.forEach((button) => resp.addReaction(button.emoji));
173
+ this.activeMessages[resp.id] = {
174
+ args: args,
175
+ command: msg.command,
176
+ message: resp,
177
+ timeout: setTimeout(() => {
178
+ this.unwatchMessage(resp.id, resp.channel.id);
179
+ }, msg.command.reactionButtonTimeout),
180
+ };
181
+ }
182
+ }
183
+ if (msg.command.hooks.postCommand) {
184
+ msg.command.hooks.postCommand(msg, args, resp);
185
+ }
186
+ } catch (err) {
187
+ this.emit("error", err);
188
+ if (msg.command.hooks.postExecution) {
189
+ msg.command.hooks.postExecution(msg, args, false);
190
+ }
191
+ let newMsg;
192
+ if (msg.command.errorMessage) {
193
+ try {
194
+ if (typeof msg.command.errorMessage === "function") {
195
+ const reply = await msg.command.errorMessage(msg, err);
196
+ if (reply !== undefined) {
197
+ newMsg = await this.createMessage(msg.channel.id, reply);
198
+ }
199
+ } else {
200
+ newMsg = await this.createMessage(msg.channel.id, msg.command.errorMessage);
201
+ }
202
+ } catch (err) {
203
+ this.emit("error", err);
204
+ }
205
+ }
206
+ if (msg.command.hooks.postCommand) {
207
+ msg.command.hooks.postCommand(msg, args, newMsg);
208
+ }
209
+ }
210
+ }
211
+ }
212
+ }
213
+
214
+ async onMessageReactionEvent(msg, emoji, reactor) {
215
+ const userID = typeof reactor === "object" ? reactor.id : reactor;
216
+ const activeMessage = this.activeMessages[msg.id];
217
+ if (!this.ready || userID === this.user.id || !activeMessage) {
218
+ return;
219
+ }
220
+ // Messages in uncached channels, like DMs, only come with their ID: use the response as last sent
221
+ if (!(msg.content || msg.embeds || msg.attachments)) {
222
+ msg = activeMessage.message;
223
+ }
224
+
225
+ emoji = emoji.id ? `${emoji.name}:${emoji.id}` : emoji.name;
226
+
227
+ if (activeMessage.command.reactionButtons) {
228
+ const action = activeMessage.command.reactionButtons.find((button) => button.emoji === emoji);
229
+ if (!action) {
230
+ return;
231
+ }
232
+
233
+ if (action.filter && !action.filter(msg, emoji, userID)) {
234
+ return;
235
+ }
236
+
237
+ switch (action.type) {
238
+ case "cancel": {
239
+ this.unwatchMessage(msg.id, msg.channel.guild && msg.channel.id);
240
+ try {
241
+ const resp = await action.execute(msg, activeMessage.args, userID);
242
+ if (resp != null) {
243
+ await this.editMessage(msg.channel.id, msg.id, resp);
244
+ }
245
+ } catch {} // eslint-disable-line no-empty
246
+ break;
247
+ }
248
+ case "edit":
249
+ default: {
250
+ try {
251
+ const resp = await action.execute(msg, activeMessage.args, userID);
252
+ if (resp != null) {
253
+ activeMessage.message = await this.editMessage(msg.channel.id, msg.id, resp);
254
+ }
255
+ } catch {} // eslint-disable-line no-empty
256
+ break;
257
+ }
258
+ }
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Register a command
264
+ * @arg {String} label The command label
265
+ * @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.
266
+ * 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.
267
+ * `generator(msg, args)`
268
+ * @arg {Object} [options] Command options
269
+ * @arg {Array<String>} [options.aliases] An array of command aliases
270
+ * @arg {Boolean} [options.argsRequired=false] If arguments are required or not
271
+ * @arg {Boolean} [options.caseInsensitive=false] Whether the command label (and aliases) is case insensitive or not
272
+ * @arg {Number} [options.cooldown] The cooldown between command usage in milliseconds
273
+ * @arg {Object} [options.cooldownExclusions={}] A set of factors that limit where cooldowns are active
274
+ * @arg {Array<String>} [options.cooldownExclusions.channelIDs] An array of channel IDs representing channels that are not affected by cooldowns.
275
+ * @arg {Array<String>} [options.cooldownExclusions.guildIDs] An array of guild IDs representing guilds that are not affected by cooldowns.
276
+ * @arg {Array<String>} [options.cooldownExclusions.userIDs] An array of user IDs representing users that are not affected by cooldowns.
277
+ * @arg {Function | String} [options.cooldownMessage] A string or a function that returns a string to show when the command is on cooldown
278
+ * @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.
279
+ * @arg {Object} [options.defaultSubcommandOptions={}] Default subcommand options. This object takes the same options as a normal Command
280
+ * @arg {Boolean} [options.deleteCommand=false] Whether to delete the user command message or not
281
+ * @arg {String} [options.description="No description"] A short description of the command to show in the default help command
282
+ * @arg {Boolean} [options.dmOnly=false] Whether to prevent the command from being used in guilds or not
283
+ * @arg {Function | String} [options.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 command message and the error as parameters.
284
+ * @arg {String} [options.fullDescription="No full description"] A detailed description of the command to show in the default help command
285
+ * @arg {Boolean} [options.guildOnly=false] Whether to prevent the command from being used in Direct Messages or not
286
+ * @arg {Boolean} [options.hidden=false] Whether or not the command should be hidden from the default help command list
287
+ * @arg {Object} [options.hooks] A set of functions to be executed at different times throughout the command's processing
288
+ * @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.
289
+ * @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.
290
+ * @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.
291
+ * @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.
292
+ * @arg {Function | String} [options.invalidUsageMessage] A string or a function that returns a string to show when a command was improperly used
293
+ * @arg {Function | String} [options.permissionMessage] A string or a function that returns a string to show when the user doesn't have permissions to use the command
294
+ * @arg {Array<{emoji: String, type: String, response: (Function | String | Array<Function | String>)}>} [options.reactionButtons] An array of objects specifying reaction buttons
295
+ * `emoji` specifies the button emoji. Custom emojis should be in format `emojiName:emojiID`
296
+ * `type` specifies the type of the reaction button, either "edit" or "cancel"
297
+ * `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
298
+ * `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
299
+ * @arg {Number} [options.reactionButtonTimeout=60000] Time (in milliseconds) to wait before invalidating the command's reaction buttons
300
+ * @arg {Object} [options.requirements] A set of factors that limit who can call the command
301
+ * @arg {Function} [options.requirements.custom] A function that accepts a message and returns true if the command should be run
302
+ * @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
303
+ * i.e.:
304
+ * ```
305
+ * {
306
+ * "administrator": false,
307
+ * "manageMessages": true
308
+ * }
309
+ * ```
310
+ * In the above example, the user must not have administrator permissions, but must have manageMessages to use the command
311
+ * @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
312
+ * @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
313
+ * @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
314
+ * @arg {Boolean} [option.restartCooldown=false] Whether or not to restart a command's cooldown every time it's used.
315
+ * @arg {String} [options.usage] Details on how to call the command to show in the default help command
316
+ * @returns {Command}
317
+ */
318
+ registerCommand(label, generator, options = {}) {
319
+ if (label.includes(" ")) {
320
+ throw new Error("Command label may not have spaces");
321
+ }
322
+ let lowercaseCommand = label.toLowerCase();
323
+ if (this.commands[label] || (this.commands[lowercaseCommand] && this.commands[lowercaseCommand].caseInsensitive)) {
324
+ throw new Error(`You have already registered a command for ${label}`);
325
+ }
326
+ // Aliases are not deleted when deleting commands
327
+ let command = this.commandAliases[label]; // Just to make the following if statement less messy
328
+ lowercaseCommand = this.commandAliases[label.toLowerCase()];
329
+ if (this.commands[command] || (this.commands[lowercaseCommand] && this.commands[lowercaseCommand].caseInsensitive)) {
330
+ throw new Error(`Alias ${label} already registered`);
331
+ }
332
+ options.defaultSubcommandOptions = options.defaultSubcommandOptions || {};
333
+ for (const key in this.commandOptions.defaultCommandOptions) {
334
+ if (this.commandOptions.defaultCommandOptions.hasOwnProperty(key) && options[key] === undefined) {
335
+ options[key] = this.commandOptions.defaultCommandOptions[key];
336
+ options.defaultSubcommandOptions[key] = this.commandOptions.defaultCommandOptions[key];
337
+ }
338
+ }
339
+ label = options.caseInsensitive === true ? label.toLowerCase() : label;
340
+ if (this.commands[label]) {
341
+ throw new Error(`You have already registered a command for ${label}`);
342
+ }
343
+ command = this.commandAliases[label];
344
+ if (this.commands[command]) {
345
+ throw new Error(`Alias ${command} already registered`);
346
+ }
347
+ if (options.aliases) {
348
+ options.aliases.forEach((alias) => {
349
+ lowercaseCommand = alias.toLowerCase();
350
+ if (this.commands[alias] || (this.commands[lowercaseCommand] && this.commands[lowercaseCommand].caseInsensitive)) {
351
+ throw new Error(`You have already registered a command for alias ${alias}`);
352
+ }
353
+ command = this.commandAliases[alias];
354
+ lowercaseCommand = this.commandAliases[alias.toLowerCase()];
355
+ if (this.commands[command] || (this.commands[lowercaseCommand] && this.commands[lowercaseCommand].caseInsensitive)) {
356
+ throw new Error(`Alias ${alias} already registered`);
357
+ }
358
+ alias = options.caseInsensitive === true ? alias.toLowerCase() : alias;
359
+ if (this.commands[alias]) {
360
+ throw new Error(`You have already registered a command for alias ${alias}`);
361
+ }
362
+ command = this.commandAliases[alias];
363
+ if (this.commands[command]) {
364
+ throw new Error(`Alias ${alias} already registered`);
365
+ }
366
+ this.commandAliases[alias] = label;
367
+ });
368
+ }
369
+ this.commands[label] = new Command(label, generator, options);
370
+ return this.commands[label];
371
+ }
372
+
373
+ /**
374
+ * Register an alias for a command
375
+ * @arg {String} alias The alias
376
+ * @arg {String} label The original command label
377
+ */
378
+ registerCommandAlias(alias, label) {
379
+ let caseInsensitiveLabel = false;
380
+ if (!this.commands[label] && !(this.commands[(label = label.toLowerCase())] && (caseInsensitiveLabel = this.commands[label.toLowerCase()].caseInsensitive))) {
381
+ throw new Error(`No command registered for ${label}`);
382
+ }
383
+ alias = caseInsensitiveLabel === true ? alias.toLowerCase() : alias;
384
+ if (this.commandAliases[alias]) {
385
+ throw new Error(`Alias ${alias} already registered`);
386
+ }
387
+ this.commandAliases[alias] = label;
388
+ this.commands[label].aliases.push(alias);
389
+ }
390
+
391
+ /**
392
+ * Register a prefix override for a specific guild
393
+ * @arg {String} guildID The ID of the guild to override prefixes for
394
+ * @arg {String | Array} prefix The bot prefix. Can be either an array of prefixes or a single prefix. "@mention" will be automatically replaced with the bot's actual mention
395
+ */
396
+ registerGuildPrefix(guildID, prefix) {
397
+ if (!this.preReady) {
398
+ this.guildPrefixes[guildID] = prefix;
399
+ } else if (Array.isArray(prefix)) {
400
+ for (let i = 0; i < prefix.length; ++i) {
401
+ prefix[i] = prefix[i].replace(/@mention/g, this.user.mention);
402
+ }
403
+ this.guildPrefixes[guildID] = prefix;
404
+ } else {
405
+ this.guildPrefixes[guildID] = prefix.replace(/@mention/g, this.user.mention);
406
+ }
407
+ }
408
+
409
+ resolveCommand(label) {
410
+ label = this.commandAliases[label] || label;
411
+ let command = this.commands[label];
412
+ if (command) {
413
+ return command;
414
+ }
415
+ label = label.toLowerCase();
416
+ label = this.commandAliases[label] || label;
417
+ command = this.commands[label];
418
+ if (command && command.caseInsensitive) {
419
+ return command;
420
+ }
421
+ }
422
+
423
+ /**
424
+ * Unregister a command
425
+ * @arg {String} label The command label
426
+ */
427
+ unregisterCommand(label) {
428
+ const original = this.commandAliases[label];
429
+ if (original) {
430
+ this.commands[original].aliases.splice(this.commands[original].aliases.indexOf(label), 1);
431
+ delete this.commandAliases[label];
432
+ } else {
433
+ delete this.commands[label];
434
+ }
435
+ }
436
+
437
+ unwatchMessage(id, channelID) {
438
+ delete this.activeMessages[id];
439
+ if (channelID) {
440
+ this.removeMessageReactions(channelID, id).catch(() => {});
441
+ }
442
+ }
443
+
444
+ toString() {
445
+ return `[CommandClient ${this.user.id}]`;
446
+ }
447
+
448
+ toJSON(props = []) {
449
+ return super.toJSON([
450
+ "activeMessages",
451
+ "commandAliases",
452
+ "commandOptions",
453
+ "commands",
454
+ "guildPrefixes",
455
+ ...props,
456
+ ]);
457
+ }
458
+ }
459
+
460
+ module.exports = CommandClient;