-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathcodeyCommand.ts
More file actions
444 lines (412 loc) · 15.9 KB
/
codeyCommand.ts
File metadata and controls
444 lines (412 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
import {
ApplicationCommandOptionBase,
ApplicationCommandOptionWithChoicesAndAutocompleteMixin,
SlashCommandBuilder,
SlashCommandIntegerOption,
SlashCommandNumberOption,
SlashCommandStringOption,
SlashCommandSubcommandBuilder,
SlashCommandSubcommandsOnlyBuilder,
} from '@discordjs/builders';
import {
ApplicationCommandRegistries,
ArgType,
Args,
ChatInputCommand,
RegisterBehavior,
SapphireClient,
Command as SapphireCommand,
container,
} from '@sapphire/framework';
import { APIApplicationCommandOptionChoice, APIMessage } from 'discord-api-types/v9';
import {
ApplicationCommandOptionType,
BaseMessageOptions,
CommandInteraction,
Message,
MessagePayload,
User,
} from 'discord.js';
import { CodeyUserError } from './codeyUserError';
import { logger } from './logger/default';
export type SapphireSentMessageType = Message | CommandInteraction;
export type SapphireMessageResponse =
| string
| MessagePayload
| BaseMessageOptions
// void when the command handles sending a response on its own
| void;
export class SapphireMessageResponseWithMetadata {
response: SapphireMessageResponse;
metadata: Record<string, unknown>;
constructor(response: SapphireMessageResponse, metadata: Record<string, unknown>) {
this.response = response;
this.metadata = metadata;
}
}
export type SapphireMessageExecuteType = (
client: SapphireClient<boolean>,
// Message is for normal commands, ChatInputCommandInteraction is for slash commands
messageFromUser: Message | SapphireCommand.ChatInputCommandInteraction,
// Command arguments
args: CodeyCommandArguments,
) => Promise<SapphireMessageResponse | SapphireMessageResponseWithMetadata>;
export type SapphireAfterReplyType = (
/** The result from executeCommand, that contains the original message content and the metadata */
result: SapphireMessageResponseWithMetadata,
/** The message that is sent */
sentMessage: SapphireSentMessageType,
) => Promise<unknown>;
// Command options
/** The type of the codey command option */
export enum CodeyCommandOptionType {
STRING = ApplicationCommandOptionType.String,
INTEGER = ApplicationCommandOptionType.Integer,
BOOLEAN = ApplicationCommandOptionType.Boolean,
USER = ApplicationCommandOptionType.User,
CHANNEL = ApplicationCommandOptionType.Channel,
ROLE = ApplicationCommandOptionType.Role,
MENTIONABLE = ApplicationCommandOptionType.Mentionable,
NUMBER = ApplicationCommandOptionType.Number,
ATTACHMENT = ApplicationCommandOptionType.Attachment,
}
/** The codey command option */
export interface CodeyCommandOption {
/** The name of the option */
name: string;
/** The description of the option */
description: string;
/** The type of the option */
type: CodeyCommandOptionType;
/** Whether the option is required */
required: boolean;
/** Mention choices for the field if needed */
choices?: APIApplicationCommandOptionChoice[];
/** Client-side validation options */
validation?: {
/** Minimum length or value */
min?: number;
/** Maximum length or value */
max?: number;
};
}
/** Sets the command option in the slash command builder */
const setCommandOption = (
builder: SlashCommandBuilder | SlashCommandSubcommandBuilder,
option: CodeyCommandOption,
): SlashCommandBuilder | SlashCommandSubcommandBuilder => {
function setupCommand<T extends ApplicationCommandOptionBase>(commandOption: T): T {
let result = commandOption
.setName(option.name)
.setDescription(option.description)
.setRequired(option.required);
if (result instanceof SlashCommandStringOption && option.validation?.min !== undefined)
result = result.setMinLength(option.validation.min);
if (result instanceof SlashCommandStringOption && option.validation?.max !== undefined)
result = result.setMaxLength(option.validation.max);
if (
(result instanceof SlashCommandNumberOption || result instanceof SlashCommandIntegerOption) &&
option.validation?.min !== undefined
)
result = result.setMinValue(option.validation.min);
if (
(result instanceof SlashCommandNumberOption || result instanceof SlashCommandIntegerOption) &&
option.validation?.max !== undefined
)
result = result.setMaxValue(option.validation.max);
return result;
}
function setupChoices<
B extends string | number,
T extends ApplicationCommandOptionBase &
ApplicationCommandOptionWithChoicesAndAutocompleteMixin<B>,
>(commandOption: T): T {
return option.choices
? commandOption.addChoices(...(option.choices as APIApplicationCommandOptionChoice<B>[]))
: commandOption;
}
switch (option.type) {
case CodeyCommandOptionType.STRING:
return <SlashCommandBuilder>builder.addStringOption((x) => setupCommand(setupChoices(x)));
case CodeyCommandOptionType.INTEGER:
return <SlashCommandBuilder>builder.addIntegerOption((x) => setupCommand(setupChoices(x)));
case CodeyCommandOptionType.BOOLEAN:
return <SlashCommandBuilder>builder.addBooleanOption(setupCommand);
case CodeyCommandOptionType.USER:
return <SlashCommandBuilder>builder.addUserOption(setupCommand);
case CodeyCommandOptionType.CHANNEL:
return <SlashCommandBuilder>builder.addChannelOption(setupCommand);
case CodeyCommandOptionType.ROLE:
return <SlashCommandBuilder>builder.addRoleOption(setupCommand);
case CodeyCommandOptionType.MENTIONABLE:
return <SlashCommandBuilder>builder.addMentionableOption(setupCommand);
case CodeyCommandOptionType.NUMBER:
return <SlashCommandBuilder>builder.addNumberOption((x) => setupCommand(setupChoices(x)));
case CodeyCommandOptionType.ATTACHMENT:
return <SlashCommandBuilder>builder.addAttachmentOption(setupCommand);
default:
throw new Error(`Unknown option type.`);
}
};
/** The possible types of the value of a command option */
export type CodeyCommandArgumentValueType = string | number | boolean | User | undefined;
/** A standardized dictionary that stores the arguments of the command */
export type CodeyCommandArguments = { [key: string]: CodeyCommandArgumentValueType };
/** Details for the codey command (or subcommand) */
export class CodeyCommandDetails {
/** The name of the command */
name!: string;
/** The aliases of the command (for regular commands) */
aliases: string[] = [];
/** A short description of the command (shown in the slash command menu) */
description = `Codey command for ${this.name}`;
/** A longer description of the command (shown in the help menu for the command) */
detailedDescription: string = this.description;
// The following can all technically be nullable, because the actual command might not be used
// Rather, the command might just be a "folder" for subcommands.
/** The message to display when the command is executing (for slash commands) */
messageWhenExecutingCommand?: string;
/** The function to be called to execute the command */
executeCommand?: SapphireMessageExecuteType;
/** A callback that takes in the *sent* message */
afterMessageReply?: SapphireAfterReplyType;
/** The message to display if the command fails */
messageIfFailure?: string;
/** A flag to indicate if the command response is ephemeral (ie visible to others) */
isCommandResponseEphemeral? = true;
/** Options for the Codey command */
options: CodeyCommandOption[] = [];
/** Subcommands under the CodeyCommand */
subcommandDetails: { [name: string]: CodeyCommandDetails } = {};
/** The default subcommand to execute if no subcommand is specified */
defaultSubcommandDetails?: CodeyCommandDetails;
}
/** Sets the command subcommand in the slash command builder */
const setCommandSubcommand = (
builder: SlashCommandBuilder,
subcommandDetails: CodeyCommandDetails,
): SlashCommandSubcommandsOnlyBuilder => {
return builder.addSubcommand((subcommandBuilder) => {
subcommandBuilder.setName(subcommandDetails.name);
subcommandBuilder.setDescription(subcommandDetails.description);
for (const commandOption of subcommandDetails.options) {
setCommandOption(subcommandBuilder, commandOption);
}
return subcommandBuilder;
});
};
/**
* Gets the User object from a message response.
*
* Retrieving the `User` depends on whether slash commands were used or not.
* This method helps generalize this process.
* */
export const getUserFromMessage = (
message: Message | SapphireCommand.ChatInputCommandInteraction,
): User => {
if (message instanceof Message) {
return message.author;
} else {
return message.user;
}
};
const defaultBackendErrorMessage = 'Codey backend error - contact a mod for assistance';
/** The codey command class */
export class CodeyCommand extends SapphireCommand {
/** The details of the command */
details!: CodeyCommandDetails;
// Get slash command builder
public configureSlashCommandBuilder(builder: SlashCommandBuilder): SlashCommandBuilder {
builder.setName(this.details.name);
builder.setDescription(this.details.description);
for (const commandOption of this.details.options) {
setCommandOption(builder, commandOption);
}
for (const subcommandName in this.details.subcommandDetails) {
setCommandSubcommand(builder, this.details.subcommandDetails[subcommandName]);
}
return builder;
}
// Register application commands
public override registerApplicationCommands(registry: ChatInputCommand.Registry): void {
// This ensures any new changes are made to the slash commands are made
ApplicationCommandRegistries.setDefaultBehaviorWhenNotIdentical(RegisterBehavior.Overwrite);
// We need to do this because TS is weird
registry.registerChatInputCommand((builder) =>
this.configureSlashCommandBuilder(<SlashCommandBuilder>(<unknown>builder)),
);
}
// Regular command
public async messageRun(
message: Message,
commandArgs: Args,
): Promise<Message<boolean> | undefined> {
const { client } = container;
const subcommandName = message.content.split(' ')[1];
/** The command details object to use */
let commandDetails = this.details.subcommandDetails[subcommandName];
if (!commandDetails) {
// Check whether the subcommand is an alias of another command
for (const subcommandDetail of Object.values(this.details.subcommandDetails)) {
if (subcommandDetail.aliases.includes(subcommandName)) {
commandDetails = subcommandDetail;
break;
}
}
// If the subcommand is not an alias of another subcommand, use the default
if (!commandDetails) {
// If subcommands exist, use the default subcommand
if (Object.keys(this.details.subcommandDetails).length !== 0) {
commandDetails = this.details.defaultSubcommandDetails!;
}
// Otherwise, use the original command
else {
commandDetails = this.details;
}
}
}
// Move the "argument picker" by one parameter if subcommand name exists and is a string
if (subcommandName && isNaN(parseInt(subcommandName))) {
await commandArgs.pick('string');
}
const args: CodeyCommandArguments = {};
for (let i = 0; i < commandDetails.options!.length; i++) {
const commandOption = commandDetails.options![i];
try {
// take all remaining arguments given if this is the last argument option
if (i == commandDetails.options!.length - 1) {
args[commandOption.name] = <CodeyCommandArgumentValueType>(
await commandArgs.rest(
<keyof ArgType>ApplicationCommandOptionType[commandOption.type].toLowerCase(),
)
);
} else {
args[commandOption.name] = <CodeyCommandArgumentValueType>(
await commandArgs.pick(
<keyof ArgType>ApplicationCommandOptionType[commandOption.type].toLowerCase(),
)
);
}
} catch (e) {}
}
try {
const successResponse = await commandDetails.executeCommand!(client, message, args);
if (!successResponse) return;
// If response contains metadata
if (successResponse instanceof SapphireMessageResponseWithMetadata) {
const response = successResponse.response;
// If response is not undefined, reply to the original message with the response
if (typeof response !== 'undefined') {
const msg = await message.reply(<string | MessagePayload>response);
if (commandDetails.afterMessageReply) {
commandDetails.afterMessageReply(successResponse, msg);
}
return msg;
}
}
// If response does not contain metadata
else {
return await message.reply(<string | MessagePayload>successResponse);
}
} catch (e) {
if (e instanceof CodeyUserError) {
if (!e.message) {
e.message = message;
}
logger.error(e.errorMessage);
e.sendToUser();
} else {
logger.error(e);
message.reply(commandDetails.messageIfFailure ?? defaultBackendErrorMessage);
}
}
}
// Slash command
public async chatInputRun(
interaction: SapphireCommand.ChatInputCommandInteraction,
): Promise<APIMessage | Message<boolean> | undefined> {
const { client } = container;
// Get subcommand name
let subcommandName = '';
try {
subcommandName = interaction.options.getSubcommand();
} catch (e) {}
/** The command details object to use */
const commandDetails = this.details.subcommandDetails[subcommandName] ?? this.details;
// Get command arguments
const args: CodeyCommandArguments = Object.assign(
{},
...commandDetails.options
.map((commandOption) => commandOption.name)
.map((commandOptionName) => {
const commandInteractionOption = interaction.options.get(commandOptionName);
let result: CodeyCommandArgumentValueType;
if (commandInteractionOption) {
const type = commandInteractionOption.type;
switch (type) {
case ApplicationCommandOptionType.User:
return {
[commandOptionName]: commandInteractionOption.user,
};
default:
return {
[commandOptionName]: commandInteractionOption.value,
};
}
}
return {
[commandOptionName]: result,
};
}),
);
try {
let successResponse = await commandDetails.executeCommand!(client, interaction, args);
// convenience, allows returning `string` from executeCommand
if (typeof successResponse === 'string') {
successResponse = {
content: successResponse,
};
}
if (
successResponse instanceof SapphireMessageResponseWithMetadata &&
typeof successResponse.response === 'string'
) {
successResponse.response = { content: successResponse.response };
}
// cannot double reply to a slash command (in case command replies on its own), runtime error
if (!interaction.replied) {
await interaction.reply(
Object.assign(
{
ephemeral: commandDetails.isCommandResponseEphemeral,
},
successResponse instanceof SapphireMessageResponseWithMetadata
? successResponse.response
: successResponse,
),
);
// If after message reply is defined and the response contains metadata,
// run the function
if (
successResponse instanceof SapphireMessageResponseWithMetadata &&
commandDetails.afterMessageReply
) {
commandDetails.afterMessageReply(successResponse, interaction);
}
}
} catch (e) {
if (e instanceof CodeyUserError) {
logger.error(e.errorMessage);
if (!e.message) {
e.message = interaction;
}
e.sendToUser();
} else {
logger.error(e);
return await interaction.editReply(
commandDetails.messageIfFailure ?? defaultBackendErrorMessage,
);
}
}
}
}