Files
xiao/commands/search/anime.js
T
2020-01-14 18:25:35 -05:00

180 lines
4.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const Command = require('../../structures/Command');
const { MessageEmbed } = require('discord.js');
const request = require('node-superfetch');
const { stripIndents } = require('common-tags');
const { cleanAnilistHTML } = require('../../util/Util');
const ANILIST_USERNAME = process.env.ANILIST_USERNAME || 'dragonfire535';
const searchGraphQL = stripIndents`
query ($search: String, $type: MediaType, $isAdult: Boolean) {
anime: Page (perPage: 10) {
results: media (type: $type, isAdult: $isAdult, search: $search) {
id
title {
english
romaji
}
}
}
}
`;
const resultGraphQL = stripIndents`
query media($id: Int, $type: MediaType) {
Media(id: $id, type: $type) {
id
title {
english
romaji
}
coverImage {
large
medium
}
startDate { year }
description(asHtml: false)
season
type
siteUrl
status
episodes
isAdult
meanScore
}
}
`;
const personalGraphQL = stripIndents`
query ($name: String, $type: MediaType) {
MediaListCollection(userName: $name, type: $type) {
lists {
entries {
mediaId
score(format: POINT_10)
status
}
name
}
}
}
`;
const seasons = {
WINTER: 'Winter',
SPRING: 'Spring',
SUMMER: 'Summer',
FALL: 'Fall'
};
const statuses = {
FINISHED: 'Finished',
RELEASING: 'Releasing',
NOT_YET_RELEASED: 'Unreleased',
CANCELLED: 'Cancelled'
};
const userStatuses = {
CURRENT: 'Watching',
PLANNING: 'Planning',
COMPLETED: 'Completed',
DROPPED: 'Dropped',
PAUSED: 'Paused',
REPEATING: 'Rewatching'
};
module.exports = class AnimeCommand extends Command {
constructor(client) {
super(client, {
name: 'anime',
aliases: ['anilist-anime', 'anilist'],
group: 'search',
memberName: 'anime',
description: 'Searches AniList for your query, getting anime results.',
clientPermissions: ['EMBED_LINKS'],
credit: [
{
name: 'AniList',
url: 'https://anilist.co/',
reason: 'API',
reasonURL: 'https://anilist.gitbook.io/anilist-apiv2-docs/'
}
],
args: [
{
key: 'query',
prompt: 'What anime would you like to search for?',
type: 'string'
}
]
});
this.personalList = null;
}
async run(msg, { query }) {
try {
const id = await this.search(query);
if (!id) return msg.say('Could not find any results.');
const anime = await this.fetchAnime(id);
await this.fetchPersonalList();
const entry = this.personalList.find(ani => ani.mediaId === id);
const embed = new MessageEmbed()
.setColor(0x02A9FF)
.setAuthor('AniList', 'https://i.imgur.com/iUIRC7v.png', 'https://anilist.co/')
.setURL(anime.siteUrl)
.setThumbnail(anime.coverImage.large || anime.coverImage.medium || null)
.setTitle(anime.title.english || anime.title.romaji)
.setDescription(anime.description ? cleanAnilistHTML(anime.description) : 'No description.')
.addField(' Status', statuses[anime.status], true)
.addField(' Episodes', anime.episodes || '???', true)
.addField(' Season', anime.season ? `${seasons[anime.season]} ${anime.startDate.year}` : '???', true)
.addField(' Average Score', anime.meanScore ? `${anime.meanScore}/100` : '???', true)
.addField(` ${ANILIST_USERNAME}'s Score`, entry && entry.score ? `${entry.score}/10` : '?/10', true)
.addField(` ${ANILIST_USERNAME}'s Progress`,
entry && entry.status ? userStatuses[entry.status] : 'Not Planned', true);
return msg.embed(embed);
} catch (err) {
return msg.reply(`Oh no, an error occurred: \`${err.message}\`. Try again later!`);
}
}
async search(query) {
const { body } = await request
.post('https://graphql.anilist.co/')
.send({
variables: {
search: query,
type: 'ANIME'
},
query: searchGraphQL
});
if (!body.data.anime.results.length) return null;
return body.data.anime.results[0].id;
}
async fetchAnime(id) {
const { body } = await request
.post('https://graphql.anilist.co/')
.send({
variables: {
id,
type: 'ANIME'
},
query: resultGraphQL
});
return body.data.Media;
}
async fetchPersonalList() {
if (this.personalList) return this.personalList;
const { body } = await request
.post('https://graphql.anilist.co/')
.send({
variables: {
name: ANILIST_USERNAME,
type: 'ANIME'
},
query: personalGraphQL
});
const { lists } = body.data.MediaListCollection;
this.personalList = [];
for (const list of Object.values(lists)) this.personalList.push(...list.entries);
setTimeout(() => { this.personalList = null; }, 3.6e+6);
return this.personalList;
}
};