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

feat: add anime search #27

Merged
merged 6 commits into from
Mar 29, 2023
Merged
Show file tree
Hide file tree
Changes from 5 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
74 changes: 74 additions & 0 deletions src/commands/general/AnimeCommand.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { ApplyOptions } from "@sapphire/decorators";
import { ApplicationCommandRegistry, Command, RegisterBehavior } from "@sapphire/framework";
import { ApplicationCommandOptionType, ActionRowBuilder, StringSelectMenuBuilder } from "discord.js";

import { guildsToRegister } from "../../config";
import { Anilist } from "../../utils/Anilist";
import { SelectMenuCustomIds } from "../../constants";
import { AnimeResponseBuilder } from "../../utils/responseBuilder/AnimeResponseBuilder";
@ApplyOptions<Command.Options>({
aliases: [],
name: "anime",
description: "Search anime information",
detailedDescription: {
usage: "{prefix}anime [text]"
},
requiredClientPermissions: ["EmbedLinks"]
})
export class AnimeCommand extends Command {
public override registerApplicationCommands(registry: ApplicationCommandRegistry): void {
registry.registerChatInputCommand({
name: this.name,
description: this.description,
options: [
{
name: "title",
type: ApplicationCommandOptionType.String,
description: "Anime title to find",
required: true
}
]
}, {
guildIds: guildsToRegister,
behaviorWhenNotIdentical: RegisterBehavior.Overwrite,
registerCommandIfMissing: true
});
}

// eslint-disable-next-line class-methods-use-this
public async chatInputRun(interaction: Command.ChatInputCommandInteraction): Promise<any> {
const animeTitle = interaction.options.getString("title", true);
try {
await interaction.deferReply();
const anilist = new Anilist();
const data = await anilist.findAnimeByTitle(animeTitle);
if (!data) return await interaction.editReply("Nothing found");
const firstMedia = data.media[0];
if (data.media.length === 1) return await interaction.editReply({ embeds: AnimeResponseBuilder(firstMedia, interaction.user) });
const rowOptions = data.media.map(currentMedia => {
const status = `${currentMedia.status?.charAt(0).toUpperCase() ?? ""}${currentMedia.status?.slice(1).toLowerCase().replaceAll("_", " ") ?? ""}`;
const episodes = currentMedia.episodes?.toString() ?? 0;
const genres = currentMedia.genres?.join(", ") ?? "";
const description = `${status}, ${currentMedia.startDate ? `${Anilist.parseAnimeDate(currentMedia.startDate) ?? "Unknown"}, ` : ""}${currentMedia.episodes ? `${episodes} episodes, ` : ""}${currentMedia.genres ? genres : ""}`;
return {
label: currentMedia.title.romaji,
description: Anilist.stripHtmlTag(description.slice(0, 90)),
value: currentMedia.id.toString()
};
});
const row = new ActionRowBuilder<StringSelectMenuBuilder>()
.addComponents(
new StringSelectMenuBuilder()
.setCustomId(SelectMenuCustomIds.Anime)
.setPlaceholder(`Search result: ${data.media.length}`)
.addOptions(rowOptions)
);
return await interaction.editReply({ embeds: AnimeResponseBuilder(firstMedia, interaction.user), components: [row] });
} catch (err) {
await interaction.editReply({
content: "No result found."
});
throw err;
}
}
}
8 changes: 7 additions & 1 deletion src/constants/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ export enum Roles {

export enum Emojis {
YES = "<:yes:990955540802863104>",
NO = "<:no:990955538831536200>"
NO = "<:no:990955538831536200>",
ANILIST = "<:AW_anilist:931202490584690698>",
MAL = "<:Mal:765147564612911104>"
}

export enum Guild {
Expand All @@ -37,3 +39,7 @@ export enum Images {
INFORMATION = "https://api.frutbits.org/assets/images/information.png",
QUESTION_MARK = "https://api.frutbits.org/assets/images/question_mark.png"
}

export enum SelectMenuCustomIds {
Anime = "anime-select"
}
26 changes: 26 additions & 0 deletions src/interaction-handlers/select/AnimeSelect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { InteractionHandler, InteractionHandlerTypes } from "@sapphire/framework";
import { StringSelectMenuInteraction } from "discord.js";
import { ApplyOptions } from "@sapphire/decorators";
import { Anilist, AnilistAnime } from "../../utils/Anilist";
import { SelectMenuCustomIds } from "../../constants";
import { AnimeResponseBuilder } from "../../utils/responseBuilder/AnimeResponseBuilder";
@ApplyOptions<InteractionHandler.Options>({
interactionHandlerType: InteractionHandlerTypes.SelectMenu
})
export class AnimeSelectHandler extends InteractionHandler {
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
public override async parse(interaction: StringSelectMenuInteraction) {
if (interaction.customId !== SelectMenuCustomIds.Anime) return this.none();

await interaction.deferUpdate();
const anilist = new Anilist();
const data = await anilist.getAnimeById(parseInt(interaction.values[0]));
if (!data) return this.none();
return this.some({ data });
}

// eslint-disable-next-line @typescript-eslint/explicit-function-return-type, class-methods-use-this
public override async run(interaction: StringSelectMenuInteraction, result: { data: AnilistAnime }) {
return interaction.editReply({ embeds: AnimeResponseBuilder(result.data, interaction.user) });
}
}
171 changes: 171 additions & 0 deletions src/utils/Anilist.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import { request } from "https";
import moment from "moment";

type AnilistAnimeTitle =
"english" | "native" | "romaji" | "userPreferred";
export interface AnilistAnime {
"id": number;
"idMal": number | null;
"startDate": {
"year": number | null;
"month": number | null;
"day": number | null;
} | null;
"endDate": {
"year": number | null;
"month": number | null;
"day": number | null;
} | null;
"season": string | null;
"seasonYear": number | null;
"averageScore": number | null;
"status": string | null;
"genres": string[] | null;
"description": string | null;
"episodes": number | null;
"coverImage": Record<string, string>;
"title": Record<AnilistAnimeTitle, string>;
}

export interface AnilistAnimePage {
pageInfo: {
"lastPage": number;
"hasNextPage": boolean;
};
media: AnilistAnime[];
}

export class Anilist {
public constructor(private readonly token?: string) {
this.token = token;
Plyrs1 marked this conversation as resolved.
Show resolved Hide resolved
}

public query(query: string, variables: object): Promise<AnilistAnimePage | null> {
const headers: Record<string, string> = {
// eslint-disable-next-line @typescript-eslint/naming-convention
"Content-Type": "application/json; charset=utf-8",
Accept: "application/json"
};
const options: Record<string, any> = {
hostname: "graphql.anilist.co",
port: 443,
path: "/",
method: "POST",
headers
};
return new Promise((resolve, reject) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (this.token) options.headers["Authorization"] = `Bearer ${this.token}`;
const req = request(options, res => {
Plyrs1 marked this conversation as resolved.
Show resolved Hide resolved
let raw = "";
res.on("data", chunk => raw += chunk);
res.on("end", () => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (res.statusCode! >= 200 && res.statusCode! < 300) return resolve(JSON.parse(raw).data.Page as AnilistAnimePage);
return reject(
new Error("[Anilist] Error while trying to send data to https://graphql.anilist.co," +
`${res.statusCode!.toString()} ${res.statusMessage!.toString()}`)
);
});
}).on("error", reject);
req.write(JSON.stringify({ query, variables: JSON.stringify(variables) }));
req.end();
});
}

public async findAnimeByTitle(title: string): Promise<AnilistAnimePage | null> {
return this.query(
`query($title:String) {
Page(perPage:10) {
pageInfo {
lastPage
hasNextPage
}
media(search: $title, isAdult: false, type: ANIME) {
id
idMal
startDate {
year
month
day
}
endDate {
year
month
day
}
season
seasonYear
averageScore
status
genres
description(asHtml:true)
episodes
coverImage {
large
}
title {
romaji
english
native
userPreferred
}
}
}
}`, { title }
);
}

public async getAnimeById(id: number): Promise<AnilistAnime | null> {
const query = await this.query(
`query($animeId:Int) {
Page(perPage:1) {
pageInfo {
lastPage
hasNextPage
}
media(id: $animeId, isAdult: false, type: ANIME) {
id
idMal
startDate {
year
month
day
}
endDate {
year
month
day
}
season
seasonYear
averageScore
status
genres
description(asHtml:true)
episodes
coverImage {
large
}
title {
romaji
english
native
userPreferred
}
}
}
}`, { animeId: id }
);
return new Promise(resolve => resolve(query?.media[0] ?? null));
}

public static stripHtmlTag(text: string): string {
return text.replace(/(?:<(?:[^>]+)>)/gi, "").replace(/&quot;/g, "\"").replace(/&#8213;/g, "--");
}

public static parseAnimeDate(date: Record<string, number | null | undefined> | null): string | null {
if (!date?.year || !date.month || !date.day) return null;
return moment({ year: date.year, month: date.month - 1, day: date.day }).format("D MMMM YYYY");
}
}
12 changes: 6 additions & 6 deletions src/utils/Util.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
/* eslint-disable @typescript-eslint/no-base-to-string */
import { ColorResolvable, EmbedBuilder } from "discord.js";
import { Colors, ColorResolvable, EmbedBuilder } from "discord.js";
import { request } from "https";
import prettyMilliseconds from "pretty-ms";
import { embedInfoColor, Emojis } from "../constants";
import { BotClient } from "../structures/BotClient";

type hexColorsType = "error" | "info" | "success" | "warn";
const hexColors: Record<hexColorsType, string> = {
error: "RED",
const hexColors: Record<hexColorsType, ColorResolvable> = {
error: Colors.Red,
info: embedInfoColor,
success: "GREEN",
warn: "YELLOW"
success: Colors.Green,
warn: Colors.Yellow
};

export class Util {
Expand All @@ -35,7 +35,7 @@ export class Util {

public static createEmbed(type: hexColorsType, message?: string, emoji = false): EmbedBuilder {
const embed = new EmbedBuilder()
.setColor(hexColors[type] as ColorResolvable);
.setColor(hexColors[type]);

if (message) embed.setDescription(message);
if (type === "error" && emoji) embed.setDescription(`${Emojis.NO} **|** ${message!}`);
Expand Down
49 changes: 49 additions & 0 deletions src/utils/responseBuilder/AnimeResponseBuilder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { EmbedBuilder, User, hyperlink } from "discord.js";
import { Anilist, AnilistAnime } from "../Anilist";
import { Util } from "../Util";
import { toTitleCase } from "@sapphire/utilities";
import { Emojis } from "../../constants";

export function AnimeResponseBuilder(data: AnilistAnime, user: User): EmbedBuilder[] {
const externalLink = [
hyperlink(`${Emojis.ANILIST} AniList`, `https://anilist.co/anime/${data.id}`),
hyperlink(`${Emojis.MAL} MyAnimeList`, `https://myanimelist.net/anime/${data.idMal ?? ""}`)
].join(" | ");
const animeEmbed = Util.createEmbed("info")
.setThumbnail(data.coverImage.large)
.setTitle(data.title.romaji)
.setDescription(Anilist.stripHtmlTag(data.description ?? "No Description"))
.addFields(
{
name: "Status",
value: `${toTitleCase(data.status?.replaceAll("_", " ") ?? "")}`,
inline: true
},
{
name: "Genres",
value: data.genres?.join(", ") ?? "-"
},
{
name: "Start Date",
value: Anilist.parseAnimeDate(data.startDate) ?? "-",
inline: true
},
{
name: "End Date",
value: Anilist.parseAnimeDate(data.endDate) ?? "-",
inline: true
},
{
name: "Episodes",
value: data.episodes?.toString() ?? "-",
inline: true
},
{
name: "Links",
value: externalLink
}
)
.setTimestamp()
.setFooter({ text: `Replying to: ${user.tag}`, iconURL: user.displayAvatarURL() });
return [animeEmbed];
}