Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add simulate command #172

Merged
merged 4 commits into from
Apr 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions src/commands-message/osu/simulate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { parseOsuArguments } from "@utils/args";
import { getBeatmapIdFromContext } from "@utils/osu";
import { Mode } from "@type/osu";
import { EmbedBuilderType } from "@type/embedBuilders";
import { simulateBuilder } from "@builders/simulate";
import { EmbedType } from "lilybird";
import type { DifficultyOptions } from "@type/commandArgs";
import type { Mod } from "osu-web.js";
import type { GuildTextChannel, Message } from "@lilybird/transformers";
import type { MessageCommand } from "@type/commands";

export default {
name: "simulate",
aliases: ["simulate", "sim", "s"],
description: "Display statistics of a beatmap.",
cooldown: 1000,
run
} satisfies MessageCommand;

async function run({ message, args, channel }: { message: Message, args: Array<string>, channel: GuildTextChannel }): Promise<void> {
const { user, mods, flags } = parseOsuArguments(message, args, Mode.OSU);

const options: DifficultyOptions = {
acc: Number(flags.acc ?? flags.accuracy) || undefined,
bpm: Number(flags.bpm) || undefined,
clock_rate: Number(flags.clockrate ?? flags.clockRate ?? flags.clock_rate ?? flags.cr) || undefined,
combo: Number(flags.combo) || undefined,
ar: Number(flags.ar) || undefined,
cs: Number(flags.cs) || undefined,
od: Number(flags.od) || undefined,
n300: Number(flags.n300 ?? flags["300"]) || undefined,
n100: Number(flags.n100 ?? flags["100"]) || undefined,
n50: Number(flags.n50 ?? flags["50"]) || undefined,
ngeki: Number(flags.ngeki ?? flags.geki) || undefined,
nkatu: Number(flags.natu ?? flags.katu) || undefined,
nmisses: Number(flags.nmisses ?? flags.misses ?? flags.miss ?? flags.nmiss) || undefined
};

const beatmapId = user.beatmapId ?? await getBeatmapIdFromContext({ message, client: message.client });
if (typeof beatmapId === "undefined" || beatmapId === null) {
await channel.send({
embeds: [
{
type: EmbedType.Rich,
title: "Uh oh! :x:",
description: "It seems like the beatmap ID couldn't be found :(\n"
}
]
});
return;
}

const embeds = await simulateBuilder({
type: EmbedBuilderType.SIMULATE,
initiatorId: message.author.id,
beatmapId: Number(beatmapId),
options,
mods: <Array<Mod> | null>mods.name?.match(/.{1,2}/g) ?? null
});
await channel.send({ embeds });
}
149 changes: 149 additions & 0 deletions src/commands/osu/simulate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
import { getCommandArgs } from "@utils/args";
import { getBeatmapIdFromContext } from "@utils/osu";
import { simulateBuilder } from "@builders/simulate";
import { EmbedBuilderType } from "@type/embedBuilders";
import { ApplicationCommandOptionType, EmbedType } from "lilybird";
import type { SlashCommand } from "@type/commands";
import type { Mod } from "osu-web.js";
import type { ApplicationCommandData, Interaction } from "@lilybird/transformers";

export default {
data: {
name: "simulate",
description: "Simulate a score on a beatmap..",
options: [
{
type: ApplicationCommandOptionType.STRING,
name: "map",
description: "Specify a beatmap link (eg: https://osu.ppy.sh/b/72727)"
},
{
type: ApplicationCommandOptionType.STRING,
name: "mods",
description: "Specify a mods combination.",
min_length: 2
},
{
type: ApplicationCommandOptionType.STRING,
name: "mode",
description: "Specify a gamemode."
},
{
type: ApplicationCommandOptionType.NUMBER,
name: "combo",
description: "Specify a combo.",
min_value: 0
},
{
type: ApplicationCommandOptionType.NUMBER,
name: "acc",
description: "Specify an accuracy.",
min_value: 0
},
{
type: ApplicationCommandOptionType.NUMBER,
name: "clock_rate",
description: "Specify a custom clockrate that overwrites any other rate changes."
},
{
type: ApplicationCommandOptionType.NUMBER,
name: "bpm",
description: "Specify a BPM instead of a clock rate.",
min_value: 0,
max_value: 999
},
{
type: ApplicationCommandOptionType.NUMBER,
name: "n300",
description: "Specify the amount of 300s.",
min_value: 0
},
{
type: ApplicationCommandOptionType.NUMBER,
name: "n100",
description: "Specify the amount of 100s.",
min_value: 0
},
{
type: ApplicationCommandOptionType.NUMBER,
name: "n50s",
description: "Specify the amount of 50s.",
min_value: 0
},
{
type: ApplicationCommandOptionType.NUMBER,
name: "nmisses",
description: "Specify the amount of misses.",
min_value: 0
},
{
type: ApplicationCommandOptionType.NUMBER,
name: "ngeki",
description: "Specify the amount of gekis, aka n320.",
min_value: 0
},
{
type: ApplicationCommandOptionType.NUMBER,
name: "nkatu",
description: "Specify the amount of katus, aka n200.",
min_value: 0
},
{
type: ApplicationCommandOptionType.INTEGER,
name: "ar",
description: "Overwrite the map's approach rate.",
min_value: 0,
max_value: 11
},
{
type: ApplicationCommandOptionType.INTEGER,
name: "od",
description: "Overwrite the map's overall difficulty.",
min_value: 0,
max_value: 11.11
},
{
type: ApplicationCommandOptionType.INTEGER,
name: "cs",
description: "Overwrite the map's circle size.",
min_value: 0,
max_value: 10
}
]
},
run
} satisfies SlashCommand;

async function run(interaction: Interaction<ApplicationCommandData>): Promise<void> {
if (!interaction.inGuild()) return;
await interaction.deferReply();

const args = getCommandArgs(interaction, true);

if (typeof args === "undefined") return;
const { user, mods, difficultySettings } = args;

const beatmapId = user.beatmapId ?? await getBeatmapIdFromContext({ channelId: interaction.channelId, client: interaction.client });
if (typeof beatmapId === "undefined" || beatmapId === null) {
await interaction.editReply({
embeds: [
{
type: EmbedType.Rich,
title: "Uh oh! :x:",
description: "It seems like the beatmap ID couldn't be found :(\n"
}
]
});
return;
}

const embeds = await simulateBuilder({
type: EmbedBuilderType.SIMULATE,
initiatorId: interaction.member.user.id,
options: difficultySettings ?? {},
beatmapId: Number(beatmapId),
mods: <Array<Mod> | null>mods.name?.match(/.{1,2}/g) ?? null
});
await interaction.editReply({ embeds });
}

133 changes: 133 additions & 0 deletions src/embed-builders/simulate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { client } from "@utils/initalize";
import { accuracyCalculator, downloadBeatmap, getPerformanceResults } from "@utils/osu";
import { getMap } from "@utils/database";
import { rulesets } from "@utils/emotes";
import { SPACE } from "@utils/constants";
import { EmbedType } from "lilybird";
import type { Mode } from "@type/osu";
import type { SimulateBuilderOptions } from "@type/embedBuilders";
import type { EmbedStructure } from "lilybird";

export async function simulateBuilder({
beatmapId,
mods,
options
}: SimulateBuilderOptions): Promise<Array<EmbedStructure>> {
const beatmapRequest = await client.safeParse(client.beatmaps.getBeatmap(beatmapId));
if (!beatmapRequest.success) {
return [
{
type: EmbedType.Rich,
title: "Uh oh! :x:",
description: "It seems like this beatmap couldn't be found :("
}
];
}
const map = beatmapRequest.data;
const { acc, ar, bpm, clock_rate: clockRate, combo, cs, n100, n300, n50, ngeki, nkatu, nmisses, od } = options;

const { beatmapset: mapset, mode, version } = map;

const mapData = getMap(beatmapId)?.data ?? (await downloadBeatmap(beatmapId)).contents;

const performance = await getPerformanceResults({
beatmapId,
setId: map.mode_int,
mapData,
mapSettings: { ar, cs, od },
maxCombo: combo,
hitValues: { count_100: n100, count_300: n300, count_50: n50, count_geki: ngeki, count_katu: nkatu, count_miss: nmisses },
clockRate: clockRate ?? (bpm && map.bpm ? bpm / map.bpm : undefined),
accuracy: acc,
mods: mods ?? 0
});

if (performance === null) {
return [
{
title: "ERROR",
description: "Oops, sorry about that, it seems there was an error. Maybe try again?\n\nPERFORMANCES IS NULL"
}
];
}
const { current, mapValues, difficultyAttrs, perfect, fc } = performance;

console.log(current.state);

const order = ["count_geki", "count_300", "count_katu", "count_100", "count_50", "count_miss"];

// rosu-pp exposes `state` as a Map and not an object, so you have to get them like this.
// will be fixed in the future and I will remove the eslint error things.
const hitValues = {
count_300: current.state?.get("n300"),
count_100: current.state?.get("n100"),
count_50: current.state?.get("n50"),
count_miss: current.state?.get("misses"),
count_geki: current.state?.get("nGeki"),
count_katu: current.state?.get("nKatu")
};

let hitValuesString = "";
for (let i = 0; i < order.length; i++) {
const count = order[i];
const countKey = count as keyof typeof hitValues;
const countValue = hitValues[countKey];
if (typeof countValue !== "undefined") {
if (hitValuesString.length > 0)
hitValuesString += "/";

hitValuesString += countValue;
}
}

// same thing here
const comboValue = current.state?.get("maxCombo");
const comboValues = `**${comboValue}**/${map.max_combo}x`;
const comboDifference = (comboValue ?? 0) / map.max_combo;
console.log(comboDifference);

const accuracy = accuracyCalculator(map.mode as Mode, hitValues);

const drainLengthInSeconds = map.total_length / difficultyAttrs.clockRate;
const drainMinutes = Math.floor(drainLengthInSeconds / 60);
const drainSeconds = Math.ceil(drainLengthInSeconds % 60);

const objects = map.count_circles + map.count_sliders + map.count_spinners;

const newBpm = difficultyAttrs.clockRate * mapValues.bpm;
const statsField = [
`**Stars:** **\`${current.difficulty.stars.toFixed(2)}\`** **Mods:** \`+${mods ? mods.join("") : "NM"}\` **BPM:** \`${newBpm.toFixed(0)}\``,
`**Length:** \`${drainMinutes}:${drainSeconds < 10 ? `0${drainSeconds}` : drainSeconds}\` **Max Combo:** \`${current.difficulty.maxCombo}\` **Objects:** \`${objects.toLocaleString()}\``,
`**AR:** \`${difficultyAttrs.ar.toFixed(1)}\` **OD:** \`${difficultyAttrs.od.toFixed(1)}\` **CS:** \`${difficultyAttrs.cs.toFixed(1)}\` **HP:** \`${difficultyAttrs.hp.toFixed(1)}\``
];

const scoreField = [
`**${current.pp.toFixed(2)}**/${perfect.pp.toFixed(2)}pp ${typeof current.effectiveMissCount !== "undefined" && current.effectiveMissCount > 1 || comboDifference < 0.99
? `~~[**${fc.pp.toFixed(2)}**]~~`
: ""} ${SPACE} ${accuracy.toFixed(2)}% `,
`[${comboValues}] ${SPACE} {${hitValuesString}}`
];

return [
{
title: `${mapset.artist} - ${mapset.title}`,
url: `https://osu.ppy.sh/b/${beatmapId}`,
thumbnail: { url: `https://assets.ppy.sh/beatmaps/${mapset.id}/covers/list.jpg` },
author: { name: `${mapset.status.charAt(0).toUpperCase()}${mapset.status.slice(1)} mapset by ${mapset.creator}`, icon_url: `https://a.ppy.sh/${mapset.user_id}` },
fields: [
{
name: `${rulesets[mode]} ${version}`,
value: scoreField.join("\n"),
inline: false
},
{
name: "Stats",
value: statsField.join("\n"),
inline: false
}
]
}
];
}
21 changes: 19 additions & 2 deletions src/types/commandArgs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,28 @@ interface FailUser extends BaseUser {
failMessage: string;
}

export interface DifficultyOptions {
combo?: number;
acc?: number;
clock_rate?: number;
bpm?: number;
n300?: number;
n100?: number;
n50?: number;
nmisses?: number;
ngeki?: number;
nkatu?: number;
ar?: number;
od?: number;
cs?: number;
}

export type User = SuccessUser | FailUser;

export interface CommandArgs {
export interface SlashCommandArgs {
user: User;
mods: Mods;
difficultySettings?: DifficultyOptions;
}

export interface Mods {
Expand All @@ -39,7 +56,7 @@ export interface Mods {
name: Mod | null;
}

export interface ParsedArgs {
export interface PrefixCommandArgs {
tempUser: Array<string> | null;
user: User;
flags: Record<string, string | undefined>;
Expand Down
Loading
Loading