all repos — stealth-developers @ bcf274d3451c1a8d98a6f41022875485cf8040b7

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
import { option } from "@purrkit/router";
import { Result } from "@sapphire/result";
import config from "@stealth-developers/config";
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 { RobloxUserClient, type UserRestrictionLog } 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";

const client = new RobloxUserClient({ cookie: config.roblox.cookie, apiKey: config.roblox.apiKey });

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());
}

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[]): 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) {
		return banContainer.addTextDisplayComponents(
			new TextDisplayBuilder().setContent("No bans found for this user."),
		);
	}

	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 timestamp =
			duration === "permanent" ? "Permanent" : `<t:${Math.round(duration.getTime() / 1000)}:R>`;

		const reason = log.displayReason || "No reason specified";
		const moderator = log.bannedBy;

		banContainer.addTextDisplayComponents(
			new TextDisplayBuilder().setContent(
				[
					`**Banned in ${log.projectName}** - <t:${banTime}:d> (<t:${banTime}:R>)`,
					`> **Expires:** ${timestamp}`,
					`> **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])] : [];
	});

	if (ticketNumbers.length > 0) {
		const ticketSelectMenu = new StringSelectMenuBuilder()
			.setCustomId("ticket-select:view")
			.setPlaceholder("View relevant ticket")
			.addOptions(
				ticketNumbers.map((number) =>
					new StringSelectMenuOptionBuilder()
						.setLabel(`Ticket ${number}`)
						.setValue(number.toString()),
				),
			);

		const ticketRow = new ActionRowBuilder<StringSelectMenuBuilder>().addComponents(
			ticketSelectMenu,
		);
		banContainer.addActionRowComponents(ticketRow);
	}

	return banContainer;
}

export const robloxUserCommand = useGetData.command("user", {
	description: "Get a Roblox user's information",
	options: {
		username: option.string("The username of the user", { required: false }),
		id: option.string("The user ID of the user", { required: false }),
	},
	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 banContainer = bansResponse.isOk()
			? buildBanContainer(bansResponse.unwrap())
			: new ContainerBuilder().addTextDisplayComponents(
					new TextDisplayBuilder().setContent("An error occurred while fetching ban history."),
				);

		await interaction.reply({
			components: [profileContainer, banContainer],
			flags: ["IsComponentsV2"],
		});
	},
});