This repository has been archived by the owner on Aug 10, 2022. It is now read-only.
/
gatekeeper.ts
383 lines (338 loc) · 10.8 KB
/
gatekeeper.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
import chalk from "chalk"
import type {
ApplicationCommand,
BaseCommandInteraction,
Client,
Collection,
Guild,
MessageComponentInteraction,
} from "discord.js"
import glob from "fast-glob"
import { relative } from "node:path"
import { raise, toError } from "../internal/helpers"
import { loadFile } from "../internal/load-file"
import type { ConsoleLoggerLevel, Logger } from "../internal/logger"
import { createConsoleLogger, createNoopLogger } from "../internal/logger"
import type { DiscordCommandManager } from "../internal/types"
import type { Command } from "./command/command"
import { CommandInstance } from "./command/command"
import type { MessageCommandConfig } from "./command/message-command"
import { createMessageCommands } from "./command/message-command"
import type {
SlashCommandConfig,
SlashCommandOptionConfigMap,
} from "./command/slash-command"
import { createSlashCommands } from "./command/slash-command"
import type { UserCommandConfig } from "./command/user-command"
import { createUserCommands } from "./command/user-command"
/** Options for creating a gatekeeper instance */
export type GatekeeperConfig = {
/** A Discord.JS client */
client: Client
/** The name of the bot, used for logger messages */
name?: string
/** Show colorful debug logs in the console */
logging?: boolean | ConsoleLoggerLevel[]
/**
* An *absolute path* to a folder with command files.
* Each file should `export default` a function to accept a gatekeeper instance
* and add commands to it.
*
* ```ts
* // main.ts
* Gatekeeper.create({
* commandFolder: join(__dirname, "commands"),
* })
* ```
* ```ts
* // commands/ping.ts
* export default function addCommands(gatekeeper) {
* gatekeeper.addCommand({
* name: "ping",
* description: "Pong!",
* run: (ctx) => ctx.reply(() => "Pong!"),
* })
* }
* ```
*/
commandFolder?: string
/**
* Where commands should be registered.
*
* `guild` - Register commands in all guilds (servers) that the bot joins, which appear immediately.
* This is the default, and recommended for testing, or if your bot is just in a few guilds.
*
* `global` - Register commands globally, which can take a few minutes or an hour to show up.
* Since bots have a global command limit, this is good for when your bot grows beyond just a few servers.
*
* `both` - Register commands in both guilds and globally.
*
* See the discord docs for more info: https://discord.com/developers/docs/interactions/application-commands#registering-a-command
*/
scope?: "guild" | "global" | "both"
/**
* Called when any error occurs.
* You can use this to log your own errors, send them to an error reporting service, etc.
*/
onError?: (error: Error) => void
}
/** Basic information about the commands currently added */
export type CommandInfo = {
/** The name of the command */
name: string
}
/**
* A gatekeeper instance.
* Holds commands, manages discord interactions, etc.
*/
export class Gatekeeper {
private readonly commands = new Set<Command>()
private readonly commandInstances = new Set<CommandInstance>()
private constructor(
private readonly config: GatekeeperConfig,
private readonly logger: Logger,
) {}
/** Create a {@link Gatekeeper} instance */
static async create(config: GatekeeperConfig) {
const logger = createGatekeeperLogger(config)
const instance = new Gatekeeper(config, logger)
if (config.commandFolder) {
await instance.loadCommandsFromFolder(config.commandFolder)
}
instance.addEventListeners(config.client, config.scope ?? "guild")
return instance
}
/** Returns a list of basic info for each added command */
getCommands(): readonly CommandInfo[] {
return [...this.commands]
}
/**
* Add a slash command
* ```ts
* gatekeeper.addSlashCommand({
* name: "ping",
* description: "Pong!",
* run: (ctx) => ctx.reply(() => "Pong!"),
* })
* ```
*/
addSlashCommand<Options extends SlashCommandOptionConfigMap>(
config: SlashCommandConfig<Options>,
) {
this.addCommands(createSlashCommands(config))
}
/**
* Add a user command
* ```ts
* gatekeeper.addUserCommand({
* name: 'get user color',
* run: (ctx) => ctx.reply(() => ctx.targetGuildMember?.color ?? "not in a guild!"),
* })
* ```
*/
addUserCommand(config: UserCommandConfig) {
this.addCommands(createUserCommands(config))
}
/**
* Add a message command
* ```ts
* gatekeeper.addMessageCommand({
* name: 'reverse',
* run: (ctx) => {
* ctx.reply(() => ctx.targetMessage.content.split("").reverse().join(""))
* }
* })
* ```
*/
addMessageCommand(config: MessageCommandConfig) {
this.addCommands(createMessageCommands(config))
}
private addCommands(commands: Command[]) {
for (const command of commands) {
this.commands.add(command)
}
}
private addEventListeners(
client: Client,
scope: NonNullable<GatekeeperConfig["scope"]>,
) {
client.on(
"ready",
this.withErrorHandler(async () => {
const commandList = [...this.commands]
.map((command) => chalk.bold(command.name))
.join(", ")
this.logger.success(`Using commands: ${commandList}`)
for (const guild of client.guilds.cache.values()) {
if (scope === "guild" || scope === "both") {
await this.syncGuildCommands(guild)
} else {
await this.removeAllCommands(
await guild.commands.fetch(),
`in ${guild.name}`,
)
}
}
if (scope === "global" || scope === "both") {
await this.syncGlobalCommands(client)
} else if (client.application) {
await this.removeAllCommands(
await client.application.commands.fetch(),
"globally",
)
}
}),
)
client.on(
"guildCreate",
this.withErrorHandler(async (guild) => {
if (scope === "guild" || scope === "both") {
await this.syncGuildCommands(guild)
} else {
await this.removeAllCommands(
await guild.commands.fetch(),
`in ${guild.name}`,
)
}
}),
)
client.on(
"interactionCreate",
this.withErrorHandler(async (interaction) => {
if (interaction.isCommand() || interaction.isContextMenu()) {
await this.handleCommandInteraction(interaction)
}
if (interaction.isMessageComponent()) {
await this.handleComponentInteraction(interaction)
}
}),
)
}
private async loadCommandsFromFolder(folderPath: string) {
// backslashes are ugly
const localPath = relative(process.cwd(), folderPath).replace(/\\/g, "/")
await this.logger.block(`Loading commands from ${localPath}`, async () => {
const files = await glob(`./**/*.{ts,tsx,js,jsx,mjs,cjs,mts,cts}`, {
cwd: folderPath,
absolute: true,
})
await Promise.all(
files.map(async (path) => {
const mod = await loadFile(path)
const fn = mod.default || mod
if (typeof fn === "function") fn(this)
}),
)
})
}
private async syncGuildCommands(guild: Guild) {
await this.logger.block(`Syncing commands for ${guild.name}`, async () => {
await this.syncCommands(
`in ${guild.name}`,
guild.commands,
await guild.commands.fetch(),
)
})
}
private async syncGlobalCommands(client: Client) {
await this.logger.block(`Syncing global commands`, async () => {
const commandManager =
client.application?.commands ?? raise("No client application found")
await this.syncCommands(
`globally`,
commandManager,
await commandManager.fetch(),
)
})
}
private async syncCommands(
scope: string,
commandManager: DiscordCommandManager,
remoteCommands: Collection<string, ApplicationCommand>,
) {
// remove commands first,
// just in case we've hit the max number of commands
await this.removeUnusedRemoteCommand(remoteCommands)
await this.updateChangedCommands(scope, commandManager, remoteCommands)
}
private async removeUnusedRemoteCommand(
remoteCommands: Collection<string, ApplicationCommand<{}>>,
) {
const localCommandNames = new Set([...this.commands].map((c) => c.name))
const unusedRemoteCommands = remoteCommands.filter(
(command) => !localCommandNames.has(command.name),
)
for (const [, command] of unusedRemoteCommands) {
await command.delete()
}
}
private async updateChangedCommands(
scope: string,
commandManager: DiscordCommandManager,
remoteCommands: Collection<string, ApplicationCommand<{}>>,
) {
for (const command of this.commands) {
const isExisting = remoteCommands.some((appCommand) => {
return command.matchesExisting(appCommand)
})
if (!isExisting) {
await command.register(commandManager)
this.logger.info(`Created ${scope}: ${chalk.bold(command.name)}`)
}
}
}
private async removeAllCommands(
commands: Collection<string, ApplicationCommand>,
scope: string,
) {
if (commands.size === 0) return
await this.logger.block(`Removing all commands ${scope}`, async () => {
for (const [, command] of commands) {
await command.delete()
}
})
}
private async handleCommandInteraction(interaction: BaseCommandInteraction) {
const command = [...this.commands.values()].find((command) =>
command.matchesInteraction(interaction),
)
if (!command) return
const instance = new CommandInstance(command, this.logger)
this.commandInstances.add(instance)
try {
await command.run(interaction, instance)
} catch (error) {
this.logger.error(`Error running command`, chalk.bold(command.name))
this.logger.error(error)
this.config.onError?.(toError(error))
}
}
private async handleComponentInteraction(
interaction: MessageComponentInteraction,
) {
for (const context of this.commandInstances) {
if (await context.handleComponentInteraction(interaction)) return
}
}
private withErrorHandler<Args extends unknown[], Return>(
fn: (...args: Args) => Promise<Return> | Return,
) {
return async (...args: Args) => {
try {
return await fn(...args)
} catch (error) {
this.logger.error("An error occurred:", error)
this.config.onError?.(toError(error))
}
}
}
}
export function createGatekeeperLogger(config: GatekeeperConfig) {
if (config.logging === true || config.logging == null) {
return createConsoleLogger({ name: config.name })
}
if (!config.logging) {
return createNoopLogger()
}
return createConsoleLogger({ name: config.name, levels: config.logging })
}