import { randomUUID } from "node:crypto"; import { TextChannel, ChannelType, type Guild, ContainerBuilder, TextDisplayBuilder, ActionRowBuilder, DiscordAPIError, } from "discord.js"; import { Result } from "@sapphire/framework"; import { ButtonBuilder } from "discord.js"; import db, { desc, editTicket, eq, getGuildByDiscordId, getTicketByChannelId, tickets, type Actor, } from "@stealth-developers/db"; import { upsertUser, getCategory, PublicError, logger } from "@/lib"; import type { AnyUser, MessageSendPayload } from "@/types"; import { TicketButtonPresets } from "./buttons"; import { TicketModalPresets } from "./modals"; type CreateTicketArgs = | undefined | { for: AnyUser; reason?: string; }; export async function createTicket( opener: AnyUser, guild: Guild, args?: CreateTicketArgs, ): Promise<{ channelId: string; publicId: string }> { const isOnBehalf = !!args?.for; const publicId = randomUUID(); const dbGuild = await getGuildByDiscordId(guild.id); if (!dbGuild) throw new PublicError("Failed to create ticket: Guild not found in database"); const creator = await upsertUser(opener, guild); if (!creator) throw new PublicError("Failed to create ticket: Creator user not found"); const subject = isOnBehalf ? args?.for : opener; const subjectUser = subject ? await upsertUser(subject, guild) : creator; if (!subjectUser) throw new PublicError("Failed to create ticket: Subject user not found"); if (isOnBehalf && !creator.moderator) throw new PublicError("You don't have permission to create a ticket for another user."); if (!dbGuild.ticketCategory) throw new PublicError( "Ticket category is not set up in this guild. Please contact an administrator.", ); const ticketCategory = await getCategory(dbGuild.ticketCategory); let createdChannel: TextChannel | undefined = undefined; const canDm = await canDmUser(subject); const txResult = await Result.fromAsync(async () => { return await db.transaction(async (tx) => { const [maxTicket] = await tx .select({ localId: tickets.localId }) .from(tickets) .where(eq(tickets.guildId, creator.guildId)) .orderBy(desc(tickets.localId)) .limit(1); const localId = (maxTicket?.localId ?? 0) + 1; const [ticket] = await tx .insert(tickets) .values({ id: publicId, guildId: creator.guildId, localId: localId, status: "provisioning", openedAt: new Date(), openedBy: creator.id, subject: subjectUser.id, }) .returning(); if (!ticket) throw new PublicError("Failed to add ticket to database, please try again."); const channel = await guild.channels.create({ name: channelName(localId, ticket.status), type: ChannelType.GuildText, parent: ticketCategory, }); if (!channel) throw new PublicError("Failed to create Discord channel."); createdChannel = channel; const greeting = dbGuild.ticketGreeting; const components = []; if (greeting) components.push( new ContainerBuilder() .setAccentColor(0x3a9027) .addTextDisplayComponents( new TextDisplayBuilder({ content: greeting.replaceAll("{user}", `<@${subjectUser.discordId}>`), }), ) .addActionRowComponents( new ActionRowBuilder().addComponents( TicketButtonPresets.claim(publicId), TicketButtonPresets.close(publicId), ), ), ); if (!canDm) components.push( new ContainerBuilder() .setAccentColor(0xdf8e1d) .addTextDisplayComponents( new TextDisplayBuilder().setContent("## I can't DM you!"), new TextDisplayBuilder().setContent( [ "You won't receive a notification once your ticket has been handled.", `To check the outcome, you can use the \`/ticket view\` command with the ID \`${ticket.localId}\``, "or, see all of your tickets with `/ticket manage list`.", ].join(" "), ), ), ); components.push( new ContainerBuilder() .setAccentColor(0x3a9027) .addTextDisplayComponents( new TextDisplayBuilder({ content: [ "# Uploading Videos\n", "You can either upload your video directly to this channel, or", "you can use the button below to upload it directly to us, which", "allows you to upload videos up to 2GB in size.", ].join(" "), }), ) .addActionRowComponents( new ActionRowBuilder().addComponents( TicketButtonPresets.upload(publicId), ), ), ); await channel.send({ components, flags: ["IsComponentsV2"], }); await tx .update(tickets) .set({ channelId: channel.id, status: "open" }) .where(eq(tickets.id, ticket.id)); await channel.edit({ name: channelName(localId, "open"), }); return channel; }); }); if (txResult.isErr()) { if (createdChannel) await Result.fromAsync(() => createdChannel?.delete()); const error = txResult.unwrapErr(); const message = error instanceof PublicError ? `Failed to create ticket: ${error.message}` : "There was an error creating the ticket."; if (error instanceof Error) logger.error(error.stack, error.message); throw new PublicError(message); } const channel = txResult.unwrap(); return { channelId: channel.id, publicId }; } export async function triggerCloseTicket(user: AnyUser, guild: Guild, channelId: string) { const dbGuild = await getGuildByDiscordId(guild.id); if (!dbGuild) throw new PublicError("Failed to create ticket: Guild not found in database"); const dbUser = await upsertUser(user, guild); if (!dbUser) throw new PublicError("Failed to create ticket: User not found in database"); const ticket = await getTicketByChannelId(channelId); if (!ticket) throw new PublicError("Failed to close ticket: Ticket not found in database"); return TicketModalPresets.close(ticket.id, Boolean(dbUser.moderator)); } export async function closeTicket( user: Actor, ticketId: string, reasons: { public: string; private?: string | null }, ) { const result = await editTicket(ticketId, { closedAt: new Date(), closeReason: reasons.public, privateReason: reasons.private, closedBy: user.id, status: "closed", }); if (!result) throw new PublicError("Failed to close ticket: Ticket not found in database"); return result; } export async function canDmUser(user: AnyUser): Promise { if (!("send" in user)) return false; return user .send({ content: "Hi! I'm just checking if your DMs are open.", flags: ["SuppressNotifications"], }) .then(() => true) .catch(() => false); } export async function messageUser(user: AnyUser, message: MessageSendPayload) { if (!("send" in user)) throw new PublicError("Failed to message user: User is not a Discord user"); const result = await Result.fromAsync(user.send(message)); if (result.isErr()) { const error = result.unwrapErr(); if (error instanceof DiscordAPIError && [50007, 50278].includes(error.code as number)) throw new PublicError("Failed to message user: User has DMs disabled"); throw error; } return result.unwrap(); } export function channelName(localId: number, status: string) { const initNumber = localId.toString().padStart(4, "0"); // discord errors if we try to create channels with certain phrases in them const bad = ["1488", "1919"]; if (bad.includes(initNumber)) return `${status}-filtered`; return `${status}-ticket-${localId}`; }