From b4c815f403b2af3fca0ad02b1e588bade6aafff9 Mon Sep 17 00:00:00 2001 From: Daniel Odendahl Jr Date: Fri, 8 Jun 2018 15:36:21 +0000 Subject: [PATCH] Convert everything to superagent properly --- commands/analyze/read-qr-code.js | 2 +- commands/analyze/zodiac-sign.js | 1 + commands/events/holidays.js | 2 +- commands/events/today-in-history.js | 4 +- commands/games/akinator.js | 4 +- commands/games/hangman.js | 17 +++---- commands/image-edit/osu-signature.js | 3 +- commands/number-edit/currency.js | 47 ++++++++++++------ commands/random/reddit.js | 3 +- commands/search/http-cat.js | 4 +- commands/search/kitsu-anime.js | 48 +++++++++++++++++++ commands/search/kitsu-manga.js | 48 +++++++++++++++++++ commands/search/my-anime-list-anime.js | 54 --------------------- commands/search/my-anime-list-manga.js | 55 ---------------------- commands/search/neopets-item.js | 2 +- commands/search/{vocaloid.js => vocadb.js} | 8 ++-- commands/voice/dec-talk.js | 16 +++++-- 17 files changed, 163 insertions(+), 155 deletions(-) create mode 100644 commands/search/kitsu-anime.js create mode 100644 commands/search/kitsu-manga.js delete mode 100644 commands/search/my-anime-list-anime.js delete mode 100644 commands/search/my-anime-list-manga.js rename commands/search/{vocaloid.js => vocadb.js} (90%) diff --git a/commands/analyze/read-qr-code.js b/commands/analyze/read-qr-code.js index 716cb574..c7ee3a9b 100644 --- a/commands/analyze/read-qr-code.js +++ b/commands/analyze/read-qr-code.js @@ -6,7 +6,7 @@ module.exports = class ReadQRCodeCommand extends Command { constructor(client) { super(client, { name: 'read-qr-code', - aliases: ['scan-qr-code', 'scan-qr'], + aliases: ['scan-qr-code', 'scan-qr', 'read-qr'], group: 'analyze', memberName: 'read-qr-code', description: 'Reads a QR Code.', diff --git a/commands/analyze/zodiac-sign.js b/commands/analyze/zodiac-sign.js index 39590b9d..b930905d 100644 --- a/commands/analyze/zodiac-sign.js +++ b/commands/analyze/zodiac-sign.js @@ -4,6 +4,7 @@ module.exports = class ZodiacSignCommand extends Command { constructor(client) { super(client, { name: 'zodiac-sign', + aliases: ['zodiac'], group: 'analyze', memberName: 'zodiac-sign', description: 'Responds with the Zodiac Sign for the given month/day.', diff --git a/commands/events/holidays.js b/commands/events/holidays.js index 5bdf18a1..ad5f182c 100644 --- a/commands/events/holidays.js +++ b/commands/events/holidays.js @@ -7,7 +7,7 @@ module.exports = class HolidaysCommand extends Command { constructor(client) { super(client, { name: 'holidays', - aliases: ['google-calendar'], + aliases: ['google-calendar', 'holiday'], group: 'events', memberName: 'holidays', description: 'Responds with today\'s holidays.' diff --git a/commands/events/today-in-history.js b/commands/events/today-in-history.js index 39c775ec..fe40d8c1 100644 --- a/commands/events/today-in-history.js +++ b/commands/events/today-in-history.js @@ -33,7 +33,9 @@ module.exports = class TodayInHistoryCommand extends Command { async run(msg, { month, day }) { const date = month && day ? `/${month}/${day}` : ''; try { - const { text } = await request.get(`http://history.muffinlabs.com/date${date}`); + const { text } = await request + .get(`http://history.muffinlabs.com/date${date}`) + .buffer(); const body = JSON.parse(text); const events = body.data.Events; const event = events[Math.floor(Math.random() * events.length)]; diff --git a/commands/games/akinator.js b/commands/games/akinator.js index 0efa0162..e84fae76 100644 --- a/commands/games/akinator.js +++ b/commands/games/akinator.js @@ -44,7 +44,7 @@ module.exports = class AkinatorCommand extends Command { if (msgs.first().content.toLowerCase() === 'end') break; ans = answers.indexOf(msgs.first().content.toLowerCase()); } - const guess = await this.finish(msg.channel); + const guess = await this.guess(msg.channel); if (!guess) return msg.reply('Hmm... I seem to be having a bit of trouble. Check back soon!'); const embed = new MessageEmbed() .setColor(0xF78B26) @@ -108,7 +108,7 @@ module.exports = class AkinatorCommand extends Command { return data; } - async finish(channel) { + async guess(channel) { const session = this.sessions.get(channel.id); const { body } = await request .get('http://192.99.38.142:8126/ws/list') diff --git a/commands/games/hangman.js b/commands/games/hangman.js index 456d1ceb..3e0cf989 100644 --- a/commands/games/hangman.js +++ b/commands/games/hangman.js @@ -39,7 +39,11 @@ module.exports = class HangmanCommand extends Command { =========== \`\`\` `); - const guess = await msg.channel.awaitMessages(res => res.author.id === msg.author.id, { + const filter = res => { + const choice = res.content.toLowerCase(); + return res.author.id === msg.author.id && !confirmation.includes(choice) && !incorrect.includes(choice); + }; + const guess = await msg.channel.awaitMessages(filter, { max: 1, time: 30000 }); @@ -49,21 +53,14 @@ module.exports = class HangmanCommand extends Command { } const choice = guess.first().content.toLowerCase(); if (choice === 'end') break; - if (choice.length > 1) { - if (word === choice) break; - else await msg.say('Nope, that\'s not the word, try again!'); - points++; - } else if (confirmation.includes(choice) || incorrect.includes(choice)) { - await msg.say('You have already picked that letter!'); - } else if (word.includes(choice)) { - await msg.say('Nice job!'); + if (choice.length > 1) break; + if (word.includes(choice)) { for (let i = 0; i < word.length; i++) { if (word[i] !== choice) continue; // eslint-disable-line max-depth confirmation.push(word[i]); display[i] = word[i]; } } else { - await msg.say('Nope!'); incorrect.push(choice); points++; } diff --git a/commands/image-edit/osu-signature.js b/commands/image-edit/osu-signature.js index e866a13f..77679af3 100644 --- a/commands/image-edit/osu-signature.js +++ b/commands/image-edit/osu-signature.js @@ -35,7 +35,7 @@ module.exports = class OsuSignatureCommand extends Command { async run(msg, { user, color }) { try { - const { body, text } = await request + const { body } = await request .get('https://lemmmy.pw/osusig/sig.php') .query({ colour: color, @@ -48,7 +48,6 @@ module.exports = class OsuSignatureCommand extends Command { onlineindicator: '', xpbar: '' }); - if (text.includes('Warning')) return msg.say('Could not find any results.'); return msg.say({ files: [{ attachment: body, name: 'osu-signature.png' }] }); } catch (err) { return msg.reply(`Oh no, an error occurred: \`${err.message}\`. Try again later!`); diff --git a/commands/number-edit/currency.js b/commands/number-edit/currency.js index f3f9a9c0..e7abf6da 100644 --- a/commands/number-edit/currency.js +++ b/commands/number-edit/currency.js @@ -1,7 +1,5 @@ const Command = require('../../structures/Command'); const request = require('superagent'); -const { list } = require('../../util/Util'); -const codes = require('../../assets/json/currency'); module.exports = class CurrencyCommand extends Command { constructor(client) { @@ -11,7 +9,6 @@ module.exports = class CurrencyCommand extends Command { group: 'number-edit', memberName: 'currency', description: 'Converts money from one currency to another.', - details: `**Codes**: ${codes.join(', ')}`, args: [ { key: 'amount', @@ -20,34 +17,54 @@ module.exports = class CurrencyCommand extends Command { }, { key: 'base', - prompt: `What currency code do you want to use as the base? Either ${list(codes, 'or')}.`, + prompt: 'What currency code do you want to use as the base?', type: 'string', - oneOf: codes, parse: base => base.toUpperCase() }, { key: 'target', - prompt: `What currency code do you want to convert to? Either ${list(codes, 'or')}.`, + prompt: 'What currency code do you want to convert to?', type: 'string', - oneOf: codes, parse: target => target.toUpperCase() } ] }); + + this.currencies = null; + this.rates = new Map(); } async run(msg, { base, target, amount }) { - if (base === target) return msg.say(`Converting ${base} to ${target} is the same value, dummy.`); try { - const { body } = await request - .get('http://api.fixer.io/latest') - .query({ - base, - symbols: target - }); - return msg.say(`${amount} ${base} is ${amount * body.rates[target]} ${target}.`); + if (!this.currencies) await this.fetchCurrencies(); + base = this.currencies[base] || this.currencies.find($ => $.currencyName.toLowerCase() === base); + if (!base) return msg.say('Invalid base.'); + target = this.currencies[target] || this.currencies.find($ => $.currencyName.toLowerCase() === target); + if (!target) return msg.say('Invalid target.'); + if (base.id === target.id) return msg.say(`Converting ${base.id} to ${target.id} is the same value, dummy.`); + const rate = await this.fetchRate(base, target); + return msg.say(`${amount} ${base.id} is ${amount * rate} ${target.id}.`); } catch (err) { return msg.reply(`Oh no, an error occurred: \`${err.message}\`. Try again later!`); } } + + async fetchCurrencies() { + const { body } = await request.get('https://free.currencyconverterapi.com/api/v5/currencies'); + this.currencies = body.results; + return body.results; + } + + async fetchRate(base, target) { + const query = `${base.id}_${target.id}`; + if (this.rates.has(query)) return this.rates.get(query); + const { body } = await request + .get('https://free.currencyconverterapi.com/api/v5/convert') + .query({ + q: query, + compact: 'ultra' + }); + this.rates.set(query, body[query]); + return body[query]; + } }; diff --git a/commands/random/reddit.js b/commands/random/reddit.js index 28a675bd..8932b594 100644 --- a/commands/random/reddit.js +++ b/commands/random/reddit.js @@ -33,8 +33,7 @@ module.exports = class RedditCommand extends Command { **${post.title}** - ⬆ ${post.ups} - ⬇ ${post.downs} + ⬆ ${post.ups} ⬇ ${post.downs} `); } catch (err) { if (err.status === 403) return msg.say('This subreddit is private.'); diff --git a/commands/search/http-cat.js b/commands/search/http-cat.js index e707c519..51be9bb8 100644 --- a/commands/search/http-cat.js +++ b/commands/search/http-cat.js @@ -21,10 +21,10 @@ module.exports = class HttpCatCommand extends Command { async run(msg, { code }) { try { - const { body, headers } = await request.get(`https://http.cat/${code}.jpg`); - if (headers['content-type'] === 'text/html') return msg.say('Could not find any results.'); + const { body } = await request.get(`https://http.cat/${code}.jpg`); return msg.say({ files: [{ attachment: body, name: `${code}.jpg` }] }); } catch (err) { + if (err.status === 404) return msg.say('Could not find any results.'); return msg.reply(`Oh no, an error occurred: \`${err.message}\`. Try again later!`); } } diff --git a/commands/search/kitsu-anime.js b/commands/search/kitsu-anime.js new file mode 100644 index 00000000..d78fe427 --- /dev/null +++ b/commands/search/kitsu-anime.js @@ -0,0 +1,48 @@ +const Command = require('../../structures/Command'); +const { MessageEmbed } = require('discord.js'); +const request = require('superagent'); +const { shorten } = require('../../util/Util'); + +module.exports = class KitsuAnimeCommand extends Command { + constructor(client) { + super(client, { + name: 'kitsu-anime', + aliases: ['my-anime-list-anime', 'mal-anime', 'anime'], + group: 'search', + memberName: 'kitsu-anime', + description: 'Searches Kitsu.io for your query, getting anime results.', + clientPermissions: ['EMBED_LINKS'], + args: [ + { + key: 'query', + prompt: 'What anime would you like to search for?', + type: 'string' + } + ] + }); + } + + async run(msg, { query }) { + try { + const { body } = await request + .get('https://kitsu.io/api/edge/anime') + .query({ 'filter[text]': query }); + if (!body.data.length) return msg.say('Could not find any results.'); + const data = body.data[0].attributes; + const embed = new MessageEmbed() + .setColor(0xF75239) + .setAuthor('Kitsu.io', 'https://i.imgur.com/lVqooyd.png', 'https://kitsu.io/explore/anime') + .setURL(`https://kitsu.io/anime/${data.slug}`) + .setThumbnail(data.posterImage ? data.posterImage.original : null) + .setTitle(data.canonicalTitle) + .setDescription(shorten(data.synopsis)) + .addField('❯ Type', `${data.showType} - ${data.status}`, true) + .addField('❯ Episodes', data.episodeCount || '???', true) + .addField('❯ Start Date', data.startDate ? new Date(data.startDate).toDateString() : '???', true) + .addField('❯ End Date', data.endDate ? new Date(data.endDate).toDateString() : '???', true); + return msg.embed(embed); + } catch (err) { + return msg.reply(`Oh no, an error occurred: \`${err.message}\`. Try again later!`); + } + } +}; diff --git a/commands/search/kitsu-manga.js b/commands/search/kitsu-manga.js new file mode 100644 index 00000000..8318a338 --- /dev/null +++ b/commands/search/kitsu-manga.js @@ -0,0 +1,48 @@ +const Command = require('../../structures/Command'); +const { MessageEmbed } = require('discord.js'); +const request = require('superagent'); +const { shorten } = require('../../util/Util'); + +module.exports = class KitsuMangaCommand extends Command { + constructor(client) { + super(client, { + name: 'kitsu-manga', + aliases: ['my-anime-list-manga', 'mal-manga', 'manga'], + group: 'search', + memberName: 'kitsu-manga', + description: 'Searches Kitsu.io for your query, getting manga results.', + clientPermissions: ['EMBED_LINKS'], + args: [ + { + key: 'query', + prompt: 'What manga would you like to search for?', + type: 'string' + } + ] + }); + } + + async run(msg, { query }) { + try { + const { body } = await request + .get('https://kitsu.io/api/edge/manga') + .query({ 'filter[text]': query }); + if (!body.data.length) return msg.say('Could not find any results.'); + const data = body.data[0].attributes; + const embed = new MessageEmbed() + .setColor(0xF75239) + .setAuthor('Kitsu.io', 'https://i.imgur.com/lVqooyd.png', 'https://kitsu.io/explore/manga') + .setURL(`https://kitsu.io/manga/${data.slug}`) + .setThumbnail(data.posterImage ? data.posterImage.original : null) + .setTitle(data.canonicalTitle) + .setDescription(shorten(data.synopsis)) + .addField('❯ Type', `${data.subtype} - ${data.status}`, true) + .addField('❯ Volumes / Chapters', `${data.volumeCount || '???'} / ${data.chapterCount || '???'}`, true) + .addField('❯ Start Date', data.startDate ? new Date(data.startDate).toDateString() : '???', true) + .addField('❯ End Date', data.endDate ? new Date(data.endDate).toDateString() : '???', true); + return msg.embed(embed); + } catch (err) { + return msg.reply(`Oh no, an error occurred: \`${err.message}\`. Try again later!`); + } + } +}; diff --git a/commands/search/my-anime-list-anime.js b/commands/search/my-anime-list-anime.js deleted file mode 100644 index 2f3b69d0..00000000 --- a/commands/search/my-anime-list-anime.js +++ /dev/null @@ -1,54 +0,0 @@ -const Command = require('../../structures/Command'); -const { MessageEmbed } = require('discord.js'); -const request = require('superagent'); -const { parseString } = require('xml2js'); -const { promisify } = require('util'); -const xml = promisify(parseString); -const { shorten, base64, cleanXML } = require('../../util/Util'); -const { MAL_USERNAME, MAL_PASSWORD } = process.env; - -module.exports = class MyAnimeListAnimeCommand extends Command { - constructor(client) { - super(client, { - name: 'my-anime-list-anime', - aliases: ['mal-anime', 'anime'], - group: 'search', - memberName: 'my-anime-list-anime', - description: 'Searches My Anime List for your query, getting anime results.', - clientPermissions: ['EMBED_LINKS'], - args: [ - { - key: 'query', - prompt: 'What anime would you like to search for?', - type: 'string' - } - ] - }); - } - - async run(msg, { query }) { - try { - const { text } = await request - .get('https://myanimelist.net/api/anime/search.xml') - .query({ q: query }) - .set({ Authorization: `Basic ${base64(`${MAL_USERNAME}:${MAL_PASSWORD}`)}` }); - const body = await xml(text); - const data = body.anime.entry[0]; - const embed = new MessageEmbed() - .setColor(0x2D54A2) - .setAuthor('My Anime List', 'https://i.imgur.com/5rivpMM.png', 'https://myanimelist.net/') - .setURL(`https://myanimelist.net/anime/${data.id[0]}`) - .setThumbnail(data.image[0]) - .setTitle(data.title[0]) - .setDescription(shorten(cleanXML(data.synopsis[0]))) - .addField('❯ Type', `${data.type[0]} - ${data.status[0]}`, true) - .addField('❯ Episodes', data.episodes[0], true) - .addField('❯ Start Date', data.start_date[0] !== '0000-00-00' ? data.start_date[0] : '???', true) - .addField('❯ End Date', data.end_date[0] !== '0000-00-00' ? data.end_date[0] : '???', true); - return msg.embed(embed); - } catch (err) { - if (err.message === 'Parse Error') return msg.say('Could not find any results.'); - return msg.reply(`Oh no, an error occurred: \`${err.message}\`. Try again later!`); - } - } -}; diff --git a/commands/search/my-anime-list-manga.js b/commands/search/my-anime-list-manga.js deleted file mode 100644 index 77a1d400..00000000 --- a/commands/search/my-anime-list-manga.js +++ /dev/null @@ -1,55 +0,0 @@ -const Command = require('../../structures/Command'); -const { MessageEmbed } = require('discord.js'); -const request = require('superagent'); -const { parseString } = require('xml2js'); -const { promisify } = require('util'); -const xml = promisify(parseString); -const { shorten, base64, cleanXML } = require('../../util/Util'); -const { MAL_USERNAME, MAL_PASSWORD } = process.env; - -module.exports = class MyAnimeListMangaCommand extends Command { - constructor(client) { - super(client, { - name: 'my-anime-list-manga', - aliases: ['mal-manga', 'manga'], - group: 'search', - memberName: 'my-anime-list-manga', - description: 'Searches My Anime List for your query, getting manga results.', - clientPermissions: ['EMBED_LINKS'], - args: [ - { - key: 'query', - prompt: 'What manga would you like to search for?', - type: 'string' - } - ] - }); - } - - async run(msg, { query }) { - try { - const { text } = await request - .get('https://myanimelist.net/api/manga/search.xml') - .query({ q: query }) - .set({ Authorization: `Basic ${base64(`${MAL_USERNAME}:${MAL_PASSWORD}`)}` }); - const body = await xml(text); - const data = body.manga.entry[0]; - const embed = new MessageEmbed() - .setColor(0x2D54A2) - .setAuthor('My Anime List', 'https://i.imgur.com/5rivpMM.png', 'https://myanimelist.net/') - .setURL(`https://myanimelist.net/manga/${data.id[0]}`) - .setThumbnail(data.image[0]) - .setTitle(data.title[0]) - .setDescription(shorten(cleanXML(data.synopsis[0]))) - .addField('❯ Type', `${data.type[0]} - ${data.status[0]}`, true) - .addField('❯ Volumes / Chapters', - `${Number.parseInt(data.volumes[0], 10) || '???'} / ${Number.parseInt(data.chapters[0], 10) || '???'}`, true) - .addField('❯ Start Date', data.start_date[0] !== '0000-00-00' ? data.start_date[0] : '???', true) - .addField('❯ End Date', data.end_date[0] !== '0000-00-00' ? data.end_date[0] : '???', true); - return msg.embed(embed); - } catch (err) { - if (err.message === 'Parse Error') return msg.say('Could not find any results.'); - return msg.reply(`Oh no, an error occurred: \`${err.message}\`. Try again later!`); - } - } -}; diff --git a/commands/search/neopets-item.js b/commands/search/neopets-item.js index 12b374b5..9553b316 100644 --- a/commands/search/neopets-item.js +++ b/commands/search/neopets-item.js @@ -51,7 +51,7 @@ module.exports = class NeopetsItemCommand extends Command { const price = text.match(/([0-9,]+) (NP|NC)/); const url = `https://items.jellyneo.net/item/${id[1]}/`; const details = await request.get(url); - const detailsText = details.raw.toString(); + const detailsText = details.text; return { id: id[1], url, diff --git a/commands/search/vocaloid.js b/commands/search/vocadb.js similarity index 90% rename from commands/search/vocaloid.js rename to commands/search/vocadb.js index bf34eee9..2d4495f0 100644 --- a/commands/search/vocaloid.js +++ b/commands/search/vocadb.js @@ -3,13 +3,13 @@ const { MessageEmbed } = require('discord.js'); const request = require('superagent'); const { shorten } = require('../../util/Util'); -module.exports = class VocaloidCommand extends Command { +module.exports = class VocaDBCommand extends Command { constructor(client) { super(client, { - name: 'vocaloid', - aliases: ['vocadb', 'vocaloid-song', 'vocaloid-music'], + name: 'vocadb', + aliases: ['vocaloid', 'vocaloid-song', 'vocaloid-music'], group: 'search', - memberName: 'vocaloid', + memberName: 'vocadb', description: 'Searches VocaDB for your query.', clientPermissions: ['EMBED_LINKS'], args: [ diff --git a/commands/voice/dec-talk.js b/commands/voice/dec-talk.js index 52228d08..998a50d1 100644 --- a/commands/voice/dec-talk.js +++ b/commands/voice/dec-talk.js @@ -35,11 +35,17 @@ module.exports = class DECTalkCommand extends Command { if (this.client.voiceConnections.has(channel.guild.id)) return msg.say('I am already playing a sound.'); try { const connection = await channel.join(); - const data = await request - .get('http://tts.cyzon.us/tts') - .query({ text }) - .redirects(0); - const dispatcher = connection.play(`http://tts.cyzon.us${data.headers.location}`); + let url = 'http://tts.cyzon.us'; + try { + await request + .get('http://tts.cyzon.us/tts') + .query({ text }) + .redirects(0); + } catch (err) { + if (err.reponse.headers.location) url += err.response.headers.location; + else throw err; + } + const dispatcher = connection.play(url); dispatcher.once('finish', () => channel.leave()); dispatcher.once('error', () => channel.leave()); return null;