aboutsummaryrefslogtreecommitdiff
path: root/src/commands/config/config.ts
blob: adc41d89a9ad8dfe1907e7753c5931259e295bec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
import {
	addOrRemoveFromArray,
	BotCommand,
	colors,
	emojis,
	formatList,
	GuildNoArraySetting,
	guildSettingsObj,
	settingsArr,
	type ArgType,
	type CommandMessage,
	type GuildSettings,
	type GuildSettingType,
	type SlashMessage
} from '#lib';
import assert from 'assert/strict';
import { type ArgumentGeneratorReturn, type SlashOption } from 'discord-akairo';
import {
	ActionRowBuilder,
	ApplicationCommandOptionType,
	BaseChannel,
	ButtonBuilder,
	ButtonStyle,
	EmbedBuilder,
	GuildMember,
	InteractionUpdateOptions,
	italic,
	PermissionFlagsBits,
	Role,
	SelectMenuBuilder,
	SelectMenuOptionBuilder,
	User,
	type Message,
	type MessageComponentInteraction,
	type MessageOptions
} from 'discord.js';
import _ from 'lodash';
const { camelCase, snakeCase } = _;

export const arrayActions = ['view' as const, 'add' as const, 'remove' as const, 'clear' as const];
export type ArrayActions = typeof arrayActions[number];
export const actionsString = ['view' as const, 'set' as const, 'delete' as const];
export type ActionsString = typeof actionsString[number];
export const allActions = [...arrayActions, ...actionsString];
export type Action = typeof allActions[number];
type SlashArgType = 'ROLE' | 'STRING' | 'CHANNEL' | 'USER';
type BaseSettingTypes = 'string' | 'channel' | 'role' | 'user' | 'custom';

export default class ConfigCommand extends BotCommand {
	public constructor() {
		super('config', {
			aliases: ['config', 'settings', 'setting', 'configure'],
			category: 'config',
			description: 'Configure server settings.',
			usage: [`settings (${settingsArr.map((s) => `'${s}'`).join(', ')}) (${allActions.map((s) => `'${s}'`)})`],
			examples: ['settings', 'config prefix set -'],
			slash: true,
			slashOptions: settingsArr.map((setting): SlashOption => {
				const obj = guildSettingsObj[setting];
				const type = obj.type;
				const baseTypeUpper = type.replace('-array', '').toUpperCase() as SlashArgType;
				const isArray = type.includes('-array');
				const loweredName = obj.name.toLowerCase();

				const enumType =
					baseTypeUpper === 'CHANNEL'
						? ApplicationCommandOptionType.Channel
						: baseTypeUpper === 'ROLE'
						? ApplicationCommandOptionType.Role
						: baseTypeUpper === 'STRING'
						? ApplicationCommandOptionType.String
						: baseTypeUpper === 'USER'
						? ApplicationCommandOptionType.User
						: new Error(`Unknown type: ${type}`);
				if (enumType instanceof Error) throw enumType;

				return {
					name: snakeCase(setting),
					description: `Manage the server's ${loweredName}`,
					type: ApplicationCommandOptionType.SubcommandGroup,
					options: isArray
						? [
								{
									name: 'view',
									description: `View the server's ${loweredName}.`,
									type: ApplicationCommandOptionType.Subcommand
								},
								{
									name: 'add',
									description: `Add a value to the server's ${loweredName}.`,
									type: ApplicationCommandOptionType.Subcommand,
									options: [
										{
											name: 'value',
											description: `What would you like to add to the server's ${loweredName}?'`,
											type: enumType,
											channelTypes: baseTypeUpper === 'CHANNEL' && obj.subType ? obj.subType : undefined,
											required: true
										}
									]
								},
								{
									name: 'remove',
									description: `Remove a value from the server's ${loweredName}.`,
									type: ApplicationCommandOptionType.Subcommand,
									options: [
										{
											name: 'value',
											description: `What would you like to remove from the server's ${loweredName}?'`,
											type: enumType,
											channelTypes: baseTypeUpper === 'CHANNEL' && obj.subType ? obj.subType : undefined,
											required: true
										}
									]
								},
								{
									name: 'clear',
									description: `Remove all values from a server's ${loweredName}.`,
									type: ApplicationCommandOptionType.Subcommand
								}
						  ]
						: [
								{
									name: 'view',
									description: `View the server's ${loweredName}.`,
									type: ApplicationCommandOptionType.Subcommand
								},
								{
									name: 'set',
									description: `Set the server's ${loweredName}.`,
									type: ApplicationCommandOptionType.Subcommand,
									options: [
										{
											name: 'value',
											description: `What would you like to set the server's ${loweredName} to?'`,
											type: enumType,
											channelTypes: baseTypeUpper === 'CHANNEL' && obj.subType ? obj.subType : undefined,
											required: true
										}
									]
								},
								{
									name: 'delete',
									description: `Delete the server's ${loweredName}.`,
									type: ApplicationCommandOptionType.Subcommand
								}
						  ]
				};
			}),
			channel: 'guild',
			clientPermissions: [],
			userPermissions: ['ManageGuild']
		});
	}

	public override *args(message: CommandMessage): ArgumentGeneratorReturn {
		const optional = message.util.parsed!.alias === 'settings';
		const setting: GuildSettings = yield {
			id: 'setting',
			type: settingsArr,
			prompt: {
				start: `What setting would you like to see or change? You can choose one of the following: ${settingsArr
					.map((s) => `\`${s}\``)
					.join(', ')}`,
				retry: `{error} Choose one of the following settings: ${settingsArr.map((s) => `\`${s}\``).join(', ')}`,
				optional
			}
		};

		const actionType = setting ? (this.isArrayType(guildSettingsObj[setting].type) ? arrayActions : actionsString) : undefined;

		const action: Action = setting
			? yield {
					id: 'action',
					type: actionType,
					prompt: {
						start: `Would you like to ${formatList(
							actionType!.map((a) => `\`${a}\``),
							'or'
						)} the \`${setting}\` setting?`,
						retry: `{error} Choose one of the following actions to perform on the ${setting} setting: ${formatList(
							actionType!.map((a) => `\`${a}\``),
							'or'
						)}`,
						optional
					}
			  }
			: undefined;

		const valueType = setting && action && action !== 'view' ? this.baseType(guildSettingsObj[setting].type) : undefined;

		const grammar = this.grammar(action, setting);

		const value: typeof valueType =
			setting && action !== 'view'
				? yield {
						id: 'value',
						type: valueType,
						match: 'restContent',
						prompt: {
							start: `What would you like to ${action} ${grammar}?`,
							retry: `{error} You must choose a ${valueType === 'string' ? 'value' : valueType} to ${action} ${grammar}.`,
							optional
						}
				  }
				: undefined;

		return { setting, action, value };
	}

	public override async exec(
		message: CommandMessage | SlashMessage,
		args: {
			setting?: GuildSettings;
			subcommandGroup?: GuildSettings;
			action?: Action;
			subcommand?: Action;
			value: ArgType<'channel' | 'role'> | string;
		}
	) {
		assert(message.inGuild());
		assert(message.member);

		if (!message.member.permissions.has(PermissionFlagsBits.ManageGuild) && !message.member?.user.isOwner())
			return await message.util.reply(`${emojis.error} You must have the **Manage Server** permission to run this command.`);
		const setting = message.util.isSlash ? (camelCase(args.subcommandGroup)! as GuildSettings) : args.setting!;
		const action = message.util.isSlash ? args.subcommand! : args.action!;
		const value = args.value;

		let msg: Message;

		if (!setting || action === 'view') {
			const messageOptions = await this.generateMessageOptions(message, setting ?? undefined);
			msg = (await message.util.reply(messageOptions)) as Message;
		} else {
			const parseVal = (val: string | BaseChannel | Role | User | GuildMember) => {
				if (val instanceof BaseChannel || val instanceof Role || val instanceof User || val instanceof GuildMember) {
					return val.id;
				}
				return val;
			};

			if (!value && !(['clear', 'delete'] as const).includes(action))
				return await message.util.reply(`${emojis.error} You must choose a value to ${action} ${this.grammar(action, setting)}`);

			switch (action) {
				case 'add':
				case 'remove': {
					const existing = (await message.guild.getSetting(setting)) as string[];
					const updated = addOrRemoveFromArray(action, existing, parseVal(value));
					await message.guild.setSetting(setting, updated, message.member);
					const messageOptions = await this.generateMessageOptions(message, setting);
					msg = (await message.util.reply(messageOptions)) as Message;
					break;
				}
				case 'set': {
					await message.guild.setSetting(setting, parseVal(value), message.member);
					const messageOptions = await this.generateMessageOptions(message, setting);
					msg = (await message.util.reply(messageOptions)) as Message;
					break;
				}
				case 'clear': {
					await message.guild.setSetting(setting, [], message.member);
					const messageOptions = await this.generateMessageOptions(message, setting);
					msg = (await message.util.reply(messageOptions)) as Message;
					break;
				}
				case 'delete': {
					await message.guild.setSetting(setting, guildSettingsObj[setting].replaceNullWith(), message.member);
					const messageOptions = await this.generateMessageOptions(message, setting);
					msg = (await message.util.reply(messageOptions)) as Message;
					break;
				}
			}
		}

		const collector = msg.createMessageComponentCollector({
			time: 300_000,
			filter: (i) => i.guildId === msg.guildId && i.message?.id === msg.id
		});

		collector.on('collect', async (interaction: MessageComponentInteraction) => {
			if (interaction.user.id === message.author.id || this.client.config.owners.includes(interaction.user.id)) {
				assert(message.inGuild());

				switch (interaction.customId) {
					case 'command_settingsSel': {
						if (!interaction.isSelectMenu()) return;

						await interaction.update(
							await this.generateMessageOptions(message, interaction.values[0] as keyof typeof guildSettingsObj)
						);
						return;
					}
					case 'command_settingsBack': {
						if (!interaction.isButton()) return;

						await interaction.update(await this.generateMessageOptions(message));
						return;
					}
				}
			} else {
				await interaction?.deferUpdate().catch(() => undefined);
				return;
			}
		});
	}

	public async generateMessageOptions(
		message: CommandMessage | SlashMessage,
		setting?: undefined | keyof typeof guildSettingsObj
	): Promise<MessageOptions & InteractionUpdateOptions> {
		assert(message.inGuild());

		const settingsEmbed = new EmbedBuilder().setColor(colors.default);
		if (!setting) {
			settingsEmbed.setTitle(`${message.guild.name}'s Settings`);
			const desc = settingsArr.map((s) => `:wrench: **${guildSettingsObj[s].name}**`).join('\n');
			settingsEmbed.setDescription(desc);

			const selMenu = new ActionRowBuilder<SelectMenuBuilder>().addComponents(
				new SelectMenuBuilder()
					.addOptions(
						settingsArr.map((s) =>
							new SelectMenuOptionBuilder()
								.setLabel(guildSettingsObj[s].name)
								.setValue(s)
								.setDescription(guildSettingsObj[s].description)
						)
					)
					.setPlaceholder('Select A Setting to View')
					.setMaxValues(1)
					.setMinValues(1)
					.setCustomId('command_settingsSel')
			);
			return { embeds: [settingsEmbed], components: [selMenu] };
		} else {
			settingsEmbed.setTitle(guildSettingsObj[setting].name);
			const generateCurrentValue = async (type: GuildSettingType): Promise<string> => {
				const feat = await message.guild.getSetting(setting);

				const func = ((): ((v: string | any) => string) => {
					switch (type.replace('-array', '') as BaseSettingTypes) {
						case 'string':
							return (v) => this.client.utils.inspectAndRedact(v);
						case 'channel':
							return (v) => `<#${v}>`;
						case 'role':
							return (v) => `<@&${v}>`;
						case 'user':
							return (v) => `<@${v}>`;
						case 'custom':
							return this.client.utils.inspectAndRedact;
						default:
							return (v) => v;
					}
				})();

				return Array.isArray(feat)
					? feat.length
						? (<any[]>feat).map((v) => func(v)).join('\n')
						: '[Empty Array]'
					: feat !== null
					? func(feat)
					: '[No Value Set]';
			};

			const components = new ActionRowBuilder<ButtonBuilder>().addComponents(
				new ButtonBuilder({ style: ButtonStyle.Primary, customId: 'command_settingsBack', label: 'Back' })
			);
			settingsEmbed.setDescription(
				`${italic(guildSettingsObj[setting].description)}\n\n**Type:** ${guildSettingsObj[setting].type}`
			);

			settingsEmbed.setFooter({
				text: `Run "${this.client.utils.prefix(message)}${message.util.parsed?.alias ?? 'config'} ${
					message.util.isSlash ? snakeCase(setting) : setting
				} ${guildSettingsObj[setting].type.includes('-array') ? 'add/remove' : 'set'} <value>" to set this setting.`
			});
			settingsEmbed.addFields({
				name: 'value',
				value: (await generateCurrentValue(guildSettingsObj[setting].type)) || '[No Value Set]'
			});
			return { embeds: [settingsEmbed], components: [components] };
		}
	}

	private isArrayType(type: GuildSettingType): boolean {
		return type.includes('-array');
	}

	private baseType(type: GuildSettingType): GuildNoArraySetting {
		return type.replace('-array', '') as GuildNoArraySetting;
	}

	private grammar(action: Action, setting: GuildSettings) {
		if (!setting || !action || action === 'view') return undefined;

		switch (action) {
			case 'add':
				return `to the ${setting} setting`;
			case 'remove':
				return `from the ${setting} setting`;
			case 'set':
				return `the ${setting} setting to`;
			case 'clear':
			case 'delete':
				return `the ${setting} setting`;
		}
	}
}