import { HaltExecution } from "@purrkit/router"; import { Result } from "@sapphire/framework"; import { getTicketByChannelId, getTicketByGuild, getTicketById, upsertGuild, } from "@stealth-developers/db"; import { kitten } from "@/client"; import { getTextChannel, logger, upsertUser } from "@/lib"; const base = kitten.builder(); export const useGetData = base .use(async (interaction) => { if (!interaction.guild) return {}; const user = await upsertUser(interaction.user, interaction.guild); if (!user) throw new HaltExecution("Failed to add you to the database. Please try again."); return { user }; }) .use(async (interaction) => { if (!interaction.guild) return {}; const actor = await upsertUser(interaction.user, interaction.guild); if (!actor) throw new HaltExecution("Failed to add you to the database. Please try again."); return { actor }; }) .use(async (interaction) => { if (!interaction.guild) return {}; const guild = await upsertGuild({ discordId: interaction.guild.id, icon: interaction.guild.iconURL(), name: interaction.guild.name, }); if (!guild) throw new HaltExecution("Failed to find your guild in the database. Please try again."); return { guild }; }); export const useGetTicketData = useGetData.use(async (interaction, { guild }) => { if (interaction.isChatInputCommand()) { const ticketId = interaction.options.getNumber("ticket", false); if (ticketId && guild) { const ticket = await getTicketByGuild(guild.id, ticketId); if (!ticket) return {}; return { ticket }; } } if (interaction.isButton()) { const customId = interaction.customId; if (customId.includes("ticket:")) { const ticketId = customId.split(":")[1]; if (ticketId) { const ticket = await getTicketById(ticketId); if (!ticket) return {}; if (!ticket.channelId) return { ticket }; const ticketChannelResult = await Result.fromAsync(getTextChannel(ticket.channelId, true)); if (ticketChannelResult.isErr()) { logger.error( ticketChannelResult.unwrapErr(), "Failed to get ticket channel in middleware", ); return { ticket }; } return { ticket, ticketChannel: ticketChannelResult.unwrap() }; } } } if (!interaction.channel) { logger.warn({ interaction }, "No channel found in interaction"); return {}; } const ticket = await getTicketByChannelId(interaction.channel.id); if (!ticket) { logger.warn({ interaction }, `No ticket found in channel ${interaction.channel.id}`); return {}; } if (!ticket.channelId) return { ticket }; const ticketChannel = await getTextChannel(ticket.channelId, true); return { ticket, ticketChannel }; });