src/interactions/commands/catlb.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 |
import { UserModel } from "@/database/schemas";
import {
ActionRowBuilder,
ButtonBuilder,
type ButtonInteraction,
ButtonStyle,
type ChatInputCommandInteraction,
type Client,
ContainerBuilder,
SeparatorBuilder,
SlashCommandBuilder,
TextDisplayBuilder,
} from "discord.js";
const PAGE_SIZE = 10;
const commandData = new SlashCommandBuilder()
.setName("cat-leaderboard")
.setDescription("show the top cat point earners in this server");
type SessionState = {
userId: string;
currentPage: number;
pageCount: number;
userIds: string[];
};
const sessionStore = new Map<string, SessionState>();
function makeSessionId(): string {
return `${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
}
function makeButtonRow(
sessionId: string,
currentPage: number,
pageCount: number,
) {
return new ActionRowBuilder<ButtonBuilder>().addComponents(
new ButtonBuilder()
.setCustomId(`cat-leaderboard:prev:${sessionId}`)
.setLabel("previous")
.setStyle(ButtonStyle.Secondary)
.setDisabled(currentPage === 1),
new ButtonBuilder()
.setCustomId(`cat-leaderboard:next:${sessionId}`)
.setLabel("next")
.setStyle(ButtonStyle.Secondary)
.setDisabled(currentPage === pageCount || pageCount === 0),
);
}
function buildLeaderboardContainer(
users: { user_id: string; cat_points: number }[],
currentPage: number,
pageCount: number,
) {
const startRank = (currentPage - 1) * PAGE_SIZE + 1;
const lines = users.map(
(user, i) =>
`${startRank + i}. <@${user.user_id}> — ${user.cat_points} cat point${user.cat_points === 1 ? "" : "s"}`,
);
const container = new ContainerBuilder()
.setAccentColor([245, 197, 66])
.addTextDisplayComponents(
new TextDisplayBuilder().setContent("# 🐱 cat points leaderboard"),
new TextDisplayBuilder().setContent(
lines.length > 0
? lines.join("\n")
: "no cat points have been awarded yet!",
),
)
.addSeparatorComponents(
new SeparatorBuilder().setDivider(false).setSpacing(1),
)
.addTextDisplayComponents(
new TextDisplayBuilder().setContent(
`-# page ${currentPage} of ${pageCount} • last updated: <t:${Math.floor(Date.now() / 1000)}:R>`,
),
);
return container;
}
async function execute(
_client: Client,
interaction: ChatInputCommandInteraction,
) {
if (!interaction.guild) {
await interaction.reply({
content: "❌ this command can only be used in a server.",
flags: ["Ephemeral"],
});
return;
}
const allUsers = await UserModel.find({
guild_id: interaction.guildId,
cat_points: { $exists: true, $ne: null },
})
.sort({ cat_points: -1, user_id: 1 })
.select("user_id cat_points")
.lean();
const pageCount = Math.max(1, Math.ceil(allUsers.length / PAGE_SIZE));
const currentPage = 1;
const users = allUsers.slice(0, PAGE_SIZE);
const sessionId = makeSessionId();
sessionStore.set(sessionId, {
userId: interaction.user.id,
currentPage,
pageCount,
userIds: allUsers.map((u) => u.user_id),
});
const container = buildLeaderboardContainer(users, currentPage, pageCount);
const actions = makeButtonRow(sessionId, currentPage, pageCount);
await interaction.reply({
flags: ["IsComponentsV2"],
components: [container, actions],
allowedMentions: { users: [] },
});
}
async function buttonExecute(_client: Client, interaction: ButtonInteraction) {
const [, action, sessionId] = interaction.customId.split(":");
const session = sessionStore.get(sessionId);
if (!session) {
return interaction.reply({
content:
"❌ this leaderboard session has expired. Please run the command again.",
flags: ["Ephemeral"],
});
}
if (interaction.user.id !== session.userId) {
return interaction.reply({
content: `❌ only <@${session.userId}> can interact with this leaderboard.`,
flags: ["Ephemeral"],
});
}
let newPage = session.currentPage;
if (action === "prev") newPage = Math.max(1, session.currentPage - 1);
else if (action === "next")
newPage = Math.min(session.pageCount, session.currentPage + 1);
if (newPage !== session.currentPage) {
session.currentPage = newPage;
sessionStore.set(sessionId, session);
const allUsers = await UserModel.find({
guild_id: interaction.guildId,
cat_points: { $exists: true, $ne: null },
})
.sort({ cat_points: -1, user_id: 1 })
.select("user_id cat_points")
.lean();
session.pageCount = Math.max(1, Math.ceil(allUsers.length / PAGE_SIZE));
const users = allUsers.slice(
(newPage - 1) * PAGE_SIZE,
newPage * PAGE_SIZE,
);
const container = buildLeaderboardContainer(
users,
newPage,
session.pageCount,
);
const actions = makeButtonRow(sessionId, newPage, session.pageCount);
await interaction.update({
flags: ["IsComponentsV2"],
components: [container, actions],
allowedMentions: { users: [] },
});
} else {
await interaction.deferUpdate();
}
}
export default {
data: commandData,
execute,
buttonExecute,
};
|