This repository has been archived by the owner on Aug 10, 2022. It is now read-only.
/
slash-command.ts
430 lines (382 loc) · 11.5 KB
/
slash-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
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
import type {
ApplicationCommandChannelOptionData,
ApplicationCommandData,
ApplicationCommandOptionData,
ChatInputApplicationCommandData,
CommandInteraction,
GuildChannel,
Role,
} from "discord.js"
import { GuildMember, User } from "discord.js"
import { isDeepEqual, raise } from "../../internal/helpers"
import type { ValueOf } from "../../internal/types"
import type { InteractionContext } from "../interaction-context"
import { createInteractionContext } from "../interaction-context"
import type { Command } from "./command"
import { createCommand } from "./command"
/**
* Configuration for a slash command. See {@link Gatekeeper.addSlashCommand}
*/
export type SlashCommandConfig<
Options extends SlashCommandOptionConfigMap = SlashCommandOptionConfigMap,
> = {
/**
* The name of the command.
* e.g. If you pass the name "airhorn",
* the command will be run with /airhorn in Discord
*/
name: string
/** Aliases: alternate names to call this command with */
aliases?: string[]
/**
* The description of the command.
* Shows up when showing a list of the bot's commands
*/
description: string
/**
* An object of options for the command, also called arguments, or parameters.
*/
options?: Options
/**
* The function to run when the command is called.
* Receives a {@link SlashCommandInteractionContext} object as the first argument.
*/
run: (
context: SlashCommandInteractionContext<Options>,
) => void | Promise<unknown>
}
/**
* Valid slash command option config, only used for typescript inference
*/
export type SlashCommandOptionConfigMap = {
[name: string]: SlashCommandOptionConfig
}
/**
* A possible option for a slash command.
* See {@link SlashCommandOptionValueMap} for a list of possible options
* and the values they resolve to.
*/
export type SlashCommandOptionConfig = SlashCommandOptionConfigBase &
(
| {
type: "STRING"
choices?: Array<SlashCommandOptionChoiceConfig<string>>
}
| {
type: "NUMBER" | "INTEGER"
choices?: Array<SlashCommandOptionChoiceConfig<number>>
}
| { type: "BOOLEAN" }
| { type: "USER" }
| {
type: "CHANNEL"
channelTypes?: SlashCommandOptionChannelType[]
}
| { type: "ROLE" }
| { type: "MENTIONABLE" }
)
/**
* All possible channel types to filter by when using the `CHANNEL` option type
*/
export type SlashCommandOptionChannelType =
| "GUILD_TEXT"
| "DM"
| "GUILD_VOICE"
| "GROUP_DM"
| "GUILD_CATEGORY"
| "GUILD_NEWS"
| "GUILD_STORE"
| "GUILD_NEWS_THREAD"
| "GUILD_PUBLIC_THREAD"
| "GUILD_PRIVATE_THREAD"
| "GUILD_STAGE_VOICE"
/**
* A potential choice for a slash command option
*/
export type SlashCommandOptionChoiceConfig<Value> = {
name: string
value: Value
}
/**
* This is the magic that takes your option config
* and gives you a typesafe object of values.
*/
export type SlashCommandOptionValues<
Options extends SlashCommandOptionConfigMap,
> = {
[Name in keyof Options]: Options[Name]["required"] extends true
? SlashCommandOptionValueMap[Options[Name]["type"]]
: SlashCommandOptionValueMap[Options[Name]["type"]] | undefined
}
/**
* A map of option types to the kind of value it resolves to.
* e.g. If an option has a type of "NUMBER", it will resolve to a number.
*/
export type SlashCommandOptionValueMap = {
STRING: string
NUMBER: number
INTEGER: number
BOOLEAN: boolean
USER: User
CHANNEL: GuildChannel
ROLE: Role
MENTIONABLE: SlashCommandMentionableValue
}
/**
* A resolved mentionable option for a slash command
*/
export type SlashCommandMentionableValue = {
/**
* A string that can be sent in a message as a mention.
* e.g. `"<@!123456789>"` for users, `"<@&123456789>"` for roles
*/
mention: string
} & (
| {
/**
* Whether or not this mention is a user mention.
* If using typescript, this property _must_ be checked
* to use the related properties
*/
isUser: true
/**
* The mentioned user
*/
user: User
/**
* The guild (server) member object, if in a guild
*/
guildMember: GuildMember | undefined
}
| {
/**
* Whether or not this mention is a user mention.
* If using typescript, this property _must_ be checked
* to use the related properties
*/
isUser: false
/**
* The role that was mentioned, only available in guilds (servers)
*/
role: Role
}
)
/**
* The interaction context for a slash command
*/
export type SlashCommandInteractionContext<
Options extends SlashCommandOptionConfigMap = SlashCommandOptionConfigMap,
> = InteractionContext & {
/**
* An object of the options that were passed when running the slash command
*/
options: SlashCommandOptionValues<Options>
}
/**
* Shared properties for all slash command option types
*/
export type SlashCommandOptionConfigBase = {
/**
* Description for the option, shows up when tabbing through the options in Discord
*/
description: string
/**
* Whether the option is required.
* If true, the value will be guaranteed to exist in the options object,
* otherwise it will be undefined
*/
required?: boolean
}
/** Sorts channel types based on Discord's list */
function sortChannelTypes(
arrA: SlashCommandOptionChannelType[],
): SlashCommandOptionChannelType[] {
const channelTypesOrder = [
"GUILD_TEXT",
"DM",
"GUILD_VOICE",
"GROUP_DM",
"GUILD_CATEGORY",
"GUILD_NEWS",
"GUILD_STORE",
"GUILD_NEWS_THREAD",
"GUILD_PUBLIC_THREAD",
"GUILD_PRIVATE_THREAD",
"GUILD_STAGE_VOICE",
]
return [...arrA].sort(
(a, b) => channelTypesOrder.indexOf(a) - channelTypesOrder.indexOf(b),
)
}
export function createSlashCommands<
Options extends SlashCommandOptionConfigMap,
>(config: SlashCommandConfig<Options>): Command[] {
const names = [config.name, ...(config.aliases || [])]
return names.map((name) => {
const options: ApplicationCommandOptionData[] = Object.entries(
config.options ?? {},
).map(([name, option]) => ({
name,
description: option.description,
type: option.type,
// discord always returns a boolean, even if the user didn't send one
required: option.required ?? false,
// discord returns undefined if the user passed an empty array,
// so normalize undefined to an empty array
choices: ("choices" in option && option.choices) || [],
// Discord returns channel types in a specific order
channelTypes:
("channelTypes" in option &&
sortChannelTypes(option.channelTypes ?? [])) ||
undefined,
}))
const commandData: ApplicationCommandData = {
name,
description: config.description,
options,
}
return createCommand({
name,
matchesExisting: (command) => {
if (command.type !== "CHAT_INPUT") return false
const existingCommandData: ChatInputApplicationCommandData = {
name: command.name,
description: command.description,
// need to use the same shape so they can be compared
options: command.options.map(
(option): ApplicationCommandOptionData => ({
name: option.name,
description: option.description,
type: option.type,
required: (option as any).required, // ???
choices: ("choices" in option && option.choices) || [],
/* option.channelTypes includes "UNKNOWN", but it's not allowed by ApplicationCommandOptionData */
channelTypes:
(("channelTypes" in option &&
option.channelTypes) as ApplicationCommandChannelOptionData["channelTypes"]) ||
undefined,
}),
),
}
return isDeepEqual(commandData, existingCommandData)
},
register: async (manager) => {
await manager.create(commandData)
},
matchesInteraction: (interaction) => {
return interaction.isCommand() && interaction.commandName === name
},
run: async (interaction, command) => {
await config.run({
...createInteractionContext({ interaction, command }),
options: collectSlashCommandOptionValues(
config,
interaction as CommandInteraction,
),
})
},
})
})
}
function collectSlashCommandOptionValues<
Options extends SlashCommandOptionConfigMap,
>(
slashCommand: SlashCommandConfig<Options>,
interaction: CommandInteraction,
): SlashCommandOptionValues<Options> {
const options: Record<
string,
ValueOf<SlashCommandOptionValueMap> | undefined
> = {}
for (const [name, optionDefinition] of Object.entries(
slashCommand.options ?? {},
)) {
if (optionDefinition.type === "STRING") {
options[name] =
interaction.options.getString(name, optionDefinition.required) ??
optionFallback(name, optionDefinition, slashCommand)
}
if (optionDefinition.type === "NUMBER") {
options[name] =
interaction.options.getNumber(name, optionDefinition.required) ??
optionFallback(name, optionDefinition, slashCommand)
}
if (optionDefinition.type === "INTEGER") {
options[name] =
interaction.options.getInteger(name, optionDefinition.required) ??
optionFallback(name, optionDefinition, slashCommand)
}
if (optionDefinition.type === "BOOLEAN") {
options[name] =
interaction.options.getBoolean(name, optionDefinition.required) ??
optionFallback(name, optionDefinition, slashCommand)
}
if (optionDefinition.type === "USER") {
options[name] =
interaction.options.getUser(name, optionDefinition.required) ??
optionFallback(name, optionDefinition, slashCommand)
}
if (optionDefinition.type === "CHANNEL") {
const channel = interaction.options.getChannel(
name,
optionDefinition.required,
) as GuildChannel | null
options[name] =
channel ?? optionFallback(name, optionDefinition, slashCommand)
}
if (optionDefinition.type === "ROLE") {
const role = interaction.options.getRole(
name,
optionDefinition.required,
) as Role | null
options[name] =
role ?? optionFallback(name, optionDefinition, slashCommand)
}
if (optionDefinition.type === "MENTIONABLE") {
const value = interaction.options.getMentionable(
name,
optionDefinition.required,
) as User | GuildMember | Role | null
options[name] = value
? createResolvedMentionable(value)
: optionFallback(name, optionDefinition, slashCommand)
}
}
return options as SlashCommandOptionValues<Options>
}
function createResolvedMentionable(
value: User | GuildMember | Role,
): SlashCommandMentionableValue {
if (value instanceof User) {
return {
isUser: true,
user: value,
guildMember: undefined,
mention: `<@!${value.id}>`,
}
}
if (value instanceof GuildMember) {
return {
isUser: true,
user: value.user,
guildMember: value,
mention: `<@!${value.id}>`,
}
}
return {
isUser: false,
role: value,
mention: `<@&${value.id}>`,
}
}
function optionFallback(
optionName: string,
optionDefinition: SlashCommandOptionConfig,
slashCommand: SlashCommandConfig<any>,
): string | number | boolean | undefined {
return optionDefinition.required
? raise(
`Could not get required option "${optionName}" for command "${slashCommand.name}"`,
)
: undefined
}