Skip to content

Commit

Permalink
added new database logic
Browse files Browse the repository at this point in the history
instead of each table having its own function, I merged everything together and you will have to pass in a `Table` enum to get/remove a table. Same with inserting data.
  • Loading branch information
yorunoken committed Apr 20, 2024
1 parent aa5a151 commit 3729645
Show file tree
Hide file tree
Showing 22 changed files with 202 additions and 167 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ You can look at all of the libraries I use by going to `package.json` in the mai

- [rosu-pp's JavaScript bind](https://github.com/MaxOhn/rosu-pp-js) to calculate pp, bpm values, other technical stuff of osu!

Invite the bot to your server using [this link](https://discord.com/api/oauth2/authorize?client_id=995999045157916763&permissions=330752&scope=bot)
Invite the bot to your guild using [this link](https://discord.com/api/oauth2/authorize?client_id=995999045157916763&permissions=330752&scope=bot)

## Commands ⭐

Expand All @@ -42,7 +42,7 @@ These are the bare-bone ones.

- `/top` get a user's osu! top plays

use `/help` in your server for more information.
use `/help` in your guild for more information.

## Contributing 😶‍🌫️

Expand Down
9 changes: 5 additions & 4 deletions src/cleaners/scores.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { accuracyCalculator, getPerformanceResults, getRetryCount, hitValueCalculator } from "@utils/osu";
import { grades, rulesets } from "@utils/emotes";
import { insertData } from "@utils/database";
import { Tables } from "@type/database";
import type { Mode, UserScore, Beatmap, LeaderboardScores, PlayStatistics, ScoresInfo, Score, UserBestScore } from "@type/osu";
import type { ISOTimestamp } from "osu-web.js";

Expand Down Expand Up @@ -75,19 +76,19 @@ export async function getScore({ scores, beatmap: map_, index, mode, mapData }:

if (play.passed && "score" in play) {
insertData({
table: "osu_scores_pp",
table: Tables.PP,
id: play.id,
data: [
{
name: "pp",
key: "pp",
value: current.pp
},
{
name: "pp_fc",
key: "pp_fc",
value: fc.pp
},
{
name: "pp_perfect",
key: "pp_perfect",
value: perfect.pp
}
]
Expand Down
14 changes: 7 additions & 7 deletions src/commands/general/config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { getUser, insertData } from "@utils/database";
import { ScoreEmbed } from "@type/database";
import { getEntry, insertData } from "@utils/database";
import { ScoreEmbed, Tables } from "@type/database";
import { ApplicationCommandOptionType } from "lilybird";
import type { ApplicationCommandData, GuildInteraction } from "@lilybird/transformers";
import type { EmbedStructure } from "lilybird";
Expand Down Expand Up @@ -89,9 +89,9 @@ async function list(interaction: GuildInteraction<ApplicationCommandData>): Prom
};

const userId = interaction.member.user.id;
let user = getUser(userId);
let user = getEntry(Tables.USER, userId);
if (!user) {
insertData({ table: "users", id: userId, data: [ { name: "banchoId", value: null } ] });
insertData({ table: Tables.USER, id: userId, data: [ { key: "banchoId", value: null } ] });
user = { banchoId: null, mode: null, score_embeds: null, embed_type: null, id: userId };
}
const embeds: EmbedStructure = { fields: [], title: `Config settings of ${interaction.member.user.username}` };
Expand All @@ -110,13 +110,13 @@ async function list(interaction: GuildInteraction<ApplicationCommandData>): Prom
}

function mode(memberId: string, choice: string): void {
insertData({ table: "users", id: memberId, data: [ { name: "mode", value: choice } ] });
insertData({ table: Tables.USER, id: memberId, data: [ { key: "mode", value: choice } ] });
}

function scoreEmbed(memberId: string, choice: number): void {
insertData({ table: "users", id: memberId, data: [ { name: "score_embeds", value: choice } ] });
insertData({ table: Tables.USER, id: memberId, data: [ { key: "score_embeds", value: choice } ] });
}

function embedType(memberId: string, choice: string): void {
insertData({ table: "users", id: memberId, data: [ { name: "embed_type", value: choice } ] });
insertData({ table: Tables.USER, id: memberId, data: [ { key: "embed_type", value: choice } ] });
}
33 changes: 17 additions & 16 deletions src/commands/general/prefix.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { getServer, insertData } from "@utils/database";
import { getEntry, insertData } from "@utils/database";
import { DEFAULT_PREFIX, MAX_AMOUNT_OF_PREFIXES } from "@utils/constants";
import { prefixesCache } from "@listeners/guildCreate";
import { Tables } from "@type/database";
import { ApplicationCommandOptionType, EmbedType, PermissionFlags } from "lilybird";
import type { ApplicationCommandData, GuildInteraction } from "@lilybird/transformers";
import type { SlashCommand } from "@type/commands";
Expand Down Expand Up @@ -75,9 +76,9 @@ async function add({ prefix, interaction, guildId }: { prefix?: string, interact
if (checkPerms === false)
return;

const server = getServer(guildId);
if (!prefix || !server) return;
let { prefixes } = server;
const guild = getEntry(Tables.GUILD, guildId);
if (typeof prefix === "undefined" || guild === null) return;
let { prefixes } = guild;

if (prefixes !== null && !Array.isArray(prefixes))
prefixes = JSON.parse(prefixes) as Array<string>;
Expand All @@ -94,7 +95,7 @@ async function add({ prefix, interaction, guildId }: { prefix?: string, interact

const newPrefixes = prefixes === null ? [prefix] : [...prefixes, prefix];

insertData({ table: "servers", id: guildId, data: [ { name: "prefixes", value: JSON.stringify(newPrefixes) } ] });
insertData({ table: Tables.GUILD, id: guildId, data: [ { key: "prefixes", value: JSON.stringify(newPrefixes) } ] });
prefixesCache.set(guildId, newPrefixes);

await interaction.editReply(`**The prefix \`${prefix}\` has been added to the list.**`);
Expand All @@ -106,12 +107,12 @@ async function remove({ prefix, interaction, guildId }: { prefix?: string, inter
if (checkPerms === false)
return;

const server = getServer(guildId);
if (!prefix || !server) return;
const { prefixes } = server;
const guild = getEntry(Tables.GUILD, guildId);
if (typeof prefix === "undefined" || guild === null) return;
const { prefixes } = guild;

if (prefixes === null) {
await interaction.editReply("**There aren't any prefixes on this server. You can add a new prefixes by using `/prefix add`**");
await interaction.editReply("**There aren't any prefixes on this guild. You can add a new prefixes by using `/prefix add`**");
return;
}

Expand All @@ -121,27 +122,27 @@ async function remove({ prefix, interaction, guildId }: { prefix?: string, inter
}

const newPrefixes = prefixes.filter((item) => item !== prefix);
insertData({ table: "servers", id: guildId, data: [ { name: "prefixes", value: newPrefixes.length > 0 ? JSON.stringify(newPrefixes) : null } ] });
insertData({ table: Tables.GUILD, id: guildId, data: [ { key: "prefixes", value: newPrefixes.length > 0 ? JSON.stringify(newPrefixes) : null } ] });
prefixesCache.set(guildId, newPrefixes.length > 0 ? newPrefixes : DEFAULT_PREFIX);

let message = `**The prefix \`${prefix}\` has been removed from the list.**`;
if (newPrefixes.length === 0)
message = `**__Warning__:\nThere are no more custom prefixes on the server left. The default prefix is \`${DEFAULT_PREFIX.join("")}\`**`;
message = `**__Warning__:\nThere are no more custom prefixes on the guild left. The default prefix is \`${DEFAULT_PREFIX.join("")}\`**`;

await interaction.editReply(message);
return;
}

async function list({ interaction, guildId }: { interaction: GuildInteraction<ApplicationCommandData>, guildId: string }): Promise<void> {
const server = getServer(guildId);
if (!server) return;
const guild = getEntry(Tables.GUILD, guildId);
if (guild === null) return;

const { prefixes } = server;
const { prefixes } = guild;

if (prefixes === null) {
await interaction.editReply(`**There aren't any custom prefixes on this server. The default is \`${DEFAULT_PREFIX.join("")}\`**`);
await interaction.editReply(`**There aren't any custom prefixes on this guild. The default is \`${DEFAULT_PREFIX.join("")}\`**`);
return;
}

await interaction.editReply({ embeds: [ { type: EmbedType.Rich, title: "Prefixes!", description: `- \`${prefixes.join("`\n- `")}\`` } ] });
await interaction.editReply({ embeds: [ { type: EmbedType.Rich, title: "Currently defined prefixes", description: `**\`${prefixes.join("`**, `")}\`**` } ] });
}
7 changes: 4 additions & 3 deletions src/commands/osu/unlink.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { getUser, removeUser } from "@utils/database";
import { getEntry, removeEntry } from "@utils/database";
import { slashCommandsIds } from "@utils/cache";
import { Tables } from "@type/database";
import type { SlashCommand } from "@type/commands";
import type { ApplicationCommandData, GuildInteraction } from "@lilybird/transformers";

Expand All @@ -13,12 +14,12 @@ async function run(interaction: GuildInteraction<ApplicationCommandData>): Promi

const linkCommand = slashCommandsIds.get("link");
const userId = interaction.member.user.id;
const user = getUser(userId);
const user = getEntry(Tables.USER, userId);
if (!user?.banchoId) {
await interaction.editReply(`You are not linked to the bot! You can link yourself using ${linkCommand}, if you want.`);
return;
}

removeUser(userId);
removeEntry(Tables.USER, userId);
await interaction.editReply(`Sad to see you go :(\nYou can always re-link yourself using ${linkCommand}!`);
}
5 changes: 3 additions & 2 deletions src/commands/owner/owner.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { getServer, query } from "@utils/database";
import { getEntry, query } from "@utils/database";
import { Tables } from "@type/database";
import { ApplicationCommandOptionType } from "lilybird";
import type { ApplicationCommandData, GuildInteraction } from "@lilybird/transformers";
import type { SlashCommand } from "@type/commands";
Expand Down Expand Up @@ -73,7 +74,7 @@ ${response}

async function servers(interaction: GuildInteraction<ApplicationCommandData>): Promise<void> {
const id = interaction.data.getString("id", true);
const guild = getServer(id);
const guild = getEntry(Tables.GUILD, id);
if (guild === null) {
await interaction.editReply("Server not found!");
return;
Expand Down
5 changes: 3 additions & 2 deletions src/embed-builders/compare.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { getProfile } from "@cleaners/profile";
import { getScore } from "@cleaners/scores";
import { SPACE } from "@utils/constants";
import { getMap } from "@utils/database";
import { getEntry } from "@utils/database";
import { downloadBeatmap, saveScoreDatas } from "@utils/osu";
import { Tables } from "@type/database";
import { EmbedType } from "lilybird";
import type { CompareBuilderOptions } from "@type/embedBuilders";
import type { EmbedStructure } from "lilybird";
Expand Down Expand Up @@ -59,7 +60,7 @@ async function getMultiplePlays({ plays, profile, beatmap, mode }:
mode: Mode
}): Promise<Array<EmbedStructure>> {
const beatmapId = beatmap.id;
const mapData = getMap(beatmapId)?.data ?? (await downloadBeatmap(beatmapId)).contents;
const mapData = getEntry(Tables.MAP, beatmapId)?.data ?? (await downloadBeatmap(beatmapId)).contents;

const playsTemp: Array<Promise<ScoresInfo>> = [];
for (let i = 0; i < plays.length; i++) playsTemp.push(getScore({ scores: plays, index: i, mode, beatmap, mapData }));
Expand Down
5 changes: 3 additions & 2 deletions src/embed-builders/leaderboard.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { getScore } from "@cleaners/scores";
import { SPACE } from "@utils/constants";
import { getMap } from "@utils/database";
import { getEntry } from "@utils/database";
import { downloadBeatmap } from "@utils/osu";
import { Tables } from "@type/database";
import { EmbedType } from "lilybird";
import type { LeaderboardBuilderOptions } from "@type/embedBuilders";
import type { EmbedStructure } from "lilybird";
Expand All @@ -28,7 +29,7 @@ export async function leaderboardBuilder({
async function getPlays(plays: Array<LeaderboardScores>, beatmap: Beatmap, page: number): Promise<Array<EmbedStructure>> {
const beatmapId = beatmap.id;
const mode = <Mode>beatmap.mode;
const mapData = getMap(beatmapId)?.data ?? (await downloadBeatmap(beatmapId)).contents;
const mapData = getEntry(Tables.MAP, beatmapId)?.data ?? (await downloadBeatmap(beatmapId)).contents;

const pageStart = page * 5;
const pageEnd = pageStart + 5;
Expand Down
5 changes: 3 additions & 2 deletions src/embed-builders/map.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { client } from "@utils/initalize";
import { downloadBeatmap, getPerformanceResults } from "@utils/osu";
import { getMap } from "@utils/database";
import { getEntry } from "@utils/database";
import { rulesets } from "@utils/emotes";
import { Tables } from "@type/database";
import { EmbedType } from "lilybird";
import type { MapBuilderOptions } from "@type/embedBuilders";
import type { EmbedStructure } from "lilybird";
Expand All @@ -24,7 +25,7 @@ export async function mapBuilder({

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

const mapData = getMap(beatmapId)?.data ?? (await downloadBeatmap(beatmapId)).contents;
const mapData = getEntry(Tables.MAP, beatmapId)?.data ?? (await downloadBeatmap(beatmapId)).contents;

const performancesAsync = [];
const accuracyList = [98, 97, 95];
Expand Down
6 changes: 3 additions & 3 deletions src/embed-builders/plays.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { SPACE } from "@utils/constants";
import { EmbedScoreType } from "@type/database";
import { saveScoreDatas } from "@utils/osu";
import { EmbedType } from "lilybird";
import type { DatabaseUser } from "@type/database";
import type { User } from "@type/database";
import type { UserScore, Mode, ProfileInfo, ScoresInfo, UserBestScore } from "@type/osu";
import type { PlaysBuilderOptions } from "@type/embedBuilders";
import type { EmbedAuthorStructure, EmbedFieldStructure, EmbedFooterStructure, EmbedImageStructure, EmbedStructure, EmbedThumbnailStructure } from "lilybird";
Expand Down Expand Up @@ -75,7 +75,7 @@ async function getSinglePlay({ mode, index, plays, profile, authorDb, isMultiple
mode: Mode,
profile: ProfileInfo,
index: number,
authorDb: DatabaseUser | null,
authorDb: User | null,
isMultiple?: boolean
}): Promise<Array<EmbedStructure>> {
const isMaximized = (authorDb?.score_embeds ?? 1) === 1;
Expand Down Expand Up @@ -215,7 +215,7 @@ async function getMultiplePlays({ plays, page, mode, profile, authorDb }:
page: number,
mode: Mode,
profile: ProfileInfo,
authorDb: DatabaseUser | null
authorDb: User | null
}): Promise<Array<EmbedStructure>> {
const embedType = authorDb?.embed_type ?? EmbedScoreType.Hanami;

Expand Down
5 changes: 3 additions & 2 deletions src/embed-builders/simulate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { client } from "@utils/initalize";
import { accuracyCalculator, downloadBeatmap, getPerformanceResults, gradeCalculator, hitValueCalculator } from "@utils/osu";
import { getMap } from "@utils/database";
import { getEntry } from "@utils/database";
import { grades, rulesets } from "@utils/emotes";
import { SPACE } from "@utils/constants";
import { Tables } from "@type/database";
import { EmbedType } from "lilybird";
import type { Mode } from "@type/osu";
import type { SimulateBuilderOptions } from "@type/embedBuilders";
Expand All @@ -31,7 +32,7 @@ export async function simulateBuilder({

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

const mapData = getMap(beatmapId)?.data ?? (await downloadBeatmap(beatmapId)).contents;
const mapData = getEntry(Tables.MAP, beatmapId)?.data ?? (await downloadBeatmap(beatmapId)).contents;

const performance = await getPerformanceResults({
beatmapId,
Expand Down
21 changes: 12 additions & 9 deletions src/listeners/guildCreate.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,32 @@
import { getServer, insertData, removeServer } from "@utils/database";
import { getEntry, insertData, removeEntry } from "@utils/database";
import { Tables } from "@type/database";
import type { Guild } from "@type/database";
import type { Event } from "@lilybird/handlers";

export const prefixesCache = new Map<string, Array<string>>();

export default {
event: "guildCreate",
run: (guild) => {
// Remove guild from database if it's unavailable.
if (!("name" in guild)) {
removeServer(guild.id);
removeEntry(Tables.GUILD, guild.id);
return;
}

const document = getServer(guild.id);
const document = getEntry(Tables.GUILD, guild.id);

const data: Array<{ name: string, value: string | number | null }> = [
{ name: "name", value: guild.name },
{ name: "owner_id", value: guild.ownerId },
{ name: "joined_at", value: guild.joinedAt }
const data: Array<{ key: keyof Guild, value: string | number | null }> = [
{ key: "name", value: guild.name },
{ key: "owner_id", value: guild.ownerId },
{ key: "joined_at", value: guild.joinedAt }
];

if (document === null)
data.push({ name: "prefixes", value: null });
data.push({ key: "prefixes", value: null });

insertData({
table: "servers",
table: Tables.GUILD,
id: guild.id,
data
});
Expand Down
5 changes: 3 additions & 2 deletions src/listeners/guildDelete.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { removeServer } from "@utils/database";
import { removeEntry } from "@utils/database";
import { Tables } from "@type/database";
import type { Event } from "@lilybird/handlers";

export const prefixesCache = new Map<string, Array<string>>();

export default {
event: "guildDelete",
run: (_, guild) => {
removeServer(guild.id);
removeEntry(Tables.GUILD, guild.id);
}
} satisfies Event<"guildDelete">;
Loading

0 comments on commit 3729645

Please sign in to comment.