aboutsummaryrefslogtreecommitdiff
path: root/src/lib/extensions/discord.js/ExtendedGuild.ts
blob: c58916cc10613696c01a008aaa7a0e6b86b6a729 (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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
import {
	AllowedMentions,
	banResponse,
	colors,
	dmResponse,
	emojis,
	permissionsResponse,
	punishmentEntryRemove,
	type BanResponse,
	type GuildFeatures,
	type GuildLogType,
	type GuildModel
} from '#lib';
import {
	AttachmentBuilder,
	AttachmentPayload,
	Collection,
	Guild,
	JSONEncodable,
	Message,
	MessageType,
	PermissionFlagsBits,
	SnowflakeUtil,
	ThreadChannel,
	type APIMessage,
	type GuildMember,
	type GuildMemberResolvable,
	type GuildTextBasedChannel,
	type MessageOptions,
	type MessagePayload,
	type NewsChannel,
	type Snowflake,
	type TextChannel,
	type User,
	type UserResolvable,
	type VoiceChannel,
	type Webhook,
	type WebhookMessageOptions
} from 'discord.js';
import _ from 'lodash';
import * as Moderation from '../../common/util/Moderation.js';
import { Guild as GuildDB } from '../../models/instance/Guild.js';
import { ModLogType } from '../../models/instance/ModLog.js';
import { addOrRemoveFromArray } from '../../utils/BushUtils.js';

declare module 'discord.js' {
	export interface Guild {
		/**
		 * Checks if the guild has a certain custom feature.
		 * @param feature The feature to check for
		 */
		hasFeature(feature: GuildFeatures): Promise<boolean>;
		/**
		 * Adds a custom feature to the guild.
		 * @param feature The feature to add
		 * @param moderator The moderator responsible for adding a feature
		 */
		addFeature(feature: GuildFeatures, moderator?: GuildMember): Promise<GuildDB['enabledFeatures']>;
		/**
		 * Removes a custom feature from the guild.
		 * @param feature The feature to remove
		 * @param moderator The moderator responsible for removing a feature
		 */
		removeFeature(feature: GuildFeatures, moderator?: GuildMember): Promise<GuildDB['enabledFeatures']>;
		/**
		 * Makes a custom feature the opposite of what it was before
		 * @param feature The feature to toggle
		 * @param moderator The moderator responsible for toggling a feature
		 */
		toggleFeature(feature: GuildFeatures, moderator?: GuildMember): Promise<GuildDB['enabledFeatures']>;
		/**
		 * Fetches a custom setting for the guild
		 * @param setting The setting to get
		 */
		getSetting<K extends keyof GuildModel>(setting: K): Promise<GuildModel[K]>;
		/**
		 * Sets a custom setting for the guild
		 * @param setting The setting to change
		 * @param value The value to change the setting to
		 * @param moderator The moderator to responsible for changing the setting
		 */
		setSetting<K extends Exclude<keyof GuildModel, 'id'>>(
			setting: K,
			value: GuildModel[K],
			moderator?: GuildMember
		): Promise<GuildModel>;
		/**
		 * Get a the log channel configured for a certain log type.
		 * @param logType The type of log channel to get.
		 * @returns Either the log channel or undefined if not configured.
		 */
		getLogChannel(logType: GuildLogType): Promise<TextChannel | undefined>;
		/**
		 * Sends a message to the guild's specified logging channel
		 * @param logType The corresponding channel that the message will be sent to
		 * @param message The parameters for {@link BushTextChannel.send}
		 */
		sendLogChannel(logType: GuildLogType, message: string | MessagePayload | MessageOptions): Promise<Message | null | undefined>;
		/**
		 * Sends a formatted error message in a guild's error log channel
		 * @param title The title of the error embed
		 * @param message The description of the error embed
		 */
		error(title: string, message: string): Promise<void>;
		/**
		 * Bans a user, dms them, creates a mod log entry, and creates a punishment entry.
		 * @param options Options for banning the user.
		 * @returns A string status message of the ban.
		 */
		bushBan(options: GuildBushBanOptions): Promise<BanResponse>;
		/**
		 * {@link bushBan} with less resolving and checks
		 * @param options Options for banning the user.
		 * @returns A string status message of the ban.
		 * **Preconditions:**
		 * - {@link me} has the `BanMembers` permission
		 * **Warning:**
		 * - Doesn't emit bushBan Event
		 */
		massBanOne(options: GuildMassBanOneOptions): Promise<BanResponse>;
		/**
		 * Unbans a user, dms them, creates a mod log entry, and destroys the punishment entry.
		 * @param options Options for unbanning the user.
		 * @returns A status message of the unban.
		 */
		bushUnban(options: GuildBushUnbanOptions): Promise<UnbanResponse>;
		/**
		 * Denies send permissions in specified channels
		 * @param options The options for locking down the guild
		 */
		lockdown(options: LockdownOptions): Promise<LockdownResponse>;
		quote(rawQuote: APIMessage, channel: GuildTextBasedChannel): Promise<Message | null>;
	}
}

/**
 * Represents a guild (or a server) on Discord.
 * <info>It's recommended to see if a guild is available before performing operations or reading data from it. You can
 * check this with {@link ExtendedGuild.available}.</info>
 */
export class ExtendedGuild extends Guild {
	/**
	 * Checks if the guild has a certain custom feature.
	 * @param feature The feature to check for
	 */
	public override async hasFeature(feature: GuildFeatures): Promise<boolean> {
		const features = await this.getSetting('enabledFeatures');
		return features.includes(feature);
	}

	/**
	 * Adds a custom feature to the guild.
	 * @param feature The feature to add
	 * @param moderator The moderator responsible for adding a feature
	 */
	public override async addFeature(feature: GuildFeatures, moderator?: GuildMember): Promise<GuildModel['enabledFeatures']> {
		const features = await this.getSetting('enabledFeatures');
		const newFeatures = addOrRemoveFromArray('add', features, feature);
		return (await this.setSetting('enabledFeatures', newFeatures, moderator)).enabledFeatures;
	}

	/**
	 * Removes a custom feature from the guild.
	 * @param feature The feature to remove
	 * @param moderator The moderator responsible for removing a feature
	 */
	public override async removeFeature(feature: GuildFeatures, moderator?: GuildMember): Promise<GuildModel['enabledFeatures']> {
		const features = await this.getSetting('enabledFeatures');
		const newFeatures = addOrRemoveFromArray('remove', features, feature);
		return (await this.setSetting('enabledFeatures', newFeatures, moderator)).enabledFeatures;
	}

	/**
	 * Makes a custom feature the opposite of what it was before
	 * @param feature The feature to toggle
	 * @param moderator The moderator responsible for toggling a feature
	 */
	public override async toggleFeature(feature: GuildFeatures, moderator?: GuildMember): Promise<GuildModel['enabledFeatures']> {
		return (await this.hasFeature(feature))
			? await this.removeFeature(feature, moderator)
			: await this.addFeature(feature, moderator);
	}

	/**
	 * Fetches a custom setting for the guild
	 * @param setting The setting to get
	 */
	public override async getSetting<K extends keyof GuildModel>(setting: K): Promise<GuildModel[K]> {
		return (
			this.client.cache.guilds.get(this.id)?.[setting] ??
			((await GuildDB.findByPk(this.id)) ?? GuildDB.build({ id: this.id }))[setting]
		);
	}

	/**
	 * Sets a custom setting for the guild
	 * @param setting The setting to change
	 * @param value The value to change the setting to
	 * @param moderator The moderator to responsible for changing the setting
	 */
	public override async setSetting<K extends Exclude<keyof GuildModel, 'id'>>(
		setting: K,
		value: GuildDB[K],
		moderator?: GuildMember
	): Promise<GuildDB> {
		const row = (await GuildDB.findByPk(this.id)) ?? GuildDB.build({ id: this.id });
		const oldValue = row[setting] as GuildDB[K];
		row[setting] = value;
		this.client.cache.guilds.set(this.id, row.toJSON() as GuildDB);
		this.client.emit('bushUpdateSettings', setting, this, oldValue, row[setting], moderator);
		return await row.save();
	}

	/**
	 * Get a the log channel configured for a certain log type.
	 * @param logType The type of log channel to get.
	 * @returns Either the log channel or undefined if not configured.
	 */
	public override async getLogChannel(logType: GuildLogType): Promise<TextChannel | undefined> {
		const channelId = (await this.getSetting('logChannels'))[logType];
		if (!channelId) return undefined;
		return (
			(this.channels.cache.get(channelId) as TextChannel | undefined) ??
			((await this.channels.fetch(channelId)) as TextChannel | null) ??
			undefined
		);
	}

	/**
	 * Sends a message to the guild's specified logging channel
	 * @param logType The corresponding channel that the message will be sent to
	 * @param message The parameters for {@link BushTextChannel.send}
	 */
	public override async sendLogChannel(
		logType: GuildLogType,
		message: string | MessagePayload | MessageOptions
	): Promise<Message | null | undefined> {
		const logChannel = await this.getLogChannel(logType);
		if (!logChannel || !logChannel.isTextBased()) return;
		if (
			!logChannel
				.permissionsFor(this.members.me!.id)
				?.has([PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.EmbedLinks])
		)
			return;

		return await logChannel.send(message).catch(() => null);
	}

	/**
	 * Sends a formatted error message in a guild's error log channel
	 * @param title The title of the error embed
	 * @param message The description of the error embed
	 */
	public override async error(title: string, message: string): Promise<void> {
		void this.client.console.info(_.camelCase(title), message.replace(/\*\*(.*?)\*\*/g, '<<$1>>'));
		void this.sendLogChannel('error', { embeds: [{ title: title, description: message, color: colors.error }] });
	}

	/**
	 * Bans a user, dms them, creates a mod log entry, and creates a punishment entry.
	 * @param options Options for banning the user.
	 * @returns A string status message of the ban.
	 */
	public override async bushBan(options: GuildBushBanOptions): Promise<BanResponse> {
		// checks
		if (!this.members.me!.permissions.has(PermissionFlagsBits.BanMembers)) return banResponse.MISSING_PERMISSIONS;

		let caseID: string | undefined = undefined;
		let dmSuccessEvent: boolean | undefined = undefined;
		const user = await this.client.utils.resolveNonCachedUser(options.user);
		const moderator = this.client.users.resolve(options.moderator ?? this.client.user!);
		if (!user || !moderator) return banResponse.CANNOT_RESOLVE_USER;

		if ((await this.bans.fetch()).has(user.id)) return banResponse.ALREADY_BANNED;

		const ret = await (async () => {
			// add modlog entry
			const { log: modlog } = await Moderation.createModLogEntry({
				client: this.client,
				type: options.duration ? ModLogType.TEMP_BAN : ModLogType.PERM_BAN,
				user: user,
				moderator: moderator.id,
				reason: options.reason,
				duration: options.duration,
				guild: this,
				evidence: options.evidence
			});
			if (!modlog) return banResponse.MODLOG_ERROR;
			caseID = modlog.id;

			// dm user
			dmSuccessEvent = await Moderation.punishDM({
				client: this.client,
				modlog: modlog.id,
				guild: this,
				user: user,
				punishment: 'banned',
				duration: options.duration ?? 0,
				reason: options.reason ?? undefined,
				sendFooter: true
			});

			// ban
			const banSuccess = await this.bans
				.create(user?.id ?? options.user, {
					reason: `${moderator.tag} | ${options.reason ?? 'No reason provided.'}`,
					deleteMessageDays: options.deleteDays
				})
				.catch(() => false);
			if (!banSuccess) return banResponse.ACTION_ERROR;

			// add punishment entry so they can be unbanned later
			const punishmentEntrySuccess = await Moderation.createPunishmentEntry({
				client: this.client,
				type: 'ban',
				user: user,
				guild: this,
				duration: options.duration,
				modlog: modlog.id
			});
			if (!punishmentEntrySuccess) return banResponse.PUNISHMENT_ENTRY_ADD_ERROR;

			if (!dmSuccessEvent) return banResponse.DM_ERROR;
			return banResponse.SUCCESS;
		})();

		if (!([banResponse.ACTION_ERROR, banResponse.MODLOG_ERROR, banResponse.PUNISHMENT_ENTRY_ADD_ERROR] as const).includes(ret))
			this.client.emit(
				'bushBan',
				user,
				moderator,
				this,
				options.reason ?? undefined,
				caseID!,
				options.duration ?? 0,
				dmSuccessEvent,
				options.evidence
			);
		return ret;
	}

	/**
	 * {@link bushBan} with less resolving and checks
	 * @param options Options for banning the user.
	 * @returns A string status message of the ban.
	 * **Preconditions:**
	 * - {@link me} has the `BanMembers` permission
	 * **Warning:**
	 * - Doesn't emit bushBan Event
	 */
	public override async massBanOne(options: GuildMassBanOneOptions): Promise<BanResponse> {
		if (this.bans.cache.has(options.user)) return banResponse.ALREADY_BANNED;

		const ret = await (async () => {
			// add modlog entry
			const { log: modlog } = await Moderation.createModLogEntrySimple({
				client: this.client,
				type: ModLogType.PERM_BAN,
				user: options.user,
				moderator: options.moderator,
				reason: options.reason,
				duration: 0,
				guild: this.id
			});
			if (!modlog) return banResponse.MODLOG_ERROR;

			let dmSuccessEvent: boolean | undefined = undefined;
			// dm user
			if (this.members.cache.has(options.user)) {
				dmSuccessEvent = await Moderation.punishDM({
					client: this.client,
					modlog: modlog.id,
					guild: this,
					user: options.user,
					punishment: 'banned',
					duration: 0,
					reason: options.reason ?? undefined,
					sendFooter: true
				});
			}

			// ban
			const banSuccess = await this.bans
				.create(options.user, {
					reason: `${options.moderator} | ${options.reason}`,
					deleteMessageDays: options.deleteDays
				})
				.catch(() => false);
			if (!banSuccess) return banResponse.ACTION_ERROR;

			// add punishment entry so they can be unbanned later
			const punishmentEntrySuccess = await Moderation.createPunishmentEntry({
				client: this.client,
				type: 'ban',
				user: options.user,
				guild: this,
				duration: 0,
				modlog: modlog.id
			});
			if (!punishmentEntrySuccess) return banResponse.PUNISHMENT_ENTRY_ADD_ERROR;

			if (!dmSuccessEvent) return banResponse.DM_ERROR;
			return banResponse.SUCCESS;
		})();
		return ret;
	}

	/**
	 * Unbans a user, dms them, creates a mod log entry, and destroys the punishment entry.
	 * @param options Options for unbanning the user.
	 * @returns A status message of the unban.
	 */
	public override async bushUnban(options: GuildBushUnbanOptions): Promise<UnbanResponse> {
		// checks
		if (!this.members.me!.permissions.has(PermissionFlagsBits.BanMembers)) return unbanResponse.MISSING_PERMISSIONS;

		let caseID: string | undefined = undefined;
		let dmSuccessEvent: boolean | undefined = undefined;
		const user = await this.client.utils.resolveNonCachedUser(options.user);
		const moderator = this.client.users.resolve(options.moderator ?? this.client.user!);
		if (!user || !moderator) return unbanResponse.CANNOT_RESOLVE_USER;

		const ret = await (async () => {
			const bans = await this.bans.fetch();

			let notBanned = false;
			if (!bans.has(user.id)) notBanned = true;

			const unbanSuccess = await this.bans
				.remove(user, `${moderator.tag} | ${options.reason ?? 'No reason provided.'}`)
				.catch((e) => {
					if (e?.code === 'UNKNOWN_BAN') {
						notBanned = true;
						return true;
					} else return false;
				});

			if (notBanned) return unbanResponse.NOT_BANNED;
			if (!unbanSuccess) return unbanResponse.ACTION_ERROR;

			// add modlog entry
			const { log: modlog } = await Moderation.createModLogEntry({
				client: this.client,
				type: ModLogType.UNBAN,
				user: user.id,
				moderator: moderator.id,
				reason: options.reason,
				guild: this,
				evidence: options.evidence
			});
			if (!modlog) return unbanResponse.MODLOG_ERROR;
			caseID = modlog.id;

			// remove punishment entry
			const removePunishmentEntrySuccess = await Moderation.removePunishmentEntry({
				client: this.client,
				type: 'ban',
				user: user.id,
				guild: this
			});
			if (!removePunishmentEntrySuccess) return unbanResponse.PUNISHMENT_ENTRY_REMOVE_ERROR;

			// dm user
			dmSuccessEvent = await Moderation.punishDM({
				client: this.client,
				guild: this,
				user: user,
				punishment: 'unbanned',
				reason: options.reason ?? undefined,
				sendFooter: false
			});

			if (!dmSuccessEvent) return unbanResponse.DM_ERROR;
			return unbanResponse.SUCCESS;
		})();
		if (
			!([unbanResponse.ACTION_ERROR, unbanResponse.MODLOG_ERROR, unbanResponse.PUNISHMENT_ENTRY_REMOVE_ERROR] as const).includes(
				ret
			)
		)
			this.client.emit(
				'bushUnban',
				user,
				moderator,
				this,
				options.reason ?? undefined,
				caseID!,
				dmSuccessEvent!,
				options.evidence
			);
		return ret;
	}

	/**
	 * Denies send permissions in specified channels
	 * @param options The options for locking down the guild
	 */
	public override async lockdown(options: LockdownOptions): Promise<LockdownResponse> {
		if (!options.all && !options.channel) return 'all not chosen and no channel specified';
		const channelIds = options.all ? await this.getSetting('lockdownChannels') : [options.channel!.id];

		if (!channelIds.length) return 'no channels configured';
		const mappedChannels = channelIds.map((id) => this.channels.cache.get(id));

		const invalidChannels = mappedChannels.filter((c) => c === undefined);
		if (invalidChannels.length) return `invalid channel configured: ${invalidChannels.join(', ')}`;

		const moderator = this.members.resolve(options.moderator);
		if (!moderator) return 'moderator not found';

		const errors = new Collection<Snowflake, Error>();
		const success = new Collection<Snowflake, boolean>();
		const ret = await (async (): Promise<LockdownResponse> => {
			for (const _channel of mappedChannels) {
				const channel = _channel!;
				if (!channel.isTextBased()) {
					errors.set(channel.id, new Error('wrong channel type'));
					success.set(channel.id, false);
					continue;
				}
				if (!channel.permissionsFor(this.members.me!.id)?.has([PermissionFlagsBits.ManageChannels])) {
					errors.set(channel.id, new Error('client no permission'));
					success.set(channel.id, false);
					continue;
				} else if (!channel.permissionsFor(moderator)?.has([PermissionFlagsBits.ManageChannels])) {
					errors.set(channel.id, new Error('moderator no permission'));
					success.set(channel.id, false);
					continue;
				}

				const reason = `[${options.unlock ? 'Unlockdown' : 'Lockdown'}] ${moderator.user.tag} | ${
					options.reason ?? 'No reason provided'
				}`;

				const permissionOverwrites = channel.isThread() ? channel.parent!.permissionOverwrites : channel.permissionOverwrites;
				const perms = {
					SendMessagesInThreads: options.unlock ? null : false,
					SendMessages: options.unlock ? null : false
				};
				const permsForMe = {
					[channel.isThread() ? 'SendMessagesInThreads' : 'SendMessages']: options.unlock ? null : true
				}; // so I can send messages in the channel

				const changePermSuccess = await permissionOverwrites.edit(this.id, perms, { reason }).catch((e) => e);
				if (changePermSuccess instanceof Error) {
					errors.set(channel.id, changePermSuccess);
					success.set(channel.id, false);
				} else {
					success.set(channel.id, true);
					await permissionOverwrites.edit(this.members.me!, permsForMe, { reason });
					await channel.send({
						embeds: [
							{
								author: { name: moderator.user.tag, icon_url: moderator.displayAvatarURL() },
								title: `This channel has been ${options.unlock ? 'un' : ''}locked`,
								description: options.reason ?? 'No reason provided',
								color: options.unlock ? colors.Green : colors.Red,
								timestamp: new Date().toISOString()
							}
						]
					});
				}
			}

			if (errors.size) return errors;
			else return `success: ${success.filter((c) => c === true).size}`;
		})();

		this.client.emit(options.unlock ? 'bushUnlockdown' : 'bushLockdown', moderator, options.reason, success, options.all);
		return ret;
	}

	public override async quote(rawQuote: APIMessage, channel: GuildTextBasedChannel): Promise<Message | null> {
		if (!channel.isTextBased() || channel.isDMBased() || channel.guildId !== this.id || !this.members.me) return null;
		if (!channel.permissionsFor(this.members.me).has('ManageWebhooks')) return null;

		const quote = new Message(this.client, rawQuote);

		const target = channel instanceof ThreadChannel ? channel.parent : channel;
		if (!target) return null;

		const webhooks: Collection<string, Webhook> = await target.fetchWebhooks().catch((e) => e);
		if (!(webhooks instanceof Collection)) return null;

		// find a webhook that we can use
		let webhook = webhooks.find((w) => !!w.token) ?? null;
		if (!webhook)
			webhook = await target
				.createWebhook({
					name: `${this.client.user!.username} Quotes #${target.name}`,
					avatar: this.client.user!.displayAvatarURL({ size: 2048 }),
					reason: 'Creating a webhook for quoting'
				})
				.catch(() => null);

		if (!webhook) return null;

		const sendOptions: Omit<WebhookMessageOptions, 'flags'> = {};

		const displayName = quote.member?.displayName ?? quote.author.username;

		switch (quote.type) {
			case MessageType.Default:
			case MessageType.Reply:
			case MessageType.ChatInputCommand:
			case MessageType.ContextMenuCommand:
			case MessageType.ThreadStarterMessage:
				sendOptions.content = quote.content || undefined;
				sendOptions.threadId = channel instanceof ThreadChannel ? channel.id : undefined;
				sendOptions.embeds = quote.embeds.length ? quote.embeds : undefined;
				//@ts-expect-error: jank
				sendOptions.attachments = quote.attachments.size
					? [...quote.attachments.values()].map((a) => AttachmentBuilder.from(a as JSONEncodable<AttachmentPayload>))
					: undefined;

				if (quote.stickers.size && !(quote.content || quote.embeds.length || quote.attachments.size))
					sendOptions.content = '[[This message has a sticker but not content]]';

				break;
			case MessageType.RecipientAdd: {
				const recipient = rawQuote.mentions[0];
				if (!recipient) {
					sendOptions.content = `${emojis.error} Cannot resolve recipient.`;
					break;
				}

				if (quote.channel.isThread()) {
					const recipientDisplay = quote.guild?.members.cache.get(recipient.id)?.displayName ?? recipient.username;
					sendOptions.content = `${emojis.join} ${displayName} added ${recipientDisplay} to the thread.`;
				} else {
					// this should never happen
					sendOptions.content = `${emojis.join} ${displayName} added ${recipient.username} to the group.`;
				}

				break;
			}
			case MessageType.RecipientRemove: {
				const recipient = rawQuote.mentions[0];
				if (!recipient) {
					sendOptions.content = `${emojis.error} Cannot resolve recipient.`;
					break;
				}

				if (quote.channel.isThread()) {
					const recipientDisplay = quote.guild?.members.cache.get(recipient.id)?.displayName ?? recipient.username;
					sendOptions.content = `${emojis.leave} ${displayName} removed ${recipientDisplay} from the thread.`;
				} else {
					// this should never happen
					sendOptions.content = `${emojis.leave} ${displayName} removed ${recipient.username} from the group.`;
				}

				break;
			}

			case MessageType.ChannelNameChange:
				sendOptions.content = `<:pencil:957988608994861118> ${displayName} changed the channel name: **${quote.content}**`;

				break;

			case MessageType.ChannelPinnedMessage:
				throw new Error('Not implemented yet: MessageType.ChannelPinnedMessage case');
			case MessageType.GuildMemberJoin: {
				const messages = [
					'{username} joined the party.',
					'{username} is here.',
					'Welcome, {username}. We hope you brought pizza.',
					'A wild {username} appeared.',
					'{username} just landed.',
					'{username} just slid into the server.',
					'{username} just showed up!',
					'Welcome {username}. Say hi!',
					'{username} hopped into the server.',
					'Everyone welcome {username}!',
					"Glad you're here, {username}.",
					'Good to see you, {username}.',
					'Yay you made it, {username}!'
				];

				const timestamp = SnowflakeUtil.timestampFrom(quote.id);

				// this is the same way that the discord client decides what message to use.
				const message = messages[timestamp % messages.length].replace(/{username}/g, displayName);

				sendOptions.content = `${emojis.join} ${message}`;
				break;
			}
			case MessageType.UserPremiumGuildSubscription:
				sendOptions.content = `<:NitroBoost:585558042309820447> ${displayName} just boosted the server${
					quote.content ? ` **${quote.content}** times` : ''
				}!`;

				break;
			case MessageType.UserPremiumGuildSubscriptionTier1:
			case MessageType.UserPremiumGuildSubscriptionTier2:
			case MessageType.UserPremiumGuildSubscriptionTier3:
				sendOptions.content = `<:NitroBoost:585558042309820447> ${displayName} just boosted the server${
					quote.content ? ` **${quote.content}** times` : ''
				}! ${quote.guild?.name} has achieved **Level ${quote.type - 8}!**`;

				break;
			case MessageType.ChannelFollowAdd:
				sendOptions.content = `${displayName} has added **${quote.content}** to this channel. Its most important updates will show up here.`;

				break;
			case MessageType.GuildDiscoveryDisqualified:
				sendOptions.content =
					'<:SystemMessageCross:842172192418693173> This server has been removed from Server Discovery because it no longer passes all the requirements. Check Server Settings for more details.';

				break;
			case MessageType.GuildDiscoveryRequalified:
				sendOptions.content =
					'<:SystemMessageCheck:842172191801212949> This server is eligible for Server Discovery again and has been automatically relisted!';

				break;
			case MessageType.GuildDiscoveryGracePeriodInitialWarning:
				sendOptions.content =
					'<:SystemMessageWarn:842172192401915971> This server has failed Discovery activity requirements for 1 week. If this server fails for 4 weeks in a row, it will be automatically removed from Discovery.';

				break;
			case MessageType.GuildDiscoveryGracePeriodFinalWarning:
				sendOptions.content =
					'<:SystemMessageWarn:842172192401915971> This server has failed Discovery activity requirements for 3 weeks in a row. If this server fails for 1 more week, it will be removed from Discovery.';

				break;
			case MessageType.ThreadCreated: {
				const threadId = rawQuote.message_reference?.channel_id;

				sendOptions.content = `<:thread:865033845753249813> ${displayName} started a thread: **[${quote.content}](https://discord.com/channels/${quote.guildId}/${threadId}
				)**. See all threads.`;

				break;
			}
			case MessageType.GuildInviteReminder:
				sendOptions.content = 'Wondering who to invite? Start by inviting anyone who can help you build the server!';

				break;
			case MessageType.ChannelIconChange:
			case MessageType.Call:
			default:
				sendOptions.content = `${emojis.error} I cannot quote **${
					MessageType[quote.type] || quote.type
				}** messages, please report this to my developers.`;

				break;
		}

		sendOptions.allowedMentions = AllowedMentions.none();
		sendOptions.username = quote.member?.displayName ?? quote.author.username;
		sendOptions.avatarURL = quote.member?.displayAvatarURL({ size: 2048 }) ?? quote.author.displayAvatarURL({ size: 2048 });

		return await webhook.send(sendOptions); /* .catch((e: any) => e); */
	}
}

/**
 * Options for unbanning a user
 */
export interface GuildBushUnbanOptions {
	/**
	 * The user to unban
	 */
	user: UserResolvable | User;

	/**
	 * The reason for unbanning the user
	 */
	reason?: string | null;

	/**
	 * The moderator who unbanned the user
	 */
	moderator?: UserResolvable;

	/**
	 * The evidence for the unban
	 */
	evidence?: string;
}

export interface GuildMassBanOneOptions {
	/**
	 * The user to ban
	 */
	user: Snowflake;

	/**
	 * The reason to ban the user
	 */
	reason: string;

	/**
	 * The moderator who banned the user
	 */
	moderator: Snowflake;

	/**
	 * The number of days to delete the user's messages for
	 */
	deleteDays?: number;
}

/**
 * Options for banning a user
 */
export interface GuildBushBanOptions {
	/**
	 * The user to ban
	 */
	user: UserResolvable;

	/**
	 * The reason to ban the user
	 */
	reason?: string | null;

	/**
	 * The moderator who banned the user
	 */
	moderator?: UserResolvable;

	/**
	 * The duration of the ban
	 */
	duration?: number;

	/**
	 * The number of days to delete the user's messages for
	 */
	deleteDays?: number;

	/**
	 * The evidence for the ban
	 */
	evidence?: string;
}

type ValueOf<T> = T[keyof T];

export const unbanResponse = Object.freeze({
	...dmResponse,
	...permissionsResponse,
	...punishmentEntryRemove,
	NOT_BANNED: 'user not banned'
} as const);

/**
 * Response returned when unbanning a user
 */
export type UnbanResponse = ValueOf<typeof unbanResponse>;

/**
 * Options for locking down channel(s)
 */
export interface LockdownOptions {
	/**
	 * The moderator responsible for the lockdown
	 */
	moderator: GuildMemberResolvable;

	/**
	 * Whether to lock down all (specified) channels
	 */
	all: boolean;

	/**
	 * Reason for the lockdown
	 */
	reason?: string;

	/**
	 * A specific channel to lockdown
	 */
	channel?: ThreadChannel | NewsChannel | TextChannel | VoiceChannel;

	/**
	 * Whether or not to unlock the channel(s) instead of locking them
	 */
	unlock?: boolean;
}

/**
 * Response returned when locking down a channel
 */
export type LockdownResponse =
	| `success: ${number}`
	| 'all not chosen and no channel specified'
	| 'no channels configured'
	| `invalid channel configured: ${string}`
	| 'moderator not found'
	| Collection<string, Error>;