meocord 2.1.1 → 3.1.0
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.
- package/AUTHOR.md +2 -3
- package/README.md +289 -41
- package/dist/cjs/_shared/controller.decorator-MUHA_A3z.cjs +529 -0
- package/dist/cjs/core/index.cjs +288 -85
- package/dist/cjs/decorator/index.cjs +5 -1
- package/dist/cjs/enum/index.cjs +17 -4
- package/dist/cjs/testing/index.cjs +88 -4
- package/dist/esm/bin/builder-template/builder/primary-entry-point.builder.template +26 -0
- package/dist/esm/bin/builder-template/controller/autocomplete.controller.template +16 -0
- package/dist/esm/bin/builder-template/controller/channel-select-menu.controller.template +12 -0
- package/dist/esm/bin/builder-template/controller/context-menu.controller.template +2 -2
- package/dist/esm/bin/builder-template/controller/mentionable-select-menu.controller.template +12 -0
- package/dist/esm/bin/builder-template/controller/modal-submit.controller.template +1 -1
- package/dist/esm/bin/builder-template/controller/primary-entry-point.controller.template +12 -0
- package/dist/esm/bin/builder-template/controller/role-select-menu.controller.template +12 -0
- package/dist/esm/bin/builder-template/controller/slash.controller.template +1 -1
- package/dist/esm/bin/builder-template/controller/user-select-menu.controller.template +12 -0
- package/dist/esm/bin/generator.js +4 -9
- package/dist/esm/bin/helper/controller-generator.helper.js +24 -7
- package/dist/esm/core/meocord.app.js +289 -85
- package/dist/esm/decorator/controller.decorator.js +157 -24
- package/dist/esm/decorator/index.js +1 -1
- package/dist/esm/enum/controller.enum.js +23 -4
- package/dist/esm/testing/mock-interaction.js +89 -5
- package/dist/esm/util/interaction.util.js +174 -0
- package/dist/types/controller.enum-DYfhYaat.d.ts +36 -0
- package/dist/types/core/index.d.ts +94 -0
- package/dist/types/decorator/index.d.ts +74 -41
- package/dist/types/enum/index.d.ts +1 -1
- package/dist/types/interface/index.d.ts +87 -3
- package/dist/types/testing/index.d.ts +3 -21
- package/package.json +2 -2
- package/dist/cjs/_shared/controller.decorator-DX5lFlPZ.cjs +0 -216
- package/dist/types/controller.enum-QA-IuReF.d.ts +0 -18
|
@@ -1,13 +1,66 @@
|
|
|
1
1
|
import { SlashCommandBuilder, MessageFlagsBitField } from 'discord.js';
|
|
2
2
|
import { Logger } from '../common/logger.js';
|
|
3
3
|
import '../common/theme.js';
|
|
4
|
-
import { getCommandMap, getMessageHandlers, getReactionHandlers } from '../decorator/controller.decorator.js';
|
|
4
|
+
import { getCommandMap, findAmbiguousRoutes, PARAM_SEPARATOR, getAutocompleteHandlers, getMessageHandlers, getReactionHandlers } from '../decorator/controller.decorator.js';
|
|
5
5
|
import { sample } from 'lodash-es';
|
|
6
6
|
import { createErrorEmbed } from '../util/embed.util.js';
|
|
7
|
+
import { describeInteraction, hasCustomId, matchesCommandType, resolveCommandPaths, focusedOptionName, resolveOptionParams } from '../util/interaction.util.js';
|
|
7
8
|
import { ReactionHandlerAction, CommandType } from '../enum/controller.enum.js';
|
|
8
9
|
import CliTable3 from 'cli-table3';
|
|
9
10
|
|
|
11
|
+
/**
|
|
12
|
+
* The name a builder registers under, which is what Discord deduplicates on.
|
|
13
|
+
*
|
|
14
|
+
* Read from the built payload rather than from the `@Command` argument: a builder is
|
|
15
|
+
* free to name the command something other than the string it was handed, and it is
|
|
16
|
+
* the payload Discord sees.
|
|
17
|
+
*/ function commandNameOf(builder) {
|
|
18
|
+
try {
|
|
19
|
+
const json = typeof builder.toJSON === 'function' ? builder.toJSON() : builder;
|
|
20
|
+
return typeof json?.name === 'string' ? json.name : undefined;
|
|
21
|
+
} catch {
|
|
22
|
+
// A builder missing a required field throws from toJSON. Surfacing that is the
|
|
23
|
+
// registration call's job, where it is reported against the command Discord
|
|
24
|
+
// rejected -- deduplication should not be what turns it into a startup crash.
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
10
28
|
class MeoCordApp {
|
|
29
|
+
/**
|
|
30
|
+
* Runs an event handler so a failure inside it cannot take the process down.
|
|
31
|
+
*
|
|
32
|
+
* discord.js calls listeners without awaiting them, so a rejection escaping one has
|
|
33
|
+
* nothing left to settle it: Node reports an unhandled rejection, which terminates
|
|
34
|
+
* the process by default. Losing the whole bot because one reaction landed on a
|
|
35
|
+
* deleted message, or one controller could not be resolved, is a worse failure than
|
|
36
|
+
* the one that caused it -- every other user is served by the same process.
|
|
37
|
+
*
|
|
38
|
+
* Nothing is silenced. The error is logged against the event that produced it, so a
|
|
39
|
+
* genuine misconfiguration -- an unbound controller, a missing dependency -- shows
|
|
40
|
+
* up on the very first interaction rather than staying hidden.
|
|
41
|
+
*
|
|
42
|
+
* @param event - The gateway event being handled, named in the log.
|
|
43
|
+
* @param run - The handler to run.
|
|
44
|
+
*/ async runListener(event, run) {
|
|
45
|
+
try {
|
|
46
|
+
await run();
|
|
47
|
+
} catch (error) {
|
|
48
|
+
this.logger.error(`Unhandled error while handling "${event}":`, error);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Rotates the bot's activity.
|
|
53
|
+
*
|
|
54
|
+
* Guarded separately from {@link runListener}: this runs on a timer rather than an
|
|
55
|
+
* event, and a throw from a timer callback is an uncaught exception no listener
|
|
56
|
+
* wrapper can reach.
|
|
57
|
+
*/ updateActivity() {
|
|
58
|
+
try {
|
|
59
|
+
this.bot.user?.setActivity(sample(this.activities));
|
|
60
|
+
} catch (error) {
|
|
61
|
+
this.logger.error('Could not update the bot activity:', error);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
11
64
|
getInstance(controllerClass) {
|
|
12
65
|
if (!this.controllerInstancesCache.has(controllerClass)) {
|
|
13
66
|
this.controllerInstancesCache.set(controllerClass, this.container.get(controllerClass));
|
|
@@ -17,30 +70,20 @@ class MeoCordApp {
|
|
|
17
70
|
async start() {
|
|
18
71
|
try {
|
|
19
72
|
this.logger.log('Starting bot...');
|
|
20
|
-
this.bot.on('clientReady', async ()=>{
|
|
21
|
-
|
|
22
|
-
this.
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
this.bot.on('
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
user,
|
|
35
|
-
action: ReactionHandlerAction.ADD
|
|
36
|
-
});
|
|
37
|
-
});
|
|
38
|
-
this.bot.on('messageReactionRemove', async (reaction, user)=>{
|
|
39
|
-
await this.handleReaction(reaction, {
|
|
40
|
-
user,
|
|
41
|
-
action: ReactionHandlerAction.REMOVE
|
|
42
|
-
});
|
|
43
|
-
});
|
|
73
|
+
this.bot.on('clientReady', ()=>this.runListener('clientReady', async ()=>{
|
|
74
|
+
this.activityInterval = setInterval(()=>this.updateActivity(), 10000);
|
|
75
|
+
await this.registerCommands();
|
|
76
|
+
}));
|
|
77
|
+
this.bot.on('interactionCreate', (interaction)=>this.runListener('interactionCreate', ()=>this.handleInteraction(interaction)));
|
|
78
|
+
this.bot.on('messageCreate', (message)=>this.runListener('messageCreate', ()=>this.handleMessage(message)));
|
|
79
|
+
this.bot.on('messageReactionAdd', (reaction, user)=>this.runListener('messageReactionAdd', ()=>this.handleReaction(reaction, {
|
|
80
|
+
user,
|
|
81
|
+
action: ReactionHandlerAction.ADD
|
|
82
|
+
})));
|
|
83
|
+
this.bot.on('messageReactionRemove', (reaction, user)=>this.runListener('messageReactionRemove', ()=>this.handleReaction(reaction, {
|
|
84
|
+
user,
|
|
85
|
+
action: ReactionHandlerAction.REMOVE
|
|
86
|
+
})));
|
|
44
87
|
await this.bot.login(this.discordToken);
|
|
45
88
|
this.logger.log('Bot is online!');
|
|
46
89
|
} catch (error) {
|
|
@@ -48,7 +91,11 @@ class MeoCordApp {
|
|
|
48
91
|
}
|
|
49
92
|
}
|
|
50
93
|
async registerCommands() {
|
|
51
|
-
|
|
94
|
+
// Keyed by registered name: a command whose subcommands live in separate methods
|
|
95
|
+
// declares the same name more than once, and sending its builder twice makes
|
|
96
|
+
// Discord reject the whole payload. The first builder wins, and a second one that
|
|
97
|
+
// is not the same object is reported rather than silently dropped.
|
|
98
|
+
const buildersByName = new Map();
|
|
52
99
|
for (const controllerClass of this.controllerClasses){
|
|
53
100
|
const instance = this.getInstance(controllerClass);
|
|
54
101
|
const commandMap = getCommandMap(instance);
|
|
@@ -56,12 +103,20 @@ class MeoCordApp {
|
|
|
56
103
|
const commandMetadataArray = commandMap[commandName];
|
|
57
104
|
if (!Array.isArray(commandMetadataArray)) continue;
|
|
58
105
|
for (const { builder, type } of commandMetadataArray){
|
|
59
|
-
if (type in CommandType
|
|
60
|
-
|
|
106
|
+
if (!(type in CommandType) || !builder) continue;
|
|
107
|
+
const registeredName = commandNameOf(builder) ?? commandName;
|
|
108
|
+
const existing = buildersByName.get(registeredName);
|
|
109
|
+
if (existing === undefined) {
|
|
110
|
+
buildersByName.set(registeredName, builder);
|
|
111
|
+
} else if (existing !== builder) {
|
|
112
|
+
this.logger.warn(`Command "${registeredName}" is built more than once; only the first builder is registered. ` + `Declare the builder on one @Command and give the others the plain CommandType.`);
|
|
61
113
|
}
|
|
62
114
|
}
|
|
63
115
|
}
|
|
64
116
|
}
|
|
117
|
+
const builders = [
|
|
118
|
+
...buildersByName.values()
|
|
119
|
+
];
|
|
65
120
|
try {
|
|
66
121
|
if (this.bot.application) {
|
|
67
122
|
await this.bot.application.commands.set(builders);
|
|
@@ -80,7 +135,7 @@ class MeoCordApp {
|
|
|
80
135
|
});
|
|
81
136
|
for (const builder of builders){
|
|
82
137
|
const json = typeof builder.toJSON === 'function' ? builder.toJSON() : builder;
|
|
83
|
-
const typeName = json?.type === 1 ? 'SlashCommand' : json?.type === 2 ? 'UserContextMenu' : json?.type === 3 ? 'MessageContextMenu' : builder instanceof SlashCommandBuilder ? 'SlashCommand' : 'Command';
|
|
138
|
+
const typeName = json?.type === 1 ? 'SlashCommand' : json?.type === 2 ? 'UserContextMenu' : json?.type === 3 ? 'MessageContextMenu' : json?.type === 4 ? 'PrimaryEntryPoint' : builder instanceof SlashCommandBuilder ? 'SlashCommand' : 'Command';
|
|
84
139
|
const name = json?.name || builder.name;
|
|
85
140
|
const subCommands = Array.isArray(json?.options) && json.options.length ? json.options.map((opt)=>opt.name).join(', ') : '';
|
|
86
141
|
table.push([
|
|
@@ -95,78 +150,219 @@ class MeoCordApp {
|
|
|
95
150
|
this.logger.error('Error during command registration:', error);
|
|
96
151
|
}
|
|
97
152
|
}
|
|
98
|
-
|
|
153
|
+
getComponentRoutes() {
|
|
154
|
+
if (this.componentRoutes) return this.componentRoutes;
|
|
155
|
+
const routes = [];
|
|
99
156
|
for (const controllerClass of this.controllerClasses){
|
|
100
|
-
const
|
|
101
|
-
const commandMap = getCommandMap(controllerInstance);
|
|
157
|
+
const commandMap = getCommandMap(this.getInstance(controllerClass));
|
|
102
158
|
if (!commandMap) continue;
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
const foundEntry = Object.entries(commandMap).find(([commandName, metaArray])=>{
|
|
111
|
-
if (!Array.isArray(metaArray)) return false;
|
|
112
|
-
return metaArray.some((meta)=>{
|
|
113
|
-
if (!meta.regex || !commandIdentifier) return false;
|
|
114
|
-
const match = meta.regex.exec(commandIdentifier);
|
|
115
|
-
if (match?.groups) {
|
|
116
|
-
interaction.dynamicParams = match.groups;
|
|
117
|
-
return true;
|
|
118
|
-
}
|
|
119
|
-
return commandIdentifier === commandName;
|
|
159
|
+
for (const [pattern, metaArray] of Object.entries(commandMap)){
|
|
160
|
+
if (!Array.isArray(metaArray)) continue;
|
|
161
|
+
for (const meta of metaArray){
|
|
162
|
+
if (meta.regex) routes.push({
|
|
163
|
+
controllerClass,
|
|
164
|
+
meta,
|
|
165
|
+
pattern
|
|
120
166
|
});
|
|
121
|
-
});
|
|
122
|
-
if (foundEntry) {
|
|
123
|
-
commandMetadataArray = foundEntry[1];
|
|
124
167
|
}
|
|
125
168
|
}
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
169
|
+
}
|
|
170
|
+
routes.sort((a, b)=>(b.meta.specificity ?? 0) - (a.meta.specificity ?? 0));
|
|
171
|
+
this.reportAmbiguousRoutes(routes);
|
|
172
|
+
this.componentRoutes = routes;
|
|
173
|
+
return routes;
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Warns rather than throws: an app whose patterns overlap boots and works today, and
|
|
177
|
+
* refusing to start would turn a latent mis-route into an outage on upgrade.
|
|
178
|
+
*/ reportAmbiguousRoutes(routes) {
|
|
179
|
+
// Grouped by command type first: dispatch only considers routes whose component
|
|
180
|
+
// type matches the interaction, so a button and a select menu sharing a pattern
|
|
181
|
+
// are never in competition and reporting them would be a false alarm.
|
|
182
|
+
const byType = new Map();
|
|
183
|
+
for (const { meta, pattern } of routes){
|
|
184
|
+
const patterns = byType.get(meta.type) ?? [];
|
|
185
|
+
patterns.push(pattern);
|
|
186
|
+
byType.set(meta.type, patterns);
|
|
187
|
+
}
|
|
188
|
+
const collisions = [
|
|
189
|
+
...byType.values()
|
|
190
|
+
].flatMap((patterns)=>findAmbiguousRoutes(patterns));
|
|
191
|
+
if (collisions.length === 0) return;
|
|
192
|
+
this.logger.warn(`${collisions.length} pattern pair(s) can match the same customId, so which one runs is decided by ` + `ranking rather than by the ids themselves:\n` + collisions.map(([left, right])=>` "${left}" vs "${right}"`).join('\n') + `\nA parameter stops at "${PARAM_SEPARATOR}", so separating these segments with it makes them distinct.`);
|
|
193
|
+
}
|
|
194
|
+
getAutocompleteRoutes() {
|
|
195
|
+
if (this.autocompleteRoutes) return this.autocompleteRoutes;
|
|
196
|
+
const routes = [];
|
|
197
|
+
for (const controllerClass of this.controllerClasses){
|
|
198
|
+
for (const meta of getAutocompleteHandlers(this.getInstance(controllerClass))){
|
|
199
|
+
routes.push({
|
|
200
|
+
controllerClass,
|
|
201
|
+
meta
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
routes.sort((a, b)=>Number(Boolean(b.meta.optionName)) - Number(Boolean(a.meta.optionName)));
|
|
206
|
+
this.autocompleteRoutes = routes;
|
|
207
|
+
return routes;
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Dispatches an interaction, and makes sure a failure anywhere in that still reaches
|
|
211
|
+
* the person who triggered it.
|
|
212
|
+
*
|
|
213
|
+
* {@link executeCommand} already reports what a handler throws, but everything
|
|
214
|
+
* *before* the handler can fail too — resolving a controller through the container
|
|
215
|
+
* is the common case — and a component that fails there would otherwise look dead
|
|
216
|
+
* with nothing said to the user and nothing in the log.
|
|
217
|
+
*/ async handleInteraction(interaction) {
|
|
218
|
+
try {
|
|
219
|
+
await this.dispatchInteraction(interaction);
|
|
220
|
+
} catch (error) {
|
|
221
|
+
this.logger.error(`Error dispatching ${describeInteraction(interaction)}:`, error);
|
|
222
|
+
// Autocomplete has no reply to fall back on; closing its window is the only
|
|
223
|
+
// thing that stops the client showing a loading state until it times out.
|
|
224
|
+
if (interaction.isAutocomplete()) {
|
|
225
|
+
await this.respondEmpty(interaction);
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
await this.replyWithError(interaction, 'An error occurred while executing the command.');
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
async dispatchInteraction(interaction) {
|
|
232
|
+
// Autocomplete first, and on its own path: it is answered with `respond()` rather
|
|
233
|
+
// than a reply, it has no customId to route on, and the "Command not found!" reply
|
|
234
|
+
// the other paths end in cannot be sent to it at all.
|
|
235
|
+
if (interaction.isAutocomplete()) {
|
|
236
|
+
await this.handleAutocomplete(interaction);
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
// Component interactions route on a pattern, so they go through the ranked table.
|
|
240
|
+
// Commands match their registered name exactly and cannot overlap.
|
|
241
|
+
if (hasCustomId(interaction)) {
|
|
242
|
+
const customId = interaction.customId;
|
|
243
|
+
for (const { controllerClass, meta } of this.getComponentRoutes()){
|
|
244
|
+
// A button and a select menu may legitimately share a customId shape, so the
|
|
245
|
+
// pattern alone does not identify the handler -- the component type does.
|
|
246
|
+
if (!matchesCommandType(meta.type, interaction)) continue;
|
|
247
|
+
const match = meta.regex.exec(customId);
|
|
248
|
+
if (!match) continue;
|
|
249
|
+
interaction.dynamicParams = match.groups ?? {};
|
|
250
|
+
await this.executeCommand(this.getInstance(controllerClass), meta, interaction, customId);
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
// Paths are walked outside the controller loop so the full subcommand path always
|
|
255
|
+
// beats the bare command name, whatever order the controllers were registered in.
|
|
256
|
+
for (const path of this.resolveNameRoutes(interaction)){
|
|
257
|
+
for (const controllerClass of this.controllerClasses){
|
|
258
|
+
const controllerInstance = this.getInstance(controllerClass);
|
|
259
|
+
const commandMap = getCommandMap(controllerInstance);
|
|
260
|
+
const commandMetadata = commandMap?.[path]?.find((meta)=>matchesCommandType(meta.type, interaction));
|
|
261
|
+
if (!commandMetadata) continue;
|
|
262
|
+
await this.executeCommand(controllerInstance, commandMetadata, interaction, path);
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
// Log what actually failed to match. The user's "Command not found!" says nothing
|
|
267
|
+
// about which id was unroutable, so a control that is emitted but never routed --
|
|
268
|
+
// a customId whose value broke its pattern, or a handler nobody wrote -- stays
|
|
269
|
+
// invisible until somebody reports the dead button.
|
|
270
|
+
this.logger.warn(`No handler matched ${describeInteraction(interaction)}. Check that a @Command pattern is ` + `declared for it and that its controller is registered.`);
|
|
271
|
+
await this.replyWithError(interaction, 'Command not found!');
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* The names a command interaction can be handled under, most specific first.
|
|
275
|
+
*
|
|
276
|
+
* Empty for anything that is not a registered command, which is how a component
|
|
277
|
+
* whose customId matched no pattern falls through to the unmatched warning instead
|
|
278
|
+
* of being looked up under a name it does not have.
|
|
279
|
+
*/ resolveNameRoutes(interaction) {
|
|
280
|
+
if (interaction.isChatInputCommand()) return resolveCommandPaths(interaction);
|
|
281
|
+
if (interaction.isContextMenuCommand() || interaction.isPrimaryEntryPointCommand()) {
|
|
282
|
+
return [
|
|
283
|
+
interaction.commandName
|
|
284
|
+
];
|
|
285
|
+
}
|
|
286
|
+
return [];
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Answers an autocomplete interaction from the `@Autocomplete` handler that claims it.
|
|
290
|
+
*
|
|
291
|
+
* Discord closes the window after three seconds and shows a loading state until
|
|
292
|
+
* something arrives, so an unclaimed option is answered with an empty list rather
|
|
293
|
+
* than left to time out -- a visibly empty menu is a better failure than a stuck one,
|
|
294
|
+
* and the warning says which option is missing a handler.
|
|
295
|
+
*/ async handleAutocomplete(interaction) {
|
|
296
|
+
const focusedName = focusedOptionName(interaction);
|
|
297
|
+
for (const path of resolveCommandPaths(interaction)){
|
|
298
|
+
for (const { controllerClass, meta } of this.getAutocompleteRoutes()){
|
|
299
|
+
if (meta.commandPath !== path) continue;
|
|
300
|
+
if (meta.optionName !== undefined && meta.optionName !== focusedName) continue;
|
|
129
301
|
try {
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
if (interaction.isChatInputCommand() && interaction.options) {
|
|
134
|
-
dynamicParams = interaction.options.data.reduce((acc, opt)=>{
|
|
135
|
-
acc[opt.name] = opt.value;
|
|
136
|
-
return acc;
|
|
137
|
-
}, {});
|
|
138
|
-
} else if (interaction.isButton() || interaction.isStringSelectMenu() || interaction.isModalSubmit()) {
|
|
139
|
-
dynamicParams = interaction.dynamicParams || {};
|
|
140
|
-
}
|
|
141
|
-
await controllerInstance[methodName](interaction, dynamicParams);
|
|
142
|
-
return;
|
|
143
|
-
} else {
|
|
144
|
-
this.logger.debug(type, methodName, CommandType.BUTTON, interaction.isButton());
|
|
145
|
-
this.logger.warn(`Interaction type mismatch for command "${commandIdentifier}". Interaction type: ${interaction.type}.`);
|
|
146
|
-
}
|
|
302
|
+
const controllerInstance = this.getInstance(controllerClass);
|
|
303
|
+
this.logger.log('[AUTOCOMPLETE]', `[${path}]`, `[${meta.methodName}]`);
|
|
304
|
+
await controllerInstance[meta.methodName](interaction, resolveOptionParams(interaction));
|
|
147
305
|
} catch (error) {
|
|
148
|
-
this.logger.error(`Error
|
|
149
|
-
|
|
150
|
-
const embed = createErrorEmbed('An error occurred while executing the command.');
|
|
151
|
-
await interaction.reply({
|
|
152
|
-
embeds: [
|
|
153
|
-
embed
|
|
154
|
-
],
|
|
155
|
-
flags: MessageFlagsBitField.Flags.Ephemeral
|
|
156
|
-
});
|
|
157
|
-
}
|
|
306
|
+
this.logger.error(`Error handling ${describeInteraction(interaction)}:`, error);
|
|
307
|
+
await this.respondEmpty(interaction);
|
|
158
308
|
}
|
|
159
309
|
return;
|
|
160
310
|
}
|
|
161
311
|
}
|
|
162
|
-
|
|
163
|
-
|
|
312
|
+
this.logger.warn(`No handler matched ${describeInteraction(interaction)}. Declare an @Autocomplete handler for it, ` + `or drop setAutocomplete(true) from the option.`);
|
|
313
|
+
await this.respondEmpty(interaction);
|
|
314
|
+
}
|
|
315
|
+
/** Closes an autocomplete window that nothing else answered. */ async respondEmpty(interaction) {
|
|
316
|
+
if (interaction.responded) return;
|
|
317
|
+
try {
|
|
318
|
+
await interaction.respond([]);
|
|
319
|
+
} catch (error) {
|
|
320
|
+
// The three-second window may already have closed, which is not actionable.
|
|
321
|
+
this.logger.debug(`Could not close autocomplete window: ${String(error)}`);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Runs a resolved command, shared by both dispatch paths so a pattern-matched
|
|
326
|
+
* component and a named slash command behave identically once the route is chosen.
|
|
327
|
+
*/ async executeCommand(controllerInstance, commandMetadata, interaction, commandIdentifier) {
|
|
328
|
+
const { methodName, type } = commandMetadata;
|
|
329
|
+
// No interaction-type check here: both callers pick the route with
|
|
330
|
+
// `matchesCommandType` before getting this far, and `@Command` re-checks the
|
|
331
|
+
// interaction on the way into the handler.
|
|
332
|
+
try {
|
|
333
|
+
this.logger.log('[INTERACTION]', `[${type}]`, `[${methodName}]`);
|
|
334
|
+
let dynamicParams = {};
|
|
335
|
+
if (interaction.isChatInputCommand()) {
|
|
336
|
+
dynamicParams = resolveOptionParams(interaction);
|
|
337
|
+
} else if (hasCustomId(interaction)) {
|
|
338
|
+
dynamicParams = interaction.dynamicParams ?? {};
|
|
339
|
+
}
|
|
340
|
+
await controllerInstance[methodName](interaction, dynamicParams);
|
|
341
|
+
} catch (error) {
|
|
342
|
+
this.logger.error(`Error executing command "${commandIdentifier}":`, error);
|
|
343
|
+
await this.replyWithError(interaction, 'An error occurred while executing the command.');
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Tells the user something went wrong, if the interaction can still hear it.
|
|
348
|
+
*
|
|
349
|
+
* A handler that replies and *then* throws is the common shape of a failure, and
|
|
350
|
+
* replying twice throws in turn -- out of the catch block, where nothing is left to
|
|
351
|
+
* handle it. Whatever the interaction's state, reporting an error must not be able
|
|
352
|
+
* to become a second, worse one.
|
|
353
|
+
*/ async replyWithError(interaction, message) {
|
|
354
|
+
if (!interaction.isRepliable() || interaction.replied || interaction.deferred) return;
|
|
355
|
+
try {
|
|
356
|
+
const embed = createErrorEmbed(message);
|
|
164
357
|
await interaction.reply({
|
|
165
358
|
embeds: [
|
|
166
359
|
embed
|
|
167
360
|
],
|
|
168
361
|
flags: MessageFlagsBitField.Flags.Ephemeral
|
|
169
362
|
});
|
|
363
|
+
} catch (error) {
|
|
364
|
+
// Unknown or already-acknowledged interaction; the user cannot be told anything.
|
|
365
|
+
this.logger.debug(`Could not deliver the error reply: ${String(error)}`);
|
|
170
366
|
}
|
|
171
367
|
}
|
|
172
368
|
async handleMessage(message) {
|
|
@@ -198,7 +394,15 @@ class MeoCordApp {
|
|
|
198
394
|
}
|
|
199
395
|
}
|
|
200
396
|
async handleReaction(reaction, { user, action }) {
|
|
201
|
-
|
|
397
|
+
// A reaction arrives for messages the bot may no longer be able to read -- deleted,
|
|
398
|
+
// or in a channel it lost access to -- and `fetch` rejects for all of them. That is
|
|
399
|
+
// an ordinary outcome rather than a fault, so the reaction is skipped quietly.
|
|
400
|
+
try {
|
|
401
|
+
await reaction.message.fetch();
|
|
402
|
+
} catch (error) {
|
|
403
|
+
this.logger.debug(`Skipping a reaction whose message could not be fetched: ${String(error)}`);
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
202
406
|
const relevantControllers = this.controllerClasses.filter((controllerClass)=>{
|
|
203
407
|
const instance = this.getInstance(controllerClass);
|
|
204
408
|
const reactionHandlers = getReactionHandlers(instance);
|