all repos — stealth-developers @ 36113331b3becdcf4a0ddf623201e2310b00e95f

src/events/messageCreate.ts (view raw)

 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
import {
	attachments,
	db,
	ticketMessages,
	tickets,
	userPreferences,
} from "@/database";
import { getPublicUrl, s3 } from "@/utils/s3";
import {
	AttachmentBuilder,
	type Client,
	Events,
	type GuildMember,
	type Message,
} from "discord.js";
import { and, eq } from "drizzle-orm";
import { nanoid } from "nanoid";
import Uwuifier from "uwuifier";

import config from "@/config";
import { loggers } from "@/utils/logging";
import { hasManagerPermissions } from "@/utils/permissions";
const logger = loggers.events.child({ name: "messageCreate" });

type UploadStatus = "queued" | "uploading" | "done" | "failed";

async function handleUwuification(message: Message): Promise<boolean> {
	if (message.author.bot) return false;
	if (!message.content && message.attachments.size === 0) return false;

	const userPref = db
		.select()
		.from(userPreferences)
		.where(eq(userPreferences.userId, message.author.id))
		.get();

	if (userPref?.uwuifyMessages !== "enabled") return false;

	const uwuifier = new Uwuifier();
	const uwuifiedContent = message.content
		? uwuifier.uwuifySentence(message.content)
		: "";

	const blacklistedWords = [
		"twerks",
		"sees bulge",
		"notices buldge",
		"starts twerking",
	];

	const finalText = blacklistedWords.reduce((acc, word) => {
		return acc.replace(new RegExp(word, "gi"), "----");
	}, uwuifiedContent);

	try {
		let replyReference = null;
		if (message.reference?.messageId) {
			try {
				replyReference = await message.channel.messages.fetch(
					message.reference.messageId,
				);
			} catch (error) {
				logger.warn(
					error,
					"Failed to fetch referenced message for uwuified reply",
				);
			}
		}

		const files: AttachmentBuilder[] = [];
		for (const attachment of message.attachments.values()) {
			try {
				const resp = await fetch(attachment.url);
				if (!resp.ok) {
					logger.warn(
						`Failed to fetch attachment ${attachment.name}, status ${resp.status}`,
					);
					continue;
				}

				const buffer = await resp.arrayBuffer();
				const attachmentBuilder = new AttachmentBuilder(Buffer.from(buffer), {
					name: attachment.name,
				});
				files.push(attachmentBuilder);
			} catch (error) {
				logger.error(error, `Failed to download attachment ${attachment.name}`);
			}
		}

		await message.delete();

		const contentParts = [
			`**<@${message.author.id}>**: ${finalText || "(no text)"}`,
		];

		if (message.channel.isSendable()) {
			const sendOptions: {
				content: string;
				files?: AttachmentBuilder[];
				reply?: { messageReference: string };
			} = {
				content: contentParts.join("\n"),
			};

			if (files.length > 0) {
				sendOptions.files = files;
			}

			if (replyReference) {
				sendOptions.reply = {
					messageReference: replyReference.id,
				};
			}

			await message.channel.send({
				allowedMentions: {
					users: [],
				},
				...sendOptions,
			});
		}

		return true;
	} catch (error) {
		logger.error(error, "Failed to uwuify and resend message");
		return false;
	}
}

export default {
	event: Events.MessageCreate,
	async execute(client: Client, message: Message) {
		if (!client.user) return;

		const triggers = ["grok is this true", "grok is this false "];
		if (
			message.channel.isSendable() &&
			triggers.some((trigger) =>
				message.content.toLowerCase().includes(trigger),
			)
		) {
			const chance = Math.random() * 100;
			if (chance < 25 || message.author.id === "470956810866655242") {
				await message.channel.send("gorque* 🇫🇷🥖");
				message.channel.send("but oui");
			} else {
				message.channel.send("yeh");
			}
		}

		if (
			message.channel.isSendable() &&
			message.content.includes("gorque is this true")
		) {
			message.channel.send("oui 🇫🇷🥖");
		}

		await handleUwuification(message);

		const ticket = db
			.select()
			.from(tickets)
			.where(
				and(
					eq(tickets.channelId, message.channelId),
					eq(tickets.guildId, message.guildId ?? ""),
				),
			)
			.get();

		if (!ticket) return;

		try {
			const isSystem = message.author.id === client.user.id;
			const isModerator = await hasManagerPermissions(
				message?.member as GuildMember,
			);
			const authorType = isSystem ? "system" : isModerator ? "staff" : "user";

			const anonymisedContent = message.content.replace(
				new RegExp(ticket.authorId, "g"),
				"-".repeat(ticket.authorId.length),
			);

			const savedMessage = db
				.insert(ticketMessages)
				.values({
					ticketId: ticket.id,
					authorId: message.author.id,
					authorType: authorType,
					content: anonymisedContent,
					createdAt: message.createdAt,
				})
				.returning()
				.get();

			if (message.attachments.size > 0) {
				const attachmentsArray = Array.from(message.attachments.values());
				const total = attachmentsArray.length;

				const statusList: {
					attachment: (typeof attachmentsArray)[number];
					status: UploadStatus;
					url?: string;
				}[] = attachmentsArray.map((att) => ({
					attachment: att,
					status: "queued",
				}));

				const formatSize = (size: number) => {
					if (size < 1024) return `${size} B`;
					if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`;
					if (size < 1024 * 1024 * 1024)
						return `${(size / (1024 * 1024)).toFixed(2)} MB`;
					return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`;
				};

				const renderBoard = () => {
					const list = statusList
						.map((item) => {
							const name = item.attachment.name ?? "unknown";
							const emoji = (() => {
								switch (item.status) {
									case "done":
										return ":white_check_mark:";
									case "uploading":
										return ":hourglass_flowing_sand:";
									case "queued":
										return ":black_large_square:";
									case "failed":
										return ":x:";
								}
							})();

							if (item.status === "done" && item.url)
								return `${emoji} [${name}](<${item.url}>) (${formatSize(item.attachment.size)})`;
							return `${emoji} ${name} (${formatSize(item.attachment.size)})`;
						})
						.join("\n");

					return list;
				};

				let statusMessage: Message | null = null;
				if (message.channel.isSendable()) {
					statusMessage = await message.reply({
						content: `**Attachment upload status**\n${renderBoard()}`,
					});
				}

				for (let i = 0; i < total; i++) {
					const { attachment } = statusList[i];
					if (!statusMessage) continue;

					try {
						statusList[i].status = "uploading";
						await statusMessage.edit(
							`**Attachment upload status**\n${renderBoard()}`,
						);

						const key = `${ticket.anonymousId}/${savedMessage.id}/${nanoid(
							8,
						)}_${attachment.name}`;
						const file = s3.file(key);

						const resp = await fetch(attachment.url);
						const blob = await resp.blob();
						await file.write(blob);

						const publicUrl = getPublicUrl(key);

						await db.insert(attachments).values({
							id: attachment.id,
							ownerType: "ticket_message",
							ownerId: savedMessage.id,
							fileName: attachment.name,
							contentType: attachment.contentType ?? "application/octet-stream",
							size: attachment.size,
							bucket: config.s3.bucket,
							key: key,
							url: publicUrl,
						});

						statusList[i].status = "done";
						statusList[i].url = publicUrl;
						await statusMessage.edit(
							`**Attachment upload status**\n${renderBoard()}`,
						);
					} catch (error) {
						logger.error(
							error,
							`Failed to upload attachment ${attachment.name}`,
						);
						statusList[i].status = "failed";
						await statusMessage.edit(
							`**Attachment upload status**\n${renderBoard()}`,
						);
					}
				}
			}
		} catch (error) {
			logger.error(error, "Failed to log ticket message");
		}
	},
};