-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
ApplicationCommandRegistry.ts
628 lines (528 loc) · 21.5 KB
/
ApplicationCommandRegistry.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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
import type {
ContextMenuCommandBuilder,
SlashCommandBuilder,
SlashCommandOptionsOnlyBuilder,
SlashCommandSubcommandsOnlyBuilder
} from '@discordjs/builders';
import { container } from '@sapphire/pieces';
import { isNullishOrEmpty } from '@sapphire/utilities';
import {
ApplicationCommandType,
type RESTPostAPIChatInputApplicationCommandsJSONBody,
type RESTPostAPIContextMenuApplicationCommandsJSONBody
} from 'discord-api-types/v10';
import {
Collection,
type ApplicationCommand,
type ApplicationCommandManager,
type ChatInputApplicationCommandData,
type MessageApplicationCommandData,
type UserApplicationCommandData
} from 'discord.js';
import type { Args } from '../../parsers/Args';
import type { Command } from '../../structures/Command';
import type { CommandOptions } from '../../types/CommandTypes';
import { InternalRegistryAPIType, RegisterBehavior } from '../../types/Enums';
import { allGuildIdsToFetchCommandsFor, getDefaultBehaviorWhenNotIdentical, getDefaultGuildIds } from './ApplicationCommandRegistries';
import type { CommandDifference } from './compute-differences/_shared';
import { getCommandDifferences, getCommandDifferencesFast } from './computeDifferences';
import { convertApplicationCommandToApiData, normalizeChatInputCommand, normalizeContextMenuCommand } from './normalizeInputs';
export class ApplicationCommandRegistry {
/**
* The piece this registry is for.
*/
public readonly commandName: string;
/**
* A set of all chat input command names and ids that point to this registry.
* You should not use this field directly, but instead use {@link ApplicationCommandRegistry.globalChatInputCommandIds}
*/
public readonly chatInputCommands = new Set<string>();
/**
* A set of all context menu command names and ids that point to this registry.
* You should not use this field directly, but instead use {@link ApplicationCommandRegistry.globalContextMenuCommandIds}
*/
public readonly contextMenuCommands = new Set<string>();
/**
* The guild ids that we need to fetch the commands for.
*/
public readonly guildIdsToFetch = new Set<string>();
/**
* The global slash command id for this command.
* @deprecated This field will only show the first global command id registered for this registry.
* Use {@link ApplicationCommandRegistry.globalChatInputCommandIds} instead.
*/
public globalCommandId: string | null = null;
/**
* A set of all registered and valid global chat input command ids that point to this registry.
*/
public readonly globalChatInputCommandIds = new Set<string>();
/**
* A set of all registered and valid global context menu command ids that point to this registry.
*/
public readonly globalContextMenuCommandIds = new Set<string>();
/**
* The guild command ids for this command.
* @deprecated This field will only show the first guild command id registered for this registry per guild.
* Use {@link ApplicationCommandRegistry.guildIdToChatInputCommandIds} and {@link ApplicationCommandRegistry.guildIdToContextMenuCommandIds} instead.
*/
public readonly guildCommandIds = new Collection<string, string>();
/**
* A map of guild ids to a set of registered and valid chat input command ids that point to this registry.
*/
public readonly guildIdToChatInputCommandIds = new Collection<string, Set<string>>();
/**
* A map of guild ids to a set of registered and valid context menu command ids that point to this registry.
*/
public readonly guildIdToContextMenuCommandIds = new Collection<string, Set<string>>();
private readonly apiCalls: InternalAPICall[] = [];
public constructor(commandName: string) {
this.commandName = commandName;
}
public get command(): Command<Args, CommandOptions> | undefined {
return container.stores.get('commands').get(this.commandName);
}
public registerChatInputCommand(
command:
| ChatInputApplicationCommandData
| SlashCommandBuilder
| SlashCommandSubcommandsOnlyBuilder
| SlashCommandOptionsOnlyBuilder
| Omit<SlashCommandBuilder, 'addSubcommand' | 'addSubcommandGroup'>
| ((builder: SlashCommandBuilder) => unknown),
options?: ApplicationCommandRegistryRegisterOptions
) {
const builtData = normalizeChatInputCommand(command);
this.chatInputCommands.add(builtData.name);
const guildIdsToRegister = this.getGuildIdsToRegister(options);
const registerOptions = {
registerCommandIfMissing: true,
behaviorWhenNotIdentical: getDefaultBehaviorWhenNotIdentical(),
guildIds: guildIdsToRegister,
...(options ?? {})
};
this.apiCalls.push({
builtData,
registerOptions,
type: InternalRegistryAPIType.ChatInput
});
if (options?.idHints) {
for (const hint of options.idHints) {
this.chatInputCommands.add(hint);
}
}
this.processGuildIds(guildIdsToRegister);
return this;
}
public registerContextMenuCommand(
command:
| UserApplicationCommandData
| MessageApplicationCommandData
| ContextMenuCommandBuilder
| ((builder: ContextMenuCommandBuilder) => unknown),
options?: ApplicationCommandRegistryRegisterOptions
) {
const builtData = normalizeContextMenuCommand(command);
this.contextMenuCommands.add(builtData.name);
const guildIdsToRegister = this.getGuildIdsToRegister(options);
const registerOptions = {
registerCommandIfMissing: true,
behaviorWhenNotIdentical: getDefaultBehaviorWhenNotIdentical(),
guildIds: guildIdsToRegister,
...(options ?? {})
};
this.apiCalls.push({
builtData,
registerOptions,
type: InternalRegistryAPIType.ContextMenu
});
if (options?.idHints) {
for (const hint of options.idHints) {
this.contextMenuCommands.add(hint);
}
}
this.processGuildIds(guildIdsToRegister);
return this;
}
public addChatInputCommandNames(...names: string[] | string[][]) {
const flattened = names.flat(Infinity) as string[];
for (const command of flattened) {
this.debug(`Registering name "${command}" to internal chat input map`);
this.warn(
`Registering the chat input command "${command}" using a name is not recommended.`,
'Please use the "addChatInputCommandIds" method instead with a command id.'
);
this.chatInputCommands.add(command);
}
return this;
}
public addContextMenuCommandNames(...names: string[] | string[][]) {
const flattened = names.flat(Infinity) as string[];
for (const command of flattened) {
this.debug(`Registering name "${command}" to internal context menu map`);
this.warn(
`Registering the context menu command "${command}" using a name is not recommended.`,
'Please use the "addContextMenuCommandIds" method instead with a command id.'
);
this.contextMenuCommands.add(command);
}
return this;
}
public addChatInputCommandIds(...commandIds: string[] | string[][]) {
const flattened = commandIds.flat(Infinity) as string[];
for (const entry of flattened) {
try {
BigInt(entry);
this.debug(`Registering id "${entry}" to internal chat input map`);
} catch {
// Don't be silly, save yourself the headaches and do as we say
this.debug(`Registering name "${entry}" to internal chat input map`);
this.warn(
`Registering the chat input command "${entry}" using a name *and* trying to bypass this warning by calling "addChatInputCommandIds" is not recommended.`,
'Please use the "addChatInputCommandIds" method with a valid command id instead.'
);
}
this.chatInputCommands.add(entry);
}
return this;
}
public addContextMenuCommandIds(...commandIds: string[] | string[][]) {
const flattened = commandIds.flat(Infinity) as string[];
for (const entry of flattened) {
try {
BigInt(entry);
this.debug(`Registering id "${entry}" to internal context menu map`);
} catch {
this.debug(`Registering name "${entry}" to internal context menu map`);
// Don't be silly, save yourself the headaches and do as we say
this.warn(
`Registering the context menu command "${entry}" using a name *and* trying to bypass this warning by calling "addContextMenuCommandIds" is not recommended.`,
'Please use the "addContextMenuCommandIds" method with a valid command id instead.'
);
}
this.contextMenuCommands.add(entry);
}
return this;
}
protected async runAPICalls(
applicationCommands: ApplicationCommandManager,
globalCommands: Collection<string, ApplicationCommand>,
guildCommands: Map<string, Collection<string, ApplicationCommand>>
) {
// Early return for no API calls
if (this.apiCalls.length === 0) {
// If we have no API calls to do then we simply return (can happen if the registry is used directly)
this.trace('No API calls to run, and no command to register');
return;
}
if (getDefaultBehaviorWhenNotIdentical() === RegisterBehavior.BulkOverwrite) {
throw new RangeError(
`"runAPICalls" was called for "${this.commandName}" but the defaultBehaviorWhenNotIdentical is "BulkOverwrite". This should not happen.`
);
}
this.debug(`Preparing to process ${this.apiCalls.length} possible command registrations / updates...`);
const results = await Promise.allSettled(
this.apiCalls.map((call) => this.handleAPICall(applicationCommands, globalCommands, guildCommands, call))
);
const errored = results.filter((result) => result.status === 'rejected') as PromiseRejectedResult[];
if (errored.length) {
this.error(`Received ${errored.length} errors while processing command registrations / updates`);
for (const error of errored) {
this.error(error.reason.stack ?? error.reason);
}
}
}
protected handleIdAddition(type: InternalRegistryAPIType, id: string, guildId?: string | null) {
switch (type) {
case InternalRegistryAPIType.ChatInput: {
this.addChatInputCommandIds(id);
if (guildId) {
this.guildIdToChatInputCommandIds.ensure(guildId, () => new Set()).add(id);
} else {
this.globalChatInputCommandIds.add(id);
}
break;
}
case InternalRegistryAPIType.ContextMenu: {
this.addContextMenuCommandIds(id);
if (guildId) {
this.guildIdToContextMenuCommandIds.ensure(guildId, () => new Set()).add(id);
} else {
this.globalContextMenuCommandIds.add(id);
}
break;
}
}
// Old field handling
if (guildId) {
// Old, wrongly typed field (thx kyra for spotting >_>)
if (!this.guildCommandIds.has(guildId)) {
this.guildCommandIds.set(guildId, id);
}
} else {
// First come, first serve (thx kyra for spotting >_>)
this.globalCommandId ??= id;
}
}
private getGuildIdsToRegister(options?: ApplicationCommandRegistryRegisterOptions) {
let guildIdsToRegister: ApplicationCommandRegistry.RegisterOptions['guildIds'] = undefined;
if (!isNullishOrEmpty(options?.guildIds)) {
guildIdsToRegister = options!.guildIds;
} else if (!isNullishOrEmpty(getDefaultGuildIds())) {
guildIdsToRegister = getDefaultGuildIds();
}
return guildIdsToRegister;
}
private processGuildIds(guildIdsToRegister: ApplicationCommandRegistry.RegisterOptions['guildIds']) {
if (!isNullishOrEmpty(guildIdsToRegister)) {
for (const id of guildIdsToRegister) {
this.guildIdsToFetch.add(id);
allGuildIdsToFetchCommandsFor.add(id);
}
}
}
private async handleAPICall(
commandsManager: ApplicationCommandManager,
globalCommands: Collection<string, ApplicationCommand>,
allGuildsCommands: Map<string, Collection<string, ApplicationCommand>>,
apiCall: InternalAPICall
) {
const { builtData, registerOptions } = apiCall;
const commandName = builtData.name;
const behaviorIfNotEqual = registerOptions.behaviorWhenNotIdentical ?? getDefaultBehaviorWhenNotIdentical();
const findCallback = (entry: ApplicationCommand) => {
// If the command is a chat input command, we need to check if the entry is a chat input command
if (apiCall.type === InternalRegistryAPIType.ChatInput && entry.type !== ApplicationCommandType.ChatInput) return false;
// If the command is a context menu command, we need to check if the entry is a context menu command of the same type
if (apiCall.type === InternalRegistryAPIType.ContextMenu) {
// If its a chat input command, it doesn't match
if (entry.type === ApplicationCommandType.ChatInput) return false;
// Check the command type (must match)
if (apiCall.builtData.type !== entry.type) return false;
}
// Find the command by name or by id hint (mostly useful for context menus)
const isInIdHint = registerOptions.idHints?.includes(entry.id);
return typeof isInIdHint === 'boolean' ? isInIdHint || entry.name === commandName : entry.name === commandName;
};
let type: string;
switch (apiCall.type) {
case InternalRegistryAPIType.ChatInput:
type = 'chat input';
break;
case InternalRegistryAPIType.ContextMenu:
switch (apiCall.builtData.type) {
case ApplicationCommandType.Message:
type = 'message context menu';
break;
case ApplicationCommandType.User:
type = 'user context menu';
break;
default:
type = 'unknown-type context menu';
}
break;
default:
type = 'unknown';
}
if (!registerOptions.guildIds?.length) {
const globalCommand = globalCommands.find(findCallback);
if (globalCommand) {
this.debug(`Checking if command "${commandName}" is identical with global ${type} command with id "${globalCommand.id}"`);
this.handleIdAddition(apiCall.type, globalCommand.id);
await this.handleCommandPresent(globalCommand, builtData, behaviorIfNotEqual, null);
} else if (registerOptions.registerCommandIfMissing ?? true) {
this.debug(`Creating new global ${type} command with name "${commandName}"`);
await this.createMissingCommand(commandsManager, builtData, type);
} else {
this.debug(`Doing nothing about missing global ${type} command with name "${commandName}"`);
}
return;
}
for (const guildId of registerOptions.guildIds) {
const guildCommands = allGuildsCommands.get(guildId);
if (!guildCommands) {
this.debug(`There are no commands for guild with id "${guildId}". Will create ${type} command "${commandName}".`);
await this.createMissingCommand(commandsManager, builtData, type, guildId);
continue;
}
const existingGuildCommand = guildCommands.find(findCallback);
if (existingGuildCommand) {
this.debug(`Checking if guild ${type} command "${commandName}" is identical to command "${existingGuildCommand.id}"`);
this.handleIdAddition(apiCall.type, existingGuildCommand.id, guildId);
await this.handleCommandPresent(existingGuildCommand, builtData, behaviorIfNotEqual, guildId);
} else if (registerOptions.registerCommandIfMissing ?? true) {
this.debug(`Creating new guild ${type} command with name "${commandName}" for guild "${guildId}"`);
await this.createMissingCommand(commandsManager, builtData, type, guildId);
} else {
this.debug(`Doing nothing about missing guild ${type} command with name "${commandName}" for guild "${guildId}"`);
}
}
}
private async handleCommandPresent(
applicationCommand: ApplicationCommand,
apiData: InternalAPICall['builtData'],
behaviorIfNotEqual: RegisterBehavior,
guildId: string | null
) {
if (behaviorIfNotEqual === RegisterBehavior.BulkOverwrite) {
this.debug(
`Command "${this.commandName}" has the behaviorIfNotEqual set to "BulkOverwrite" which is invalid. Using defaultBehaviorWhenNotIdentical instead`
);
behaviorIfNotEqual = getDefaultBehaviorWhenNotIdentical();
if (behaviorIfNotEqual === RegisterBehavior.BulkOverwrite) {
throw new Error(
`Invalid behaviorIfNotEqual value ("BulkOverwrite") for command "${this.commandName}", and defaultBehaviorWhenNotIdentical is also "BulkOverwrite". This should not happen.`
);
}
}
let differences: CommandDifference[] = [];
if (behaviorIfNotEqual === RegisterBehavior.VerboseOverwrite) {
const now = Date.now();
// Step 0: compute differences
differences = [...getCommandDifferences(convertApplicationCommandToApiData(applicationCommand), apiData, guildId !== null)];
const later = Date.now() - now;
this.debug(`Took ${later}ms to process differences via computing differences`);
// Step 1: if there are no differences, return
if (!differences.length) {
this.debug(
`${guildId ? 'Guild command' : 'Command'} "${apiData.name}" is identical to command "${applicationCommand.name}" (${
applicationCommand.id
})`
);
return;
}
}
// Run the fast path even if the user wants to just log if the command has a difference
if (behaviorIfNotEqual === RegisterBehavior.Overwrite || behaviorIfNotEqual === RegisterBehavior.LogToConsole) {
const now = Date.now();
// Step 0: compute differences
const areThereDifferences = getCommandDifferencesFast(convertApplicationCommandToApiData(applicationCommand), apiData, guildId !== null);
const later = Date.now() - now;
this.debug(`Took ${later}ms to process differences via fast compute differences`);
// Step 1: if there are no differences, return
if (!areThereDifferences) {
this.debug(
`${guildId ? 'Guild command' : 'Command'} "${apiData.name}" is identical to command "${applicationCommand.name}" (${
applicationCommand.id
})`
);
return;
}
}
this.logCommandDifferencesFound(applicationCommand, behaviorIfNotEqual === RegisterBehavior.LogToConsole, differences);
// Step 2: if the behavior is to log to console, only log the differences
if (behaviorIfNotEqual === RegisterBehavior.LogToConsole) {
return;
}
// Step 3: if the behavior is to update, update the command
try {
await applicationCommand.edit(apiData as ChatInputApplicationCommandData);
this.debug(`Updated command ${applicationCommand.name} (${applicationCommand.id}) with new api data`);
} catch (error) {
this.error(`Failed to update command ${applicationCommand.name} (${applicationCommand.id})`, error);
}
}
private logCommandDifferencesFound(applicationCommand: ApplicationCommand, logAsWarn: boolean, differences: CommandDifference[]) {
const finalMessage: string[] = [];
const pad = ' '.repeat(5);
for (const difference of differences) {
finalMessage.push(
[
`└── At path: ${difference.key}`, //
`${pad}├── Received: ${difference.original}`,
`${pad}└── Expected: ${difference.expected}`,
''
].join('\n')
);
}
const finalMessageNewLine = finalMessage.length ? '\n' : '';
const header = `Found differences for command "${applicationCommand.name}" (${applicationCommand.id}) versus provided api data.${finalMessageNewLine}`;
logAsWarn ? this.warn(header, ...finalMessage) : this.debug(header, ...finalMessage);
}
private async createMissingCommand(
commandsManager: ApplicationCommandManager,
apiData: InternalAPICall['builtData'],
type: string,
guildId?: string
) {
try {
const result = await commandsManager.create(apiData, guildId);
this.info(
`Successfully created ${type}${guildId ? ' guild' : ''} command "${apiData.name}" with id "${
result.id
}". You should add the id to the "idHints" property of the register method you used!`
);
switch (apiData.type) {
case undefined:
case ApplicationCommandType.ChatInput: {
this.handleIdAddition(InternalRegistryAPIType.ChatInput, result.id, guildId);
break;
}
case ApplicationCommandType.Message:
case ApplicationCommandType.User: {
this.handleIdAddition(InternalRegistryAPIType.ContextMenu, result.id, guildId);
break;
}
}
} catch (err) {
this.error(
`Failed to register${guildId ? ' guild' : ''} application command with name "${apiData.name}"${
guildId ? ` for guild "${guildId}"` : ''
}`,
err
);
}
}
private info(message: string, ...other: unknown[]) {
container.logger.info(`ApplicationCommandRegistry[${this.commandName}] ${message}`, ...other);
}
private error(message: string, ...other: unknown[]) {
container.logger.error(`ApplicationCommandRegistry[${this.commandName}] ${message}`, ...other);
}
private warn(message: string, ...other: unknown[]) {
container.logger.warn(`ApplicationCommandRegistry[${this.commandName}] ${message}`, ...other);
}
private debug(message: string, ...other: unknown[]) {
container.logger.debug(`ApplicationCommandRegistry[${this.commandName}] ${message}`, ...other);
}
private trace(message: string, ...other: unknown[]) {
container.logger.trace(`ApplicationCommandRegistry[${this.commandName}] ${message}`, ...other);
}
}
export namespace ApplicationCommandRegistry {
export interface RegisterOptions {
/**
* If this is specified, the application commands will only be registered for these guild ids.
*/
guildIds?: string[];
/**
* If we should register the command when it is missing
* @default true
*/
registerCommandIfMissing?: boolean;
/**
* Specifies what we should do when the command is present, but not identical with the data you provided
* @default `ApplicationCommandRegistries.getDefaultBehaviorWhenNotIdentical()`
*/
behaviorWhenNotIdentical?: Exclude<RegisterBehavior, RegisterBehavior.BulkOverwrite>;
/**
* Specifies a list of command ids that we should check in the event of a name mismatch
* @default []
*/
idHints?: string[];
}
}
export type ApplicationCommandRegistryRegisterOptions = ApplicationCommandRegistry.RegisterOptions;
type InternalRegisterOptions = Omit<ApplicationCommandRegistry.RegisterOptions, 'behaviorWhenNotIdentical'> & {
behaviorWhenNotIdentical?: RegisterBehavior;
};
export type InternalAPICall =
| {
builtData: RESTPostAPIChatInputApplicationCommandsJSONBody;
registerOptions: InternalRegisterOptions;
type: InternalRegistryAPIType.ChatInput;
}
| {
builtData: RESTPostAPIContextMenuApplicationCommandsJSONBody;
registerOptions: InternalRegisterOptions;
type: InternalRegistryAPIType.ContextMenu;
};