apps/bot/src/middleware/index.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 |
import { HaltExecution } from "@purrkit/router";
import { kitten } from "@/client";
import {
getTicketByChannelId,
getTicketByGuild,
getTicketById,
upsertGuild,
} from "@stealth-developers/db";
import { getTextChannel, logger, upsertUser } from "@/lib";
import { Result } from "@sapphire/framework";
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) return {};
const ticket = await getTicketByChannelId(interaction.channel.id);
if (!ticket) return {};
if (!ticket.channelId) return { ticket };
const ticketChannel = await getTextChannel(ticket.channelId, true);
return { ticket, ticketChannel };
});
|