nuxt-discord 0.0.17 → 0.2.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/README.md +249 -171
- package/dist/module.d.mts +146 -10
- package/dist/module.json +3 -3
- package/dist/module.mjs +1077 -348
- package/dist/runtime/acknowledgement.d.ts +11 -0
- package/dist/runtime/acknowledgement.js +156 -0
- package/dist/runtime/client/chat-theme.css +52 -0
- package/dist/runtime/client/components/ChatAvatar.d.vue.ts +6 -0
- package/dist/runtime/client/components/ChatAvatar.vue +11 -0
- package/dist/runtime/client/components/ChatAvatar.vue.d.ts +6 -0
- package/dist/runtime/client/components/CommandPicker.d.vue.ts +24 -0
- package/dist/runtime/client/components/CommandPicker.vue +67 -0
- package/dist/runtime/client/components/CommandPicker.vue.d.ts +24 -0
- package/dist/runtime/client/components/CommandReference.d.vue.ts +20 -0
- package/dist/runtime/client/components/CommandReference.vue +21 -0
- package/dist/runtime/client/components/CommandReference.vue.d.ts +20 -0
- package/dist/runtime/client/components/CommandTestBar.d.vue.ts +60 -0
- package/dist/runtime/client/components/CommandTestBar.vue +332 -0
- package/dist/runtime/client/components/CommandTestBar.vue.d.ts +60 -0
- package/dist/runtime/client/components/CommandTranscript.d.vue.ts +39 -0
- package/dist/runtime/client/components/CommandTranscript.vue +147 -0
- package/dist/runtime/client/components/CommandTranscript.vue.d.ts +39 -0
- package/dist/runtime/client/components/ProjectLogo.d.vue.ts +3 -0
- package/dist/runtime/client/components/ProjectLogo.vue +31 -0
- package/dist/runtime/client/components/ProjectLogo.vue.d.ts +3 -0
- package/dist/runtime/client/components/ReferenceContent.d.ts +26 -0
- package/dist/runtime/client/components/ReferenceContent.js +73 -0
- package/dist/runtime/client/components/TheHeader.d.vue.ts +3 -0
- package/dist/runtime/client/components/TheHeader.vue +53 -16
- package/dist/runtime/client/components/TheHeader.vue.d.ts +2 -2
- package/dist/runtime/client/components/appearance-select.d.ts +17 -0
- package/dist/runtime/client/components/appearance-select.js +15 -0
- package/dist/runtime/client/pages/activity.d.vue.ts +3 -0
- package/dist/runtime/client/pages/activity.vue +202 -0
- package/dist/runtime/client/pages/activity.vue.d.ts +3 -0
- package/dist/runtime/client/pages/context-menus.d.vue.ts +3 -0
- package/dist/runtime/client/pages/context-menus.vue +120 -0
- package/dist/runtime/client/pages/context-menus.vue.d.ts +3 -0
- package/dist/runtime/client/pages/listeners.d.vue.ts +3 -0
- package/dist/runtime/client/pages/listeners.vue +68 -0
- package/dist/runtime/client/pages/listeners.vue.d.ts +3 -0
- package/dist/runtime/client/pages/overview.d.vue.ts +3 -0
- package/dist/runtime/client/pages/overview.vue +280 -0
- package/dist/runtime/client/pages/overview.vue.d.ts +3 -0
- package/dist/runtime/client/pages/slash-commands.d.vue.ts +3 -0
- package/dist/runtime/client/pages/slash-commands.vue +185 -359
- package/dist/runtime/client/pages/slash-commands.vue.d.ts +2 -3
- package/dist/runtime/client/reference.css +46 -0
- package/dist/runtime/client/style.css +4 -1
- package/dist/runtime/client/useActivityLog.d.ts +7 -0
- package/dist/runtime/client/useActivityLog.js +76 -0
- package/dist/runtime/client/useCommandRegistry.d.ts +7 -0
- package/dist/runtime/client/useCommandRegistry.js +34 -0
- package/dist/runtime/client/useDashboardCatalog.d.ts +5 -0
- package/dist/runtime/client/useDashboardCatalog.js +9 -0
- package/dist/runtime/client/useDiscordCommandReference.d.ts +2 -0
- package/dist/runtime/client/useDiscordCommandReference.js +6 -0
- package/dist/runtime/dashboard/auth.d.ts +4 -0
- package/dist/runtime/dashboard/auth.js +55 -0
- package/dist/runtime/dashboard/oauth.d.ts +17 -0
- package/dist/runtime/dashboard/oauth.js +172 -0
- package/dist/runtime/dashboard/origin.d.ts +3 -0
- package/dist/runtime/dashboard/origin.js +15 -0
- package/dist/runtime/dashboard/permissions.d.ts +4 -0
- package/dist/runtime/dashboard/permissions.js +84 -0
- package/dist/runtime/dashboard/signin.d.ts +3 -0
- package/dist/runtime/dashboard/signin.js +42 -0
- package/dist/runtime/diagnostics.d.ts +4 -0
- package/dist/runtime/diagnostics.js +24 -0
- package/dist/runtime/discordInvocation.d.ts +14 -0
- package/dist/runtime/discordInvocation.js +28 -0
- package/dist/runtime/middleware.d.ts +1 -0
- package/dist/runtime/middleware.js +12 -0
- package/dist/runtime/reference/access.d.ts +6 -0
- package/dist/runtime/reference/access.js +143 -0
- package/dist/runtime/reference/catalog.d.ts +2 -0
- package/dist/runtime/reference/catalog.js +9 -0
- package/dist/runtime/reference/document.d.ts +2 -0
- package/dist/runtime/reference/document.js +22 -0
- package/dist/runtime/reference/hosted.d.ts +2 -0
- package/dist/runtime/reference/hosted.js +16 -0
- package/dist/runtime/reference/oauth.d.ts +2 -0
- package/dist/runtime/reference/oauth.js +4 -0
- package/dist/runtime/registration.d.ts +65 -0
- package/dist/runtime/registration.js +354 -0
- package/dist/runtime/server/api/discord/activity.get.d.ts +2 -0
- package/dist/runtime/server/api/discord/activity.get.js +6 -0
- package/dist/runtime/server/api/discord/catalog.get.d.ts +2 -0
- package/dist/runtime/server/api/discord/catalog.get.js +3 -0
- package/dist/runtime/server/api/discord/slash-command/autocomplete.post.d.ts +2 -0
- package/dist/runtime/server/api/discord/slash-command/autocomplete.post.js +14 -0
- package/dist/runtime/server/api/discord/slash-command/register.post.d.ts +1 -1
- package/dist/runtime/server/api/discord/slash-command/register.post.js +1 -1
- package/dist/runtime/server/api/discord/slash-command/remote-all.get.d.ts +1 -1
- package/dist/runtime/server/api/discord/slash-command/remote-diff.post.d.ts +1 -238
- package/dist/runtime/server/api/discord/slash-command/remote-diff.post.js +3 -1
- package/dist/runtime/server/api/discord/slash-command/test.post.d.ts +20 -0
- package/dist/runtime/server/api/discord/slash-command/test.post.js +19 -0
- package/dist/runtime/server/plugins/discord.js +95 -31
- package/dist/runtime/server/utils/client.d.ts +59 -246
- package/dist/runtime/server/utils/client.js +413 -451
- package/dist/runtime/server/utils/defineContextMenu.d.ts +49 -0
- package/dist/runtime/server/utils/defineContextMenu.js +12 -0
- package/dist/runtime/server/utils/defineListener.d.ts +24 -0
- package/dist/runtime/server/utils/defineListener.js +7 -0
- package/dist/runtime/server/utils/defineMiddleware.d.ts +29 -0
- package/dist/runtime/server/utils/defineMiddleware.js +24 -0
- package/dist/runtime/server/utils/describeCommand.d.ts +2 -0
- package/dist/runtime/server/utils/describeOption.d.ts +1 -1
- package/dist/runtime/server/utils/messageSender.d.ts +37 -0
- package/dist/runtime/server/utils/messageSender.js +149 -0
- package/dist/runtime/server/utils/middleware/cooldown.d.ts +1 -0
- package/dist/runtime/server/utils/middleware/cooldown.js +39 -0
- package/dist/runtime/server/utils/middleware/guildOnly.d.ts +1 -0
- package/dist/runtime/server/utils/middleware/guildOnly.js +6 -0
- package/dist/runtime/server/utils/middleware/ownerOnly.d.ts +1 -0
- package/dist/runtime/server/utils/middleware/ownerOnly.js +10 -0
- package/dist/runtime/server/utils/middleware/requireRole.d.ts +1 -0
- package/dist/runtime/server/utils/middleware/requireRole.js +15 -0
- package/dist/runtime/server/utils/reply.d.ts +13 -3
- package/dist/runtime/server/utils/reply.js +111 -162
- package/dist/runtime/server/utils/simulateInteraction.d.ts +20 -0
- package/dist/runtime/server/utils/simulateInteraction.js +127 -0
- package/dist/runtime/server/utils/useTextChannel.d.ts +56 -0
- package/dist/runtime/server/utils/useTextChannel.js +105 -0
- package/dist/types.d.mts +11 -1
- package/dist/types.d.ts +11 -1
- package/package.json +62 -44
- package/dist/runtime/client/components/TheHeader.css +0 -1
- package/dist/runtime/client/pages/slash-commands.css +0 -1
- package/dist/runtime/client/uno.config.d.ts +0 -2
- package/dist/runtime/client/uno.config.js +0 -10
|
@@ -1,125 +1,343 @@
|
|
|
1
|
+
import { once } from "node:events";
|
|
1
2
|
import process from "node:process";
|
|
2
|
-
import { ApplicationCommandOptionType, Events, Client as InternalClient,
|
|
3
|
-
import { useNitroApp } from "nitropack/runtime";
|
|
4
|
-
import { effectScope, isRef } from "vue";
|
|
3
|
+
import { ApplicationCommandOptionType, Events, Client as InternalClient, MessageFlags, REST } from "discord.js";
|
|
4
|
+
import { useNitroApp, useRuntimeConfig, useStorage } from "nitropack/runtime";
|
|
5
|
+
import { effectScope, isRef, onScopeDispose } from "vue";
|
|
6
|
+
import { interactionSender, scheduleAcknowledgement } from "../../acknowledgement.js";
|
|
7
|
+
import { DiscordConfigurationError, discordDiagnostic, logDiscordFailure } from "../../diagnostics.js";
|
|
8
|
+
import { currentInvocation, runInvocation, setInvocationFields } from "../../discordInvocation.js";
|
|
5
9
|
import { logger } from "../../logger.js";
|
|
10
|
+
import { resolveMiddlewareTags } from "../../middleware.js";
|
|
11
|
+
import { CommandRegistration, commandScopes, planRegistrations } from "../../registration.js";
|
|
12
|
+
import { MiddlewareError } from "./defineMiddleware.js";
|
|
6
13
|
import { reply } from "./reply.js";
|
|
7
|
-
let currentInteraction = null;
|
|
8
14
|
export function useInteraction() {
|
|
9
|
-
return
|
|
15
|
+
return currentInvocation()?.interaction ?? null;
|
|
10
16
|
}
|
|
17
|
+
export function setCurrentChannel(channel) {
|
|
18
|
+
setInvocationFields({ channel });
|
|
19
|
+
}
|
|
20
|
+
export function getCurrentChannel() {
|
|
21
|
+
return currentInvocation()?.channel ?? null;
|
|
22
|
+
}
|
|
23
|
+
class UnknownCommandError extends Error {
|
|
24
|
+
}
|
|
25
|
+
class MissingOptionError extends Error {
|
|
26
|
+
constructor(option) {
|
|
27
|
+
super(`Missing required option "${option}"`);
|
|
28
|
+
this.option = option;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const LISTENER_CHANNEL_ACCESSORS = {
|
|
32
|
+
messageCreate: (msg) => msg.channel ?? null,
|
|
33
|
+
messageUpdate: (_old, newMsg) => newMsg?.channel ?? null,
|
|
34
|
+
messageDelete: (msg) => msg.channel ?? null,
|
|
35
|
+
messageReactionAdd: (reaction) => reaction?.message?.channel ?? null,
|
|
36
|
+
messageReactionRemove: (reaction) => reaction?.message?.channel ?? null,
|
|
37
|
+
typingStart: (typing) => typing?.channel ?? null,
|
|
38
|
+
channelCreate: (ch) => ch && "send" in ch ? ch : null,
|
|
39
|
+
channelUpdate: (_old, newCh) => newCh && "send" in newCh ? newCh : null,
|
|
40
|
+
channelDelete: (ch) => ch && "send" in ch ? ch : null,
|
|
41
|
+
threadCreate: (thread) => thread,
|
|
42
|
+
threadUpdate: (_old, newThread) => newThread,
|
|
43
|
+
threadDelete: (thread) => thread,
|
|
44
|
+
voiceStateUpdate: (_old, newState) => newState?.channel && "send" in newState.channel ? newState.channel : null
|
|
45
|
+
};
|
|
11
46
|
export class DiscordClient {
|
|
12
47
|
#client = null;
|
|
13
48
|
get internalClient() {
|
|
14
49
|
return this.#client;
|
|
15
50
|
}
|
|
16
51
|
#slashCommands = [];
|
|
52
|
+
#contextMenus = [];
|
|
53
|
+
#activityLog = [];
|
|
54
|
+
#activityId = 0;
|
|
55
|
+
#onActivity;
|
|
17
56
|
#nitro = useNitroApp();
|
|
18
57
|
#token;
|
|
19
|
-
#
|
|
20
|
-
#
|
|
58
|
+
#registration;
|
|
59
|
+
#registeredGuildOverrides = /* @__PURE__ */ new Map();
|
|
21
60
|
constructor() {
|
|
22
61
|
if (!process.env.DISCORD_TOKEN) {
|
|
23
|
-
throw new
|
|
62
|
+
throw new DiscordConfigurationError("DISCORD_TOKEN environment variable is not set");
|
|
24
63
|
}
|
|
25
64
|
this.#token = process.env.DISCORD_TOKEN;
|
|
26
|
-
this.#rest = new REST().setToken(this.#token);
|
|
27
65
|
if (!process.env.DISCORD_CLIENT_ID) {
|
|
28
|
-
throw new
|
|
66
|
+
throw new DiscordConfigurationError("DISCORD_CLIENT_ID environment variable is not set");
|
|
29
67
|
}
|
|
30
|
-
|
|
31
|
-
this.#
|
|
32
|
-
|
|
68
|
+
const appId = process.env.DISCORD_CLIENT_ID;
|
|
69
|
+
this.#registration = new CommandRegistration(new REST().setToken(this.#token), appId, {
|
|
70
|
+
load: () => useStorage("data").getItem(`nuxt-discord:${appId}:registration-scopes`),
|
|
71
|
+
save: (scopes) => useStorage("data").setItem(`nuxt-discord:${appId}:registration-scopes`, scopes)
|
|
72
|
+
}, (error) => {
|
|
73
|
+
logDiscordFailure("SlashCommandRegistrationError", error);
|
|
74
|
+
void this.#notify("discord:client:error", { type: "SlashCommandRegistrationError", client: this, error });
|
|
33
75
|
});
|
|
76
|
+
const timeout = useRuntimeConfig().discord?.interactionTimeout;
|
|
77
|
+
if (typeof timeout === "number" && Number.isFinite(timeout) && timeout >= 0)
|
|
78
|
+
this.#interactionTimeout = timeout;
|
|
34
79
|
}
|
|
35
80
|
#clientOptions;
|
|
36
|
-
|
|
81
|
+
#listeners = [];
|
|
82
|
+
#connection;
|
|
83
|
+
#starting;
|
|
84
|
+
#stopping;
|
|
85
|
+
start(options) {
|
|
86
|
+
if (this.#stopping)
|
|
87
|
+
return this.#stopping.then(() => this.start(options));
|
|
88
|
+
if (this.#starting)
|
|
89
|
+
return this.#starting;
|
|
90
|
+
const connection = new AbortController();
|
|
91
|
+
this.#connection = connection;
|
|
92
|
+
this.#starting = this.#connect(options, connection.signal).catch(async (error) => {
|
|
93
|
+
if (!connection.signal.aborted)
|
|
94
|
+
await this.stop();
|
|
95
|
+
throw error;
|
|
96
|
+
});
|
|
97
|
+
return this.#starting;
|
|
98
|
+
}
|
|
99
|
+
async #connect(options, signal) {
|
|
37
100
|
this.#clientOptions = { ...options };
|
|
38
101
|
await this.#nitro.hooks.callHook("discord:client:config", this.#clientOptions);
|
|
39
|
-
|
|
40
|
-
|
|
102
|
+
signal.throwIfAborted();
|
|
103
|
+
const client = new InternalClient(this.#clientOptions);
|
|
104
|
+
this.#client = client;
|
|
105
|
+
client.on(Events.InteractionCreate, (interaction) => this.dispatchInteraction(interaction));
|
|
41
106
|
this.startScope();
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
});
|
|
48
|
-
await this.#client.login(this.#token);
|
|
49
|
-
return promise;
|
|
107
|
+
this.#attachListeners(this.#listeners);
|
|
108
|
+
await Promise.all([once(client, Events.ClientReady, { signal }), client.login(this.#token)]);
|
|
109
|
+
signal.throwIfAborted();
|
|
110
|
+
logger.log(`Discord client is ready! Logged in as ${client.user?.tag}`);
|
|
111
|
+
void this.#nitro.hooks.callHook("discord:client:ready", this)?.catch((error) => logDiscordFailure("Discord ready hook failed:", error));
|
|
50
112
|
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
if (!
|
|
58
|
-
logger.warn(`Unknown slash command: ${commandName}`);
|
|
59
|
-
this.#nitro.hooks.callHook("discord:client:error", {
|
|
60
|
-
type: "UnknownSlashCommandError",
|
|
61
|
-
client: this,
|
|
62
|
-
interaction
|
|
63
|
-
});
|
|
113
|
+
registerListeners(listeners) {
|
|
114
|
+
this.#listeners.push(...listeners);
|
|
115
|
+
if (this.#client)
|
|
116
|
+
this.#attachListeners(listeners);
|
|
117
|
+
}
|
|
118
|
+
#attachListeners(listeners) {
|
|
119
|
+
if (!this.#client)
|
|
64
120
|
return;
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
const
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
121
|
+
for (const listener of listeners) {
|
|
122
|
+
const accessor = LISTENER_CHANNEL_ACCESSORS[listener.event];
|
|
123
|
+
const handler = async (...args) => {
|
|
124
|
+
const scope = this.#createScope();
|
|
125
|
+
try {
|
|
126
|
+
const channel = accessor?.(...args) ?? null;
|
|
127
|
+
await runInvocation(scope, { channel }, () => listener.execute(...args));
|
|
128
|
+
} catch (error) {
|
|
129
|
+
logDiscordFailure(`Listener error [${listener.event}]:`, error);
|
|
130
|
+
} finally {
|
|
131
|
+
scope.stop();
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
if (listener.once) {
|
|
135
|
+
this.#client.once(listener.event, handler);
|
|
73
136
|
} else {
|
|
74
|
-
|
|
137
|
+
this.#client.on(listener.event, handler);
|
|
75
138
|
}
|
|
76
139
|
}
|
|
77
|
-
if (
|
|
78
|
-
logger.
|
|
79
|
-
this.#nitro.hooks.callHook("discord:client:error", {
|
|
80
|
-
type: "UnknownSlashCommandError",
|
|
81
|
-
client: this,
|
|
82
|
-
interaction
|
|
83
|
-
});
|
|
84
|
-
return;
|
|
140
|
+
if (listeners.length > 0) {
|
|
141
|
+
logger.log(`Registered ${listeners.length} event listener(s)`);
|
|
85
142
|
}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
}
|
|
143
|
+
}
|
|
144
|
+
addContextMenus(menus) {
|
|
145
|
+
this.#contextMenus.push(...menus);
|
|
146
|
+
}
|
|
147
|
+
getContextMenus() {
|
|
148
|
+
return this.#contextMenus;
|
|
149
|
+
}
|
|
150
|
+
async dispatchInteraction(interaction, options = {}) {
|
|
151
|
+
const scope = this.#createScope();
|
|
152
|
+
const dispose = () => scope.stop();
|
|
153
|
+
const menu = interaction.isUserContextMenuCommand() || interaction.isMessageContextMenuCommand();
|
|
154
|
+
if (!menu && !interaction.isChatInputCommand() && !interaction.isAutocomplete()) {
|
|
155
|
+
dispose();
|
|
156
|
+
return { status: "error", detail: "Unsupported interaction type", dispose };
|
|
100
157
|
}
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
158
|
+
const type = menu ? "context-menu" : interaction.isAutocomplete() ? "autocomplete" : "command";
|
|
159
|
+
const start = Date.now();
|
|
160
|
+
const ctx = { interaction, type };
|
|
161
|
+
const middleware = {};
|
|
162
|
+
const result = { status: "ok", dispose };
|
|
163
|
+
let command;
|
|
164
|
+
let activityDetail;
|
|
165
|
+
let cancelAcknowledgement;
|
|
166
|
+
if (!options.simulation && this.#interactionTimeout !== 0) {
|
|
167
|
+
const timeout = this.#interactionTimeout ?? Math.max(0, DiscordClient.DISCORD_TOKEN_LIFETIME - (start - (interaction.createdTimestamp ?? start)));
|
|
168
|
+
const timer = setTimeout(dispose, timeout);
|
|
169
|
+
timer.unref();
|
|
170
|
+
scope.run(() => onScopeDispose(() => clearTimeout(timer)));
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
if (interaction.isChatInputCommand() || interaction.isAutocomplete())
|
|
174
|
+
command = this.resolveSlashCommand(interaction.commandName, interaction.options.getSubcommandGroup?.(false), interaction.options.getSubcommand?.(false), interaction.commandGuildId);
|
|
175
|
+
if (!interaction.isAutocomplete() && (command?.defer || !options.simulation && this.#clientOptions?.deferOnPromise)) {
|
|
176
|
+
cancelAcknowledgement = scheduleAcknowledgement(interaction, command?.defer, !options.simulation);
|
|
177
|
+
scope.run(() => onScopeDispose(cancelAcknowledgement));
|
|
178
|
+
}
|
|
179
|
+
await runInvocation(scope, { channel: interaction.channel, interaction: interaction.isChatInputCommand() ? interaction : void 0, middleware }, async () => {
|
|
180
|
+
if (!options.simulation && type !== "autocomplete")
|
|
181
|
+
await this.#nitro.hooks.callHook("discord:interaction:before", ctx);
|
|
182
|
+
if (interaction.isUserContextMenuCommand() || interaction.isMessageContextMenuCommand()) {
|
|
183
|
+
const menuType = interaction.isUserContextMenuCommand() ? "user" : "message";
|
|
184
|
+
const menu2 = this.#contextMenus.find((m) => m.name === interaction.commandName && m.type === menuType && this.#matchesScope(m, interaction.commandGuildId));
|
|
185
|
+
if (!menu2)
|
|
186
|
+
throw new UnknownCommandError(`Unknown context menu "${interaction.commandName}"`);
|
|
187
|
+
const entries2 = [...resolveMiddlewareTags(menu2.middleware, menu2.name), ...menu2.middlewareEntries ?? []];
|
|
188
|
+
await this.#runMiddleware(entries2, interaction, void 0, "context-menu", middleware, async () => {
|
|
189
|
+
const value = scope.run(() => {
|
|
190
|
+
if (menu2.type === "user" && interaction.isUserContextMenuCommand())
|
|
191
|
+
return menu2.execute(interaction);
|
|
192
|
+
if (menu2.type === "message" && interaction.isMessageContextMenuCommand())
|
|
193
|
+
return menu2.execute(interaction);
|
|
194
|
+
});
|
|
195
|
+
await this.#respond(value, interaction, scope);
|
|
196
|
+
});
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (!command)
|
|
200
|
+
throw new UnknownCommandError(`Unknown slash command "${interaction.commandName}"`);
|
|
201
|
+
if (interaction.isAutocomplete()) {
|
|
202
|
+
await this.#handleAutocomplete(interaction, command, scope);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
if (!command.execute && command.load)
|
|
206
|
+
Object.assign(command, await command.load());
|
|
207
|
+
const resolved = command;
|
|
208
|
+
const entries = [...resolveMiddlewareTags(resolved.middleware, resolved.path), ...resolved.middlewareEntries ?? []];
|
|
209
|
+
await this.#runMiddleware(entries, interaction, resolved, "command", middleware, async () => {
|
|
210
|
+
const args = this.#commandArgs(interaction, resolved);
|
|
211
|
+
if (!resolved.execute)
|
|
212
|
+
throw new Error(`Command "${interaction.commandName}" has no execute function`);
|
|
213
|
+
await this.#respond(scope.run(() => resolved.execute(...args)), interaction, scope);
|
|
214
|
+
});
|
|
108
215
|
});
|
|
109
|
-
|
|
216
|
+
} catch (error) {
|
|
217
|
+
result.status = error instanceof MiddlewareError ? "denied" : "error";
|
|
218
|
+
result.detail = error instanceof Error ? error.message : String(error);
|
|
219
|
+
if (interaction.isAutocomplete()) {
|
|
220
|
+
if (scope.active && !interaction.responded)
|
|
221
|
+
await interaction.respond([]).catch(() => {
|
|
222
|
+
});
|
|
223
|
+
} else if (scope.active && !interaction.replied) {
|
|
224
|
+
const sender = interactionSender(interaction);
|
|
225
|
+
await sender.send({ content: result.status === "denied" ? result.detail : "An error occurred.", flags: MessageFlags.Ephemeral }).catch(() => {
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
if (!options.simulation) {
|
|
229
|
+
let hookError;
|
|
230
|
+
if (error instanceof MiddlewareError) {
|
|
231
|
+
const denied = { ...ctx, middleware: error.identifier ?? "unknown", reason: error.reason };
|
|
232
|
+
hookError = { ...denied, type: "MiddlewareDeniedError", identifier: error.identifier, client: this };
|
|
233
|
+
await this.#notify("discord:interaction:denied", denied);
|
|
234
|
+
} else if (error instanceof UnknownCommandError) {
|
|
235
|
+
hookError = { type: "UnknownSlashCommandError", interaction, client: this };
|
|
236
|
+
} else if (error instanceof MissingOptionError) {
|
|
237
|
+
hookError = { type: "MissingRequiredOptionError", interaction, client: this, command, option: error.option };
|
|
238
|
+
} else {
|
|
239
|
+
hookError = { type: "SlashCommandExecutionError", interaction, client: this, command, error };
|
|
240
|
+
}
|
|
241
|
+
logDiscordFailure(hookError.type, error);
|
|
242
|
+
activityDetail = result.status === "denied" ? "Denied by middleware" : discordDiagnostic(error);
|
|
243
|
+
await this.#notify("discord:client:error", hookError);
|
|
244
|
+
}
|
|
245
|
+
} finally {
|
|
246
|
+
cancelAcknowledgement?.();
|
|
247
|
+
if (!options.simulation && type !== "autocomplete") {
|
|
248
|
+
this.#logActivity({
|
|
249
|
+
type,
|
|
250
|
+
name: menu ? interaction.commandName : `/${interaction.commandName}`,
|
|
251
|
+
status: result.status,
|
|
252
|
+
detail: activityDetail,
|
|
253
|
+
duration: Date.now() - start,
|
|
254
|
+
userId: interaction.user?.id,
|
|
255
|
+
userName: interaction.user?.displayName,
|
|
256
|
+
guildId: interaction.guildId ?? void 0,
|
|
257
|
+
guildName: interaction.guild?.name,
|
|
258
|
+
channelId: interaction.channelId ?? void 0
|
|
259
|
+
});
|
|
260
|
+
await this.#notify("discord:interaction:after", { ...ctx, status: result.status, detail: result.detail });
|
|
261
|
+
}
|
|
262
|
+
if (result.status !== "ok" || type === "autocomplete")
|
|
263
|
+
dispose();
|
|
110
264
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
265
|
+
return result;
|
|
266
|
+
}
|
|
267
|
+
resolveSlashCommand(name, group, leaf, commandGuildId) {
|
|
268
|
+
const root = this.getSlashCommand(name, commandGuildId);
|
|
269
|
+
if (!root?.subcommands?.length)
|
|
270
|
+
return group || leaf ? void 0 : root;
|
|
271
|
+
if (!leaf)
|
|
272
|
+
return void 0;
|
|
273
|
+
if (group)
|
|
274
|
+
return root.subcommands.find((cmd) => cmd.name === group)?.subcommands?.find((cmd) => cmd.name === leaf);
|
|
275
|
+
return root.subcommands.find((cmd) => cmd.name === leaf && !cmd.subcommands?.length);
|
|
276
|
+
}
|
|
277
|
+
async #notify(name, event) {
|
|
278
|
+
try {
|
|
279
|
+
await this.#nitro.hooks.callHook(name, event);
|
|
280
|
+
} catch (error) {
|
|
281
|
+
logDiscordFailure(`Discord observer failed [${name}]`, error);
|
|
115
282
|
}
|
|
116
283
|
}
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
284
|
+
#logActivity(entry) {
|
|
285
|
+
const full = { ...entry, id: ++this.#activityId, timestamp: Date.now() };
|
|
286
|
+
this.#activityLog.push(full);
|
|
287
|
+
if (this.#activityLog.length > 200)
|
|
288
|
+
this.#activityLog.shift();
|
|
289
|
+
try {
|
|
290
|
+
this.#onActivity?.(full);
|
|
291
|
+
} catch (error) {
|
|
292
|
+
logDiscordFailure("Discord activity observer failed:", error);
|
|
121
293
|
}
|
|
294
|
+
return full;
|
|
295
|
+
}
|
|
296
|
+
onActivity(callback) {
|
|
297
|
+
this.#onActivity = callback;
|
|
298
|
+
}
|
|
299
|
+
getActivityLog() {
|
|
300
|
+
return this.#activityLog;
|
|
301
|
+
}
|
|
302
|
+
async #runMiddleware(entries, interaction, command, type, context, execute) {
|
|
303
|
+
const runChain = async (index) => {
|
|
304
|
+
const entry = entries[index];
|
|
305
|
+
if (!entry)
|
|
306
|
+
return execute();
|
|
307
|
+
let continuation;
|
|
308
|
+
await entry.fn({
|
|
309
|
+
interaction,
|
|
310
|
+
command,
|
|
311
|
+
type,
|
|
312
|
+
next: async (ctx) => {
|
|
313
|
+
if (continuation)
|
|
314
|
+
throw new Error(`Middleware ${entry.name} called next() twice`);
|
|
315
|
+
Object.assign(context, ctx);
|
|
316
|
+
continuation = runChain(index + 1);
|
|
317
|
+
await continuation;
|
|
318
|
+
}
|
|
319
|
+
}, entry.options);
|
|
320
|
+
if (!continuation)
|
|
321
|
+
throw new MiddlewareError("Command was stopped by middleware.", entry.name);
|
|
322
|
+
await continuation;
|
|
323
|
+
};
|
|
324
|
+
await runChain(0);
|
|
325
|
+
}
|
|
326
|
+
stop() {
|
|
327
|
+
if (this.#stopping)
|
|
328
|
+
return this.#stopping;
|
|
329
|
+
this.#connection?.abort();
|
|
330
|
+
this.#connection = void 0;
|
|
331
|
+
this.#starting = void 0;
|
|
332
|
+
const client = this.#client;
|
|
333
|
+
this.#client = null;
|
|
122
334
|
this.stopScope();
|
|
335
|
+
if (!client)
|
|
336
|
+
return Promise.resolve();
|
|
337
|
+
this.#stopping = Promise.resolve().then(() => client.destroy()).finally(() => {
|
|
338
|
+
this.#stopping = void 0;
|
|
339
|
+
});
|
|
340
|
+
return this.#stopping;
|
|
123
341
|
}
|
|
124
342
|
#scope;
|
|
125
343
|
startScope() {
|
|
@@ -140,7 +358,7 @@ export class DiscordClient {
|
|
|
140
358
|
return this.#client?.isReady() ?? false;
|
|
141
359
|
}
|
|
142
360
|
addSlashCommand(command) {
|
|
143
|
-
const existingCommandIndex = this.#slashCommands.findIndex((cmd) => cmd.name === command.name);
|
|
361
|
+
const existingCommandIndex = this.#slashCommands.findIndex((cmd) => cmd.name === command.name && cmd.path === command.path);
|
|
144
362
|
if (existingCommandIndex !== -1) {
|
|
145
363
|
this.#slashCommands[existingCommandIndex] = command;
|
|
146
364
|
} else {
|
|
@@ -152,8 +370,8 @@ export class DiscordClient {
|
|
|
152
370
|
this.addSlashCommand(command);
|
|
153
371
|
}
|
|
154
372
|
}
|
|
155
|
-
removeSlashCommand(name) {
|
|
156
|
-
const index = this.#slashCommands.findIndex((cmd) => cmd.name === name);
|
|
373
|
+
removeSlashCommand(name, commandGuildId) {
|
|
374
|
+
const index = this.#slashCommands.findIndex((cmd) => cmd.name === name && this.#matchesScope(cmd, commandGuildId));
|
|
157
375
|
if (index !== -1) {
|
|
158
376
|
this.#slashCommands.splice(index, 1);
|
|
159
377
|
}
|
|
@@ -164,388 +382,132 @@ export class DiscordClient {
|
|
|
164
382
|
getSlashCommands() {
|
|
165
383
|
return this.#slashCommands;
|
|
166
384
|
}
|
|
167
|
-
|
|
168
|
-
|
|
385
|
+
#configuredGuilds() {
|
|
386
|
+
const configured = useRuntimeConfig().discord?.guilds;
|
|
387
|
+
return configured?.length ? configured : (process.env.DISCORD_GUILD_ID ?? "").split(",").map((id) => id.trim()).filter(Boolean);
|
|
388
|
+
}
|
|
389
|
+
#matchesScope(command, commandGuildId) {
|
|
390
|
+
if (commandGuildId === void 0)
|
|
391
|
+
return true;
|
|
392
|
+
if (command.guilds === true && commandGuildId != null)
|
|
393
|
+
return this.#registeredGuildOverrides.get(commandGuildId) ?? this.#configuredGuilds().includes(commandGuildId);
|
|
394
|
+
return commandScopes(command.guilds, []).includes(commandGuildId ?? "global");
|
|
395
|
+
}
|
|
396
|
+
getSlashCommand(name, commandGuildId) {
|
|
397
|
+
return this.#slashCommands.find((cmd) => cmd.name === name && this.#matchesScope(cmd, commandGuildId));
|
|
398
|
+
}
|
|
399
|
+
#interactionTimeout;
|
|
400
|
+
static DISCORD_TOKEN_LIFETIME = 15 * 60 * 1e3;
|
|
401
|
+
#createScope() {
|
|
402
|
+
return this.#scope?.run(() => effectScope()) ?? effectScope(true);
|
|
169
403
|
}
|
|
170
|
-
#
|
|
171
|
-
#commandFinalizationRegistry = new FinalizationRegistry((scope) => scope.stop());
|
|
172
|
-
async #handleSlashCommand(interaction, command) {
|
|
404
|
+
#commandArgs(interaction, command) {
|
|
173
405
|
const args = [];
|
|
174
406
|
for (const option of command.options) {
|
|
175
|
-
const opt = interaction.options.get(option.name,
|
|
176
|
-
if (option.required && opt == null)
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
407
|
+
const opt = interaction.options.get(option.name, false);
|
|
408
|
+
if (option.required && opt == null)
|
|
409
|
+
throw new MissingOptionError(option.name);
|
|
410
|
+
switch (option.type) {
|
|
411
|
+
case ApplicationCommandOptionType.Channel:
|
|
412
|
+
args.push(opt?.channel ?? void 0);
|
|
413
|
+
break;
|
|
414
|
+
case ApplicationCommandOptionType.User:
|
|
415
|
+
args.push(opt?.user ?? void 0);
|
|
416
|
+
break;
|
|
417
|
+
case ApplicationCommandOptionType.Role:
|
|
418
|
+
args.push(opt?.role ?? void 0);
|
|
419
|
+
break;
|
|
420
|
+
case ApplicationCommandOptionType.Mentionable:
|
|
421
|
+
args.push(opt?.user ?? opt?.member ?? opt?.role ?? void 0);
|
|
422
|
+
break;
|
|
423
|
+
case ApplicationCommandOptionType.Attachment:
|
|
424
|
+
args.push(opt?.attachment ?? void 0);
|
|
425
|
+
break;
|
|
426
|
+
default:
|
|
427
|
+
args.push(opt?.value);
|
|
428
|
+
break;
|
|
185
429
|
}
|
|
186
|
-
args.push(opt?.value);
|
|
187
|
-
}
|
|
188
|
-
let scope;
|
|
189
|
-
if (this.#scope) {
|
|
190
|
-
this.#scope.run(() => scope = effectScope());
|
|
191
|
-
} else {
|
|
192
|
-
scope = effectScope();
|
|
193
|
-
}
|
|
194
|
-
this.#interactionScopes.set(interaction, scope);
|
|
195
|
-
if (import.meta.dev)
|
|
196
|
-
this.#commandFinalizationRegistry.register(command, scope);
|
|
197
|
-
try {
|
|
198
|
-
let result;
|
|
199
|
-
scope.run(() => {
|
|
200
|
-
currentInteraction = interaction;
|
|
201
|
-
result = command.execute(...args);
|
|
202
|
-
currentInteraction = null;
|
|
203
|
-
});
|
|
204
|
-
if (this.#clientOptions?.deferOnPromise && isPromise(result)) {
|
|
205
|
-
await interaction.deferReply();
|
|
206
|
-
}
|
|
207
|
-
await this.#handleSlashCommandReturn(result, interaction, command);
|
|
208
|
-
} catch (error) {
|
|
209
|
-
this.#nitro.hooks.callHook("discord:client:error", {
|
|
210
|
-
type: "SlashCommandExecutionError",
|
|
211
|
-
client: this,
|
|
212
|
-
interaction,
|
|
213
|
-
command,
|
|
214
|
-
error
|
|
215
|
-
});
|
|
216
430
|
}
|
|
431
|
+
return args;
|
|
217
432
|
}
|
|
218
|
-
async #
|
|
219
|
-
result = await
|
|
220
|
-
if (!
|
|
433
|
+
async #respond(value, interaction, scope) {
|
|
434
|
+
const result = await value;
|
|
435
|
+
if (result == null || !scope.active)
|
|
221
436
|
return;
|
|
437
|
+
if (typeof result === "string" || isRef(result))
|
|
438
|
+
return this.#respond(reply(result), interaction, scope);
|
|
439
|
+
if (typeof result === "function")
|
|
440
|
+
return scope.run(() => result.call(this, interaction, this));
|
|
441
|
+
if (typeof result !== "object")
|
|
442
|
+
throw new TypeError(`Unexpected command return type: ${typeof result}`);
|
|
443
|
+
const generator = Symbol.asyncIterator in result ? result[Symbol.asyncIterator]() : Symbol.iterator in result ? result[Symbol.iterator]() : void 0;
|
|
444
|
+
if (!generator) {
|
|
445
|
+
if (interaction.replied || interaction.deferred)
|
|
446
|
+
return result;
|
|
447
|
+
throw new Error("Unexpected command return value");
|
|
222
448
|
}
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
const scope = this.#interactionScopes.get(interaction);
|
|
228
|
-
if (!scope) {
|
|
229
|
-
return result.call(this, interaction, this);
|
|
230
|
-
} else {
|
|
231
|
-
return scope.run(() => result.call(this, interaction, this));
|
|
232
|
-
}
|
|
233
|
-
} else if (Symbol.iterator in result && typeof result[Symbol.iterator] === "function") {
|
|
234
|
-
const gen = result[Symbol.iterator]();
|
|
235
|
-
let next = gen.next();
|
|
236
|
-
while (!next.done) {
|
|
237
|
-
next = gen.next(await this.#handleSlashCommandReturn(await next.value, interaction, command));
|
|
238
|
-
}
|
|
239
|
-
if (next.value != null) {
|
|
240
|
-
return this.#handleSlashCommandReturn(next.value, interaction, command);
|
|
241
|
-
}
|
|
242
|
-
} else if (Symbol.asyncIterator in result && typeof result[Symbol.asyncIterator] === "function") {
|
|
243
|
-
const gen = result[Symbol.asyncIterator]();
|
|
244
|
-
let next = await gen.next();
|
|
245
|
-
while (!next.done) {
|
|
246
|
-
next = await gen.next(await this.#handleSlashCommandReturn(await next.value, interaction, command));
|
|
247
|
-
}
|
|
248
|
-
if (next.value != null) {
|
|
249
|
-
return this.#handleSlashCommandReturn(next.value, interaction, command);
|
|
250
|
-
}
|
|
251
|
-
} else {
|
|
252
|
-
if (result != null) {
|
|
253
|
-
throw new Error(`Unexpected return type from slash command: ${typeof result}`);
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
} catch (error) {
|
|
257
|
-
this.#nitro.hooks.callHook("discord:client:error", {
|
|
258
|
-
type: "SlashCommandExecutionError",
|
|
259
|
-
client: this,
|
|
260
|
-
interaction,
|
|
261
|
-
command,
|
|
262
|
-
error
|
|
263
|
-
});
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
async #handleAutocomplete(interaction, command) {
|
|
267
|
-
const commandName = interaction.commandName;
|
|
268
|
-
if (!command) {
|
|
269
|
-
logger.warn(`Unknown slash command: ${commandName}`);
|
|
270
|
-
this.#nitro.hooks.callHook("discord:client:error", {
|
|
271
|
-
type: "UnknownSlashCommandError",
|
|
272
|
-
client: this,
|
|
273
|
-
interaction
|
|
274
|
-
});
|
|
275
|
-
return;
|
|
276
|
-
}
|
|
277
|
-
const focusedOption = interaction.options.getFocused(true);
|
|
278
|
-
const varname = command.options.find((opt) => opt.name === focusedOption.name)?.varname;
|
|
279
|
-
if (!varname) {
|
|
280
|
-
return;
|
|
281
|
-
}
|
|
282
|
-
const autocompleteFunction = command.optionMacros?.[varname]?.autocomplete;
|
|
283
|
-
if (!autocompleteFunction) {
|
|
284
|
-
return;
|
|
285
|
-
}
|
|
286
|
-
const choices = await autocompleteFunction(focusedOption.value, interaction);
|
|
287
|
-
await interaction.respond(choices);
|
|
288
|
-
}
|
|
289
|
-
#getSlashCommandBuilder(command, builder) {
|
|
290
|
-
builder ??= new SlashCommandBuilder();
|
|
291
|
-
builder.setName(command.name).setDescription(command.description);
|
|
292
|
-
if (command.subcommands != null && command.subcommands.length > 0) {
|
|
293
|
-
for (const subcommand of command.subcommands) {
|
|
294
|
-
if (builder instanceof SlashCommandBuilder) {
|
|
295
|
-
if ("subcommands" in subcommand && (subcommand.subcommands?.length ?? 0) > 0) {
|
|
296
|
-
builder.addSubcommandGroup((subcommandGroupBuilder) => this.#getSlashCommandBuilder(subcommand, subcommandGroupBuilder));
|
|
297
|
-
} else {
|
|
298
|
-
builder.addSubcommand((subcommandBuilder) => this.#getSlashCommandBuilder(subcommand, subcommandBuilder));
|
|
299
|
-
}
|
|
300
|
-
} else if (builder instanceof SlashCommandSubcommandGroupBuilder) {
|
|
301
|
-
builder.addSubcommand((subcommandBuilder) => this.#getSlashCommandBuilder(subcommand, subcommandBuilder));
|
|
302
|
-
} else {
|
|
303
|
-
throw new TypeError(`Unexpected builder type: ${builder.constructor.name}`);
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
} else if (builder instanceof SlashCommandBuilder || builder instanceof SlashCommandSubcommandBuilder) {
|
|
307
|
-
for (const option of command.options) {
|
|
308
|
-
switch (option.type) {
|
|
309
|
-
case ApplicationCommandOptionType.String:
|
|
310
|
-
builder.addStringOption((opt) => {
|
|
311
|
-
opt.setName(option.name).setRequired(option.required);
|
|
312
|
-
if (option.description.length > 0)
|
|
313
|
-
opt = opt.setDescription(option.description);
|
|
314
|
-
if (option.minLength)
|
|
315
|
-
opt = opt.setMinLength(option.minLength);
|
|
316
|
-
if (option.maxLength)
|
|
317
|
-
opt = opt.setMaxLength(option.maxLength);
|
|
318
|
-
if (option.choices)
|
|
319
|
-
opt = opt.addChoices(...option.choices);
|
|
320
|
-
if (option.hasAutocomplete) {
|
|
321
|
-
opt = opt.setAutocomplete(true);
|
|
322
|
-
}
|
|
323
|
-
return opt;
|
|
324
|
-
});
|
|
325
|
-
break;
|
|
326
|
-
case ApplicationCommandOptionType.Integer:
|
|
327
|
-
builder.addIntegerOption((opt) => {
|
|
328
|
-
opt.setName(option.name).setRequired(option.required);
|
|
329
|
-
if (option.description.length > 0)
|
|
330
|
-
opt = opt.setDescription(option.description);
|
|
331
|
-
if (option.min)
|
|
332
|
-
opt = opt.setMinValue(option.min);
|
|
333
|
-
if (option.max)
|
|
334
|
-
opt = opt.setMaxValue(option.max);
|
|
335
|
-
if (option.choices)
|
|
336
|
-
opt = opt.addChoices(...option.choices);
|
|
337
|
-
if (option.hasAutocomplete)
|
|
338
|
-
opt = opt.setAutocomplete(true);
|
|
339
|
-
return opt;
|
|
340
|
-
});
|
|
341
|
-
break;
|
|
342
|
-
case ApplicationCommandOptionType.Number:
|
|
343
|
-
builder.addNumberOption((opt) => {
|
|
344
|
-
opt.setName(option.name).setRequired(option.required);
|
|
345
|
-
if (option.description.length > 0)
|
|
346
|
-
opt = opt.setDescription(option.description);
|
|
347
|
-
if (option.min)
|
|
348
|
-
opt = opt.setMinValue(option.min);
|
|
349
|
-
if (option.max)
|
|
350
|
-
opt = opt.setMaxValue(option.max);
|
|
351
|
-
if (option.choices)
|
|
352
|
-
opt = opt.addChoices(...option.choices);
|
|
353
|
-
if (option.hasAutocomplete)
|
|
354
|
-
opt = opt.setAutocomplete(true);
|
|
355
|
-
return opt;
|
|
356
|
-
});
|
|
357
|
-
break;
|
|
358
|
-
case ApplicationCommandOptionType.Boolean:
|
|
359
|
-
builder.addBooleanOption((opt) => {
|
|
360
|
-
opt.setName(option.name).setRequired(option.required);
|
|
361
|
-
if (option.description.length > 0)
|
|
362
|
-
opt = opt.setDescription(option.description);
|
|
363
|
-
return opt;
|
|
364
|
-
});
|
|
365
|
-
break;
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
|
-
}
|
|
369
|
-
return builder;
|
|
370
|
-
}
|
|
371
|
-
#cachedRemoteSlashCommands = null;
|
|
372
|
-
async getRemoteSlashCommands() {
|
|
373
|
-
this.#cachedRemoteSlashCommands = await this.#rest.get(Routes.applicationCommands(this.#clientId));
|
|
374
|
-
return this.#cachedRemoteSlashCommands;
|
|
375
|
-
}
|
|
376
|
-
async diffRemoteSlashCommands(localCommands = this.#slashCommands, forceRefresh = false) {
|
|
377
|
-
if (!this.#cachedRemoteSlashCommands || forceRefresh) {
|
|
378
|
-
await this.getRemoteSlashCommands();
|
|
449
|
+
let step = await scope.run(() => generator.next());
|
|
450
|
+
while (step && !step.done && scope.active) {
|
|
451
|
+
const response = await this.#respond(step.value, interaction, scope);
|
|
452
|
+
step = await scope.run(() => generator.next(response));
|
|
379
453
|
}
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
const subcommands = cmd.options?.flatMap((option) => {
|
|
383
|
-
const name = `${cmd.name} ${option.name}`;
|
|
384
|
-
if (option.type === ApplicationCommandOptionType.Subcommand) {
|
|
385
|
-
return [{ ...option, name, subcommands: [] }];
|
|
386
|
-
} else if (option.type === ApplicationCommandOptionType.SubcommandGroup) {
|
|
387
|
-
const subcommands2 = option.options?.flatMap((suboption) => {
|
|
388
|
-
return suboption.type === ApplicationCommandOptionType.Subcommand ? [{ ...suboption, name: `${name} ${suboption.name}`, subcommands: [] }] : [];
|
|
389
|
-
}) ?? [];
|
|
390
|
-
return [
|
|
391
|
-
{ ...option, name, subcommands: subcommands2 },
|
|
392
|
-
...subcommands2
|
|
393
|
-
];
|
|
394
|
-
}
|
|
395
|
-
return [];
|
|
396
|
-
}) ?? [];
|
|
397
|
-
return [
|
|
398
|
-
{ ...cmd, subcommands },
|
|
399
|
-
...subcommands
|
|
400
|
-
];
|
|
401
|
-
});
|
|
402
|
-
const flattenedLocalCommands = localCommands.flatMap(
|
|
403
|
-
(cmd) => [
|
|
404
|
-
cmd,
|
|
405
|
-
...cmd.subcommands?.flatMap((subcmd) => {
|
|
406
|
-
const name = `${cmd.name} ${subcmd.name}`;
|
|
407
|
-
return [
|
|
408
|
-
{ ...subcmd, name },
|
|
409
|
-
...subcmd.subcommands?.map((subsubcmd) => ({ ...subsubcmd, name: `${name} ${subsubcmd.name}` })) ?? []
|
|
410
|
-
];
|
|
411
|
-
}) ?? []
|
|
412
|
-
]
|
|
413
|
-
);
|
|
414
|
-
const nameToCommands = flattenedLocalCommands.reduce((acc, command) => {
|
|
415
|
-
(acc[command.name] ??= []).push(command);
|
|
416
|
-
return acc;
|
|
417
|
-
}, {});
|
|
418
|
-
return flattenedLocalCommands.reduce((acc, command) => {
|
|
419
|
-
if (nameToCommands[command.name].length > 1) {
|
|
420
|
-
acc.conflict.push(command);
|
|
421
|
-
return acc;
|
|
422
|
-
}
|
|
423
|
-
const remoteCommand = flattenedRemoteCommands.find((cmd) => cmd.name === command.name);
|
|
424
|
-
if (!remoteCommand) {
|
|
425
|
-
acc.added.push(command);
|
|
426
|
-
} else if (
|
|
427
|
-
// if some properties are different
|
|
428
|
-
!propsEqual(command, remoteCommand, [
|
|
429
|
-
"description"
|
|
430
|
-
/* TODO: more */
|
|
431
|
-
]) || !((command.subcommands?.length ?? 0) > 0 && remoteCommand.subcommands.length > 0) && ((command.options?.length ?? 0) !== (remoteCommand.options?.length ?? 0) || (remoteCommand.options ?? []).some((opt, i) => !optionEqual(command.options[i], opt)))
|
|
432
|
-
) {
|
|
433
|
-
acc.changed.push({ local: command, remote: remoteCommand });
|
|
434
|
-
} else {
|
|
435
|
-
if ("id" in remoteCommand && !command.id) {
|
|
436
|
-
command.id = remoteCommand.id;
|
|
437
|
-
}
|
|
438
|
-
acc.synced.push({ local: command, remote: remoteCommand });
|
|
439
|
-
}
|
|
440
|
-
return acc;
|
|
441
|
-
}, {
|
|
442
|
-
added: [],
|
|
443
|
-
removed: flattenedRemoteCommands.filter(({ name }) => !(name in nameToCommands)),
|
|
444
|
-
changed: [],
|
|
445
|
-
synced: [],
|
|
446
|
-
conflict: []
|
|
447
|
-
});
|
|
454
|
+
if (step?.done && step.value != null)
|
|
455
|
+
return this.#respond(step.value, interaction, scope);
|
|
448
456
|
}
|
|
449
|
-
async
|
|
450
|
-
const
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
type: "SlashCommandRegistrationError",
|
|
472
|
-
client: this,
|
|
473
|
-
error
|
|
474
|
-
});
|
|
475
|
-
return [];
|
|
476
|
-
}
|
|
477
|
-
} else {
|
|
478
|
-
const results = await Promise.allSettled(
|
|
479
|
-
diff.changed.map((command) => {
|
|
480
|
-
if (!("id" in command.remote))
|
|
481
|
-
return Promise.reject(new Error(`Remote command ${command.local.name} does not have an ID`));
|
|
482
|
-
logger.log(`Updating slash command: ${command.local.name}`);
|
|
483
|
-
const builder = this.#getSlashCommandBuilder(command.local);
|
|
484
|
-
return this.#rest.patch(
|
|
485
|
-
Routes.applicationCommand(this.#clientId, command.remote.id),
|
|
486
|
-
{ body: builder.toJSON() }
|
|
487
|
-
);
|
|
488
|
-
})
|
|
489
|
-
);
|
|
490
|
-
results.forEach((result, i) => {
|
|
491
|
-
if (result.status === "rejected") {
|
|
492
|
-
this.#nitro.hooks.callHook("discord:client:error", {
|
|
493
|
-
type: "SlashCommandRegistrationError",
|
|
494
|
-
client: this,
|
|
495
|
-
command: result.reason.command,
|
|
496
|
-
error: result.reason.error
|
|
497
|
-
});
|
|
498
|
-
} else {
|
|
499
|
-
const command = diff.changed[i];
|
|
500
|
-
command.local.id = result.value.id;
|
|
501
|
-
}
|
|
502
|
-
});
|
|
503
|
-
return results;
|
|
457
|
+
async #handleAutocomplete(interaction, command, scope) {
|
|
458
|
+
const choices = async () => {
|
|
459
|
+
if (!command.execute && command.load)
|
|
460
|
+
Object.assign(command, await command.load());
|
|
461
|
+
const focused = interaction.options.getFocused(true);
|
|
462
|
+
const varname = command.options.find((opt) => opt.name === focused.name)?.varname;
|
|
463
|
+
const complete = varname && command.optionMacros?.[varname]?.autocomplete;
|
|
464
|
+
if (!complete)
|
|
465
|
+
throw new Error(`No autocomplete handler for "${focused.name}"`);
|
|
466
|
+
return complete(String(focused.value), interaction);
|
|
467
|
+
};
|
|
468
|
+
const fallback = Promise.withResolvers();
|
|
469
|
+
const elapsed = Date.now() - (interaction.createdTimestamp ?? Date.now());
|
|
470
|
+
const timer = setTimeout(() => fallback.resolve([]), Math.max(0, 2e3 - elapsed));
|
|
471
|
+
timer.unref();
|
|
472
|
+
scope.run(() => onScopeDispose(() => fallback.resolve([])));
|
|
473
|
+
try {
|
|
474
|
+
const result = await Promise.race([choices(), fallback.promise]);
|
|
475
|
+
if (scope.active && !interaction.responded)
|
|
476
|
+
await interaction.respond(result.slice(0, 25));
|
|
477
|
+
} finally {
|
|
478
|
+
clearTimeout(timer);
|
|
504
479
|
}
|
|
505
480
|
}
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
for (const prop of props) {
|
|
509
|
-
if (a[prop] !== b[prop]) {
|
|
510
|
-
return false;
|
|
511
|
-
}
|
|
481
|
+
getRemoteSlashCommands() {
|
|
482
|
+
return this.#registration.read("global");
|
|
512
483
|
}
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
function optionEqual(a, b) {
|
|
516
|
-
if (a.name !== b.name || a.description !== b.description || a.required !== !!b.required || a.type !== b.type) {
|
|
517
|
-
return false;
|
|
518
|
-
}
|
|
519
|
-
if (!!("choices" in a && a.choices) !== !!("choices" in b && b.choices)) {
|
|
520
|
-
return false;
|
|
521
|
-
} else if ("choices" in a && a.choices && "choices" in b && b.choices) {
|
|
522
|
-
if (a.choices.length !== b.choices.length) {
|
|
523
|
-
return false;
|
|
524
|
-
}
|
|
525
|
-
for (let i = 0; i < a.choices.length; i++) {
|
|
526
|
-
if (a.choices[i].name !== b.choices[i].name || a.choices[i].value !== b.choices[i].value) {
|
|
527
|
-
return false;
|
|
528
|
-
}
|
|
529
|
-
}
|
|
484
|
+
diffRemoteSlashCommands(commands = this.#slashCommands, _forceRefresh = false) {
|
|
485
|
+
return this.#registration.diff(this.#registrationPlan(commands));
|
|
530
486
|
}
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
return false;
|
|
534
|
-
} else if ("min" in a && "min_value" in b && a.min !== b.min_value) {
|
|
535
|
-
return false;
|
|
536
|
-
}
|
|
487
|
+
#registrationPlan(commands = this.#slashCommands, guilds) {
|
|
488
|
+
return planRegistrations(commands, this.#contextMenus, guilds ?? this.#configuredGuilds());
|
|
537
489
|
}
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
490
|
+
async syncCommandRegistrations(options = {}) {
|
|
491
|
+
const configured = this.#configuredGuilds();
|
|
492
|
+
const guilds = options.guilds ?? configured;
|
|
493
|
+
const results = await this.#registration.sync(this.#registrationPlan(this.#slashCommands, guilds), options.changedOnly);
|
|
494
|
+
for (const { scope, error } of results) {
|
|
495
|
+
if (scope === "global" || error)
|
|
496
|
+
continue;
|
|
497
|
+
if (guilds.includes(scope) === configured.includes(scope))
|
|
498
|
+
this.#registeredGuildOverrides.delete(scope);
|
|
499
|
+
else
|
|
500
|
+
this.#registeredGuildOverrides.set(scope, guilds.includes(scope));
|
|
543
501
|
}
|
|
502
|
+
return results;
|
|
544
503
|
}
|
|
545
|
-
|
|
546
|
-
|
|
504
|
+
async registerSlashCommands(guilds) {
|
|
505
|
+
const results = await this.syncCommandRegistrations({ guilds });
|
|
506
|
+
const errors = results.filter((result) => result.error);
|
|
507
|
+
if (errors.length)
|
|
508
|
+
throw new Error(errors.map((result) => `${result.scope}: ${result.error}`).join(", "));
|
|
509
|
+
return results.flatMap((result) => result.commands);
|
|
547
510
|
}
|
|
548
|
-
return true;
|
|
549
511
|
}
|
|
550
512
|
export function isPromise(value) {
|
|
551
513
|
return typeof value?.then === "function";
|