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 |
import { attachments, db, ticketMessages, tickets } from "@/database";
import { getPublicUrl, s3 } from "@/utils/s3";
import {
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
type Client,
Events,
type GuildMember,
type Message,
} from "discord.js";
import { and, eq } from "drizzle-orm";
import { nanoid } from "nanoid";
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";
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),
)
) {
message.channel.send("yeh");
}
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");
}
},
};
|