apps/bot/src/feats/roblox/user.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 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 |
import { option } from "@purrkit/router";
import { Result } from "@sapphire/result";
import {
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
ContainerBuilder,
SectionBuilder,
StringSelectMenuBuilder,
StringSelectMenuOptionBuilder,
TextDisplayBuilder,
ThumbnailBuilder,
} from "discord.js";
import { errorMessage, logger } from "@/lib";
import { useGetData } from "@/middleware";
import { Projects } from "../bugs/shared";
import { viewTicketMenu } from "../tickets/misc";
import { type UserRestrictionLog, client } from "./client";
type BannedBy = { displayName: string; username: string; id: string };
type Project = (typeof Projects)[keyof typeof Projects];
type EnrichedUserRestrictionLog = UserRestrictionLog & {
bannedBy: BannedBy;
};
type EnrichedBans = Project & { bans: EnrichedUserRestrictionLog[] };
const DEFAULT_AVATAR_URL =
"https://images-ext-1.discordapp.net/external/j7H9Ep50cCN5igmEKGwFnv7frj2590Xg2Z4hvHGFPPo/%3Fsize%3D4096/https/cdn.discordapp.com/icons/895998762630127616/36c6e14d0933eb338826599b632df818.png?format=webp&quality=lossless&width=852&height=852";
function calculateBanDuration(from: Date, duration: string): Date {
const match = duration.trim().match(/^(\d+)\s*([a-zA-Z]?)$/);
if (!match) return new Date();
const value = parseInt(match[1]!, 10);
const unit = (match[2] ?? "s").toLowerCase();
const multipliers: Record<string, number> = {
s: 1000,
m: 60 * 1000,
h: 60 * 60 * 1000,
d: 24 * 60 * 60 * 1000,
y: 365 * 24 * 60 * 60 * 1000,
};
const multiplier = multipliers[unit];
if (multiplier === undefined) return new Date();
return new Date(from.getTime() + value * multiplier);
}
function getModeratorId(log: UserRestrictionLog): string | null {
if ("robloxUser" in log.moderator) {
return log.moderator.robloxUser.split("/")[1] ?? null;
}
const privateReason = log.privateReason;
const match = privateReason ? privateReason.match(/^Banned by (.+)$/) : null;
return match ? (match[1] ?? null) : null;
}
function resolveBannedBy(
log: UserRestrictionLog,
userProfiles: Map<string, { displayName: string; name: string }>,
): BannedBy {
const modId = getModeratorId(log);
if (modId) {
const profile = userProfiles.get(modId);
return profile
? { displayName: profile.displayName, username: profile.name, id: modId }
: { displayName: `User ID: ${modId}`, username: `User ID: ${modId}`, id: modId };
}
if ("gameScript" in log.moderator) {
return { displayName: "Game Script", username: "Game Script", id: "none" };
}
return { displayName: "unknown", username: "unknown", id: "unknown" };
}
async function resolveUserId(username?: string, id?: string): Promise<string | null> {
if (id) return id;
if (!username) return null;
const response = await Result.fromAsync(client.getUserId(username));
if (response.isErr()) {
logger.error(response.unwrapErr(), `error fetching user ID for username ${username}`);
return null;
}
return String(response.unwrap());
}
function getBansStateSignature(projectsWithBans: EnrichedBans[]): string {
return JSON.stringify(
projectsWithBans.map((project) => ({
universe: project.universe,
bans: project.bans.map((ban) => ({
createTime: ban.createTime,
active: ban.active,
displayReason: ban.displayReason,
duration: ban.duration,
moderatorId: ban.bannedBy.id,
})),
})),
);
}
export async function getLastBans(userId: string | number): Promise<EnrichedBans[]> {
const filter = `user == 'users/${userId}'`;
const uniqueUserIds = new Set<string>();
const rawProjectBans = await Promise.all(
Object.values(Projects).map(async (project) => {
const projectBans = await client.listUserRestrictionLogs(project.universe, { filter });
const logs = projectBans?.logs ?? [];
for (const log of logs) {
const modId = getModeratorId(log);
if (modId) uniqueUserIds.add(modId);
}
return { project, logs };
}),
);
const userProfiles = new Map<string, { displayName: string; name: string }>();
await Promise.all(
Array.from(uniqueUserIds).map(async (id) => {
try {
const profile = await client.getUserProfile(id);
if (profile) userProfiles.set(id, profile);
} catch (error) {
logger.error(error, `failed to fetch profile for user ${id}`);
}
}),
);
return rawProjectBans.map(({ project, logs }) => {
const enrichedLogs = logs.map((log) => ({
...log,
bannedBy: resolveBannedBy(log, userProfiles),
}));
return { ...project, bans: enrichedLogs };
});
}
function buildProfileContainer(user: any, thumbnailUrl: string, id: string): ContainerBuilder {
const date = Math.round(new Date(user.createTime).getTime() / 1000);
const userSection = new SectionBuilder()
.addTextDisplayComponents(
new TextDisplayBuilder().setContent(`# ${user.displayName || user.name}`),
new TextDisplayBuilder().setContent(
`@${user.name} - ${user.id} - created <t:${date}> (<t:${date}:R>)`,
),
new TextDisplayBuilder().setContent(user.about ? `>>> ${user.about}` : "No bio provided."),
)
.setThumbnailAccessory(new ThumbnailBuilder().setURL(thumbnailUrl));
const linkRow = new ActionRowBuilder<ButtonBuilder>().addComponents(
new ButtonBuilder()
.setStyle(ButtonStyle.Link)
.setLabel("Open Profile")
.setURL(`https://roblox.com/users/${id}/profile`),
);
return new ContainerBuilder().addSectionComponents(userSection).addActionRowComponents(linkRow);
}
function buildBanContainer(
projectsWithBans: EnrichedBans[],
nextSyncAt?: Date | null,
): ContainerBuilder {
const banContainer = new ContainerBuilder();
const allBans = projectsWithBans
.flatMap((project) => project.bans.map((ban) => ({ ...ban, projectName: project.displayName })))
.sort((a, b) => a.createTime.localeCompare(b.createTime))
.slice(-5);
if (allBans.length === 0) {
banContainer.addTextDisplayComponents(
new TextDisplayBuilder().setContent("No bans found for this user."),
);
} else {
for (const log of allBans) {
const banTime = Math.round(new Date(log.createTime).getTime() / 1000);
const duration =
"duration" in log && log.duration
? calculateBanDuration(new Date(log.createTime), log.duration)
: "permanent";
const isActive = log.active !== false;
const statusLabel = isActive ? "Expires" : "Status";
const statusValue = isActive
? duration === "permanent"
? "Permanent"
: `<t:${Math.round(duration.getTime() / 1000)}:R>`
: "Ban removed";
const isUnbanned = statusValue === "Ban removed";
const reason = log.displayReason || "No reason specified";
const moderator = log.bannedBy;
banContainer.addTextDisplayComponents(
new TextDisplayBuilder().setContent(
[
isUnbanned
? `**Unbanned from ${log.projectName}** - <t:${banTime}:d> (<t:${banTime}:R>)`
: `**Banned in ${log.projectName}** - <t:${banTime}:d> (<t:${banTime}:R>)`,
`> **${statusLabel}:** ${statusValue}`,
`> **Reason:** ${reason}`,
`> **Moderator:** [${moderator.displayName || moderator.username}](https://www.roblox.com/users/${moderator.id})`,
].join("\n"),
),
);
}
const ticketNumbers = allBans.flatMap((log) => {
const match = log.privateReason?.trim().match(/^ticket\s+(\d+)$/i);
return match ? [Number(match[1])] : [];
});
const uniqueTicketNumbers = Array.from(new Set(ticketNumbers));
if (uniqueTicketNumbers.length > 0) {
const ticketSelectMenu = new StringSelectMenuBuilder()
.setCustomId(viewTicketMenu.id())
.setPlaceholder("View relevant ticket")
.addOptions(
uniqueTicketNumbers.map((number) =>
new StringSelectMenuOptionBuilder()
.setLabel(`Ticket ${number}`)
.setValue(number.toString()),
),
);
const ticketRow = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
ticketSelectMenu,
);
banContainer.addActionRowComponents(ticketRow);
}
}
if (nextSyncAt) {
const nextSyncTimestamp = Math.round(nextSyncAt.getTime() / 1000);
banContainer.addTextDisplayComponents(
new TextDisplayBuilder().setContent(`\n*Next sync <t:${nextSyncTimestamp}:R>*`),
);
} else if (nextSyncAt === null) {
banContainer.addTextDisplayComponents(
new TextDisplayBuilder().setContent("\n*Syncing finished*"),
);
}
return banContainer;
}
export const robloxUserCommand = useGetData.command("user", {
description: "Get a Roblox user's information",
options: {
username: option.string.optional("The username of the user"),
id: option.string.optional("The user ID of the user"),
},
run: async (interaction, args) => {
const { username, id: userIdInput } = args;
if (!username && !userIdInput) {
return errorMessage(interaction, "You must provide either a username or user ID.");
}
const id = await resolveUserId(username, userIdInput);
if (!id) {
return errorMessage(interaction, "There was an error fetching the user's ID.");
}
const [profileResponse, thumbnailResponse, bansResponse] = await Promise.all([
Result.fromAsync(client.getUserProfile(id)),
Result.fromAsync(client.getAvatarUrl(id, { shape: "SQUARE", size: "420" })),
Result.fromAsync(getLastBans(id)),
]);
if (profileResponse.isErr()) {
logger.error(profileResponse.unwrapErr(), `error fetching profile for user ${id}`);
return errorMessage(interaction, "There was an error fetching the user's profile.");
}
const user = profileResponse.unwrap();
const thumbnailUrl =
thumbnailResponse.isOk() && thumbnailResponse.unwrap()
? thumbnailResponse.unwrap()!
: DEFAULT_AVATAR_URL;
const profileContainer = buildProfileContainer(user, thumbnailUrl, id);
const POLL_INTERVAL = 10_000;
const POLL_DURATION = 120_000;
const endTime = Date.now() + POLL_DURATION;
const initialNextSyncAt = new Date(Date.now() + POLL_INTERVAL);
let currentBans: EnrichedBans[] = [];
let currentBansKey = "error";
if (bansResponse.isOk()) {
currentBans = bansResponse.unwrap();
currentBansKey = getBansStateSignature(currentBans);
}
const banContainer = bansResponse.isOk()
? buildBanContainer(currentBans, initialNextSyncAt)
: new ContainerBuilder()
.addTextDisplayComponents(
new TextDisplayBuilder().setContent("An error occurred while fetching ban history."),
)
.addTextDisplayComponents(
new TextDisplayBuilder().setContent(
`\n*Next sync <t:${Math.round(initialNextSyncAt.getTime() / 1000)}:R>*`,
),
);
await interaction.reply({
components: [profileContainer, banContainer],
flags: ["IsComponentsV2"],
});
(async () => {
while (Date.now() < endTime) {
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL));
const newBansResponse = await Result.fromAsync(getLastBans(id));
if (newBansResponse.isErr()) {
logger.warn(newBansResponse.unwrapErr(), `Polling: failed to fetch bans for user ${id}`);
} else {
currentBans = newBansResponse.unwrap();
currentBansKey = getBansStateSignature(currentBans);
}
const nextSyncAt =
Date.now() + POLL_INTERVAL < endTime ? new Date(Date.now() + POLL_INTERVAL) : null;
let updatedBanContainer: ContainerBuilder;
if (currentBansKey === "error") {
updatedBanContainer = new ContainerBuilder().addTextDisplayComponents(
new TextDisplayBuilder().setContent("An error occurred while fetching ban history."),
);
if (nextSyncAt) {
const ts = Math.round(nextSyncAt.getTime() / 1000);
updatedBanContainer.addTextDisplayComponents(
new TextDisplayBuilder().setContent(`\n*Next sync <t:${ts}:R>*`),
);
} else {
updatedBanContainer.addTextDisplayComponents(
new TextDisplayBuilder().setContent("\n*Syncing finished*"),
);
}
} else {
updatedBanContainer = buildBanContainer(currentBans, nextSyncAt);
}
try {
await interaction.editReply({
components: [profileContainer, updatedBanContainer],
});
} catch (error) {
logger.error(error, "Failed to edit interaction reply during ban polling");
break;
}
}
if (Date.now() >= endTime) {
let finalBanContainer: ContainerBuilder;
if (currentBansKey === "error") {
finalBanContainer = new ContainerBuilder()
.addTextDisplayComponents(
new TextDisplayBuilder().setContent("An error occurred while fetching ban history."),
)
.addTextDisplayComponents(new TextDisplayBuilder().setContent("\n*Syncing finished*"));
} else {
finalBanContainer = buildBanContainer(currentBans, null);
}
try {
await interaction.editReply({
components: [profileContainer, finalBanContainer],
});
} catch (error) {
logger.error(error, "Failed to update reply on polling completion");
}
}
})().catch((error) => {
logger.error(error, "An unhandled error occurred in the ban polling loop");
});
},
});
|