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

QoL fixes for codebaes making it easier to read #63

Merged
merged 6 commits into from
Oct 25, 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
Binary file modified bun.lockb
Binary file not shown.
5 changes: 3 additions & 2 deletions ecosystem.config.cjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
module.exports = {
apps: [{
name: "Yuuko Production",
script: "./src/app.ts",
script: ".",
max_memory_restart: "812M",
watch: ["commit.hash"],
interpreter: "/usr/bin/bun",
Expand All @@ -10,7 +10,8 @@ module.exports = {
},
env_development: {
NODE_ENV: "development"
}
},
interpreter_args: "run start:prod"
}, {
name: "Yuuko Production API",
script: "./src/api.ts",
Expand Down
71 changes: 34 additions & 37 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@
"main": "src/app.js",
"scripts": {
"api": "bun run ./src/api.ts",
"start": "pm2 start ecosystem.config.js --env production",
"dev": "NODE_ENV=development bun run --watch ./src/app.ts",
"start:prod": "NODE_ENV=production bun run ./src/app.ts",
"start": "pm2 start ecosystem.config.cjs --env production",
"dev": "NODE_ENV=development bun run --define self=undefined --watch ./src/app.ts",
"start:prod": "NODE_ENV=production bun run --define self=undefined ./src/app.ts",
"test": "echo \"Error: no test specified\" && exit 1",
"format": "prettier --write .",
"lint": "eslint .",
Expand All @@ -36,43 +36,40 @@
"bindings"
],
"dependencies": {
"@acegoal07/discordjs-pagination": "^1.5.0",
"@discordjs/rest": "^0.3.0",
"@elysiajs/cors": "^1.0.2",
"@libsql/client": "^0.6.0",
"@types/bun": "^1.0.7",
"@types/dotenv-flow": "^3.3.1",
"@types/ms": "^0.7.33",
"@types/node-rsa": "^1.1.2",
"@upstash/redis": "^1.23.4",
"bun-types": "^1.0.5",
"@acegoal07/discordjs-pagination": "^1.5.9",
"@discordjs/rest": "^2.4.0",
"@elysiajs/cors": "^1.1.1",
"@libsql/client": "^0.14.0",
"@types/bun": "^1.1.12",
"@types/dotenv-flow": "^3.3.3",
"@types/ms": "^0.7.34",
"@types/node-rsa": "^1.1.4",
"@upstash/redis": "^1.34.3",
"bun-types": "^1.1.33",
"colors": "^1.4.0",
"discord.js": "^14.7.1",
"dotenv-flow": "^3.2.0",
"drizzle-orm": "^0.30.8",
"drizzle-kit": "^0.20.14",
"elysia": "^1.0.7",
"humanize-duration": "^3.27.0",
"jimp": "^0.22.10",
"discord.js": "^14.16.3",
"dotenv-flow": "^4.1.0",
"drizzle-kit": "^0.26.2",
"drizzle-orm": "^0.35.3",
"elysia": "^1.1.23",
"humanize-duration": "^3.32.1",
"jimp": "^1.6.0",
"ms": "^2.1.3",
"node-redis": "^0.1.7",
"node-rsa": "^1.1.1",
"pm2": "^5.3.0",
"redis": "^4.6.10",
"winston": "^3.11.0",
"zod": "^3.22.4"
"redis": "^4.7.0",
"winston": "^3.15.0",
"zod": "^3.23.8"
},
"devDependencies": {
"@antfu/eslint-config": "^1.0.0-beta.26",
"@graphql-codegen/cli": "^5.0.2",
"@graphql-codegen/typescript": "^4.0.8",
"@graphql-codegen/typescript-operations": "^4.2.2",
"@graphql-codegen/typescript-resolvers": "^4.2.0",
"@types/humanize-duration": "^3.27.1",
"@types/node": "^20.6.3",
"eslint": "^8.51.0",
"prettier": "^3.0.3",
"prettier-eslint": "^15.0.1",
"typescript": "^5.2.2"
"@antfu/eslint-config": "^3.8.0",
"@graphql-codegen/cli": "^5.0.3",
"@graphql-codegen/typescript": "^4.1.0",
"@graphql-codegen/typescript-operations": "^4.3.0",
"@graphql-codegen/typescript-resolvers": "^4.3.0",
"@types/humanize-duration": "^3.27.4",
"@types/node": "^22.8.1",
"eslint": "^9.13.0",
"prettier": "^3.3.3",
"prettier-eslint": "^16.3.0",
"typescript": "^5.6.3"
}
}
142 changes: 69 additions & 73 deletions src/commands/activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { embedError, graphQLRequest, SeriesTitle, getOptions, buildPagination }
import { EmbedBuilder, SlashCommandBuilder } from "discord.js";
import { mwGetUserEntry } from "#middleware/userEntry";
import type { Command } from "#structures/index";
import type { ActivityReply } from "#graphQL/types";
import type { ActivityReply, UserQueryVariables } from "#graphQL/types";

const name = "activity";
const usage = "activity <user>";
Expand All @@ -20,14 +20,9 @@ export default {
.addStringOption((option) => option.setName("user").setDescription("The user to search for").setRequired(false)),

run: async ({ interaction, client }): Promise<void> => {
if (!interaction.isCommand()) return;
getOptions;
const { user: username } = getOptions<{ user: string | undefined }>(interaction.options, ["user"]);

const vars: Partial<{
username: string;
userid: number;
}> = {
const vars: UserQueryVariables = {
username,
userid: interaction.alID,
};
Expand All @@ -53,86 +48,87 @@ export default {
const {
data: { Activity: data },
} = await graphQLRequest("Activity", vars, interaction.ALtoken);
if (data) {
const embed = new EmbedBuilder().setTimestamp(data?.createdAt * 1000);
const pageList = [];

switch (data?.__typename) {
case "ListActivity":
embed.setURL(data?.siteUrl!);
embed.setTitle(`Here's ${data?.user?.name?.toString() || "Unknown Name"}'s most recent activity!`);
embed.setDescription(
`${capitalizeString(data?.status!)} ${data?.progress?.toLowerCase() || ""} ${data?.status!.startsWith("read" || "watched") ? "of" : ""} **[${SeriesTitle(data.media?.title || undefined)}](${data?.media
?.siteUrl})**`,
);
embed.setFooter({ text: `${data?.likeCount | 0} ♥ ${data?.replyCount | 0} 💬` });
if (data.media?.bannerImage) {
embed.setImage(data.media.bannerImage);
} else {
const thumbnail = data?.media?.coverImage?.large || data?.media?.coverImage?.medium;
if (thumbnail) embed.setThumbnail(thumbnail);
}

pageList.push(embed);

// I couldn't find a good way to handle the type, so I couldn't extract it to a function
if (data.replies) {
const replyPages = Math.ceil(data.replyCount / 25);
for (let i = 0; i < replyPages; i++) {
const replyEmbed = new EmbedBuilder().setTitle(`Replies to ${data?.user?.name?.toString() || "Unknown Name"}'s activity!`);

const replies = data.replies.slice(i * 25, i * 25 + 25).map((reply) => {
if (!reply || !reply.user || !reply.text) return;
const replyText = anilistToMarkdown(reply.text, 1024);
const replyName = reply.user.name

return { name: replyName, value: replyText };
}).filter((reply) => reply !== undefined);
if (!data) {
return void interaction.editReply({ embeds: [embedError(`Couldn't find any data.`, vars)] });
}

replyEmbed.addFields(replies);
pageList.push(replyEmbed);
}
const embed = new EmbedBuilder().setTimestamp(data?.createdAt * 1000);
const pageList = [];

switch (data?.__typename) {
case "ListActivity":
embed.setURL(data?.siteUrl!);
embed.setTitle(`Here's ${data?.user?.name?.toString() || "Unknown Name"}'s most recent activity!`);
embed.setDescription(
`${capitalizeString(data?.status!)} ${data?.progress?.toLowerCase() || ""} ${data?.status!.startsWith("read") || data?.status!.startsWith("watched") ? "of" : ""} **[${SeriesTitle(data.media?.title || undefined)}](${data?.media
?.siteUrl})**`,
);
embed.setFooter({ text: `${data?.likeCount | 0} ♥ ${data?.replyCount | 0} 💬` });
if (data.media?.bannerImage) {
embed.setImage(data.media.bannerImage);
} else {
const thumbnail = data?.media?.coverImage?.large || data?.media?.coverImage?.medium;
if (thumbnail) embed.setThumbnail(thumbnail);
}

pageList.push(embed);

// I couldn't find a good way to handle the type, so I couldn't extract it to a function
if (data.replies) {
const replyPages = Math.ceil(data.replyCount / 25);
for (let i = 0; i < replyPages; i++) {
const replyEmbed = new EmbedBuilder().setTitle(`Replies to ${data?.user?.name?.toString() || "Unknown Name"}'s activity!`);

const replies = data.replies.slice(i * 25, i * 25 + 25).map((reply) => {
if (!reply || !reply.user || !reply.text) return;
const replyText = anilistToMarkdown(reply.text, 1024);
const replyName = reply.user.name

return { name: replyName, value: replyText };
}).filter((reply) => reply !== undefined);

replyEmbed.addFields(replies);
pageList.push(replyEmbed);
}
}

break;
break;

case "TextActivity":
embed
.setTitle(`Here's ${data?.user?.name?.toString() || "Unknown Name"}'s most recent activity!`)
.setDescription(anilistToMarkdown(data.text, 4096))
.setThumbnail(data?.user?.avatar?.large!)
.setFooter({ text: `${data?.likeCount | 0} ♥ ${data?.replyCount | 0} 💬` });
case "TextActivity":
embed
.setTitle(`Here's ${data?.user?.name?.toString() || "Unknown Name"}'s most recent activity!`)
.setDescription(anilistToMarkdown(data.text, 4096))
.setThumbnail(data?.user?.avatar?.large!)
.setFooter({ text: `${data?.likeCount | 0} ♥ ${data?.replyCount | 0} 💬` });

pageList.push(embed);
pageList.push(embed);

// I couldn't find a good way to handle the type, so I couldn't extract it to a function
if (data.replies) {
const replyPages = Math.ceil(data.replyCount / 25);
for (let i = 0; i < replyPages; i++) {
const replyEmbed = new EmbedBuilder().setTitle(`Replies to ${data?.user?.name?.toString() || "Unknown Name"}'s activity!`);
// I couldn't find a good way to handle the type, so I couldn't extract it to a function
if (data.replies) {
const replyPages = Math.ceil(data.replyCount / 25);
for (let i = 0; i < replyPages; i++) {
const replyEmbed = new EmbedBuilder().setTitle(`Replies to ${data?.user?.name?.toString() || "Unknown Name"}'s activity!`);

const replies = data.replies.slice(i * 25, i * 25 + 25).map((reply) => {
if (!reply || !reply.user || !reply.text) return;
const replyText = anilistToMarkdown(reply.text, 1024);
const replyName = reply.user.name
const replies = data.replies.slice(i * 25, i * 25 + 25).map((reply) => {
if (!reply || !reply.user || !reply.text) return;
const replyText = anilistToMarkdown(reply.text, 1024);
const replyName = reply.user.name

return { name: replyName, value: replyText };
}).filter((reply) => reply !== undefined);
return { name: replyName, value: replyText };
}).filter((reply) => reply !== undefined);

replyEmbed.addFields(replies);
pageList.push(replyEmbed);
}
replyEmbed.addFields(replies);
pageList.push(replyEmbed);
}
}

break;
break;

case "MessageActivity":
break;
}
return void buildPagination(interaction, pageList).paginate();
} else {
return void interaction.editReply({ embeds: [embedError(`Couldn't find any data.`, vars)] });
case "MessageActivity":
break;
}
return void buildPagination(interaction, pageList).paginate();
} catch (e: any) {
console.error(e);
interaction.editReply({ embeds: [embedError(e, vars)] });
Expand Down
75 changes: 35 additions & 40 deletions src/commands/airing.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { buildPagination, embedError, footer, graphQLRequest, SeriesTitle, getOptions } from "#utils/index";
import { EmbedBuilder, SlashCommandBuilder, TimestampStyles, time } from "discord.js";
import ms from "ms";
import { MediaType } from "#graphQL/types";
import { MediaType, type AiringQueryVariables } from "#graphQL/types";
import type { Command } from "#structures/index";

const name = "airing";
Expand All @@ -20,12 +20,7 @@ export default {
.addStringOption((option) => option.setName("in").setDescription('Airing *in* (e.g. "1 week")')),

run: async ({ interaction, client }): Promise<void> => {
if (!interaction.isCommand()) return;
const vars: {
dateStart: number;
nextDay: number;
getID: number[] | undefined;
} = {
const vars: AiringQueryVariables = {
dateStart: 0,
nextDay: 0,
getID: undefined
Expand Down Expand Up @@ -91,44 +86,44 @@ export default {
if (!data) return void interaction.reply({ embeds: [embedError("No airing anime found.")] });
const { airingSchedules } = data;

if (data) {
const chunkSize = 5;
const fields = [];
// Sort the airing anime alphabetically by title
if (!airingSchedules) return void interaction.reply({ embeds: [embedError("No airing anime found.")] });
airingSchedules.sort((a, b) => (a?.timeUntilAiring || 0) - (b?.timeUntilAiring || 0));
if (!data) {
return void interaction.reply({
embeds: [embedError("No airing anime found.")],
});
}

for (let i = 0; i < airingSchedules.length; i += chunkSize) {
fields.push(airingSchedules.slice(i, i + chunkSize));
}
const chunkSize = 5;
const fields = [];
// Sort the airing anime alphabetically by title
if (!airingSchedules) return void interaction.reply({ embeds: [embedError("No airing anime found.")] });
airingSchedules.sort((a, b) => (a?.timeUntilAiring || 0) - (b?.timeUntilAiring || 0));

// ^ Create pages with 5 airing anime per page and then make them into embeds
const pageList: EmbedBuilder[] = [];
fields.forEach((fieldSet, index) => {
const embed = new EmbedBuilder();
embed.setTitle(`Airing between ${day.toDateString()} to ${nextWeek.toDateString()}`);
embed.setColor("Green");
embed.setFooter(footer(headers));

fieldSet.forEach((field) => {
if (!field) return;
const { media, episode, airingAt } = field;

embed.addFields({
name: `${SeriesTitle(media?.title || undefined)}`,
value: `> **[EP - ${episode}]** :airplane: ${(new Date(airingAt * 1000) > new Date() ? `Going to air ` : `Aired`) + time(airingAt, TimestampStyles.RelativeTime)}`,
inline: false,
});
for (let i = 0; i < airingSchedules.length; i += chunkSize) {
fields.push(airingSchedules.slice(i, i + chunkSize));
}

// ^ Create pages with 5 airing anime per page and then make them into embeds
const pageList: EmbedBuilder[] = [];
fields.forEach((fieldSet, index) => {
const embed = new EmbedBuilder();
embed.setTitle(`Airing between ${day.toDateString()} to ${nextWeek.toDateString()}`);
embed.setColor("Green");
embed.setFooter(footer(headers));

fieldSet.forEach((field) => {
if (!field) return;
const { media, episode, airingAt } = field;

embed.addFields({
name: `${SeriesTitle(media?.title || undefined)}`,
value: `> **[EP - ${episode}]** :airplane: ${(new Date(airingAt * 1000) > new Date() ? `Going to air ` : `Aired`) + time(airingAt, TimestampStyles.RelativeTime)}`,
inline: false,
});
pageList.push(embed);
});
pageList.push(embed);
});

buildPagination(interaction, pageList).paginate();
} else {
interaction.reply({
embeds: [embedError("No airing anime found.")],
});
}
buildPagination(interaction, pageList).paginate();
} catch (e: any) {
console.error(e);
interaction.reply({ embeds: [embedError(e, vars)] });
Expand Down
Loading
Loading