Implement .verify bot command
This commit is contained in:
@@ -8,6 +8,7 @@
|
||||
},
|
||||
"peerDependencies": {},
|
||||
"dependencies": {
|
||||
"@blade-and-brawn/domain": "workspace:*",
|
||||
"@elysia/eden": "^1.4.10",
|
||||
"discord.js": "^14.27.0"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
import {
|
||||
ActionRowBuilder,
|
||||
ButtonBuilder,
|
||||
ButtonStyle,
|
||||
ComponentType,
|
||||
EmbedBuilder,
|
||||
MessageFlags,
|
||||
ModalBuilder,
|
||||
TextInputStyle,
|
||||
type Message,
|
||||
} from "discord.js";
|
||||
import { Activity, cmToIn, kgToLb, type ActivityVerifications } from "@blade-and-brawn/domain";
|
||||
import type { Command } from "../../models";
|
||||
import { api } from "../../util";
|
||||
|
||||
const REVIEW_TIMEOUT_MS = 15 * 60_000;
|
||||
const NOTES_TIMEOUT_MS = 10 * 60_000;
|
||||
const MEDIA_TEXT_LIMIT = 3800;
|
||||
|
||||
const ACTIVITIES = Object.values(Activity);
|
||||
|
||||
const ACTIVITY_LABEL: Record<Activity, string> = {
|
||||
[Activity.BackSquat]: "Back Squat",
|
||||
[Activity.Deadlift]: "Deadlift",
|
||||
[Activity.BenchPress]: "Bench Press",
|
||||
[Activity.Run]: "Run",
|
||||
[Activity.BroadJump]: "Broad Jump",
|
||||
[Activity.ConeDrill]: "Cone Drill",
|
||||
};
|
||||
|
||||
const VERF_COLUMN = {
|
||||
[Activity.BackSquat]: "verf_back_squat",
|
||||
[Activity.Deadlift]: "verf_deadlift",
|
||||
[Activity.BenchPress]: "verf_bench_press",
|
||||
[Activity.Run]: "verf_run",
|
||||
[Activity.BroadJump]: "verf_broad_jump",
|
||||
[Activity.ConeDrill]: "verf_cone_drill",
|
||||
} as const satisfies Record<Activity, string>;
|
||||
|
||||
const PERF_COLUMN = {
|
||||
[Activity.BackSquat]: "perf_back_squat",
|
||||
[Activity.Deadlift]: "perf_deadlift",
|
||||
[Activity.BenchPress]: "perf_bench_press",
|
||||
[Activity.Run]: "perf_run",
|
||||
[Activity.BroadJump]: "perf_broad_jump",
|
||||
[Activity.ConeDrill]: "perf_cone_drill",
|
||||
} as const satisfies Record<Activity, string>;
|
||||
|
||||
async function loadVerification(id: string) {
|
||||
return await api.verifications({ id }).get();
|
||||
}
|
||||
|
||||
type Verification = NonNullable<Awaited<ReturnType<typeof loadVerification>>["data"]>;
|
||||
type Result = boolean | null;
|
||||
|
||||
function formatPerformance(activity: Activity, value: number | null): string {
|
||||
if (value === null) return "—";
|
||||
switch (activity) {
|
||||
case Activity.BackSquat:
|
||||
case Activity.Deadlift:
|
||||
case Activity.BenchPress:
|
||||
return `${Math.round(kgToLb(value))} lb`;
|
||||
case Activity.Run: {
|
||||
const totalSeconds = Math.floor(value / 1000);
|
||||
return `${Math.floor(totalSeconds / 60)}m ${totalSeconds % 60}s`;
|
||||
}
|
||||
case Activity.ConeDrill:
|
||||
return `${(value / 1000).toFixed(2)} seconds`;
|
||||
case Activity.BroadJump: {
|
||||
const inches = cmToIn(value);
|
||||
const ft = Math.floor(inches / 12);
|
||||
return `${ft}' ${Math.round((inches - ft * 12) * 2) / 2}"`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function formatSize(bytes: number | undefined): string {
|
||||
if (bytes === undefined) return "—";
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
function resultIcon(result: Result): string {
|
||||
if (result === true) return "✅";
|
||||
if (result === false) return "❌";
|
||||
return "⬜";
|
||||
}
|
||||
|
||||
function nextResult(result: Result): Result {
|
||||
if (result === null) return true;
|
||||
if (result === true) return false;
|
||||
return null;
|
||||
}
|
||||
|
||||
function errorText(error: { status: number, value: unknown }): string {
|
||||
return (error.value as { error?: string } | undefined)?.error ?? "Something went wrong talking to the API.";
|
||||
}
|
||||
|
||||
function mediaText(media: Verification["media"]): string {
|
||||
if (media.length === 0) return "No media uploaded";
|
||||
|
||||
const lines: string[] = [];
|
||||
let length = 0;
|
||||
for (const [i, file] of media.entries()) {
|
||||
const line = `[File ${i + 1}](${file.url}) · ${formatSize(file.size)}`;
|
||||
if (length + line.length > MEDIA_TEXT_LIMIT) {
|
||||
lines.push(`…and ${media.length - i} more (see the portal)`);
|
||||
break;
|
||||
}
|
||||
lines.push(line);
|
||||
length += line.length + 1;
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export default {
|
||||
name: "verify",
|
||||
description: "Review a player's submitted verification",
|
||||
usage: ".verify <user>",
|
||||
execute: async (message: Message) => {
|
||||
if (message.mentions.users.size > 1) {
|
||||
await message.reply("Only one player may be provided.");
|
||||
return;
|
||||
}
|
||||
|
||||
const user = message.mentions.users.first();
|
||||
if (!user) {
|
||||
await message.reply("No valid player was provided.");
|
||||
return;
|
||||
}
|
||||
|
||||
const classmasterId = message.author.id;
|
||||
|
||||
const listRes = await api.accounts({ id: `@${user.id}` }).verifications.get({
|
||||
query: { limit: 1, status: "submitted" },
|
||||
});
|
||||
if (listRes.error) {
|
||||
await message.reply(errorText(listRes.error));
|
||||
return;
|
||||
}
|
||||
|
||||
const latest = listRes.data[0];
|
||||
if (!latest) {
|
||||
await message.reply("This player has no submitted verification.");
|
||||
return;
|
||||
}
|
||||
|
||||
const res = await loadVerification(latest.id);
|
||||
if (res.error) {
|
||||
await message.reply(errorText(res.error));
|
||||
return;
|
||||
}
|
||||
|
||||
const v = res.data;
|
||||
const results = Object.fromEntries(ACTIVITIES.map((a) => [a, v[VERF_COLUMN[a]]])) as Record<Activity, Result>;
|
||||
let notes = v.reviewer_notes ?? "";
|
||||
|
||||
const reviewedCount = () => ACTIVITIES.filter((a) => results[a] !== null).length;
|
||||
|
||||
const embeds = () => [
|
||||
new EmbedBuilder()
|
||||
.setColor(0xEEE8AA)
|
||||
.setTitle(v.name)
|
||||
.setDescription(`${user} · ${v.gender} · age ${v.age} · ${Math.round(kgToLb(v.weight))} lb`)
|
||||
.addFields(
|
||||
ACTIVITIES.map((a) => ({
|
||||
name: ACTIVITY_LABEL[a],
|
||||
value: formatPerformance(a, v[PERF_COLUMN[a]]),
|
||||
inline: true,
|
||||
}))
|
||||
)
|
||||
.addFields(notes ? [{ name: "Reviewer notes", value: notes.slice(0, 1024) }] : [])
|
||||
.setFooter({ text: `${reviewedCount()} / ${ACTIVITIES.length} reviewed · Click an activity to cycle Pass → Fail → Unreviewed` }),
|
||||
new EmbedBuilder()
|
||||
.setTitle(`Media (${v.media.length})`)
|
||||
.setDescription(mediaText(v.media)),
|
||||
];
|
||||
|
||||
const components = () => [
|
||||
new ActionRowBuilder<ButtonBuilder>().addComponents(ACTIVITIES.slice(0, 3).map(activityButton)),
|
||||
new ActionRowBuilder<ButtonBuilder>().addComponents(ACTIVITIES.slice(3).map(activityButton)),
|
||||
new ActionRowBuilder<ButtonBuilder>().addComponents(
|
||||
new ButtonBuilder()
|
||||
.setCustomId("request-action")
|
||||
.setLabel("Request action")
|
||||
.setStyle(ButtonStyle.Primary),
|
||||
new ButtonBuilder()
|
||||
.setCustomId("complete")
|
||||
.setLabel("Complete")
|
||||
.setStyle(ButtonStyle.Success)
|
||||
.setDisabled(reviewedCount() < ACTIVITIES.length),
|
||||
new ButtonBuilder()
|
||||
.setCustomId("cancel")
|
||||
.setLabel("Cancel")
|
||||
.setStyle(ButtonStyle.Secondary),
|
||||
),
|
||||
];
|
||||
|
||||
const activityButton = (activity: Activity) => new ButtonBuilder()
|
||||
.setCustomId(`result:${activity}`)
|
||||
.setLabel(`${resultIcon(results[activity])} ${ACTIVITY_LABEL[activity]}`)
|
||||
.setStyle(results[activity] === true ? ButtonStyle.Success : results[activity] === false ? ButtonStyle.Danger : ButtonStyle.Secondary);
|
||||
|
||||
const activityVerifications = (): ActivityVerifications =>
|
||||
Object.fromEntries(ACTIVITIES.filter((a) => results[a] !== null).map((a) => [a, results[a]]));
|
||||
|
||||
const reply = await message.reply({ embeds: embeds(), components: components() });
|
||||
|
||||
const finish = async (content: string) => {
|
||||
collector.stop("done");
|
||||
await reply.edit({ content, embeds: embeds(), components: [] });
|
||||
};
|
||||
|
||||
const collector = reply.createMessageComponentCollector({ componentType: ComponentType.Button, time: REVIEW_TIMEOUT_MS });
|
||||
|
||||
collector.on("collect", async (i) => {
|
||||
if (i.user.id !== classmasterId) {
|
||||
await i.reply({ content: "Only the classmaster who ran this command can review it.", flags: MessageFlags.Ephemeral });
|
||||
return;
|
||||
}
|
||||
|
||||
if (i.customId.startsWith("result:")) {
|
||||
const activity = i.customId.slice("result:".length) as Activity;
|
||||
results[activity] = nextResult(results[activity]);
|
||||
await i.update({ embeds: embeds(), components: components() });
|
||||
return;
|
||||
}
|
||||
|
||||
if (i.customId === "cancel") {
|
||||
collector.stop("done");
|
||||
await i.deferUpdate();
|
||||
await reply.delete();
|
||||
return;
|
||||
}
|
||||
|
||||
if (i.customId === "complete") {
|
||||
await i.deferUpdate();
|
||||
// TODO: drop completedBy once the bot authenticates as the classmaster
|
||||
const res = await api.verifications({ id: v.id }).complete.post({
|
||||
activityVerifications: activityVerifications(),
|
||||
completedBy: `@${classmasterId}`,
|
||||
});
|
||||
if (res.error) {
|
||||
await i.followUp({ content: errorText(res.error), flags: MessageFlags.Ephemeral });
|
||||
return;
|
||||
}
|
||||
await finish(`✅ Verification completed by ${i.user}.`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (i.customId === "request-action") {
|
||||
const modalId = `request-action:${i.id}`;
|
||||
await i.showModal(
|
||||
new ModalBuilder()
|
||||
.setCustomId(modalId)
|
||||
.setTitle("Request action")
|
||||
.addLabelComponents((label) => label
|
||||
.setLabel("What needs to be fixed?")
|
||||
.setTextInputComponent((input) => {
|
||||
input
|
||||
.setCustomId("notes")
|
||||
.setStyle(TextInputStyle.Paragraph)
|
||||
.setRequired(false)
|
||||
.setMaxLength(1000);
|
||||
return notes ? input.setValue(notes) : input;
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
const submitted = await i.awaitModalSubmit({
|
||||
time: NOTES_TIMEOUT_MS,
|
||||
filter: (m) => m.customId === modalId,
|
||||
}).catch(() => null);
|
||||
if (!submitted?.isFromMessage()) return;
|
||||
|
||||
await submitted.deferUpdate();
|
||||
notes = submitted.fields.getTextInputValue("notes").trim();
|
||||
|
||||
const res = await api.verifications({ id: v.id })["request-action"].post({
|
||||
reviewerNotes: notes || undefined,
|
||||
activityVerifications: activityVerifications(),
|
||||
});
|
||||
if (res.error) {
|
||||
await submitted.followUp({ content: errorText(res.error), flags: MessageFlags.Ephemeral });
|
||||
return;
|
||||
}
|
||||
await finish(`↩️ Action requested by ${i.user}.`);
|
||||
}
|
||||
});
|
||||
|
||||
collector.on("end", async (_, reason) => {
|
||||
if (reason === "done") return;
|
||||
await reply.edit({
|
||||
content: "⌛ Review timed out. Run `.verify` again to continue.",
|
||||
components: [],
|
||||
}).catch(() => { });
|
||||
});
|
||||
}
|
||||
} satisfies Command;
|
||||
Reference in New Issue
Block a user