-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathindex.ts
332 lines (297 loc) · 9.39 KB
/
index.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
// we need to await in a loop as we're rate-limited anyway
/* eslint-disable no-await-in-loop */
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import type {
ApplicationCommand,
ApplicationCommandData,
ApplicationCommandManager,
Client,
Guild,
GuildApplicationCommandManager,
GuildResolvable,
ApplicationCommandType,
} from 'discord.js';
import { Collection } from 'discord.js';
import { ApplicationCommandTypes } from 'discord.js/typings/enums';
import { filter } from 'domyno';
import { isEqual } from 'lodash-es';
import type { CommandDataWithHandler } from '../../types';
import { modmailCommands } from '../modules/modmail';
import { asyncCatch } from '../utils/asyncCatch.js';
import { map, mapʹ } from '../utils/map.js';
import { merge } from '../utils/merge.js';
import { normalizeApplicationCommandData } from '../utils/normalizeCommand.js';
import { pipe } from '../utils/pipe.js';
import { difference, intersection } from '../utils/sets.js';
// quick responses
// base commands
import { aboutInteraction } from './about/index.js';
import { mdnCommand } from './mdn/index.js';
import { npmInteraction } from './npm/index.js';
import { phpCommand } from './php/index.js';
import { pleaseInteraction } from './please/index.js';
import { pointsHandlers } from './points/index.js';
import { jobPostCommand } from './post/index.js';
import { resourceInteraction } from './resource/index.js';
// meme commands
import { shitpostInteraction } from './shitpost/index.js';
// import { warn } from './warn/index.js';
import { whynoInteraction } from './whyno/index.js';
export const guildCommands = new Map(
[
aboutInteraction,
mdnCommand,
phpCommand,
pleaseInteraction,
pointsHandlers,
jobPostCommand,
resourceInteraction,
shitpostInteraction,
npmInteraction,
whynoInteraction,
...modmailCommands,
// warn // Not used atm
].map(command => [command.name, command])
); // placeholder for now
export const applicationCommands = new Collection<
string,
CommandDataWithHandler
>();
const getRelevantCmdProperties = ({
description,
name,
type = ApplicationCommandTypes.CHAT_INPUT,
options,
defaultPermission = true,
}: {
type?: ApplicationCommandTypes | ApplicationCommandType;
description?: string;
name: string;
options?: unknown[];
defaultPermission?: boolean;
}): ApplicationCommandData => {
const relevantData = {
type: _normalizeType(type),
description,
name,
options,
defaultPermission,
} as unknown as ApplicationCommandData;
return stripNullish(normalizeApplicationCommandData(relevantData));
};
const stripNullish = <T>(obj: T): T => {
if (typeof obj !== 'object' && obj !== null) {
return obj;
}
if (Array.isArray(obj)) {
return obj.map(stripNullish) as typeof obj;
}
return Object.fromEntries(
Object.entries(obj)
.map(([a, b]) => [a, stripNullish(b)])
.filter(([, b]) => b != null)
) as T;
};
export const registerCommands = async (client: Client): Promise<void> => {
client.on(
'interactionCreate',
asyncCatch(async interaction => {
if (!interaction.isCommand() && !interaction.isContextMenu()) {
return;
}
try {
if (applicationCommands.has(interaction.commandName)) {
await applicationCommands
.get(interaction.commandName)
?.handler(client, interaction);
} else if (guildCommands.has(interaction.commandName)) {
await guildCommands
.get(interaction.commandName)
?.handler(client, interaction);
} else {
await interaction.reply({
ephemeral: true,
content: "Couldn't recognize command.",
});
}
} catch (error) {
console.error(error);
if (interaction.deferred) {
await interaction.editReply({
content: 'Something went wrong when trying to execute the command',
});
} else {
await interaction.reply({
ephemeral: true,
content: 'Something went wrong when trying to execute the command',
});
}
}
})
);
for (const { onAttach } of applicationCommands.values()) {
// We're attaching these so it's fine
onAttach?.(client);
}
for (const { onAttach } of guildCommands.values()) {
// We're attaching these so it's fine
onAttach?.(client);
}
for (const [, oauth2Guild] of await client.guilds.fetch()) {
let guild: { name: string } | Guild = { name: 'FAILED_TO_FETCH_GUILD' };
try {
guild = await oauth2Guild.fetch();
const cmds = await (guild as Guild).commands.fetch();
await addCommands(cmds, guildCommands, (guild as Guild).commands);
} catch (error) {
console.error(`Failed to add commands to guild: ${guild.name}`, error);
}
}
console.log('Guild specific commands added');
const discordCommandsById = await client.application.commands.fetch();
await addCommands(
discordCommandsById,
applicationCommands,
client.application.commands
);
console.log('General Commands All Added');
// await client.application?.commands.set([{type:''}])
// await client.guilds.cache.get('618935554171469834').commands.set([]);
// client.guilds.cache.forEach(guild => {
// guild.commands.set([])
// })
};
function _normalizeType(
type: ApplicationCommandType | ApplicationCommandTypes
) {
if (typeof type === 'number') {
return type;
}
switch (type) {
case 'MESSAGE':
return ApplicationCommandTypes.MESSAGE;
case 'USER':
return ApplicationCommandTypes.USER;
case 'CHAT_INPUT':
default:
return ApplicationCommandTypes.CHAT_INPUT;
}
}
const interactionTypes = new Set(['CHAT_INPUT','USER','MESSAGE'])
async function addCommands(
serverCommands: Collection<
string,
ApplicationCommand
>,
commandDescriptions: Map<string, CommandDataWithHandler>,
commandManager: ApplicationCommandManager | GuildApplicationCommandManager
) {
const discordInteractionsById = serverCommands.filter(
x => interactionTypes.has(x.type)
);
const discordCommands = new Collection(
discordInteractionsById.map(value => [value.name, value])
);
const validCommands = pipe([
filter<[string, CommandDataWithHandler]>(
([, val]: [string, CommandDataWithHandler]) =>
'guild' in commandManager && val.guildValidate
? val.guildValidate(commandManager.guild)
: true
),
map(([key]): string => key),
]);
const newCommands = difference(
validCommands(commandDescriptions),
discordCommands.keys()
);
const existingCommands = intersection(
validCommands(commandDescriptions),
discordCommands.keys()
);
const deletedCommands = difference<string>(
discordCommands.keys(),
validCommands(commandDescriptions)
);
// const new = await client.application.commands.create()
await Promise.all(
merge(
createNewCommands(commandDescriptions, commandManager)(newCommands),
editExistingCommands(
commandDescriptions,
commandManager,
discordCommands
)(existingCommands),
deleteRemovedCommands(commandManager, discordCommands)(deletedCommands)
)
);
}
function getDestination(
commandManager: ApplicationCommandManager | GuildApplicationCommandManager
) {
return 'guild' in commandManager
? `Guild: ${commandManager.guild.name}`
: 'App';
}
function createNewCommands(
cmdDescriptions: Map<string, CommandDataWithHandler>,
cmdMgr: ApplicationCommandManager | GuildApplicationCommandManager
) {
const destination = getDestination(cmdMgr);
return map(async (name: string) => {
const command = cmdDescriptions.get(name);
// this is always true
if (command) {
const { onAttach, handler, managePermissions, ...rest } = command;
console.info(`Adding Command ${name} for ${destination}`);
const guildCmd = await cmdMgr.create(rest);
const { permissions, guild } = guildCmd;
// await managePermissions?.(guild, permissions);
}
});
}
function editExistingCommands(
cmdDescriptions: Map<string, CommandDataWithHandler>,
cmdMgr: ApplicationCommandManager | GuildApplicationCommandManager,
existingCommands: Map<string, ApplicationCommand>
) {
const destination = getDestination(cmdMgr);
return map(async (name: string) => {
const cmd = cmdDescriptions.get(name);
const existing = existingCommands.get(name);
const { onAttach, handler, managePermissions, ...comm } = cmd;
const command = {
defaultPermission: true,
...comm,
}
if (
!isEqual(
getRelevantCmdProperties(cmd),
getRelevantCmdProperties(existing)
)
) {
console.info(`Updating ${name} for ${destination}`);
console.log(
getRelevantCmdProperties(cmd),
getRelevantCmdProperties(existing))
await cmdMgr.edit(existing.id, command);
}
// try {
// const { permissions, guild } = existing;
// await managePermissions?.(guild, permissions);
// } catch (error) {
// console.log({ error });
// }
});
}
function deleteRemovedCommands(
cmdMgr: ApplicationCommandManager | GuildApplicationCommandManager,
existingCommands: Map<string, ApplicationCommand>
) {
const destination = getDestination(cmdMgr);
return map(async (name: string) => {
const existing = existingCommands.get(name)!;
console.warn(`Deleting ${name} from ${destination}`);
await cmdMgr.delete(existing.id);
});
}