diff --git a/Shard.js b/Shard.js index eaab8bef..27f711c9 100644 --- a/Shard.js +++ b/Shard.js @@ -1,4 +1,6 @@ const { ShardingManager } = require('discord.js'); const { TOKEN } = process.env; -const Manager = new ShardingManager('./XiaoBot.js', { token: TOKEN }); +const Manager = new ShardingManager('./XiaoBot.js', { + token: TOKEN +}); Manager.spawn(2); diff --git a/XiaoBot.js b/XiaoBot.js index 8387cedf..2eb5bd76 100644 --- a/XiaoBot.js +++ b/XiaoBot.js @@ -1,13 +1,11 @@ const { TOKEN, OWNER, PREFIX, INVITE } = process.env; const path = require('path'); -const { FriendlyError } = require('discord.js-commando'); -const CommandoClient = require('./structures/CommandoClient'); +const CommandoClient = require('./structures/Client'); const client = new CommandoClient({ commandPrefix: PREFIX, owner: OWNER, - disableEveryone: true, invite: INVITE, - unknownCommandResponse: false + disableEveryone: true }); const { carbon, dBots } = require('./structures/Stats'); const SequelizeProvider = require('./providers/Sequelize'); @@ -32,16 +30,19 @@ client.registry ['roleplay', 'Roleplay'] ]) .registerDefaultGroups() - .registerDefaultCommands({ help: false, ping: false }) + .registerDefaultCommands({ + help: false, + ping: false + }) .registerCommandsIn(path.join(__dirname, 'commands')); client.on('ready', () => { - console.log(`[Ready] Shard ${client.shard.id} Logged in as ${client.user.tag} (${client.user.id})!`); + console.log(`[READY] Shard ${client.shard.id} Logged in as ${client.user.tag} (${client.user.id})!`); client.user.setGame(`${PREFIX}help | Shard ${client.shard.id}`); }); client.on('disconnect', (event) => { - console.log(`[Disconnect] Shard ${client.shard.id} disconnected with Code ${event.code}.`); + console.log(`[DISCONNECT] Shard ${client.shard.id} disconnected with Code ${event.code}.`); process.exit(0); }); @@ -49,52 +50,52 @@ client.on('error', console.error); client.on('warn', console.warn); -client.on('commandError', (command, err) => { - if (err instanceof FriendlyError) return; - console.error(command.name, err); -}); +client.on('commandError', (command, err) => console.error(command.name, err)); client.dispatcher.addInhibitor(msg => { - if (msg.channel.type === 'dm') return false; const role = msg.guild.settings.get('singleRole'); - if (!role) return false; - if (!msg.guild.roles.has(role)) return false; - if (client.isOwner(msg.author)) return false; - if (msg.member.hasPermission('ADMINISTRATOR')) return false; - if (!msg.member.roles.has(role)) + if (!msg.guild || !msg.guild.roles.has(role) || msg.member.hasPermission('ADMINISTRATOR')) { + return false; + } + if (!msg.member.roles.has(role)) { return ['singleRole', msg.reply(`Only the ${msg.guild.roles.get(role).name} role may use commands.`)]; + } else { + return false; + } }); client.on('message', (msg) => { - if (msg.guild && msg.guild.settings.get('inviteGuard') && /(discord(\.gg\/|app\.com\/invite\/|\.me\/))/gi.test(msg.content)) { - if (msg.author.bot || - msg.member.hasPermission('ADMINISTRATOR') || - msg.author.id === msg.guild.ownerID || - msg.member.roles.has(msg.guild.settings.get('staffRole')) || - !msg.channel.permissionsFor(client.user).has('SEND_MESSAGES')) return; - if (msg.channel.permissionsFor(client.user).has('MANAGE_MESSAGES')) msg.delete(); - return msg.reply('Invites are prohibited from being posted here.'); + if (!msg.guild || !msg.guild.settings.get('inviteGuard')) return; + if (/(discord(\.gg\/|app\.com\/invite\/|\.me\/))/gi.test(msg.content)) { + if (msg.author.bot || msg.member.hasPermission('ADMINISTRATOR')) return; + if (msg.channel.permissionsFor(client.user).has(['SEND_MESSAGES', 'MANAGE_MESSAGES'])) { + msg.delete(); + return msg.reply('Invites are prohibited from being posted here.'); + } } }); client.on('messageReactionAdd', (reaction, user) => { if (reaction.emoji.name !== '⭐') return; - const msg = reaction.message; - const channel = msg.guild.channels.get(msg.guild.settings.get('starboard')); + const { message } = reaction; + const channel = message.guild.channels.get(message.guild.settings.get('starboard')); if (!channel) return; - if (user.id === msg.author.id) { - if (msg.channel.permissionsFor(client.user).has('MANAGE_MESSAGES')) reaction.remove(user); - return msg.reply('You cannot star your own messages, baka.'); + if (user.id === message.author.id) { + if (message.channel.permissionsFor(client.user).has(['SEND_MESSAGES', 'MANAGE_MESSAGES'])) { + reaction.remove(user); + return message.reply('You cannot star your own messages, baka.'); + } else return; } - client.registry.resolveCommand('random:star').run(msg, { id: msg.id }, true); + return client.registry.resolveCommand('random:star').run(message, { id: message.id }, true); }); client.on('guildMemberAdd', (member) => { const role = member.guild.roles.get(member.guild.settings.get('joinRole')); - if (role && member.guild.me.hasPermission('MANAGE_ROLES')) member.addRole(role).catch(() => null); + if (role && member.guild.me.hasPermission('MANAGE_ROLES')) { + member.addRole(role).catch(() => null); + } const channel = member.guild.channels.get(member.guild.settings.get('memberLog')); - if (!channel) return; - if (!channel.permissionsFor(client.user).has('SEND_MESSAGES')) return; + if (!channel || !channel.permissionsFor(client.user).has('SEND_MESSAGES')) return; const msg = member.guild.settings.get('joinMsg', 'Welcome !') .replace(/()/gi, member.user.username) .replace(/()/gi, member.guild.name) @@ -104,8 +105,7 @@ client.on('guildMemberAdd', (member) => { client.on('guildMemberRemove', (member) => { const channel = member.guild.channels.get(member.guild.settings.get('memberLog')); - if (!channel) return; - if (!channel.permissionsFor(client.user).has('SEND_MESSAGES')) return; + if (!channel || !channel.permissionsFor(client.user).has('SEND_MESSAGES')) return; const msg = member.guild.settings.get('leaveMsg', 'Bye ...') .replace(/()/gi, member.user.username) .replace(/()/gi, member.guild.name) diff --git a/assets/json/clear-setting.json b/assets/json/clear-setting.json index d1f7bb93..01c78fa9 100644 --- a/assets/json/clear-setting.json +++ b/assets/json/clear-setting.json @@ -4,7 +4,6 @@ "memberLog", "joinMsg", "leaveMsg", - "staffRole", "singleRole", "joinRole", "starboard" diff --git a/assets/json/math-game.json b/assets/json/math-game.json new file mode 100644 index 00000000..bcac64f5 --- /dev/null +++ b/assets/json/math-game.json @@ -0,0 +1,21 @@ +{ + "operations": [ + "+", + "-", + "*" + ], + "difficulties": [ + "easy", + "medium", + "hard", + "extreme", + "impossible" + ], + "maxValues": { + "easy": 10, + "medium": 50, + "hard": 100, + "extreme": 1000, + "impossible": 10000 + } +} diff --git a/assets/json/soundboard.json b/assets/json/soundboard.json index 03ab3e8c..b1dfd31c 100644 --- a/assets/json/soundboard.json +++ b/assets/json/soundboard.json @@ -3,20 +3,14 @@ "airhorn", "cat", "dun dun dun", - "mario death", "pikachu", - "pokemon center", - "space", - "zelda chest" + "space" ], "paths": { "airhorn": "airhorn.mp3", "cat": "cat.mp3", "dun dun dun": "dun-dun-dun.mp3", - "mario death": "mario-death.mp3", "pikachu": "pikachu.mp3", - "pokemon center": "pokemon-center.mp3", - "space": "space.mp3", - "zelda chest": "zelda-chest.mp3" + "space": "space.mp3" } } diff --git a/assets/json/typing-game.json b/assets/json/typing-game.json index 7c42fc21..14209834 100644 --- a/assets/json/typing-game.json +++ b/assets/json/typing-game.json @@ -1,32 +1,48 @@ -[ - "The quick brown fox jumps over the lazy dog.", - "Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo.", - "How razorback-jumping frogs can level six piqued gymnasts!", - "Amazingly few discotheques provide jukeboxes.", - "I am so blue I'm greener than purple.", - "I stepped on a Corn Flake, now I'm a Cereal Killer.", - "On a scale from one to ten what is your favourite colour of the alphabet?", - "The sparkly lamp ate a pillow then punched Larry.", - "My world is where everybody is a pony and we all eat rainbows and poop butterflies.", - "If your canoe is stuck in a tree with the headlights on, how many pancakes does it take to get to the moon?", - "There's a purple mushroom in my backyard, screaming Taco's!", - "When life gives you lemons, chuck them at people you hate.", - "I think I will buy the red car, or I will lease the blue one.", - "Italy is my favorite country; in fact, I plan to spend two weeks there next year.", - "She borrowed the book from him many years ago and hasn't yet returned it.", - "Lets all be unique together until we realise we are all the same.", - "If Purple People Eaters are real… where do they find purple people to eat?", - "The waves were crashing on the shore; it was a lovely sight.", - "This is the last random sentence I will be writing and I am going to stop mid-sent.", - "The memory we used to share is no longer coherent.", - "She did not cheat on the test, for it was not the right thing to do.", - "She only paints with bold colors; she does not like pastels.", - "Malls are great places to shop; I can find everything I need under one roof.", - "The body may perhaps compensates for the loss of a true metaphysics.", - "They got there early, and they got really good seats.", - "Everyone was busy, so I went to the movie alone.", - "Yeah, I think it's a good environment for learning English.", - "I would have gotten the promotion, but my attendance wasn’t good enough.", - "There were white out conditions in the town; subsequently, the roads were impassable.", - "If you like tuna and tomato sauce- try combining the two. It’s really not as bad as it sounds." -] +{ + "sentences": [ + "The quick brown fox jumps over the lazy dog.", + "Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo.", + "How razorback-jumping frogs can level six piqued gymnasts!", + "Amazingly few discotheques provide jukeboxes.", + "I am so blue I'm greener than purple.", + "I stepped on a Corn Flake, now I'm a Cereal Killer.", + "On a scale from one to ten what is your favourite colour of the alphabet?", + "The sparkly lamp ate a pillow then punched Larry.", + "My world is where everybody is a pony and we all eat rainbows and poop butterflies.", + "If your canoe is stuck in a tree with the headlights on, how many pancakes does it take to get to the moon?", + "There's a purple mushroom in my backyard, screaming Taco's!", + "When life gives you lemons, chuck them at people you hate.", + "I think I will buy the red car, or I will lease the blue one.", + "Italy is my favorite country; in fact, I plan to spend two weeks there next year.", + "She borrowed the book from him many years ago and hasn't yet returned it.", + "Lets all be unique together until we realise we are all the same.", + "If Purple People Eaters are real… where do they find purple people to eat?", + "The waves were crashing on the shore; it was a lovely sight.", + "This is the last random sentence I will be writing and I am going to stop mid-sent.", + "The memory we used to share is no longer coherent.", + "She did not cheat on the test, for it was not the right thing to do.", + "She only paints with bold colors; she does not like pastels.", + "Malls are great places to shop; I can find everything I need under one roof.", + "The body may perhaps compensates for the loss of a true metaphysics.", + "They got there early, and they got really good seats.", + "Everyone was busy, so I went to the movie alone.", + "Yeah, I think it's a good environment for learning English.", + "I would have gotten the promotion, but my attendance wasn’t good enough.", + "There were white out conditions in the town; subsequently, the roads were impassable.", + "If you like tuna and tomato sauce- try combining the two. It’s really not as bad as it sounds." + ], + "difficulties": [ + "easy", + "medium", + "hard", + "extreme", + "impossible" + ] + "times": { + "easy": 25000, + "medium": 20000, + "hard": 15000, + "extreme": 10000, + "impossible": 5000 + } +} \ No newline at end of file diff --git a/assets/json/user-info.json b/assets/json/user-info.json new file mode 100644 index 00000000..a1bf79d4 --- /dev/null +++ b/assets/json/user-info.json @@ -0,0 +1,14 @@ +{ + "statuses": { + "online": "<:online:313956277808005120> Online", + "idle": "<:away:313956277220802560> Idle", + "dnd": "<:dnd:313956276893646850> Do Not Disturb", + "offline": "<:offline:313956277237710868> Offline" + }, + "colors": { + "online": 0x00AE86, + "idle": 0xFFFF00, + "dnd": 0xFF0000, + "offline": 0x808080 + } +} diff --git a/assets/sounds/mario-death.mp3 b/assets/sounds/mario-death.mp3 deleted file mode 100644 index 5d97899b..00000000 Binary files a/assets/sounds/mario-death.mp3 and /dev/null differ diff --git a/assets/sounds/pokemon-center.mp3 b/assets/sounds/pokemon-center.mp3 deleted file mode 100644 index bca7c07c..00000000 Binary files a/assets/sounds/pokemon-center.mp3 and /dev/null differ diff --git a/assets/sounds/zelda-chest.mp3 b/assets/sounds/zelda-chest.mp3 deleted file mode 100644 index 30d70ded..00000000 Binary files a/assets/sounds/zelda-chest.mp3 and /dev/null differ diff --git a/commands/avataredit/3000-years.js b/commands/avataredit/3000-years.js index 44a1d2c3..0c98385d 100644 --- a/commands/avataredit/3000-years.js +++ b/commands/avataredit/3000-years.js @@ -22,34 +22,32 @@ module.exports = class YearsCommand extends Command { { key: 'user', prompt: 'Which user would you like to edit the avatar of?', - type: 'user' + type: 'user', + default: '' } ] }); } async run(msg, args) { - const { user } = args; + const user = args.user || msg.author; const avatarURL = user.avatarURL('png', 256); - if (!avatarURL) return msg.say('This user has no avatar.'); - try { - const Image = Canvas.Image; - const canvas = new Canvas(856, 569); - const ctx = canvas.getContext('2d'); - const base = new Image(); - const avatar = new Image(); - const generate = () => { - ctx.drawImage(base, 0, 0); - ctx.drawImage(avatar, 461, 127, 200, 200); - }; - base.src = await fs.readFileAsync(path.join(__dirname, '..', '..', 'assets', 'images', '3000-years.png')); - const { body } = await snekfetch.get(avatarURL); - avatar.src = body; - generate(); - return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'az.png' }] }) - .catch(err => msg.say(`${err.name}: ${err.message}`)); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + if (!avatarURL) { + return msg.say('The User Provided has No Avatar.'); } + const Image = Canvas.Image; + const canvas = new Canvas(856, 569); + const ctx = canvas.getContext('2d'); + const base = new Image(); + const avatar = new Image(); + const generate = () => { + ctx.drawImage(base, 0, 0); + ctx.drawImage(avatar, 461, 127, 200, 200); + }; + base.src = await fs.readFileAsync(path.join(__dirname, '..', '..', 'assets', 'images', '3000-years.png')); + const { body } = await snekfetch.get(avatarURL); + avatar.src = body; + generate(); + return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'az.png' }] }); } }; diff --git a/commands/avataredit/beautiful.js b/commands/avataredit/beautiful.js index 2a695b9a..0e2545f0 100644 --- a/commands/avataredit/beautiful.js +++ b/commands/avataredit/beautiful.js @@ -22,35 +22,33 @@ module.exports = class BeautifulCommand extends Command { { key: 'user', prompt: 'Which user would you like to edit the avatar of?', - type: 'user' + type: 'user', + default: '' } ] }); } async run(msg, args) { - const { user } = args; + const user = args.user || msg.author; const avatarURL = user.avatarURL('png', 256); - if (!avatarURL) return msg.say('This user has no avatar.'); - try { - const Image = Canvas.Image; - const canvas = new Canvas(500, 532); - const ctx = canvas.getContext('2d'); - const base = new Image(); - const avatar = new Image(); - const generate = () => { - ctx.drawImage(base, 0, 0); - ctx.drawImage(avatar, 341, 35, 117, 135); - ctx.drawImage(avatar, 343, 301, 117, 135); - }; - base.src = await fs.readFileAsync(path.join(__dirname, '..', '..', 'assets', 'images', 'beautiful.png')); - const { body } = await snekfetch.get(avatarURL); - avatar.src = body; - generate(); - return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'grunkle.png' }] }) - .catch(err => msg.say(`${err.name}: ${err.message}`)); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + if (!avatarURL) { + return msg.say('The User Provided has No Avatar.'); } + const Image = Canvas.Image; + const canvas = new Canvas(500, 532); + const ctx = canvas.getContext('2d'); + const base = new Image(); + const avatar = new Image(); + const generate = () => { + ctx.drawImage(base, 0, 0); + ctx.drawImage(avatar, 341, 35, 117, 135); + ctx.drawImage(avatar, 343, 301, 117, 135); + }; + base.src = await fs.readFileAsync(path.join(__dirname, '..', '..', 'assets', 'images', 'beautiful.png')); + const { body } = await snekfetch.get(avatarURL); + avatar.src = body; + generate(); + return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'grunkle.png' }] }); } }; diff --git a/commands/avataredit/bob-ross.js b/commands/avataredit/bob-ross.js index 0e8decaa..dacc29c3 100644 --- a/commands/avataredit/bob-ross.js +++ b/commands/avataredit/bob-ross.js @@ -22,38 +22,36 @@ module.exports = class BobRossCommand extends Command { { key: 'user', prompt: 'Which user would you like to edit the avatar of?', - type: 'user' + type: 'user', + default: '' } ] }); } async run(msg, args) { - const { user } = args; + const user = args.user || msg.author; const avatarURL = user.avatarURL('png', 256); - if (!avatarURL) return msg.say('This user has no avatar.'); - try { - const Image = Canvas.Image; - const canvas = new Canvas(600, 775); - const ctx = canvas.getContext('2d'); - const base = new Image(); - const avatar = new Image(); - const generate = () => { - ctx.fillStyle = 'white'; - ctx.fillRect(0, 0, 600, 775); - ctx.rotate(3 * Math.PI / 180); - ctx.drawImage(avatar, 69, 102, 256, 256); - ctx.rotate(-3 * Math.PI / 180); - ctx.drawImage(base, 0, 0); - }; - base.src = await fs.readFileAsync(path.join(__dirname, '..', '..', 'assets', 'images', 'bob-ross.png')); - const { body } = await snekfetch.get(avatarURL); - avatar.src = body; - generate(); - return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'ross.png' }] }) - .catch(err => msg.say(`${err.name}: ${err.message}`)); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + if (!avatarURL) { + return msg.say('The User Provided has No Avatar.'); } + const Image = Canvas.Image; + const canvas = new Canvas(600, 775); + const ctx = canvas.getContext('2d'); + const base = new Image(); + const avatar = new Image(); + const generate = () => { + ctx.fillStyle = 'white'; + ctx.fillRect(0, 0, 600, 775); + ctx.rotate(3 * Math.PI / 180); + ctx.drawImage(avatar, 69, 102, 256, 256); + ctx.rotate(-3 * Math.PI / 180); + ctx.drawImage(base, 0, 0); + }; + base.src = await fs.readFileAsync(path.join(__dirname, '..', '..', 'assets', 'images', 'bob-ross.png')); + const { body } = await snekfetch.get(avatarURL); + avatar.src = body; + generate(); + return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'ross.png' }] }); } }; diff --git a/commands/avataredit/card.js b/commands/avataredit/card.js index dd0b5f8c..4a0c8c4c 100644 --- a/commands/avataredit/card.js +++ b/commands/avataredit/card.js @@ -25,55 +25,57 @@ module.exports = class CardCommand extends Command { { key: 'member', prompt: 'Which user would you like to edit the avatar of?', - type: 'member' + type: 'member', + default: '' } ] }); } async run(msg, args) { - const { member } = args; - const avatarURL = member.user.avatarURL('png', 512); - if (!avatarURL) return msg.say('This user has no avatar.'); + const member = args.member || msg.member; + const avatarURL = member.user.avatarURL('png', 256); + if (!avatarURL) { + return msg.say('The User Provided has No Avatar.'); + } const cardID = Math.floor(Math.random() * (9999 - 1000 + 1)) + 1000; let rarity; - if (cardID < 5000) rarity = 'C'; - else if (cardID < 8000) rarity = 'U'; - else rarity = 'R'; - try { - const Image = Canvas.Image; - Canvas.registerFont(path.join(__dirname, '..', '..', 'assets', 'fonts', 'OpenSans.ttf'), { family: 'Open Sans' }); - const canvas = new Canvas(390, 544); - const ctx = canvas.getContext('2d'); - const base = new Image(); - const avatar = new Image(); - const generate = () => { - ctx.fillStyle = 'white'; - ctx.fillRect(0, 0, 390, 544); - ctx.drawImage(avatar, 11, 11, 370, 370); - ctx.drawImage(base, 0, 0); - ctx.font = '18px Open Sans'; - ctx.fillStyle = 'black'; - ctx.fillText(member.displayName, 30, 62); - ctx.fillText('Discord Join Date:', 148, 400); - ctx.fillText(moment(member.user.createdTimestamp).format('MMMM Do YYYY'), 148, 420); - ctx.fillText('Role:', 148, 457); - ctx.fillText(member.highestRole.name, 148, 477); - ctx.fillText(rarity, 73, 411); - ctx.fillText(cardID, 60, 457); - ctx.fillText(version.split('.')[0], 68, 502); - ctx.font = '14px Open Sans'; - ctx.fillText(member.id, 30, 355); - ctx.fillText(`#${member.user.discriminator}`, 313, 355); - }; - base.src = await fs.readFileAsync(path.join(__dirname, '..', '..', 'assets', 'images', 'card.png')); - const { body } = await snekfetch.get(avatarURL); - avatar.src = body; - generate(); - return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'card.png' }] }) - .catch(err => msg.say(`${err.name}: ${err.message}`)); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + if (cardID < 5000) { + rarity = 'C'; + } else if (cardID < 8000) { + rarity = 'U'; + } else { + rarity = 'R'; } + const Image = Canvas.Image; + Canvas.registerFont(path.join(__dirname, '..', '..', 'assets', 'fonts', 'OpenSans.ttf'), { family: 'Open Sans' }); + const canvas = new Canvas(390, 544); + const ctx = canvas.getContext('2d'); + const base = new Image(); + const avatar = new Image(); + const generate = () => { + ctx.fillStyle = 'white'; + ctx.fillRect(0, 0, 390, 544); + ctx.drawImage(avatar, 11, 11, 370, 370); + ctx.drawImage(base, 0, 0); + ctx.font = '18px Open Sans'; + ctx.fillStyle = 'black'; + ctx.fillText(member.displayName, 30, 62); + ctx.fillText('Discord Join Date:', 148, 400); + ctx.fillText(moment(member.user.createdTimestamp).format('MMMM Do YYYY'), 148, 420); + ctx.fillText('Role:', 148, 457); + ctx.fillText(member.highestRole.name, 148, 477); + ctx.fillText(rarity, 73, 411); + ctx.fillText(cardID, 60, 457); + ctx.fillText(version.split('.')[0], 68, 502); + ctx.font = '14px Open Sans'; + ctx.fillText(member.id, 30, 355); + ctx.fillText(`#${member.user.discriminator}`, 313, 355); + }; + base.src = await fs.readFileAsync(path.join(__dirname, '..', '..', 'assets', 'images', 'card.png')); + const { body } = await snekfetch.get(avatarURL); + avatar.src = body; + generate(); + return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'card.png' }] }); } }; diff --git a/commands/avataredit/challenger.js b/commands/avataredit/challenger.js index 10147a02..f953e28f 100644 --- a/commands/avataredit/challenger.js +++ b/commands/avataredit/challenger.js @@ -21,36 +21,34 @@ module.exports = class ChallengerCommand extends Command { { key: 'user', prompt: 'Which user would you like to edit the avatar of?', - type: 'user' + type: 'user', + default: '' } ] }); } async run(msg, args) { - const { user } = args; + const user = args.user || msg.author; const avatarURL = user.avatarURL('png', 256); - if (!avatarURL) return msg.say('This user has no avatar.'); - try { - const Image = Canvas.Image; - const canvas = new Canvas(500, 500); - const ctx = canvas.getContext('2d'); - const base = new Image(); - const avatar = new Image(); - const generate = () => { - ctx.fillStyle = '#ff0028'; - ctx.fillRect(0, 0, 500, 500); - ctx.drawImage(avatar, 226, 155, 200, 200); - ctx.drawImage(base, 0, 0); - }; - base.src = await fs.readFileAsync(path.join(__dirname, '..', '..', 'assets', 'images', 'challenger.png')); - const { body } = await snekfetch.get(avatarURL); - avatar.src = body; - generate(); - return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'challenger.png' }] }) - .catch(err => msg.say(`${err.name}: ${err.message}`)); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + if (!avatarURL) { + return msg.say('The User Provided has No Avatar.'); } + const Image = Canvas.Image; + const canvas = new Canvas(500, 500); + const ctx = canvas.getContext('2d'); + const base = new Image(); + const avatar = new Image(); + const generate = () => { + ctx.fillStyle = '#ff0028'; + ctx.fillRect(0, 0, 500, 500); + ctx.drawImage(avatar, 226, 155, 200, 200); + ctx.drawImage(base, 0, 0); + }; + base.src = await fs.readFileAsync(path.join(__dirname, '..', '..', 'assets', 'images', 'challenger.png')); + const { body } = await snekfetch.get(avatarURL); + avatar.src = body; + generate(); + return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'challenger.png' }] }); } }; diff --git a/commands/avataredit/dexter.js b/commands/avataredit/dexter.js index ef82ec30..60fd5537 100644 --- a/commands/avataredit/dexter.js +++ b/commands/avataredit/dexter.js @@ -21,36 +21,34 @@ module.exports = class DexterCommand extends Command { { key: 'user', prompt: 'Which user would you like to edit the avatar of?', - type: 'user' + type: 'user', + default: '' } ] }); } async run(msg, args) { - const { user } = args; + const user = args.user || msg.author; const avatarURL = user.avatarURL('png', 256); - if (!avatarURL) return msg.say('This user has no avatar.'); - try { - const Image = Canvas.Image; - const canvas = new Canvas(744, 554); - const ctx = canvas.getContext('2d'); - const base = new Image(); - const avatar = new Image(); - const generate = () => { - ctx.drawImage(base, 0, 0); - ctx.rotate(-11 * Math.PI / 180); - ctx.drawImage(avatar, 234, 274, 225, 225); - ctx.rotate(11 * Math.PI / 180); - }; - base.src = await fs.readFileAsync(path.join(__dirname, '..', '..', 'assets', 'images', 'dexter.png')); - const { body } = await snekfetch.get(avatarURL); - avatar.src = body; - generate(); - return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'dexter.png' }] }) - .catch(err => msg.say(`${err.name}: ${err.message}`)); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + if (!avatarURL) { + return msg.say('The User Provided has No Avatar.'); } + const Image = Canvas.Image; + const canvas = new Canvas(744, 554); + const ctx = canvas.getContext('2d'); + const base = new Image(); + const avatar = new Image(); + const generate = () => { + ctx.drawImage(base, 0, 0); + ctx.rotate(-11 * Math.PI / 180); + ctx.drawImage(avatar, 234, 274, 225, 225); + ctx.rotate(11 * Math.PI / 180); + }; + base.src = await fs.readFileAsync(path.join(__dirname, '..', '..', 'assets', 'images', 'dexter.png')); + const { body } = await snekfetch.get(avatarURL); + avatar.src = body; + generate(); + return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'dexter.png' }] }); } }; diff --git a/commands/avataredit/greyscale.js b/commands/avataredit/greyscale.js index 94b9cbdb..53320c02 100644 --- a/commands/avataredit/greyscale.js +++ b/commands/avataredit/greyscale.js @@ -19,40 +19,38 @@ module.exports = class GreyscaleCommand extends Command { { key: 'user', prompt: 'Which user would you like to edit the avatar of?', - type: 'user' + type: 'user', + default: '' } ] }); } async run(msg, args) { - const { user } = args; + const user = args.user || msg.author; const avatarURL = user.avatarURL('png', 256); - if (!avatarURL) return msg.say('This user has no avatar.'); - try { - const Image = Canvas.Image; - const canvas = new Canvas(256, 256); - const ctx = canvas.getContext('2d'); - const avatar = new Image(); - const generate = () => { - ctx.drawImage(avatar, 0, 0, 256, 256); - const imgData = ctx.getImageData(0, 0, 256, 256); - const { data } = imgData; - for (let i = 0; i < data.length; i += 4) { - const brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2]; - data[i] = brightness; - data[i + 1] = brightness; - data[i + 2] = brightness; - } - ctx.putImageData(imgData, 0, 0); - }; - const avatarImg = await snekfetch.get(avatarURL); - avatar.src = avatarImg.body; - generate(); - return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'greyscale.png' }] }) - .catch(err => msg.say(`${err.name}: ${err.message}`)); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + if (!avatarURL) { + return msg.say('The User Provided has No Avatar.'); } + const Image = Canvas.Image; + const canvas = new Canvas(256, 256); + const ctx = canvas.getContext('2d'); + const avatar = new Image(); + const generate = () => { + ctx.drawImage(avatar, 0, 0, 256, 256); + const imgData = ctx.getImageData(0, 0, 256, 256); + const { data } = imgData; + for (let i = 0; i < data.length; i += 4) { + const brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2]; + data[i] = brightness; + data[i + 1] = brightness; + data[i + 2] = brightness; + } + ctx.putImageData(imgData, 0, 0); + }; + const { body } = await snekfetch.get(avatarURL); + avatar.src = body; + generate(); + return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'greyscale.png' }] }); } }; diff --git a/commands/avataredit/invert.js b/commands/avataredit/invert.js index e4ac8218..86d2d9be 100644 --- a/commands/avataredit/invert.js +++ b/commands/avataredit/invert.js @@ -18,39 +18,37 @@ module.exports = class InvertCommand extends Command { { key: 'user', prompt: 'Which user would you like to edit the avatar of?', - type: 'user' + type: 'user', + default: '' } ] }); } async run(msg, args) { - const { user } = args; + const user = args.user || msg.author; const avatarURL = user.avatarURL('png', 256); - if (!avatarURL) return msg.say('This user has no avatar.'); - try { - const Image = Canvas.Image; - const canvas = new Canvas(256, 256); - const ctx = canvas.getContext('2d'); - const avatar = new Image(); - const generate = () => { - ctx.drawImage(avatar, 0, 0, 256, 256); - const imgData = ctx.getImageData(0, 0, 256, 256); - const { data } = imgData; - for (let i = 0; i < data.length; i += 4) { - data[i] = 255 - data[i]; - data[i + 1] = 255 - data[i + 1]; - data[i + 2] = 255 - data[i + 2]; - } - ctx.putImageData(imgData, 0, 0); - }; - const { body } = await snekfetch.get(avatarURL); - avatar.src = body; - generate(); - return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'invert.png' }] }) - .catch(err => msg.say(`${err.name}: ${err.message}`)); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + if (!avatarURL) { + return msg.say('The User Provided has No Avatar.'); } + const Image = Canvas.Image; + const canvas = new Canvas(256, 256); + const ctx = canvas.getContext('2d'); + const avatar = new Image(); + const generate = () => { + ctx.drawImage(avatar, 0, 0, 256, 256); + const imgData = ctx.getImageData(0, 0, 256, 256); + const { data } = imgData; + for (let i = 0; i < data.length; i += 4) { + data[i] = 255 - data[i]; + data[i + 1] = 255 - data[i + 1]; + data[i + 2] = 255 - data[i + 2]; + } + ctx.putImageData(imgData, 0, 0); + }; + const { body } = await snekfetch.get(avatarURL); + avatar.src = body; + generate(); + return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'invert.png' }] }); } }; diff --git a/commands/avataredit/rip.js b/commands/avataredit/rip.js index 7790142a..47fd2d9d 100644 --- a/commands/avataredit/rip.js +++ b/commands/avataredit/rip.js @@ -22,43 +22,41 @@ module.exports = class RIPCommand extends Command { { key: 'user', prompt: 'Which user would you like to edit the avatar of?', - type: 'user' + type: 'user', + default: '' } ] }); } async run(msg, args) { - const { user } = args; + const user = args.user || msg.author; const avatarURL = user.avatarURL('png', 256); - if (!avatarURL) return msg.say('This User has no Avatar.'); - try { - const Image = Canvas.Image; - const canvas = new Canvas(507, 338); - const ctx = canvas.getContext('2d'); - const base = new Image(); - const avatar = new Image(); - const generate = () => { - ctx.drawImage(base, 0, 0); - ctx.drawImage(avatar, 158, 51, 200, 200); - const imgData = ctx.getImageData(158, 51, 200, 200); - const { data } = imgData; - for (let i = 0; i < data.length; i += 4) { - const brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2]; - data[i] = brightness; - data[i + 1] = brightness; - data[i + 2] = brightness; - } - ctx.putImageData(imgData, 158, 51); - }; - base.src = await fs.readFileAsync(path.join(__dirname, '..', '..', 'assets', 'images', 'rip.png')); - const { body } = await snekfetch.get(avatarURL); - avatar.src = body; - generate(); - return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'rip.png' }] }) - .catch(err => msg.say(`${err.name}: ${err.message}`)); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + if (!avatarURL) { + return msg.say('The User Provided has No Avatar.'); } + const Image = Canvas.Image; + const canvas = new Canvas(507, 338); + const ctx = canvas.getContext('2d'); + const base = new Image(); + const avatar = new Image(); + const generate = () => { + ctx.drawImage(base, 0, 0); + ctx.drawImage(avatar, 158, 51, 200, 200); + const imgData = ctx.getImageData(158, 51, 200, 200); + const { data } = imgData; + for (let i = 0; i < data.length; i += 4) { + const brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2]; + data[i] = brightness; + data[i + 1] = brightness; + data[i + 2] = brightness; + } + ctx.putImageData(imgData, 158, 51); + }; + base.src = await fs.readFileAsync(path.join(__dirname, '..', '..', 'assets', 'images', 'rip.png')); + const { body } = await snekfetch.get(avatarURL); + avatar.src = body; + generate(); + return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'rip.png' }] }); } }; diff --git a/commands/avataredit/simba.js b/commands/avataredit/simba.js index 1f5335dc..d1520c6b 100644 --- a/commands/avataredit/simba.js +++ b/commands/avataredit/simba.js @@ -21,36 +21,34 @@ module.exports = class SimbaCommand extends Command { { key: 'user', prompt: 'Which user would you like to edit the avatar of?', - type: 'user' + type: 'user', + default: '' } ] }); } async run(msg, args) { - const { user } = args; + const user = args.user || msg.author; const avatarURL = user.avatarURL('png', 256); - if (!avatarURL) return msg.say('This user has no avatar.'); - try { - const Image = Canvas.Image; - const canvas = new Canvas(500, 281); - const ctx = canvas.getContext('2d'); - const base = new Image(); - const avatar = new Image(); - const generate = () => { - ctx.drawImage(base, 0, 0); - ctx.rotate(-24 * Math.PI / 180); - ctx.drawImage(avatar, 75, 160, 130, 150); - ctx.rotate(24 * Math.PI / 180); - }; - base.src = await fs.readFileAsync(path.join(__dirname, '..', '..', 'assets', 'images', 'simba.png')); - const { body } = await snekfetch.get(avatarURL); - avatar.src = body; - generate(); - return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'simba.png' }] }) - .catch(err => msg.say(`${err.name}: ${err.message}`)); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + if (!avatarURL) { + return msg.say('The User Provided has No Avatar.'); } + const Image = Canvas.Image; + const canvas = new Canvas(500, 281); + const ctx = canvas.getContext('2d'); + const base = new Image(); + const avatar = new Image(); + const generate = () => { + ctx.drawImage(base, 0, 0); + ctx.rotate(-24 * Math.PI / 180); + ctx.drawImage(avatar, 75, 160, 130, 150); + ctx.rotate(24 * Math.PI / 180); + }; + base.src = await fs.readFileAsync(path.join(__dirname, '..', '..', 'assets', 'images', 'simba.png')); + const { body } = await snekfetch.get(avatarURL); + avatar.src = body; + generate(); + return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'simba.png' }] }); } }; diff --git a/commands/avataredit/steam-card.js b/commands/avataredit/steam-card.js index 0740155d..6da5be6b 100644 --- a/commands/avataredit/steam-card.js +++ b/commands/avataredit/steam-card.js @@ -21,39 +21,37 @@ module.exports = class SteamCardCommand extends Command { { key: 'user', prompt: 'Which user would you like to edit the avatar of?', - type: 'user' + type: 'user', + default: '' } ] }); } async run(msg, args) { - const { user } = args; + const user = args.user || msg.author; const avatarURL = user.avatarURL('png', 512); - if (!avatarURL) return msg.say('This user has no avatar.'); - try { - const Image = Canvas.Image; - Canvas.registerFont(path.join(__dirname, '..', '..', 'assets', 'fonts', 'OpenSans.ttf'), { family: 'Open Sans' }); - const canvas = new Canvas(494, 568); - const ctx = canvas.getContext('2d'); - const base = new Image(); - const avatar = new Image(); - const generate = () => { - ctx.fillStyle = 'white'; - ctx.fillRect(0, 0, 494, 568); - ctx.drawImage(avatar, 25, 25, 450, 450); - ctx.drawImage(base, 0, 0); - ctx.font = '30px Open Sans'; - ctx.fillText(user.username, 35, 48); - }; - base.src = await fs.readFileAsync(path.join(__dirname, '..', '..', 'assets', 'images', 'steam-card.png')); - const { body } = await snekfetch.get(avatarURL); - avatar.src = body; - generate(); - return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'steam.png' }] }) - .catch(err => msg.say(`${err.name}: ${err.message}`)); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + if (!avatarURL) { + return msg.say('The User Provided has No Avatar.'); } + const Image = Canvas.Image; + Canvas.registerFont(path.join(__dirname, '..', '..', 'assets', 'fonts', 'OpenSans.ttf'), { family: 'Open Sans' }); + const canvas = new Canvas(494, 568); + const ctx = canvas.getContext('2d'); + const base = new Image(); + const avatar = new Image(); + const generate = () => { + ctx.fillStyle = 'white'; + ctx.fillRect(0, 0, 494, 568); + ctx.drawImage(avatar, 25, 25, 450, 450); + ctx.drawImage(base, 0, 0); + ctx.font = '30px Open Sans'; + ctx.fillText(user.username, 35, 48); + }; + base.src = await fs.readFileAsync(path.join(__dirname, '..', '..', 'assets', 'images', 'steam-card.png')); + const { body } = await snekfetch.get(avatarURL); + avatar.src = body; + generate(); + return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'steam.png' }] }); } }; diff --git a/commands/avataredit/triggered.js b/commands/avataredit/triggered.js index b5459556..5a478bbb 100644 --- a/commands/avataredit/triggered.js +++ b/commands/avataredit/triggered.js @@ -21,42 +21,40 @@ module.exports = class TriggeredCommand extends Command { { key: 'user', prompt: 'Which user would you like to edit the avatar of?', - type: 'user' + type: 'user', + default: '' } ] }); } async run(msg, args) { - const { user } = args; + const user = args.user || msg.author; const avatarURL = user.avatarURL('png', 512); - if (!avatarURL) return msg.say('This user has no avatar.'); - try { - const Image = Canvas.Image; - const canvas = new Canvas(320, 371); - const ctx = canvas.getContext('2d'); - const base = new Image(); - const avatar = new Image(); - const generate = () => { - ctx.fillStyle = 'white'; - ctx.fillRect(0, 0, 320, 371); - ctx.drawImage(avatar, 0, 0, 320, 320); - const imgData = ctx.getImageData(0, 0, 320, 320); - const { data } = imgData; - for (let i = 0; i < data.length; i += 4) { - data[i] = Math.max(255, data[i]); - } - ctx.putImageData(imgData, 0, 0); - ctx.drawImage(base, 0, 0); - }; - base.src = await fs.readFileAsync(path.join(__dirname, '..', '..', 'assets', 'images', 'triggered.png')); - const { body } = await snekfetch.get(avatarURL); - avatar.src = body; - generate(); - return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'triggered.png' }] }) - .catch(err => msg.say(`${err.name}: ${err.message}`)); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + if (!avatarURL) { + return msg.say('The User Provided has No Avatar.'); } + const Image = Canvas.Image; + const canvas = new Canvas(320, 371); + const ctx = canvas.getContext('2d'); + const base = new Image(); + const avatar = new Image(); + const generate = () => { + ctx.fillStyle = 'white'; + ctx.fillRect(0, 0, 320, 371); + ctx.drawImage(avatar, 0, 0, 320, 320); + const imgData = ctx.getImageData(0, 0, 320, 320); + const { data } = imgData; + for (let i = 0; i < data.length; i += 4) { + data[i] = Math.max(255, data[i]); + } + ctx.putImageData(imgData, 0, 0); + ctx.drawImage(base, 0, 0); + }; + base.src = await fs.readFileAsync(path.join(__dirname, '..', '..', 'assets', 'images', 'triggered.png')); + const { body } = await snekfetch.get(avatarURL); + avatar.src = body; + generate(); + return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'triggered.png' }] }); } }; diff --git a/commands/avataredit/wanted.js b/commands/avataredit/wanted.js index f9195064..6113ab4a 100644 --- a/commands/avataredit/wanted.js +++ b/commands/avataredit/wanted.js @@ -21,34 +21,32 @@ module.exports = class WantedCommand extends Command { { key: 'user', prompt: 'Which user would you like to edit the avatar of?', - type: 'user' + type: 'user', + default: '' } ] }); } async run(msg, args) { - const { user } = args; + const user = args.user || msg.author; const avatarURL = user.avatarURL('png', 512); - if (!avatarURL) return msg.say('This user has no avatar.'); - try { - const Image = Canvas.Image; - const canvas = new Canvas(741, 1000); - const ctx = canvas.getContext('2d'); - const base = new Image(); - const avatar = new Image(); - const generate = () => { - ctx.drawImage(base, 0, 0); - ctx.drawImage(avatar, 150, 360, 430, 430); - }; - base.src = await fs.readFileAsync(path.join(__dirname, '..', '..', 'assets', 'images', 'wanted.png')); - const { body } = await snekfetch.get(avatarURL); - avatar.src = body; - generate(); - return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'wanted.png' }] }) - .catch(err => msg.say(`${err.name}: ${err.message}`)); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + if (!avatarURL) { + return msg.say('The User Provided has No Avatar.'); } + const Image = Canvas.Image; + const canvas = new Canvas(741, 1000); + const ctx = canvas.getContext('2d'); + const base = new Image(); + const avatar = new Image(); + const generate = () => { + ctx.drawImage(base, 0, 0); + ctx.drawImage(avatar, 150, 360, 430, 430); + }; + base.src = await fs.readFileAsync(path.join(__dirname, '..', '..', 'assets', 'images', 'wanted.png')); + const { body } = await snekfetch.get(avatarURL); + avatar.src = body; + generate(); + return msg.say({ files: [{ attachment: canvas.toBuffer(), name: 'wanted.png' }] }); } }; diff --git a/commands/games/battle.js b/commands/games/battle.js index c459ab69..e8d0179f 100644 --- a/commands/games/battle.js +++ b/commands/games/battle.js @@ -24,13 +24,19 @@ module.exports = class BattleCommand extends Command { async run(msg, args) { const { opponent } = args; - if (opponent.bot) return msg.say('You cannot fight bots!'); - if (opponent.id === msg.author.id) return msg.say('You cannot fight yourself!'); - if (this.fighting.has(msg.guild.id)) return msg.say('There is already a fight in this server...'); + if (opponent.bot) { + return msg.say('Bots cannot be fought.'); + } + if (opponent.id === msg.author.id) { + return msg.say('You may not fight yourself.'); + } + if (this.fighting.has(msg.guild.id)) { + return msg.say('Only one fight may be occurring per server.'); + } this.fighting.add(msg.guild.id); await msg.say(`**${opponent.username}**, do you accept this challenge? **__Y__es** or **No**?`); try { - const verify = await msg.channel.awaitMessages(res => res.author.id === opponent.id, { + const verify = await msg.channel.awaitMessages((res) => res.author.id === opponent.id, { max: 1, time: 15000, errors: ['time'] @@ -50,14 +56,14 @@ module.exports = class BattleCommand extends Command { **${opponent.username}**: ${oppoHP}HP `); try { - const turn = await msg.channel.awaitMessages(res => res.author.id === (userTurn ? msg.author.id : opponent.id), { + const turn = await msg.channel.awaitMessages((res) => res.author.id === (userTurn ? msg.author.id : opponent.id), { max: 1, time: 15000, errors: ['time'] }); const choice = turn.first().content.toLowerCase(); if (choice === 'fight') { - const damage = Math.floor(Math.random() * (guard ? 25 : 100)) + 1; + const damage = Math.floor(Math.random() * (guard ? 10 : 100)) + 1; await msg.say(`**${username}** deals **${damage}** damage!`); if (userTurn) { oppoHP = oppoHP - damage; @@ -66,12 +72,17 @@ module.exports = class BattleCommand extends Command { userHP = userHP - damage; userTurn = true; } - if (guard) guard = false; + if (guard) { + guard = false; + } } else if (choice === 'guard') { await msg.say(`**${username}** guards!`); guard = true; - if (userTurn) userTurn = false; - else userTurn = true; + if (userTurn) { + userTurn = false; + } else { + userTurn = true; + } } else if (choice === 'special') { const hit = Math.floor(Math.random() * 4) + 1; if (hit === 1) { @@ -84,12 +95,19 @@ module.exports = class BattleCommand extends Command { userHP = userHP - damage; userTurn = true; } - if (guard) guard = false; + if (guard) { + guard = false; + } } else { await msg.say(`**${username}**'s attack missed!`); - if (guard) guard = false; - if (userTurn) userTurn = false; - else userTurn = true; + if (userTurn) { + userTurn = false; + } else { + userTurn = true; + } + if (guard) { + guard = false; + } } } else if (choice === 'cure') { if (userTurn ? userCure : oppoCure) { @@ -103,13 +121,22 @@ module.exports = class BattleCommand extends Command { oppoCure = false; userTurn = true; } - if (guard) guard = false; - } else await msg.say('You have already cured!'); + if (guard) { + guard = false; + } + } else { + await msg.say('You have already cured!'); + } } else if (choice === 'run') { await msg.say(`**${username}** flees!`); - if (userTurn) userHP = 0; - else oppoHP = 0; - } else await msg.say('I do not understand what you want to do.'); + if (userTurn) { + userHP = 0; + } else { + oppoHP = 0; + } + } else { + await msg.say('I do not understand what you want to do.'); + } } catch (err) { await msg.say('Time!'); break; @@ -118,8 +145,8 @@ module.exports = class BattleCommand extends Command { this.fighting.delete(msg.guild.id); return msg.say(stripIndents` The match is over! - **Winner: ${(userHP > oppoHP) ? `${msg.author.username}** (${userHP}HP)` : `${opponent.username}** (${oppoHP}HP)`} - **Loser: ${(userHP > oppoHP) ? `${opponent.username}** (${oppoHP}HP)` : `${msg.author.username}** (${userHP}HP)`} + **Winner: ${userHP > oppoHP ? `${msg.author.username}** (${userHP}HP)` : `${opponent.username}** (${oppoHP}HP)`} + **Loser: ${userHP > oppoHP ? `${opponent.username}** (${oppoHP}HP)` : `${msg.author.username}** (${userHP}HP)`} `); } else { this.fighting.delete(msg.guild.id); diff --git a/commands/games/lottery.js b/commands/games/lottery.js index bb55d2c4..2786287a 100644 --- a/commands/games/lottery.js +++ b/commands/games/lottery.js @@ -12,7 +12,10 @@ module.exports = class LotteryCommand extends Command { run(msg) { const lottery = Math.floor(Math.random() * 100) + 1; - if (lottery < 99) return msg.say(`Nope, sorry ${msg.author.username}, you lost.`); - return msg.say(`Wow ${msg.author.username}! You actually won! Great job!`); + if (lottery === 1) { + return msg.say(`Wow ${msg.author.username}! You actually won! Great job!`); + } else { + return msg.say(`Nope, sorry ${msg.author.username}, you lost.`); + } } }; diff --git a/commands/games/math-game.js b/commands/games/math-game.js index 944ad912..b1683afe 100644 --- a/commands/games/math-game.js +++ b/commands/games/math-game.js @@ -1,7 +1,7 @@ const Command = require('../../structures/Command'); const { RichEmbed } = require('discord.js'); const math = require('mathjs'); -const operations = ['+', '-', '*']; +const { operations, difficulties, maxValues } = require('../../assets/json/math-game'); module.exports = class MathGameCommand extends Command { constructor(client) { @@ -14,13 +14,16 @@ module.exports = class MathGameCommand extends Command { args: [ { key: 'difficulty', - prompt: 'What should the difficulty of the game be? `Easy`, `Medium`, `Hard`, `Extreme`, or `Impossible`?', + prompt: `What should the difficulty of the game be? One of: ${difficulties.join(', ')}`, type: 'string', - validate: difficulty => { - if (['easy', 'medium', 'hard', 'extreme', 'impossible'].includes(difficulty.toLowerCase())) return true; - return 'The difficulty must be either `easy`, `medium`, `hard`, `extreme`, or `impossible`.'; + validate: (difficulty) => { + if (difficulties.includes(difficulty.toLowerCase())) { + return true; + } else { + return `The difficulty must be one of: ${difficulties.join(', ')}`; + } }, - parse: difficulty => difficulty.toLowerCase() + parse: (difficulty) => difficulty.toLowerCase() } ] }); @@ -29,38 +32,24 @@ module.exports = class MathGameCommand extends Command { async run(msg, args) { const { difficulty } = args; const operation = operations[Math.floor(Math.random() * operations.length)]; - let value; - switch(difficulty) { - case 'easy': - value = 10; - break; - case 'medium': - value = 50; - break; - case 'hard': - value = 100; - break; - case 'extreme': - value = 1000; - break; - case 'impossible': - value = 10000; - break; - } + const value = maxValues[difficulty]; const expression = `${Math.floor(Math.random() * value) + 1} ${operation} ${Math.floor(Math.random() * value) + 1}`; const answer = math.eval(expression).toString(); const embed = new RichEmbed() - .setTitle('You have **10** seconds to answer:') + .setTitle('You have 10 seconds to answer:') .setDescription(expression); await msg.embed(embed); try { - const collected = await msg.channel.awaitMessages(res => res.author.id === msg.author.id, { + const collected = await msg.channel.awaitMessages((res) => res.author.id === msg.author.id, { max: 1, time: 10000, errors: ['time'] }); - if (collected.first().content !== answer) return msg.say(`Nope, sorry, it's ${answer}.`); - return msg.say('Nice job! 10/10! You deserve some cake!'); + if (collected.first().content !== answer) { + return msg.say(`Nope, sorry, it's ${answer}.`); + } else { + return msg.say('Nice job! 10/10! You deserve some cake!'); + } } catch (err) { return msg.say(`Time! It was ${answer}, sorry!`); } diff --git a/commands/games/quiz.js b/commands/games/quiz.js index baad1f4e..9dcd9986 100644 --- a/commands/games/quiz.js +++ b/commands/games/quiz.js @@ -16,35 +16,34 @@ module.exports = class QuizCommand extends Command { } async run(msg) { + const { body } = await snekfetch + .get('https://opentdb.com/api.php') + .query({ + amount: 1, + type: 'boolean', + encode: 'url3986' + }); + const answer = body.results[0].correct_answer.toLowerCase(); + const embed = new RichEmbed() + .setTitle('You have 15 seconds to answer this question:') + .setDescription(stripIndents` + **${decodeURIComponent(body.results[0].category)}** + True or False: ${decodeURIComponent(body.results[0].question)} + `); + await msg.embed(embed); try { - const { body } = await snekfetch - .get('https://opentdb.com/api.php') - .query({ - amount: 1, - type: 'boolean', - encode: 'url3986' - }); - const answer = body.results[0].correct_answer.toLowerCase(); - const embed = new RichEmbed() - .setTitle('You have **15** seconds to answer this question:') - .setDescription(stripIndents` - **${decodeURIComponent(body.results[0].category)}** - True or False: ${decodeURIComponent(body.results[0].question)} - `); - await msg.embed(embed); - try { - const collected = await msg.channel.awaitMessages(res => res.author.id === msg.author.id, { - max: 1, - time: 15000, - errors: ['time'] - }); - if (collected.first().content.toLowerCase() !== answer) return msg.say(`Nope, sorry, it's ${answer}.`); + const collected = await msg.channel.awaitMessages((res) => res.author.id === msg.author.id, { + max: 1, + time: 15000, + errors: ['time'] + }); + if (collected.first().content.toLowerCase() !== answer) { + return msg.say(`Nope, sorry, it's ${answer}.`); + } else { return msg.say('Nice job! 10/10! You deserve some cake!'); - } catch (err) { - return msg.say(`Time! It was ${answer}, sorry!`); } } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + return msg.say(`Time! It was ${answer}, sorry!`); } } }; diff --git a/commands/games/rock-paper-scissors.js b/commands/games/rock-paper-scissors.js index e5f7dd39..93ac185d 100644 --- a/commands/games/rock-paper-scissors.js +++ b/commands/games/rock-paper-scissors.js @@ -1,5 +1,5 @@ const Command = require('../../structures/Command'); -const responses = ['Paper', 'Rock', 'Scissors']; +const choices = ['paper', 'rock', 'scissors']; module.exports = class RockPaperScissorsCommand extends Command { constructor(client) { @@ -14,11 +14,14 @@ module.exports = class RockPaperScissorsCommand extends Command { key: 'choice', prompt: '`Rock`, `Paper`, or `Scissors`?', type: 'string', - validate: choice => { - if (['rock', 'paper', 'scissors'].includes(choice.toLowerCase())) return true; - return 'Please enter either `rock`, `paper`, or `scissors`.'; + validate: (choice) => { + if (choices.includes(choice.toLowerCase())) { + return true; + } else { + return 'Please enter either `rock`, `paper`, or `scissors`.'; + } }, - parse: choice => choice.toLowerCase() + parse: (choice) => choice.toLowerCase() } ] }); @@ -26,19 +29,31 @@ module.exports = class RockPaperScissorsCommand extends Command { run(msg, args) { const { choice } = args; - const response = responses[Math.floor(Math.random() * responses.length)]; + const response = choices[Math.floor(Math.random() * choices.length)]; if (choice === 'rock') { - if (response === 'Rock') return msg.say('Rock! Aw, it\'s a tie!'); - if (response === 'Paper') return msg.say('Paper! Yes! I win!'); - if (response === 'Scissors') return msg.say('Scissors! Aw... I lose...'); + if (response === 'rock') { + return msg.say('Rock! Aw... A tie...'); + } else if (response === 'paper') { + return msg.say('Paper! Yes! I win!'); + } else if (response === 'scissors') { + return msg.say('Scissors! Aw... I lose...'); + } } else if (choice === 'paper') { - if (response === 'Rock') return msg.say('Rock! Aw... I lose...'); - if (response === 'Paper') return msg.say('Paper! Aw, it\'s a tie!'); - if (response === 'Scissors') return msg.say('Scissors! Yes! I win!'); + if (response === 'rock') { + return msg.say('Rock! Aw... I lose...'); + } else if (response === 'paper') { + return msg.say('Paper! Aw... A tie...'); + } else if (response === 'scissors') { + return msg.say('Scissors! Yes! I win!'); + } } else if (choice === 'scissors') { - if (response === 'Rock') return msg.say('Rock! Yes! I win!'); - if (response === 'Paper') return msg.say('Paper! Aw... I lose...'); - if (response === 'Scissors') return msg.say('Scissors! Aw, it\'s a tie!'); + if (response === 'rock') { + return msg.say('Rock! Yes! I win!'); + } else if (response === 'paper') { + return msg.say('Paper! Aw... I lose...'); + } else if (response === 'scissors') { + return msg.say('Scissors! Aw... A tie...'); + } } } }; diff --git a/commands/games/slots.js b/commands/games/slots.js index 33fbaf9b..6dc73c94 100644 --- a/commands/games/slots.js +++ b/commands/games/slots.js @@ -1,6 +1,6 @@ const Command = require('../../structures/Command'); const { stripIndents } = require('common-tags'); -const slotThing = [':grapes:', ':tangerine:', ':pear:', ':cherries:']; +const slots = [':grapes:', ':tangerine:', ':pear:', ':cherries:']; module.exports = class SlotsCommand extends Command { constructor(client) { @@ -13,17 +13,19 @@ module.exports = class SlotsCommand extends Command { } run(msg) { - const slotOne = slotThing[Math.floor(Math.random() * slotThing.length)]; - const slotTwo = slotThing[Math.floor(Math.random() * slotThing.length)]; - const slotThree = slotThing[Math.floor(Math.random() * slotThing.length)]; - if (slotOne === slotTwo && slotOne === slotThree) + const slotOne = slots[Math.floor(Math.random() * slots.length)]; + const slotTwo = slots[Math.floor(Math.random() * slots.length)]; + const slotThree = slots[Math.floor(Math.random() * slots.length)]; + if (slotOne === slotTwo && slotOne === slotThree) { return msg.say(stripIndents` ${slotOne}|${slotTwo}|${slotThree} Wow! You won! Great job... er... luck! `); - return msg.say(stripIndents` - ${slotOne}|${slotTwo}|${slotThree} - Aww... You lost... Guess it's just bad luck, huh? - `); + } else { + return msg.say(stripIndents` + ${slotOne}|${slotTwo}|${slotThree} + Aww... You lost... Guess it's just bad luck, huh? + `); + } } }; diff --git a/commands/games/typing-game.js b/commands/games/typing-game.js index db2d41bf..26bdda75 100644 --- a/commands/games/typing-game.js +++ b/commands/games/typing-game.js @@ -1,6 +1,6 @@ const Command = require('../../structures/Command'); const { RichEmbed } = require('discord.js'); -const sentences = require('../../assets/json/typing-game'); +const { sentences, difficulties, times } = require('../../assets/json/typing-game'); module.exports = class TypingGameCommand extends Command { constructor(client) { @@ -13,13 +13,16 @@ module.exports = class TypingGameCommand extends Command { args: [ { key: 'difficulty', - prompt: 'What should the difficulty of the game be? `Easy`, `Medium`, `Hard`, `Extreme`, or `Impossible`?', + prompt: `What should the difficulty of the game be? One of: ${difficulties.join(', ')}`, type: 'string', - validate: difficulty => { - if (['easy', 'medium', 'hard', 'extreme', 'impossible'].includes(difficulty.toLowerCase())) return true; - return 'The difficulty must be either `easy`, `medium`, `hard`, `extreme`, or `impossible`.'; + validate: (difficulty) => { + if (difficulties.includes(difficulty.toLowerCase())) { + return true; + } else { + return `The difficulty must be one of: ${difficulties.join(', ')}`; + } }, - parse: difficulty => difficulty.toLowerCase() + parse: (difficulty) => difficulty.toLowerCase() } ] }); @@ -28,36 +31,22 @@ module.exports = class TypingGameCommand extends Command { async run(msg, args) { const { difficulty } = args; const sentence = sentences[Math.floor(Math.random() * sentences.length)]; - let time; - switch(difficulty) { - case 'easy': - time = 25000; - break; - case 'medium': - time = 20000; - break; - case 'hard': - time = 15000; - break; - case 'extreme': - time = 10000; - break; - case 'impossible': - time = 5000; - break; - } + const time = times[difficulty]; const embed = new RichEmbed() - .setTitle(`You have **${time / 1000}** seconds to type:`) + .setTitle(`You have ${time / 1000} seconds to type:`) .setDescription(sentence); await msg.embed(embed); try { - const collected = await msg.channel.awaitMessages(res => res.author.id === msg.author.id, { + const collected = await msg.channel.awaitMessages((res) => res.author.id === msg.author.id, { max: 1, time: time, errors: ['time'] }); - if (collected.first().content !== sentence) return msg.say('Nope, sorry!'); - return msg.say(`Good Job! You won!`); + if (collected.first().content !== sentence) { + return msg.say('Nope, sorry!'); + } else { + return msg.say('Nice job! 10/10! You deserve some cake!'); + } } catch (err) { return msg.say('Time! Sorry!'); } diff --git a/commands/guildinfo/emoji.js b/commands/guildinfo/emoji.js index fa6e945d..abb7cac3 100644 --- a/commands/guildinfo/emoji.js +++ b/commands/guildinfo/emoji.js @@ -12,7 +12,10 @@ module.exports = class EmojiCommand extends Command { } run(msg) { - return msg.say(msg.guild.emojis.map(e => e).join('')) - .catch(() => msg.say('There was an error sending the emoji.')); + const emoji = msg.guild.emojis; + if (!emoji.size) { + return msg.say('You have no Custom Emoji.'); + } + return msg.say(emoji.map((e) => e).join('')); } }; diff --git a/commands/guildinfo/server-info.js b/commands/guildinfo/server-info.js index 485ad877..a3f9ae4e 100644 --- a/commands/guildinfo/server-info.js +++ b/commands/guildinfo/server-info.js @@ -1,8 +1,7 @@ const Command = require('../../structures/Command'); const { RichEmbed } = require('discord.js'); -const { stripIndents } = require('common-tags'); const moment = require('moment'); -require('moment-duration-format'); +const filterLevels = ['Off', 'No Role', 'Everyone']; module.exports = class GuildInfoCommand extends Command { constructor(client) { @@ -21,22 +20,21 @@ module.exports = class GuildInfoCommand extends Command { const embed = new RichEmbed() .setColor(0x00AE86) .setThumbnail(msg.guild.iconURL()) - .addField('Name', + .addField('❯ Name', msg.guild.name, true) - .addField('ID', + .addField('❯ ID', msg.guild.id, true) - .addField('Creation Date', - stripIndents` - ${moment(msg.guild.createdTimestamp).format('MMMM Do YYYY h:mm:ss A')} - ${moment.duration(Date.now() - msg.guild.createdTimestamp).format('y[ years], M[ months], w[ weeks, and ]d[ days]')} ago. - `) - .addField('Default Channel', + .addField('❯ Creation Date', + moment(msg.guild.createdAt).format('MMMM Do YYYY'), true) + .addField('❯ Default Channel', msg.guild.defaultChannel, true) - .addField('Region', + .addField('❯ Region', msg.guild.region, true) - .addField('Owner', + .addField('❯ Explicit Filter', + filterLevels[msg.guild.explicitContentFilter], true) + .addField('❯ Owner', msg.guild.owner, true) - .addField('Members', + .addField('❯ Members', msg.guild.memberCount, true); return msg.embed(embed); } diff --git a/commands/moderation/ban.js b/commands/moderation/ban.js index a4b1b403..4013ffc6 100644 --- a/commands/moderation/ban.js +++ b/commands/moderation/ban.js @@ -13,7 +13,6 @@ module.exports = class BanCommand extends Command { guildOnly: true, clientPermissions: ['BAN_MEMBERS'], userPermissions: ['BAN_MEMBERS'], - allowStaff: true, args: [ { key: 'member', @@ -24,9 +23,12 @@ module.exports = class BanCommand extends Command { key: 'reason', prompt: 'What do you want to set the reason as?', type: 'string', - validate: reason => { - if (reason.length < 140) return true; - return 'Invalid Reason. Reason must be under 140 characters.'; + validate: (reason) => { + if (reason.length < 140) { + return true; + } else { + return 'Invalid Reason. Reason must be under 140 characters.'; + } } } ] @@ -35,37 +37,57 @@ module.exports = class BanCommand extends Command { async run(msg, args) { const modlogs = msg.guild.channels.get(msg.guild.settings.get('modLog')); - if (!modlogs) return msg.say('This Command requires a channel set with the `mod-channel` command.'); - if (!modlogs.permissionsFor(this.client.user).has('SEND_MESSAGES')) - return msg.say('This Command requires the `SEND_MESSAGES` Permission for the Mod Log Channel.'); - if (!modlogs.permissionsFor(this.client.user).has('EMBED_LINKS')) - return msg.say('This Command requires the `EMBED_LINKS` Permission for the Mod Log Channel.'); const { member, reason } = args; - if (!member.bannable) return msg.say('This member is not bannable. Perhaps they have a higher role than me?'); + if (!member.bannable) { + return msg.say('This member is not bannable. Perhaps they have a higher role than me?'); + } try { - try { - await member.user.send(stripIndents` - You were banned from ${msg.guild.name}! - Reason: ${reason}. - `); - } catch (err) { - await msg.say('Failed to Send DM.'); + await msg.say(`Are you sure you want to ban ${member.user.tag} (${member.id})?`); + const collected = await msg.channel.awaitMessages((res) => res.author.id === msg.author.id, { + max: 1, + time: 15000, + errors: ['time'] + }); + if (['y', 'yes'].includes(collected.first().content.toLowerCase())) { + try { + await member.user.send(stripIndents` + You were banned from ${msg.guild.name}! + Reason: ${reason} + `); + } catch (err) { + await msg.say('Failed to Send DM.'); + } + await member.ban({ + days: 7, + reason: `${msg.author.tag}: ${reason}` + }); + await msg.say(`Successfully banned ${member.user.tag}.`); + if (!modlogs || !modlogs.permissionsFor(this.client.user.has('SEND_MESSAGES'))) { + return msg.say('Could not log the ban to the mod logs.'); + } else if (!modlogs.permissionsFor(this.client.user).has('EMBED_LINKS')) { + return modlogs.send(stripIndents` + **Member:** ${member.user.tag} (${member.id}) + **Action:** Ban + **Reason:** ${reason} + **Moderator:** ${msg.author.tag} + `); + } else { + const embed = new RichEmbed() + .setAuthor(msg.author.tag, msg.author.displayAvatarURL) + .setColor(0xFF0000) + .setTimestamp() + .setDescription(stripIndents` + **Member:** ${member.user.tag} (${member.id}) + **Action:** Ban + **Reason:** ${reason} + `); + return modlogs.send({ embed }); + } + } else { + return msg.say('Aborting Ban.'); } - await member.ban({ days: 7, reason }); - msg.say(':ok_hand:'); - const embed = new RichEmbed() - .setAuthor(msg.author.tag, msg.author.displayAvatarURL) - .setColor(0xFF0000) - .setTimestamp() - .setDescription(stripIndents` - **Member:** ${member.user.tag} (${member.id}) - **Action:** Ban - **Reason:** ${reason} - `); - modlogs.send({ embed }); - return null; } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + return msg.say('Aborting Ban.'); } } }; diff --git a/commands/moderation/kick.js b/commands/moderation/kick.js index d131412c..bbbbfd79 100644 --- a/commands/moderation/kick.js +++ b/commands/moderation/kick.js @@ -6,13 +6,13 @@ module.exports = class KickCommand extends Command { constructor(client) { super(client, { name: 'kick', + aliases: ['kickke'], group: 'moderation', memberName: 'kick', description: 'Kicks a user and logs the kick to the mod logs.', guildOnly: true, clientPermissions: ['KICK_MEMBERS'], userPermissions: ['KICK_MEMBERS'], - allowStaff: true, args: [ { key: 'member', @@ -24,8 +24,11 @@ module.exports = class KickCommand extends Command { prompt: 'What do you want to set the reason as?', type: 'string', validate: reason => { - if (reason.length < 140) return true; - return 'Invalid Reason. Reason must be under 140 characters.'; + if (reason.length < 140) { + return true; + } else { + return 'Invalid Reason. Reason must be under 140 characters.'; + } } } ] @@ -34,37 +37,56 @@ module.exports = class KickCommand extends Command { async run(msg, args) { const modlogs = msg.guild.channels.get(msg.guild.settings.get('modLog')); - if (!modlogs) return msg.say('This Command requires a channel set with the `mod-channel` command.'); - if (!modlogs.permissionsFor(this.client.user).has('SEND_MESSAGES')) - return msg.say('This Command requires the `SEND_MESSAGES` Permission for the Mod Log Channel.'); - if (!modlogs.permissionsFor(this.client.user).has('EMBED_LINKS')) - return msg.say('This Command requires the `EMBED_LINKS` Permission for the Mod Log Channel.'); const { member, reason } = args; - if (!member.kickable) return msg.say('This member is not kickable. Perhaps they have a higher role than me?'); + if (!member.kickable) { + return msg.say('This member is not kickable. Perhaps they have a higher role than me?'); + } try { - try { - await member.user.send(stripIndents` - You were kicked from ${msg.guild.name}! - Reason: ${reason}. - `); - } catch (err) { - await msg.say('Failed to Send DM.'); + await msg.say(`Are you sure you want to kick ${member.user.tag} (${member.id})?`); + const collected = await msg.channel.awaitMessages((res) => res.author.id === msg.author.id, { + max: 1, + time: 15000, + errors: ['time'] + }); + if (['y', 'yes'].includes(collected.first().content.toLowerCase())) { + try { + await member.user.send(stripIndents` + You were kicked from ${msg.guild.name}! + Reason: ${reason} + `); + } catch (err) { + await msg.say('Failed to Send DM.'); + } + await member.kick({ + reason: `${msg.author.tag}: ${reason}` + }); + await msg.say(`Successfully kicked ${member.user.tag}.`); + if (!modlogs || !modlogs.permissionsFor(this.client.user.has('SEND_MESSAGES'))) { + return msg.say('Could not log the kick to the mod logs.'); + } else if (!modlogs.permissionsFor(this.client.user).has('EMBED_LINKS')) { + return modlogs.send(stripIndents` + **Member:** ${member.user.tag} (${member.id}) + **Action:** Kick + **Reason:** ${reason} + **Moderator:** ${msg.author.tag} + `); + } else { + const embed = new RichEmbed() + .setAuthor(msg.author.tag, msg.author.displayAvatarURL) + .setColor(0xFFA500) + .setTimestamp() + .setDescription(stripIndents` + **Member:** ${member.user.tag} (${member.id}) + **Action:** Kick + **Reason:** ${reason} + `); + return modlogs.send({ embed }); + } + } else { + return msg.say('Aborting Kick.'); } - await member.kick({ reason }); - msg.say(':ok_hand:'); - const embed = new RichEmbed() - .setAuthor(msg.author.tag, msg.author.displayAvatarURL) - .setColor(0xFFA500) - .setTimestamp() - .setDescription(stripIndents` - **Member:** ${member.user.tag} (${member.id}) - **Action:** Kick - **Reason:** ${reason} - `); - modlogs.send({ embed }); - return null; } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + return msg.say('Aborting Kick.'); } } }; diff --git a/commands/moderation/lockdown.js b/commands/moderation/lockdown.js index ebdb4c18..b635242f 100644 --- a/commands/moderation/lockdown.js +++ b/commands/moderation/lockdown.js @@ -7,22 +7,24 @@ module.exports = class LockdownCommand extends Command { name: 'lockdown', group: 'moderation', memberName: 'lockdown', - description: 'Locks down the current channel or removes a lockdown, which prevents non-administrator members from speaking.', + description: 'Locks down the current channel or removes a lockdown.', guildOnly: true, clientPermissions: ['ADMINISTRATOR'], userPermissions: ['ADMINISTRATOR'], - allowStaff: true, args: [ { key: 'type', prompt: 'Please enter either `start` or `stop`.', type: 'string', - validate: type => { - if (['start', 'stop'].includes(type.toLowerCase())) return true; - return 'Please enter either `start` or `stop`.'; + default: 'start', + validate: (type) => { + if (['start', 'stop'].includes(type.toLowerCase())) { + return true; + } else { + return 'Please enter either `start` or `stop`.'; + } }, - parse: type => type.toLowerCase(), - default: 'start' + parse: (type) => type.toLowerCase() } ] }); @@ -31,25 +33,14 @@ module.exports = class LockdownCommand extends Command { async run(msg, args) { const { type } = args; if (type === 'start') { - try { - await msg.channel.overwritePermissions(msg.guild.defaultRole, { SEND_MESSAGES: false }); - const staffRole = msg.guild.settings.get('staffRole'); - if (staffRole && !msg.channel.permissionOverwrites.has(staffRole)) - await msg.channel.overwritePermissions(msg.guild.roles.get(staffRole), { SEND_MESSAGES: true }); - return msg.say(stripIndents` - Lockdown Started, users without Administrator ${staffRole ? 'or the Staff Role ' : ''}can no longer post messages. - Please use \`lockdown stop\` to end the lockdown. - `); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); - } + await msg.channel.overwritePermissions(msg.guild.defaultRole, { SEND_MESSAGES: false }); + return msg.say(stripIndents` + Lockdown Started, users without Administrator can no longer post messages. + Please use \`lockdown stop\` to end the lockdown. + `); } else if (type === 'stop') { - try { - await msg.channel.overwritePermissions(msg.guild.defaultRole, { SEND_MESSAGES: null }); - return msg.say('Lockdown Ended.'); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); - } + await msg.channel.overwritePermissions(msg.guild.defaultRole, { SEND_MESSAGES: null }); + return msg.say('Lockdown Ended.'); } } }; diff --git a/commands/moderation/prune.js b/commands/moderation/prune.js index 5397ecbb..2da4c312 100644 --- a/commands/moderation/prune.js +++ b/commands/moderation/prune.js @@ -6,7 +6,7 @@ module.exports = class PruneCommand extends Command { name: 'prune', group: 'moderation', memberName: 'prune', - description: 'Deletes a specified number of messages from the current channel, up to 99.', + description: 'Deletes messages from the current channel, up to 99.', guildOnly: true, throttling: { usages: 1, @@ -14,21 +14,24 @@ module.exports = class PruneCommand extends Command { }, clientPermissions: ['READ_MESSAGE_HISTORY', 'MANAGE_MESSAGES'], userPermissions: ['MANAGE_MESSAGES'], - allowStaff: true, args: [ { key: 'count', label: 'amount of messages', prompt: 'How many messages do you want to delete? Limit of up to 99.', type: 'integer', - validate: count => { - if (count < 100 && count > 0) return true; - return 'Invalid Count. Count must be from 1-99.'; + validate: (count) => { + if (count < 100 && count > 0) { + return true; + } else { + return 'Invalid Count. Count must be from 1-99.'; + } } } ] }); } + async run(msg, args) { const { count } = args; try { diff --git a/commands/moderation/softban.js b/commands/moderation/softban.js index 5d2bbafa..48c78b6c 100644 --- a/commands/moderation/softban.js +++ b/commands/moderation/softban.js @@ -13,7 +13,6 @@ module.exports = class SoftbanCommand extends Command { guildOnly: true, clientPermissions: ['BAN_MEMBERS'], userPermissions: ['KICK_MEMBERS'], - allowStaff: true, args: [ { key: 'member', @@ -24,9 +23,12 @@ module.exports = class SoftbanCommand extends Command { key: 'reason', prompt: 'What do you want to set the reason as?', type: 'string', - validate: reason => { - if (reason.length < 140) return true; - return 'Invalid Reason. Reason must be under 140 characters.'; + validate: (reason) => { + if (reason.length < 140) { + return true; + } else { + return 'Invalid Reason. Reason must be under 140 characters.'; + } } } ] @@ -35,38 +37,58 @@ module.exports = class SoftbanCommand extends Command { async run(msg, args) { const modlogs = msg.guild.channels.get(msg.guild.settings.get('modLog')); - if (!modlogs) return msg.say('This Command requires a channel set with the `mod-channel` command.'); - if (!modlogs.permissionsFor(this.client.user).has('SEND_MESSAGES')) - return msg.say('This Command requires the `SEND_MESSAGES` Permission for the Mod Log Channel.'); - if (!modlogs.permissionsFor(this.client.user).has('EMBED_LINKS')) - return msg.say('This Command requires the `EMBED_LINKS` Permission for the Mod Log Channel.'); const { member, reason } = args; - if (!member.bannable) return msg.say('This member is not softbannable. Perhaps they have a higher role than me?'); + if (!member.bannable) { + return msg.say('This member is not softbannable. Perhaps they have a higher role than me?'); + } try { - try { - await member.user.send(stripIndents` - You were softbanned from ${msg.guild.name}! - Reason: ${reason}. - `); - } catch (err) { - await msg.say('Failed to Send DM.'); + await msg.say(`Are you sure you want to softban ${member.user.tag} (${member.id})?`); + const collected = await msg.channel.awaitMessages((res) => res.author.id === msg.author.id, { + max: 1, + time: 15000, + errors: ['time'] + }); + if (['y', 'yes'].includes(collected.first().content.toLowerCase())) { + try { + await member.user.send(stripIndents` + You were softbanned from ${msg.guild.name}! + Reason: ${reason} + `); + } catch (err) { + await msg.say('Failed to Send DM.'); + } + await member.ban({ + days: 7, + reason: `${msg.author.tag}: ${reason} (Softban)` + }); + await msg.guild.unban(member.user, 'Softban'); + await msg.say(`Successfully softbanned ${member.user.tag}.`); + if (!modlogs || !modlogs.permissionsFor(this.client.user.has('SEND_MESSAGES'))) { + return msg.say('Could not log the softban to the mod logs.'); + } else if (!modlogs.permissionsFor(this.client.user).has('EMBED_LINKS')) { + return modlogs.send(stripIndents` + **Member:** ${member.user.tag} (${member.id}) + **Action:** Softban + **Reason:** ${reason} + **Moderator:** ${msg.author.tag} + `); + } else { + const embed = new RichEmbed() + .setAuthor(msg.author.tag, msg.author.displayAvatarURL) + .setColor(0xFF4500) + .setTimestamp() + .setDescription(stripIndents` + **Member:** ${member.user.tag} (${member.id}) + **Action:** Softban + **Reason:** ${reason} + `); + return modlogs.send({ embed }); + } + } else { + return msg.say('Aborting Softban.'); } - await member.ban({ days: 7, reason }); - await msg.guild.unban(member.user); - msg.say(':ok_hand:'); - const embed = new RichEmbed() - .setAuthor(msg.author.tag, msg.author.displayAvatarURL) - .setColor(0xFF4500) - .setTimestamp() - .setDescription(stripIndents` - **Member:** ${member.user.tag} (${member.id}) - **Action:** Softban - **Reason:** ${reason} - `); - modlogs.send({ embed }); - return null; } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + return msg.say('Aborting Softban.'); } } }; diff --git a/commands/moderation/unban.js b/commands/moderation/unban.js index 59ff99d9..37086306 100644 --- a/commands/moderation/unban.js +++ b/commands/moderation/unban.js @@ -13,20 +13,22 @@ module.exports = class UnbanCommand extends Command { guildOnly: true, clientPermissions: ['BAN_MEMBERS'], userPermissions: ['BAN_MEMBERS'], - allowStaff: true, args: [ { key: 'id', - prompt: 'What member do you want to unban? Please enter the ID of the user.', + prompt: 'What is the id of the member you want to unban?', type: 'string' }, { key: 'reason', prompt: 'What do you want to set the reason as?', type: 'string', - validate: reason => { - if (reason.length < 140) return true; - return 'Invalid Reason. Reason must be under 140 characters.'; + validate: (reason) => { + if (reason.length < 140) { + return true; + } else { + return 'Invalid Reason. Reason must be under 140 characters.'; + } } } ] @@ -35,31 +37,48 @@ module.exports = class UnbanCommand extends Command { async run(msg, args) { const modlogs = msg.guild.channels.get(msg.guild.settings.get('modLog')); - if (!modlogs) return msg.say('This Command requires a channel set with the `mod-channel` command.'); - if (!modlogs.permissionsFor(this.client.user).has('SEND_MESSAGES')) - return msg.say('This Command requires the `SEND_MESSAGES` Permission for the Mod Log Channel.'); - if (!modlogs.permissionsFor(this.client.user).has('EMBED_LINKS')) - return msg.say('This Command requires the `EMBED_LINKS` Permission for the Mod Log Channel.'); const { id, reason } = args; const bans = await msg.guild.fetchBans(); - if (!bans.has(id)) return msg.say('This ID is not in the Guild Banlist.'); + if (!bans.has(id)) { + return msg.say('This ID is not in the Guild Banlist.'); + } const member = bans.get(id).user; try { - await msg.guild.unban(member, reason); - msg.say(':ok_hand:'); - const embed = new RichEmbed() - .setAuthor(msg.author.tag, msg.author.displayAvatarURL) - .setColor(0x00AE86) - .setTimestamp() - .setDescription(stripIndents` - **Member:** ${member.tag} (${member.id}) - **Action:** Unban - **Reason:** ${reason} - `); - modlogs.send({ embed }); - return null; + await msg.say(`Are you sure you want to unban ${member.tag} (${member.id})?`); + const collected = await msg.channel.awaitMessages((res) => res.author.id === msg.author.id, { + max: 1, + time: 15000, + errors: ['time'] + }); + if (['y', 'yes'].includes(collected.first().content.toLowerCase())) { + await msg.guild.unban(member, `${msg.author.tag}: ${reason}`); + await msg.say(`Successfully unbanned ${member.user.tag}.`); + if (!modlogs || !modlogs.permissionsFor(this.client.user.has('SEND_MESSAGES'))) { + return msg.say('Could not log the unban to the mod logs.'); + } else if (!modlogs.permissionsFor(this.client.user).has('EMBED_LINKS')) { + return modlogs.send(stripIndents` + **Member:** ${member.tag} (${member.id}) + **Action:** Unban + **Reason:** ${reason} + **Moderator:** ${msg.author.tag} + `); + } else { + const embed = new RichEmbed() + .setAuthor(msg.author.tag, msg.author.displayAvatarURL) + .setColor(0x00AE86) + .setTimestamp() + .setDescription(stripIndents` + **Member:** ${member.tag} (${member.id}) + **Action:** Unban + **Reason:** ${reason} + `); + return modlogs.send({ embed }); + } + } else { + return msg.say('Aborting Unban.'); + } } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + return msg.say('Aborting Unban.'); } } }; diff --git a/commands/moderation/warn.js b/commands/moderation/warn.js index 4ee43efe..35d3077b 100644 --- a/commands/moderation/warn.js +++ b/commands/moderation/warn.js @@ -6,11 +6,11 @@ module.exports = class WarnCommand extends Command { constructor(client) { super(client, { name: 'warn', + aliases: ['warnne'], group: 'moderation', memberName: 'warn', description: 'Warns a user and logs the warn to the mod logs.', guildOnly: true, - allowStaff: true, userPermissions: ['KICK_MEMBERS'], args: [ { @@ -22,9 +22,12 @@ module.exports = class WarnCommand extends Command { key: 'reason', prompt: 'What do you want to set the reason as?', type: 'string', - validate: reason => { - if (reason.length < 140) return true; - return 'Invalid Reason. Reason must be under 140 characters.'; + validate: (reason) => { + if (reason.length < 140) { + return true; + } else { + return 'Invalid Reason. Reason must be under 140 characters.'; + } } } ] @@ -33,32 +36,50 @@ module.exports = class WarnCommand extends Command { async run(msg, args) { const modlogs = msg.guild.channels.get(msg.guild.settings.get('modLog')); - if (!modlogs) return msg.say('This Command requires a channel set with the `mod-channel` command.'); - if (!modlogs.permissionsFor(this.client.user).has('SEND_MESSAGES')) - return msg.say('This Command requires the `SEND_MESSAGES` Permission for the Mod Log Channel.'); - if (!modlogs.permissionsFor(this.client.user).has('EMBED_LINKS')) - return msg.say('This Command requires the `EMBED_LINKS` Permission for the Mod Log Channel.'); const { member, reason } = args; - if (!member.kickable) return msg.say('This member is not warnable. Perhaps they have a higher role than me?'); try { - await member.user.send(stripIndents` - You were warned in ${msg.guild.name}! - Reason: ${reason}. - `); + await msg.say(`Are you sure you want to warn ${member.user.tag} (${member.id})?`); + const collected = await msg.channel.awaitMessages((res) => res.author.id === msg.author.id, { + max: 1, + time: 15000, + errors: ['time'] + }); + if (['y', 'yes'].includes(collected.first().content.toLowerCase())) { + try { + await member.user.send(stripIndents` + You were warned in ${msg.guild.name}! + Reason: ${reason} + `); + } catch (err) { + await msg.say('Failed to Send DM.'); + } + await msg.say(`Successfully warned ${member.user.tag}.`); + if (!modlogs || !modlogs.permissionsFor(this.client.user.has('SEND_MESSAGES'))) { + return msg.say('Could not log the warn to the mod logs.'); + } else if (!modlogs.permissionsFor(this.client.user).has('EMBED_LINKS')) { + return modlogs.send(stripIndents` + **Member:** ${member.user.tag} (${member.id}) + **Action:** Warn + **Reason:** ${reason} + **Moderator:** ${msg.author.tag} + `); + } else { + const embed = new RichEmbed() + .setAuthor(msg.author.tag, msg.author.displayAvatarURL) + .setColor(0xFFFF00) + .setTimestamp() + .setDescription(stripIndents` + **Member:** ${member.user.tag} (${member.id}) + **Action:** Warn + **Reason:** ${reason} + `); + return modlogs.send({ embed }); + } + } else { + return msg.say('Aborting Warn.'); + } } catch (err) { - await msg.say('Failed to Send DM.'); + return msg.say('Aborting Warn.'); } - msg.say(':ok_hand:'); - const embed = new RichEmbed() - .setAuthor(msg.author.tag, msg.author.displayAvatarURL) - .setColor(0xFFFF00) - .setTimestamp() - .setDescription(stripIndents` - **Member:** ${member.user.tag} (${member.id}) - **Action:** Warn - **Reason:** ${reason} - `); - await modlogs.send({ embed }); - return null; } }; diff --git a/commands/numedit/currency.js b/commands/numedit/currency.js index 3598e88f..8e88591c 100644 --- a/commands/numedit/currency.js +++ b/commands/numedit/currency.js @@ -15,21 +15,27 @@ module.exports = class CurrencyCommand extends Command { key: 'base', prompt: 'What currency code do you want to use as the base?', type: 'string', - validate: base => { - if (codes.includes(base.toUpperCase())) return true; - return 'Invalid Currency Code. Use `help currency` to view a list of currency codes.'; + validate: (base) => { + if (codes.includes(base.toUpperCase())) { + return true; + } else { + return 'Invalid Currency Code. Use `help currency` to view a list of currency codes.'; + } }, - parse: base => base.toUpperCase() + parse: (base) => base.toUpperCase() }, { key: 'to', prompt: 'What currency code do you want to convert to?', type: 'string', - validate: to => { - if (codes.includes(to.toUpperCase())) return true; - return 'Invalid Currency Code. Use `help currency` to view a list of currency codes.'; + validate: (to) => { + if (codes.includes(to.toUpperCase())) { + return true; + } else { + return 'Invalid Currency Code. Use `help currency` to view a list of currency codes.'; + } }, - parse: to => to.toUpperCase() + parse: (to) => to.toUpperCase() }, { key: 'amount', @@ -42,18 +48,15 @@ module.exports = class CurrencyCommand extends Command { async run(msg, args) { const { base, to, amount } = args; - if (base === to) return msg.say(`Converting ${base} to ${to} is the same value, dummy.`); - try { - const { body } = await snekfetch - .get('http://api.fixer.io/latest') - .query({ - base, - symbols: to - }); - const rate = body.rates[to]; - return msg.say(`${amount} ${base} is ${amount * rate} ${to}.`); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + if (base === to) { + return msg.say(`Converting ${base} to ${to} is the same value, dummy.`); } + const { body } = await snekfetch + .get('http://api.fixer.io/latest') + .query({ + base, + symbols: to + }); + return msg.say(`${amount} ${base} is ${amount * body.rates[to]} ${to}.`); } }; diff --git a/commands/numedit/math.js b/commands/numedit/math.js index f0f1d475..de641efb 100644 --- a/commands/numedit/math.js +++ b/commands/numedit/math.js @@ -21,10 +21,10 @@ module.exports = class MathCommand extends Command { run(msg, args) { const { expression } = args; try { - const solved = math.eval(expression); - return msg.say(solved).catch(() => msg.say('Invalid Statement.')); + const solved = math.eval(expression).toString(); + return msg.say(solved); } catch (err) { - return msg.say('Invalid Statement.'); + return msg.say('Invalid Statement'); } } }; diff --git a/commands/numedit/temperature.js b/commands/numedit/temperature.js index afd07a9c..94a29b7e 100644 --- a/commands/numedit/temperature.js +++ b/commands/numedit/temperature.js @@ -12,21 +12,27 @@ module.exports = class TemperatureCommand extends Command { key: 'base', prompt: 'What temperature unit do you want to use as the base?', type: 'string', - validate: base => { - if (['celsius', 'fahrenheit', 'kelvin'].includes(base.toLowerCase())) return true; - return 'Please enter either `celsius`, `fahrenheit`, or `kelvin`.'; + validate: (base) => { + if (['celsius', 'fahrenheit', 'kelvin'].includes(base.toLowerCase())) { + return true; + } else { + return 'Please enter either `celsius`, `fahrenheit`, or `kelvin`.'; + } }, - parse: base => base.toLowerCase() + parse: (base) => base.toLowerCase() }, { key: 'to', prompt: 'What temperature unit do you want to convert to?', type: 'string', - validate: to => { - if (['celsius', 'fahrenheit', 'kelvin'].includes(to.toLowerCase())) return true; - return 'Please enter either `celsius`, `fahrenheit`, or `kelvin`.'; + validate: (to) => { + if (['celsius', 'fahrenheit', 'kelvin'].includes(to.toLowerCase())) { + return true; + } else { + return 'Please enter either `celsius`, `fahrenheit`, or `kelvin`.'; + } }, - parse: to => to.toLowerCase() + parse: (to) => to.toLowerCase() }, { key: 'amount', @@ -39,16 +45,27 @@ module.exports = class TemperatureCommand extends Command { run(msg, args) { const { base, to, amount } = args; - if (base === to) return msg.say(`Converting ${base} to ${to} is the same value, dummy.`); + if (base === to) { + return msg.say(`Converting ${base} to ${to} is the same value, dummy.`); + } if (base === 'celsius') { - if (to === 'fahrenheit') return msg.say(`${amount}°C is ${(amount * 1.8) + 32}°F.`); - if (to === 'kelvin') return msg.say(`${amount}°C is ${amount + 273.15}°K.`); + if (to === 'fahrenheit') { + return msg.say(`${amount}°C is ${(amount * 1.8) + 32}°F.`); + } else if (to === 'kelvin') { + return msg.say(`${amount}°C is ${amount + 273.15}°K.`); + } } else if (base === 'fahrenheit') { - if (to === 'celsius') return msg.say(`${amount}°F is ${(amount - 32) / 1.8}°C.`); - if (to === 'kelvin') return msg.say(`${amount}°F is ${(amount + 459.67) * (5 / 9)}°K.`); + if (to === 'celsius') { + return msg.say(`${amount}°F is ${(amount - 32) / 1.8}°C.`); + } else if (to === 'kelvin') { + return msg.say(`${amount}°F is ${(amount + 459.67) * (5 / 9)}°K.`); + } } else if (base === 'kelvin') { - if (to === 'celsius') return msg.say(`${amount}°K is ${amount - 273.15}°C.`); - if (to === 'fahrenheit') return msg.say(`${amount}°K is ${(amount * 1.8) - 459.67}°F.`); + if (to === 'celsius') { + return msg.say(`${amount}°K is ${amount - 273.15}°C.`); + } else if (to === 'fahrenheit') { + return msg.say(`${amount}°K is ${(amount * 1.8) - 459.67}°F.`); + } } } }; diff --git a/commands/random/cleverbot.js b/commands/random/cleverbot.js index b003a137..77ee1e31 100644 --- a/commands/random/cleverbot.js +++ b/commands/random/cleverbot.js @@ -29,12 +29,7 @@ module.exports = class CleverbotCommand extends Command { async run(msg, args) { const { text } = args; - msg.channel.startTyping(); - try { - const { response } = await this.clevs.ask(text); - return msg.reply(response).then(() => msg.channel.stopTyping()); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); - } + const { response } = await this.clevs.ask(text); + return msg.reply(response); } }; diff --git a/commands/random/easter-egg.js b/commands/random/easter-egg.js index 821ef9ae..303dbe23 100644 --- a/commands/random/easter-egg.js +++ b/commands/random/easter-egg.js @@ -14,11 +14,14 @@ module.exports = class EasterEggCommand extends Command { key: 'tag', prompt: 'What easter egg do you want to view?', type: 'string', - validate: tag => { - if (eastereggs[tag.toLowerCase()]) return true; - return 'Nope, that\'s not a valid easter egg. Try again!'; + validate: (tag) => { + if (eastereggs[tag.toLowerCase()]) { + return true; + } else { + return 'Nope, that\'s not a valid easter egg. Try again!'; + } }, - parse: tag => tag.toLowerCase() + parse: (tag) => tag.toLowerCase() } ] }); diff --git a/commands/random/horoscope.js b/commands/random/horoscope.js index b6a246c6..19126eb3 100644 --- a/commands/random/horoscope.js +++ b/commands/random/horoscope.js @@ -17,11 +17,14 @@ module.exports = class HoroscopeCommand extends Command { key: 'sign', prompt: 'Which sign would you like to get the horoscope for?', type: 'string', - validate: sign => { - if (signs.includes(sign.toLowerCase())) return true; - return 'Invalid sign. Use `help horoscope` for a list of signs.'; + validate: (sign) => { + if (signs.includes(sign.toLowerCase())) { + return true; + } else { + return 'Invalid sign. Use `help horoscope` for a list of signs.'; + } }, - parse: sign => sign.toLowerCase() + parse: (sign) => sign.toLowerCase() } ] }); @@ -29,24 +32,20 @@ module.exports = class HoroscopeCommand extends Command { async run(msg, args) { const { sign } = args; - try { - const { text } = await snekfetch - .get(`http://sandipbgt.com/theastrologer/api/horoscope/${sign}/today`); - const body = JSON.parse(text); - const embed = new RichEmbed() - .setColor(0x9797FF) - .setTitle(`Horoscope for ${body.sunsign}...`) - .setTimestamp() - .setDescription(body.horoscope) - .addField('Mood', - body.meta.mood, true) - .addField('Intensity', - body.meta.intensity, true) - .addField('Date', - body.date, true); - return msg.embed(embed); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); - } + const { text } = await snekfetch + .get(`http://sandipbgt.com/theastrologer/api/horoscope/${sign}/today`); + const body = JSON.parse(text); + const embed = new RichEmbed() + .setColor(0x9797FF) + .setTitle(`Horoscope for ${body.sunsign}...`) + .setTimestamp() + .setDescription(body.horoscope) + .addField('Mood', + body.meta.mood, true) + .addField('Intensity', + body.meta.intensity, true) + .addField('Date', + body.date, true); + return msg.embed(embed); } }; diff --git a/commands/random/meme.js b/commands/random/meme.js index d349aad3..dec69ac5 100644 --- a/commands/random/meme.js +++ b/commands/random/meme.js @@ -15,23 +15,26 @@ module.exports = class MemeCommand extends Command { key: 'type', prompt: 'What meme type do you want to use?', type: 'string', - validate: type => { - if (codes.includes(type.toLowerCase())) return true; - return 'Invalid meme type. Use `help meme` to view a list of meme types.'; + validate: (type) => { + if (codes.includes(type.toLowerCase())) { + return true; + } else { + return 'Invalid meme type. Use `help meme` to view a list of meme types.'; + } }, - parse: type => type.toLowerCase() + parse: (type) => type.toLowerCase() }, { key: 'top', prompt: 'What should the top row of the meme to be?', type: 'string', - parse: top => encodeURIComponent(top.replace(/[ ]/g, '-')) + parse: (top) => encodeURIComponent(top.replace(/[ ]/g, '-')) }, { key: 'bottom', prompt: 'What should the bottom row of the meme to be?', type: 'string', - parse: bottom => encodeURIComponent(bottom.replace(/[ ]/g, '-')) + parse: (bottom) => encodeURIComponent(bottom.replace(/[ ]/g, '-')) } ] }); @@ -39,7 +42,6 @@ module.exports = class MemeCommand extends Command { run(msg, args) { const { type, top, bottom } = args; - return msg.say({ files: [`https://memegen.link/${type}/${top}/${bottom}.jpg`] }) - .catch(err => msg.say(`${err.name}: ${err.message}`)); + return msg.say({ files: [`https://memegen.link/${type}/${top}/${bottom}.jpg`] }); } }; diff --git a/commands/random/soundboard.js b/commands/random/soundboard.js index 5cdc5dd4..5df80545 100644 --- a/commands/random/soundboard.js +++ b/commands/random/soundboard.js @@ -22,11 +22,14 @@ module.exports = class SoundboardCommand extends Command { key: 'sound', prompt: 'What sound would you like to play?', type: 'string', - validate: sound => { - if (names.includes(sound.toLowerCase())) return true; - return 'Invalid Sound. Use `help soundboard` for a list of sounds.'; + validate: (sound) => { + if (names.includes(sound.toLowerCase())) { + return true; + } else { + return 'Invalid Sound. Use `help soundboard` for a list of sounds.'; + } }, - parse: sound => sound.toLowerCase() + parse: (sound) => sound.toLowerCase() } ] }); @@ -34,26 +37,25 @@ module.exports = class SoundboardCommand extends Command { async run(msg, args) { const voiceChannel = msg.member.voiceChannel; - if (!voiceChannel) return msg.say('Please enter a Voice Channel first.'); - if (!voiceChannel.permissionsFor(this.client.user).has('CONNECT')) + if (!voiceChannel) { + return msg.say('Please enter a Voice Channel first.'); + } else if (!voiceChannel.permissionsFor(this.client.user).has('CONNECT')) { return msg.say('This Command requires the `CONNECT` Permission.'); - if (!voiceChannel.permissionsFor(this.client.user).has('SPEAK')) + } else if (!voiceChannel.permissionsFor(this.client.user).has('SPEAK')) { return msg.say('This Command requires the `SPEAK` Permission.'); - if (!voiceChannel.joinable) return msg.say('This Voice Channel is not joinable.'); - const alreadyConnected = this.client.voiceConnections.get(voiceChannel.guild.id); - if (alreadyConnected) return msg.say('I am already playing a sound.'); - const { sound } = args; - try { - const connection = await voiceChannel.join(); - msg.react('🔊'); - const dispatcher = connection.playFile(path.join(__dirname, '..', '..', 'assets', 'sounds', paths[sound])); - dispatcher.on('end', () => { - voiceChannel.leave(); - msg.react('✅'); - return null; - }); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + } else if (!voiceChannel.joinable) { + return msg.say('This Voice Channel is not joinable.'); + } else if (this.client.voiceConnections.get(voiceChannel.guild.id)) { + return msg.say('I am already playing a sound.'); } + const { sound } = args; + const connection = await voiceChannel.join(); + msg.react('🔊'); + const dispatcher = connection.playFile(path.join(__dirname, '..', '..', 'assets', 'sounds', paths[sound])); + dispatcher.on('end', () => { + voiceChannel.leave(); + msg.react('✅'); + return null; + }); } }; diff --git a/commands/random/spam.js b/commands/random/spam.js index 3fa875d2..b5c3338e 100644 --- a/commands/random/spam.js +++ b/commands/random/spam.js @@ -13,7 +13,6 @@ module.exports = class SpamCommand extends Command { } run(msg) { - return msg.say({ files: [path.join(__dirname, '..', '..', 'assets', 'images', 'spam.png')] }) - .catch(err => msg.say(`${err.name}: ${err.message}`)); + return msg.say({ files: [path.join(__dirname, '..', '..', 'assets', 'images', 'spam.png')] }); } }; diff --git a/commands/random/star.js b/commands/random/star.js index 46efa8b8..83858dbd 100644 --- a/commands/random/star.js +++ b/commands/random/star.js @@ -1,5 +1,6 @@ const Command = require('../../structures/Command'); const { RichEmbed } = require('discord.js'); +const { stripIndents } = require('common-tags'); const moment = require('moment'); module.exports = class StarCommand extends Command { @@ -24,23 +25,31 @@ module.exports = class StarCommand extends Command { async run(msg, args, reaction) { const { id } = args; const channel = msg.guild.channels.get(msg.guild.settings.get('starboard')); - if (!channel || !channel.permissionsFor(this.client.user).has(['SEND_MESSAGES', 'EMBED_LINKS'])) return null; - if (this.starred.includes(id)) return null; - try { - const message = await msg.channel.fetchMessage(id); - if (!reaction && msg.author.id === message.author.id) - return msg.reply('You cannot star your own messages, baka.'); + if (!channel || this.starred.includes(id)) { + return null; + } else if (!channel.permissionsFor(this.client.user).has('SEND_MESSAGES')) { + return msg.say('I do not have Permission to send the message.'); + } + const message = await msg.channel.fetchMessage(id); + if (!reaction && msg.author.id === message.author.id) { + return msg.reply('You cannot star your own messages, baka.'); + } + this.starred.push(id); + if (!channel.permissionsFor(this.client.user).has('EMBED_LINKS')) { + return msg.say(stripIndents` + **Author:** ${message.author.tag} + **Content:** ${message.content} + **Date:** ${moment(message.createdTimestamp).format('MMMM Do YYYY h:mm:ss A')} + ${message.attachments.first() ? `**Image:** ${message.attachments.first().url}` : ''} + `); + } else { const embed = new RichEmbed() .setColor(0xFFFF00) .setAuthor(message.author.tag, message.author.displayAvatarURL) .setDescription(message.content) .setImage(message.attachments.first() ? message.attachments.first().url : null) .setFooter(moment(message.createdTimestamp).format('MMMM Do YYYY h:mm:ss A')); - this.starred.push(id); - await channel.send({ embed }); - return null; - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + return channel.send({ embed }); } } }; diff --git a/commands/random/strawpoll.js b/commands/random/strawpoll.js index 2c315f8e..f3858aba 100644 --- a/commands/random/strawpoll.js +++ b/commands/random/strawpoll.js @@ -1,4 +1,5 @@ const Command = require('../../structures/Command'); +const { FriendlyError } = require('discord.js-commando'); const { stripIndents } = require('common-tags'); const snekfetch = require('snekfetch'); @@ -14,9 +15,12 @@ module.exports = class StrawpollCommand extends Command { key: 'title', prompt: 'What would you like the title of the Strawpoll to be?', type: 'string', - validate: title => { - if (title.length < 200) return true; - return 'Invalid Title. Title must be under 200 characters.'; + validate: (title) => { + if (title.length < 200) { + return true; + } else { + return 'Invalid Title. Title must be under 200 characters.'; + } } }, { @@ -24,9 +28,12 @@ module.exports = class StrawpollCommand extends Command { prompt: 'What options do you want me pick from? Maximum of 31.', type: 'string', infinite: true, - validate: choice => { - if (choice.length < 160) return true; - return 'Invalid Choice. Choices must be under 140 characters each.'; + validate: (choice) => { + if (choice.length < 160) { + return true; + } else { + return 'Invalid Choice. Choices must be under 140 characters each.'; + } } } ] @@ -35,18 +42,17 @@ module.exports = class StrawpollCommand extends Command { async run(msg, args) { const { title, options } = args; - if (options.length < 2) return msg.say('You provided less than two choices.'); - if (options.length > 31) return msg.say('You provided more than thirty choices.'); - try { - const { body } = await snekfetch - .post('https://strawpoll.me/api/v2/polls') - .send({ title, options }); - return msg.say(stripIndents` - ${body.title} - http://strawpoll.me/${body.id} - `); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + if (options.length < 2) { + throw new FriendlyError('You provided less than two choices.'); + } else if (options.length > 31) { + throw new FriendlyError('You provided more than thirty choices.'); } + const { body } = await snekfetch + .post('https://strawpoll.me/api/v2/polls') + .send({ title, options }); + return msg.say(stripIndents` + ${body.title} + http://strawpoll.me/${body.id} + `); } }; diff --git a/commands/random/today.js b/commands/random/today.js index facdf309..59e2f180 100644 --- a/commands/random/today.js +++ b/commands/random/today.js @@ -14,21 +14,17 @@ module.exports = class TodayCommand extends Command { } async run(msg) { - try { - const { text } = await snekfetch - .get('http://history.muffinlabs.com/date'); - const body = JSON.parse(text); - const events = body.data.Events; - const event = events[Math.floor(Math.random() * events.length)]; - const embed = new RichEmbed() - .setColor(0x9797FF) - .setURL(body.url) - .setTitle(`On this day (${body.date})...`) - .setTimestamp() - .setDescription(`${event.year}: ${event.text}`); - return msg.embed(embed); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); - } + const { text } = await snekfetch + .get('http://history.muffinlabs.com/date'); + const body = JSON.parse(text); + const events = body.data.Events; + const event = events[Math.floor(Math.random() * events.length)]; + const embed = new RichEmbed() + .setColor(0x9797FF) + .setURL(body.url) + .setTitle(`On this day (${body.date})...`) + .setTimestamp() + .setDescription(`${event.year}: ${event.text}`); + return msg.embed(embed); } }; diff --git a/commands/random/would-you-rather.js b/commands/random/would-you-rather.js index 7dfd3faa..6debd65a 100644 --- a/commands/random/would-you-rather.js +++ b/commands/random/would-you-rather.js @@ -15,17 +15,13 @@ module.exports = class WouldYouRatherCommand extends Command { } async run(msg) { - try { - const { body } = await snekfetch - .get('http://www.rrrather.com/botapi'); - const embed = new RichEmbed() - .setTitle(`${body.title}...`) - .setURL(body.link) - .setColor(0x9797FF) - .setDescription(`${body.choicea} OR ${body.choiceb}?`); - return msg.embed(embed); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); - } + const { body } = await snekfetch + .get('http://www.rrrather.com/botapi'); + const embed = new RichEmbed() + .setTitle(`${body.title}...`) + .setURL(body.link) + .setColor(0x9797FF) + .setDescription(`${body.choicea} OR ${body.choiceb}?`); + return msg.embed(embed); } }; diff --git a/commands/randomimg/cat.js b/commands/randomimg/cat.js index c4c3e9a7..ea9913f4 100644 --- a/commands/randomimg/cat.js +++ b/commands/randomimg/cat.js @@ -13,12 +13,8 @@ module.exports = class CatCommand extends Command { } async run(msg) { - try { - const { body } = await snekfetch - .get('http://random.cat/meow'); - return msg.say(body.file); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); - } + const { body } = await snekfetch + .get('http://random.cat/meow'); + return msg.say(body.file); } }; diff --git a/commands/randomimg/dog.js b/commands/randomimg/dog.js index 59eefa96..90778fcf 100644 --- a/commands/randomimg/dog.js +++ b/commands/randomimg/dog.js @@ -12,12 +12,8 @@ module.exports = class DogCommand extends Command { } async run(msg) { - try { - const { body } = await snekfetch - .get('https://random.dog/woof.json'); - return msg.say(body.url); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); - } + const { body } = await snekfetch + .get('https://random.dog/woof.json'); + return msg.say(body.url); } }; diff --git a/commands/randomimg/xiao.js b/commands/randomimg/xiao.js index ecb5784c..a21124e6 100644 --- a/commands/randomimg/xiao.js +++ b/commands/randomimg/xiao.js @@ -15,7 +15,6 @@ module.exports = class XiaoCommand extends Command { run(msg) { const xiao = Math.floor(Math.random() * 10) + 1; - return msg.say({ files: [path.join(__dirname, '..', '..', 'assets', 'images', `xiao${xiao}.png`)] }) - .catch(err => msg.say(`${err.name}: ${err.message}`)); + return msg.say({ files: [path.join(__dirname, '..', '..', 'assets', 'images', `xiao${xiao}.png`)] }); } }; diff --git a/commands/randomimg/xkcd.js b/commands/randomimg/xkcd.js index 56ed6710..6567c444 100644 --- a/commands/randomimg/xkcd.js +++ b/commands/randomimg/xkcd.js @@ -16,11 +16,14 @@ module.exports = class XKCDCommand extends Command { key: 'type', prompt: 'Would you like to get the comic for today or random?', type: 'string', - validate: type => { - if (['today', 'random'].includes(type.toLowerCase())) return true; - return 'Please enter either `today` or `random`'; - }, - default: 'random' + default: 'random', + validate: (type) => { + if (['today', 'random'].includes(type.toLowerCase())) { + return true; + } else { + return 'Please enter either `today` or `random`'; + } + } } ] }); @@ -28,29 +31,25 @@ module.exports = class XKCDCommand extends Command { async run(msg, args) { const { type } = args; - try { - const current = await snekfetch - .get('https://xkcd.com/info.0.json'); - if (type === 'today') { - const embed = new RichEmbed() - .setTitle(`${current.body.num} - ${current.body.title}`) - .setURL(`https://xkcd.com/${current.body.num}`) - .setImage(current.body.img) - .setFooter(current.body.alt); - return msg.embed(embed); - } else { - const random = Math.floor(Math.random() * current.body.num) + 1; - const { body } = await snekfetch - .get(`https://xkcd.com/${random}/info.0.json`); - const embed = new RichEmbed() - .setTitle(`${body.num} - ${body.title}`) - .setURL(`https://xkcd.com/${body.num}`) - .setImage(body.img) - .setFooter(body.alt); - return msg.embed(embed); - } - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + const current = await snekfetch + .get('https://xkcd.com/info.0.json'); + if (type === 'today') { + const embed = new RichEmbed() + .setTitle(`${current.body.num} - ${current.body.title}`) + .setURL(`https://xkcd.com/${current.body.num}`) + .setImage(current.body.img) + .setFooter(current.body.alt); + return msg.embed(embed); + } else { + const random = Math.floor(Math.random() * current.body.num) + 1; + const { body } = await snekfetch + .get(`https://xkcd.com/${random}/info.0.json`); + const embed = new RichEmbed() + .setTitle(`${body.num} - ${body.title}`) + .setURL(`https://xkcd.com/${body.num}`) + .setImage(body.img) + .setFooter(body.alt); + return msg.embed(embed); } } }; diff --git a/commands/response/compliment.js b/commands/response/compliment.js index 9fc852fd..af3ae9c8 100644 --- a/commands/response/compliment.js +++ b/commands/response/compliment.js @@ -7,20 +7,21 @@ module.exports = class ComplimentCommand extends Command { name: 'compliment', group: 'response', memberName: 'compliment', - description: 'Compliments something/someone.', + description: 'Compliments a user.', args: [ { - key: 'thing', - prompt: 'What do you want to compliment?', - type: 'string' + key: 'user', + prompt: 'What user do you want to compliment?', + type: 'user', + default: '' } ] }); } run(msg, args) { - const { thing } = args; + const user = args.user || msg.author; const compliment = compliments[Math.floor(Math.random() * compliments.length)]; - return msg.say(`${thing}, ${compliment}`); + return msg.say(`${user}, ${compliment}`); } }; diff --git a/commands/response/name.js b/commands/response/name.js index 0834a126..fc4d6bbe 100644 --- a/commands/response/name.js +++ b/commands/response/name.js @@ -13,11 +13,14 @@ module.exports = class RandomNameCommand extends Command { key: 'gender', prompt: 'Which gender do you want to generate a name for?', type: 'string', - validate: gender => { - if (['male', 'female'].includes(gender.toLowerCase())) return true; - return 'Please enter either `male` or `female`.'; + validate: (gender) => { + if (['male', 'female'].includes(gender.toLowerCase())) { + return true; + } else { + return 'Please enter either `male` or `female`.'; + } }, - parse: gender => gender.toLowerCase() + parse: (gender) => gender.toLowerCase() } ] }); diff --git a/commands/response/roast.js b/commands/response/roast.js index d76d9c5c..e727aa86 100644 --- a/commands/response/roast.js +++ b/commands/response/roast.js @@ -7,11 +7,11 @@ module.exports = class RoastCommand extends Command { name: 'roast', group: 'response', memberName: 'roast', - description: 'Roasts something/someone.', + description: 'Roasts a user.', args: [ { - key: 'thing', - prompt: 'What do you want to roast?', + key: 'user', + prompt: 'What user do you want to roast?', type: 'string' } ] @@ -19,8 +19,8 @@ module.exports = class RoastCommand extends Command { } run(msg, args) { - const { thing } = args; + const user = args.user || msg.author; const roast = roasts[Math.floor(Math.random() * roasts.length)]; - return msg.say(`${thing}, ${roast}`); + return msg.say(`${user}, ${roast}`); } }; diff --git a/commands/response/roll.js b/commands/response/roll.js index 24b9e042..b7c3ac92 100644 --- a/commands/response/roll.js +++ b/commands/response/roll.js @@ -13,7 +13,8 @@ module.exports = class RollCommand extends Command { key: 'value', label: 'maximum number', prompt: 'What is the maximum number you wish to appear?', - type: 'integer' + type: 'integer', + default: 6 } ] }); diff --git a/commands/response/ship.js b/commands/response/ship.js index 2a621c73..1cc8f287 100644 --- a/commands/response/ship.js +++ b/commands/response/ship.js @@ -21,12 +21,6 @@ module.exports = class ShipCommand extends Command { run(msg, args) { const { things } = args; const rating = Math.floor(Math.random() * 100) + 1; - let response; - if (rating < 25) response = 'Ouch. Might want to keep them apart.'; - else if (rating < 50) response = 'Meh, they should keep looking.'; - else if (rating < 75) response = 'Could be worse, they should try it.'; - else if (rating < 90) response = 'Not too bad. It might work out.'; - else response = 'These guys have one bright future ahead of them!'; - return msg.say(`I'd give ${things} a ${rating}%! ${response}`); + return msg.say(`I'd give ${things} a ${rating}%!`); } }; diff --git a/commands/roleplay/cuddle.js b/commands/roleplay/cuddle.js index e2ad0f58..437d360e 100644 --- a/commands/roleplay/cuddle.js +++ b/commands/roleplay/cuddle.js @@ -1,4 +1,5 @@ const Command = require('../../structures/Command'); +const { stripIndents } = require('common-tags'); module.exports = class CuddleCommand extends Command { constructor(client) { @@ -6,19 +7,22 @@ module.exports = class CuddleCommand extends Command { name: 'cuddle', group: 'roleplay', memberName: 'cuddle', - description: 'Cuddles something/someone.', + description: 'Cuddles a user.', args: [ { - key: 'thing', - prompt: 'What do you want to roleplay with?', - type: 'string' + key: 'user', + prompt: 'What user do you want to roleplay with?', + type: 'user' } ] }); } run(msg, args) { - const { thing } = args; - return msg.say(`${msg.author} *cuddles* ${thing}`); + const { user } = args; + return msg.say(stripIndents` + **${msg.author.username}** *cuddles* **${user.username}** + https://i.imgur.com/0yAIWbg.gif + `); } }; diff --git a/commands/roleplay/divorce.js b/commands/roleplay/divorce.js index 65d64dfe..04b7733b 100644 --- a/commands/roleplay/divorce.js +++ b/commands/roleplay/divorce.js @@ -1,4 +1,5 @@ const Command = require('../../structures/Command'); +const { stripIndents } = require('common-tags'); module.exports = class DivorceCommand extends Command { constructor(client) { @@ -6,19 +7,22 @@ module.exports = class DivorceCommand extends Command { name: 'divorce', group: 'roleplay', memberName: 'divorce', - description: 'Divorces something/someone.', + description: 'Divorces a user.', args: [ { - key: 'thing', - prompt: 'What do you want to roleplay with?', - type: 'string' + key: 'user', + prompt: 'What user do you want to roleplay with?', + type: 'user' } ] }); } run(msg, args) { - const { thing } = args; - return msg.say(`${msg.author} *divorces* ${thing}`); + const { user } = args; + return msg.say(stripIndents` + **${msg.author.username}** *divorces* **${user.username}** + https://i.imgur.com/IgvLWaa.gif + `); } }; diff --git a/commands/roleplay/eat.js b/commands/roleplay/eat.js index e0f6a1ab..2ce1256a 100644 --- a/commands/roleplay/eat.js +++ b/commands/roleplay/eat.js @@ -1,4 +1,5 @@ const Command = require('../../structures/Command'); +const { stripIndents } = require('common-tags'); module.exports = class EatCommand extends Command { constructor(client) { @@ -6,19 +7,22 @@ module.exports = class EatCommand extends Command { name: 'eat', group: 'roleplay', memberName: 'eat', - description: 'Eats something/someone.', + description: 'Eats a user.', args: [ { - key: 'thing', - prompt: 'What do you want to roleplay with?', - type: 'string' + key: 'user', + prompt: 'What user do you want to roleplay with?', + type: 'user' } ] }); } run(msg, args) { - const { thing } = args; - return msg.say(`${msg.author} *eats* ${thing}`); + const { user } = args; + return msg.say(stripIndents` + **${msg.author.username}** *eats* **${user.username}** + https://i.imgur.com/O7FQ5kz.gif + `); } }; diff --git a/commands/roleplay/falcon-punch.js b/commands/roleplay/falcon-punch.js index 497644be..70c05e0e 100644 --- a/commands/roleplay/falcon-punch.js +++ b/commands/roleplay/falcon-punch.js @@ -1,4 +1,5 @@ const Command = require('../../structures/Command'); +const { stripIndents } = require('common-tags'); module.exports = class FalconPunchCommand extends Command { constructor(client) { @@ -6,19 +7,22 @@ module.exports = class FalconPunchCommand extends Command { name: 'falcon-punch', group: 'roleplay', memberName: 'falcon-punch', - description: 'Falcon Punches something/someone.', + description: 'Falcon Punches a user.', args: [ { - key: 'thing', - prompt: 'What do you want to roleplay with?', - type: 'string' + key: 'user', + prompt: 'What user do you want to roleplay with?', + type: 'user' } ] }); } run(msg, args) { - const { thing } = args; - return msg.say(`${msg.author} *falcon punches* ${thing}`); + const { user } = args; + return msg.say(stripIndents` + **${msg.author.username}** *falcon punches* **${user.username}** + https://i.imgur.com/LOuK637.gif + `); } }; diff --git a/commands/roleplay/fist-bump.js b/commands/roleplay/fist-bump.js index c9f312b4..c5847795 100644 --- a/commands/roleplay/fist-bump.js +++ b/commands/roleplay/fist-bump.js @@ -1,4 +1,5 @@ const Command = require('../../structures/Command'); +const { stripIndents } = require('common-tags'); module.exports = class FistBumpCommand extends Command { constructor(client) { @@ -6,19 +7,22 @@ module.exports = class FistBumpCommand extends Command { name: 'fist-bump', group: 'roleplay', memberName: 'fist-bump', - description: 'Fistbumps something/someone.', + description: 'Fistbumps a user.', args: [ { - key: 'thing', - prompt: 'What do you want to roleplay with?', - type: 'string' + key: 'user', + prompt: 'What user do you want to roleplay with?', + type: 'user' } ] }); } run(msg, args) { - const { thing } = args; - return msg.say(`${msg.author} *fist-bumps* ${thing} *badalalala*`); + const { user } = args; + return msg.say(stripIndents` + **${msg.author.username}** *fist-bumps* **${user.username}** + *badalalala* https://i.imgur.com/lO2xZHC.gif + `); } }; diff --git a/commands/roleplay/high-five.js b/commands/roleplay/high-five.js index 5cf37f38..2c6676da 100644 --- a/commands/roleplay/high-five.js +++ b/commands/roleplay/high-five.js @@ -1,4 +1,5 @@ const Command = require('../../structures/Command'); +const { stripIndents } = require('common-tags'); module.exports = class HighFivesCommand extends Command { constructor(client) { @@ -9,16 +10,19 @@ module.exports = class HighFivesCommand extends Command { description: 'High Fives something/someone.', args: [ { - key: 'thing', - prompt: 'What do you want to roleplay with?', - type: 'string' + key: 'user', + prompt: 'What user do you want to roleplay with?', + type: 'user' } ] }); } run(msg, args) { - const { thing } = args; - return msg.say(`${msg.author} *high-fives* ${thing}`); + const { user } = args; + return msg.say(stripIndents` + **${msg.author.username}** *high-fives* **${user.username}** + https://i.imgur.com/7BJ6gfM.gif + `); } }; diff --git a/commands/roleplay/hit-with-shovel.js b/commands/roleplay/hit-with-shovel.js index aa2fa243..3659495c 100644 --- a/commands/roleplay/hit-with-shovel.js +++ b/commands/roleplay/hit-with-shovel.js @@ -1,4 +1,5 @@ const Command = require('../../structures/Command'); +const { stripIndents } = require('common-tags'); module.exports = class HitwithShovelCommand extends Command { constructor(client) { @@ -6,19 +7,22 @@ module.exports = class HitwithShovelCommand extends Command { name: 'hit-with-shovel', group: 'roleplay', memberName: 'hit-with-shovel', - description: 'Hits something/someone with a shovel.', + description: 'Hits a user with a shovel.', args: [ { - key: 'thing', - prompt: 'What do you want to roleplay with?', - type: 'string' + key: 'user', + prompt: 'What user do you want to roleplay with?', + type: 'user' } ] }); } run(msg, args) { - const { thing } = args; - return msg.say(`${msg.author} *hits* ${thing} *with a shovel*`); + const { user } = args; + return msg.say(stripIndents` + **${msg.author.username}** *hits* **${user.username}** *with a shovel* + https://i.imgur.com/4yvqw81.gif + `); } }; diff --git a/commands/roleplay/hug.js b/commands/roleplay/hug.js index ecc903f8..8a7f2c62 100644 --- a/commands/roleplay/hug.js +++ b/commands/roleplay/hug.js @@ -1,4 +1,5 @@ const Command = require('../../structures/Command'); +const { stripIndents } = require('common-tags'); module.exports = class HugCommand extends Command { constructor(client) { @@ -6,19 +7,22 @@ module.exports = class HugCommand extends Command { name: 'hug', group: 'roleplay', memberName: 'hug', - description: 'Hugs something/someone.', + description: 'Hugs a user.', args: [ { - key: 'thing', - prompt: 'What do you want to roleplay with?', - type: 'string' + key: 'user', + prompt: 'What user do you want to roleplay with?', + type: 'user' } ] }); } run(msg, args) { - const { thing } = args; - return msg.say(`${msg.author} *hugs* ${thing}`); + const { user } = args; + return msg.say(stripIndents` + **${msg.author.username}** *hugs* **${user.username}** + https://i.imgur.com/q9Wkhz4.gif + `); } }; diff --git a/commands/roleplay/inhale.js b/commands/roleplay/inhale.js index ee479292..f7b85901 100644 --- a/commands/roleplay/inhale.js +++ b/commands/roleplay/inhale.js @@ -1,4 +1,5 @@ const Command = require('../../structures/Command'); +const { stripIndents } = require('common-tags'); module.exports = class InhaleCommand extends Command { constructor(client) { @@ -6,19 +7,22 @@ module.exports = class InhaleCommand extends Command { name: 'inhale', group: 'roleplay', memberName: 'inhale', - description: 'Inhales something/someone.', + description: 'Inhales a user.', args: [ { - key: 'thing', - prompt: 'What do you want to roleplay with?', - type: 'string' + key: 'user', + prompt: 'What user do you want to roleplay with?', + type: 'user' } ] }); } run(msg, args) { - const { thing } = args; - return msg.say(`${msg.author} *inhales* ${thing} *but gained no ability...*`); + const { user } = args; + return msg.say(stripIndents` + **${msg.author.username}** *inhales* **${user.username}** *but gained no ability...* + https://i.imgur.com/b4NeOXj.gif + `); } }; diff --git a/commands/roleplay/kill.js b/commands/roleplay/kill.js index 4bb8ad24..0a7565e1 100644 --- a/commands/roleplay/kill.js +++ b/commands/roleplay/kill.js @@ -1,4 +1,5 @@ const Command = require('../../structures/Command'); +const { stripIndents } = require('common-tags'); module.exports = class KillCommand extends Command { constructor(client) { @@ -6,19 +7,22 @@ module.exports = class KillCommand extends Command { name: 'kill', group: 'roleplay', memberName: 'kill', - description: 'Kills something/someone.', + description: 'Kills a user.', args: [ { - key: 'thing', - prompt: 'What do you want to roleplay with?', - type: 'string' + key: 'user', + prompt: 'What user do you want to roleplay with?', + type: 'user' } ] }); } run(msg, args) { - const { thing } = args; - return msg.say(`${msg.author} *kills* ${thing}`); + const { user } = args; + return msg.say(stripIndents` + **${msg.author.username}** *kills* **${user.username}** + https://i.imgur.com/WxD4XMe.gif + `); } }; diff --git a/commands/roleplay/kiss.js b/commands/roleplay/kiss.js index 58c45324..90ffc347 100644 --- a/commands/roleplay/kiss.js +++ b/commands/roleplay/kiss.js @@ -1,4 +1,5 @@ const Command = require('../../structures/Command'); +const { stripIndents } = require('common-tags'); module.exports = class KissCommand extends Command { constructor(client) { @@ -6,19 +7,22 @@ module.exports = class KissCommand extends Command { name: 'kiss', group: 'roleplay', memberName: 'kiss', - description: 'Kisses something/someone.', + description: 'Kisses a user.', args: [ { - key: 'thing', - prompt: 'What do you want to roleplay with?', - type: 'string' + key: 'user', + prompt: 'What user do you want to roleplay with?', + type: 'user' } ] }); } run(msg, args) { - const { thing } = args; - return msg.say(`${msg.author} *kisses* ${thing}`); + const { user } = args; + return msg.say(stripIndents` + **${msg.author.username}** *kisses* **${user.username}** + https://i.imgur.com/S7mwPfE.gif + `); } }; diff --git a/commands/roleplay/marry.js b/commands/roleplay/marry.js index 6c47df60..e964b955 100644 --- a/commands/roleplay/marry.js +++ b/commands/roleplay/marry.js @@ -1,4 +1,5 @@ const Command = require('../../structures/Command'); +const { stripIndents } = require('common-tags'); module.exports = class MarryCommand extends Command { constructor(client) { @@ -6,19 +7,22 @@ module.exports = class MarryCommand extends Command { name: 'marry', group: 'roleplay', memberName: 'marry', - description: 'Marries something/someone.', + description: 'Marries a user.', args: [ { - key: 'thing', - prompt: 'What do you want to roleplay with?', - type: 'string' + key: 'user', + prompt: 'What user do you want to roleplay with?', + type: 'user' } ] }); } run(msg, args) { - const { thing } = args; - return msg.say(`${msg.author} *marries* ${thing}`); + const { user } = args; + return msg.say(stripIndents` + **${msg.author.username}** *marries* **${user.username}** + https://i.imgur.com/u67QLhB.gif + `); } }; diff --git a/commands/roleplay/pat.js b/commands/roleplay/pat.js index c9417755..d5a6c57b 100644 --- a/commands/roleplay/pat.js +++ b/commands/roleplay/pat.js @@ -1,4 +1,5 @@ const Command = require('../../structures/Command'); +const { stripIndents } = require('common-tags'); module.exports = class PatCommand extends Command { constructor(client) { @@ -6,19 +7,22 @@ module.exports = class PatCommand extends Command { name: 'pat', group: 'roleplay', memberName: 'pat', - description: 'Pats something/someone.', + description: 'Pats a user.', args: [ { - key: 'thing', - prompt: 'What do you want to roleplay with?', - type: 'string' + key: 'user', + prompt: 'What user do you want to roleplay with?', + type: 'user' } ] }); } run(msg, args) { - const { thing } = args; - return msg.say(`${msg.author} *pats* ${thing}`); + const { user } = args; + return msg.say(stripIndents` + **${msg.author.username}** *pats* **${user.username}** + https://i.imgur.com/oynHZmT.gif + `); } }; diff --git a/commands/roleplay/poke.js b/commands/roleplay/poke.js index 0927b103..62c1fd29 100644 --- a/commands/roleplay/poke.js +++ b/commands/roleplay/poke.js @@ -1,4 +1,5 @@ const Command = require('../../structures/Command'); +const { stripIndents } = require('common-tags'); module.exports = class PokeCommand extends Command { constructor(client) { @@ -6,19 +7,22 @@ module.exports = class PokeCommand extends Command { name: 'poke', group: 'roleplay', memberName: 'poke', - description: 'Pokes something/someone.', + description: 'Pokes a user.', args: [ { - key: 'thing', - prompt: 'What do you want to roleplay with?', - type: 'string' + key: 'user', + prompt: 'What user do you want to roleplay with?', + type: 'user' } ] }); } run(msg, args) { - const { thing } = args; - return msg.say(`${msg.author} *pokes* ${thing}`); + const { user } = args; + return msg.say(stripIndents` + **${msg.author.username}** *pokes* **${user.username}** + https://i.imgur.com/XMuJ7K8.gif + `); } }; diff --git a/commands/roleplay/punch.js b/commands/roleplay/punch.js index 61a601d5..5db35d66 100644 --- a/commands/roleplay/punch.js +++ b/commands/roleplay/punch.js @@ -1,4 +1,5 @@ const Command = require('../../structures/Command'); +const { stripIndents } = require('common-tags'); module.exports = class PunchCommand extends Command { constructor(client) { @@ -6,19 +7,22 @@ module.exports = class PunchCommand extends Command { name: 'punch', group: 'roleplay', memberName: 'punch', - description: 'Punches something/someone.', + description: 'Punches a user.', args: [ { - key: 'thing', - prompt: 'What do you want to roleplay with?', - type: 'string' + key: 'user', + prompt: 'What user do you want to roleplay with?', + type: 'user' } ] }); } run(msg, args) { - const { thing } = args; - return msg.say(`${msg.author} *punches* ${thing}`); + const { user } = args; + return msg.say(stripIndents` + **${msg.author.username}** *punches* **${user.username}** + https://i.imgur.com/R5KBiYV.gif + `); } }; diff --git a/commands/roleplay/slap.js b/commands/roleplay/slap.js index f395bb85..e231e37f 100644 --- a/commands/roleplay/slap.js +++ b/commands/roleplay/slap.js @@ -1,4 +1,5 @@ const Command = require('../../structures/Command'); +const { stripIndents } = require('common-tags'); module.exports = class SlapCommand extends Command { constructor(client) { @@ -6,19 +7,22 @@ module.exports = class SlapCommand extends Command { name: 'slap', group: 'roleplay', memberName: 'slap', - description: 'Slaps something/someone.', + description: 'Slaps a user.', args: [ { - key: 'thing', - prompt: 'What do you want to roleplay with?', - type: 'string' + key: 'user', + prompt: 'What user do you want to roleplay with?', + type: 'user' } ] }); } run(msg, args) { - const { thing } = args; - return msg.say(`${msg.author} *slaps* ${thing}`); + const { user } = args; + return msg.say(stripIndents` + **${msg.author.username}** *slaps* **${user.username}** + https://i.imgur.com/rfy8z2K.gif + `); } }; diff --git a/commands/search/anime.js b/commands/search/anime.js index a3f8e32c..b41059ac 100644 --- a/commands/search/anime.js +++ b/commands/search/anime.js @@ -1,6 +1,7 @@ const Command = require('../../structures/Command'); const { RichEmbed } = require('discord.js'); const snekfetch = require('snekfetch'); +const { cleanXML } = require('../../util/Util'); const { promisifyAll } = require('tsubaki'); const xml = promisifyAll(require('xml2js')); const { ANIMELIST_LOGIN } = process.env; @@ -32,14 +33,7 @@ module.exports = class AnimeCommand extends Command { q: query }); const { anime } = await xml.parseStringAsync(text); - const synopsis = anime.entry[0].synopsis[0].substr(0, 2000) - .replace(/(
)/g, '') - .replace(/(')/g, '\'') - .replace(/(—)/g, '—') - .replace(/(")/g, '"') - .replace(/(&)/g, '&') - .replace(/(")/g, '"') - .replace(/(\[i\]|\[\/i\])/g, '*'); + const synopsis = cleanXML(anime.entry[0].synopsis[0].substr(0, 2000)); const embed = new RichEmbed() .setColor(0x2D54A2) .setAuthor('My Anime List', 'https://i.imgur.com/R4bmNFz.png') @@ -47,17 +41,17 @@ module.exports = class AnimeCommand extends Command { .setThumbnail(anime.entry[0].image[0]) .setTitle(`${anime.entry[0].title[0]} (English: ${anime.entry[0].english[0] || 'N/A'})`) .setDescription(synopsis) - .addField('Type', + .addField('❯ Type', `${anime.entry[0].type[0]} - ${anime.entry[0].status[0]}`, true) - .addField('Episodes', + .addField('❯ Episodes', anime.entry[0].episodes[0], true) - .addField('Start Date', + .addField('❯ Start Date', anime.entry[0].start_date[0], true) - .addField('End Date', + .addField('❯ End Date', anime.entry[0].end_date[0], true); return msg.embed(embed); } catch (err) { - return msg.say('Error: No Results.'); + return msg.say('No Results.'); } } }; diff --git a/commands/search/bot-info.js b/commands/search/bot-info.js index 7a3a08b5..95b9ce55 100644 --- a/commands/search/bot-info.js +++ b/commands/search/bot-info.js @@ -26,22 +26,24 @@ module.exports = class BotSearchCommand extends Command { try { const { body } = await snekfetch .get(`https://bots.discord.pw/api/bots/${bot.id}`) - .set({ Authorization: DBOTS_KEY }); + .set({ + Authorization: DBOTS_KEY + }); const embed = new RichEmbed() .setColor(0x9797FF) .setAuthor('Discord Bots', 'https://i.imgur.com/lrKYBQi.jpg') .setTitle(body.name) .setURL(`https://bots.discord.pw/bots/${bot.id}`) .setDescription(body.description) - .addField('Library', + .addField('❯ Library', body.library, true) - .addField('Invite', + .addField('❯ Invite', `[Here](${body.invite_url})`, true) - .addField('Prefix', + .addField('❯ Prefix', body.prefix, true); return msg.embed(embed); } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + return msg.say(err.message); } } }; diff --git a/commands/search/bulbapedia.js b/commands/search/bulbapedia.js index 48616fba..14f78a3c 100644 --- a/commands/search/bulbapedia.js +++ b/commands/search/bulbapedia.js @@ -23,28 +23,26 @@ module.exports = class BulbapediaCommand extends Command { async run(msg, args) { const { query } = args; - try { - const { body } = await snekfetch - .get('http://bulbapedia.bulbagarden.net/w/api.php') - .query({ - action: 'query', - prop: 'extracts', - format: 'json', - titles: query, - exintro: '', - explaintext: '', - redirects: '', - formatversion: 2 - }); - if (body.query.pages[0].missing) throw new Error('No Results.'); - const embed = new RichEmbed() - .setColor(0x3E7614) - .setTitle(body.query.pages[0].title) - .setAuthor('Bulbapedia', 'https://i.imgur.com/09eYo5T.png') - .setDescription(body.query.pages[0].extract.substr(0, 2000).replace(/[\n]/g, '\n\n')); - return msg.embed(embed); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + const { body } = await snekfetch + .get('http://bulbapedia.bulbagarden.net/w/api.php') + .query({ + action: 'query', + prop: 'extracts', + format: 'json', + titles: query, + exintro: '', + explaintext: '', + redirects: '', + formatversion: 2 + }); + if (body.query.pages[0].missing) { + return msg.say('No Results.'); } + const embed = new RichEmbed() + .setColor(0x3E7614) + .setTitle(body.query.pages[0].title) + .setAuthor('Bulbapedia', 'https://i.imgur.com/09eYo5T.png') + .setDescription(body.query.pages[0].extract.substr(0, 2000).replace(/[\n]/g, '\n\n')); + return msg.embed(embed); } }; diff --git a/commands/search/danbooru.js b/commands/search/danbooru.js index af5c0cf2..3042c28f 100644 --- a/commands/search/danbooru.js +++ b/commands/search/danbooru.js @@ -22,18 +22,15 @@ module.exports = class DanbooruCommand extends Command { async run(msg, args) { const { query } = args; - try { - const { body } = await snekfetch - .get('https://danbooru.donmai.us/posts.json') - .query({ - tags: `${query ? `${query} ` : ''}order:random`, - limit: 1 - }); - if (!body.length) throw new Error('No Results.'); - if (!body[0].file_url) throw new Error('No Results.'); - return msg.say(`${query ? `Result for ${query}:` : 'Random Image:'} https://danbooru.donmai.us${body[0].file_url}`); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + const { body } = await snekfetch + .get('https://danbooru.donmai.us/posts.json') + .query({ + tags: `${query ? `${query} ` : ''}order:random`, + limit: 1 + }); + if (!body.length || !body[0].file_url) { + return msg.say('No Results'); } + return msg.say(`${query ? `Result for ${query}:` : 'Random Image:'} https://danbooru.donmai.us${body[0].file_url}`); } }; diff --git a/commands/search/define.js b/commands/search/define.js index 3f10d314..ac5bb910 100644 --- a/commands/search/define.js +++ b/commands/search/define.js @@ -16,7 +16,7 @@ module.exports = class DefineCommand extends Command { key: 'query', prompt: 'What would you like to define?', type: 'string', - parse: query => encodeURIComponent(query) + parse: (query) => encodeURIComponent(query) } ] }); @@ -24,23 +24,21 @@ module.exports = class DefineCommand extends Command { async run(msg, args) { const { query } = args; - try { - const { body } = await snekfetch - .get(`http://api.wordnik.com:80/v4/word.json/${query}/definitions`) - .query({ - limit: 1, - includeRelated: false, - useCanonical: false, - api_key: WORDNIK_KEY - }); - if (!body.length) throw new Error('No Results.'); - const embed = new RichEmbed() - .setColor(0x9797FF) - .setTitle(body[0].word) - .setDescription(body[0].text); - return msg.embed(embed); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + const { body } = await snekfetch + .get(`http://api.wordnik.com:80/v4/word.json/${query}/definitions`) + .query({ + limit: 1, + includeRelated: false, + useCanonical: false, + api_key: WORDNIK_KEY + }); + if (!body.length) { + return msg.say('No Results.'); } + const embed = new RichEmbed() + .setColor(0x9797FF) + .setTitle(body[0].word) + .setDescription(body[0].text); + return msg.embed(embed); } }; diff --git a/commands/search/discrim.js b/commands/search/discrim.js index ef57cb46..946c490e 100644 --- a/commands/search/discrim.js +++ b/commands/search/discrim.js @@ -15,9 +15,13 @@ module.exports = class DiscrimCommand extends Command { key: 'discrim', prompt: 'Which discriminator would you like to search for?', type: 'string', - validate: discrim => { - if (/[0-9]+$/g.test(discrim) && discrim.length === 4) return true; - return `${discrim} is not a valid discriminator.`; + default: '', + validate: (discrim) => { + if (/[0-9]+$/g.test(discrim) && discrim.length === 4) { + return true; + } else { + return 'Invalid Discriminator.'; + } } } ] @@ -25,8 +29,8 @@ module.exports = class DiscrimCommand extends Command { } run(msg, args) { - const { discrim } = args; - const users = this.client.users.filter(u => u.discriminator === discrim).map(u => u.username).sort(); + const discrim = args.discrim || msg.author.discriminator; + const users = this.client.users.filter((u) => u.discriminator === discrim).map((u) => u.username); const embed = new RichEmbed() .setTitle(`${users.length} Users with the discriminator: ${discrim}`) .setDescription(users.join(', ')); diff --git a/commands/search/forecast.js b/commands/search/forecast.js index 16188d59..f04f2dea 100644 --- a/commands/search/forecast.js +++ b/commands/search/forecast.js @@ -22,37 +22,35 @@ module.exports = class ForecastCommand extends Command { async run(msg, args) { const { query } = args; - try { - const { body } = await snekfetch - .get('https://query.yahooapis.com/v1/public/yql') - .query({ - q: `select * from weather.forecast where u=\'f\' AND woeid in (select woeid from geo.places(1) where text="${query}")`, - format: 'json' - }); - if (!body.query.count) throw new Error('Location Not Found.'); - const forecasts = body.query.results.channel.item.forecast; - const embed = new RichEmbed() - .setColor(0x0000FF) - .setAuthor(body.query.results.channel.title, 'https://i.imgur.com/2MT0ViC.png') - .setURL(body.query.results.channel.link) - .setTimestamp() - .addField(`${forecasts[0].day} - ${forecasts[0].date}`, - `**High:** ${forecasts[0].high}°F, **Low:** ${forecasts[0].low}°F, **Condition:** ${forecasts[0].text}`) - .addField(`${forecasts[1].day} - ${forecasts[1].date}`, - `**High:** ${forecasts[1].high}°F, **Low:** ${forecasts[1].low}°F, **Condition:** ${forecasts[1].text}`) - .addField(`${forecasts[2].day} - ${forecasts[2].date}`, - `**High:** ${forecasts[2].high}°F, **Low:** ${forecasts[2].low}°F, **Condition:** ${forecasts[2].text}`) - .addField(`${forecasts[3].day} - ${forecasts[3].date}`, - `**High:** ${forecasts[3].high}°F, **Low:** ${forecasts[3].low}°F, **Condition:** ${forecasts[3].text}`) - .addField(`${forecasts[4].day} - ${forecasts[4].date}`, - `**High:** ${forecasts[4].high}°F, **Low:** ${forecasts[4].low}°F, **Condition:** ${forecasts[4].text}`) - .addField(`${forecasts[5].day} - ${forecasts[5].date}`, - `**High:** ${forecasts[5].high}°F, **Low:** ${forecasts[5].low}°F, **Condition:** ${forecasts[5].text}`) - .addField(`${forecasts[6].day} - ${forecasts[6].date}`, - `**High:** ${forecasts[6].high}°F, **Low:** ${forecasts[6].low}°F, **Condition:** ${forecasts[6].text}`); - return msg.embed(embed); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + const { body } = await snekfetch + .get('https://query.yahooapis.com/v1/public/yql') + .query({ + q: `select * from weather.forecast where u=\'f\' AND woeid in (select woeid from geo.places(1) where text="${query}")`, + format: 'json' + }); + if (!body.query.count) { + return msg.say('Location Not Found.'); } + const forecasts = body.query.results.channel.item.forecast; + const embed = new RichEmbed() + .setColor(0x0000FF) + .setAuthor(body.query.results.channel.title, 'https://i.imgur.com/2MT0ViC.png') + .setURL(body.query.results.channel.link) + .setTimestamp() + .addField(`❯ ${forecasts[0].day} - ${forecasts[0].date}`, + `**High:** ${forecasts[0].high}°F, **Low:** ${forecasts[0].low}°F, **Condition:** ${forecasts[0].text}`) + .addField(`❯ ${forecasts[1].day} - ${forecasts[1].date}`, + `**High:** ${forecasts[1].high}°F, **Low:** ${forecasts[1].low}°F, **Condition:** ${forecasts[1].text}`) + .addField(`❯ ${forecasts[2].day} - ${forecasts[2].date}`, + `**High:** ${forecasts[2].high}°F, **Low:** ${forecasts[2].low}°F, **Condition:** ${forecasts[2].text}`) + .addField(`❯ ${forecasts[3].day} - ${forecasts[3].date}`, + `**High:** ${forecasts[3].high}°F, **Low:** ${forecasts[3].low}°F, **Condition:** ${forecasts[3].text}`) + .addField(`❯ ${forecasts[4].day} - ${forecasts[4].date}`, + `**High:** ${forecasts[4].high}°F, **Low:** ${forecasts[4].low}°F, **Condition:** ${forecasts[4].text}`) + .addField(`❯ ${forecasts[5].day} - ${forecasts[5].date}`, + `**High:** ${forecasts[5].high}°F, **Low:** ${forecasts[5].low}°F, **Condition:** ${forecasts[5].text}`) + .addField(`❯ ${forecasts[6].day} - ${forecasts[6].date}`, + `**High:** ${forecasts[6].high}°F, **Low:** ${forecasts[6].low}°F, **Condition:** ${forecasts[6].text}`); + return msg.embed(embed); } }; diff --git a/commands/search/gelbooru.js b/commands/search/gelbooru.js index 2218d799..f4eab674 100644 --- a/commands/search/gelbooru.js +++ b/commands/search/gelbooru.js @@ -23,7 +23,6 @@ module.exports = class GelbooruCommand extends Command { async run(msg, args) { const { query } = args; - try { const { text } = await snekfetch .get('https://gelbooru.com/index.php') .query({ @@ -34,10 +33,9 @@ module.exports = class GelbooruCommand extends Command { limit: 1 }); const { posts } = await xml.parseStringAsync(text); - if (posts.$.count === '0') throw new Error('No Results.'); + if (posts.$.count === '0') { + return msg.say('No Results.'); + } return msg.say(`Result for ${query}: https:${posts.post[0].$.file_url}`); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); - } } }; diff --git a/commands/search/giphy.js b/commands/search/giphy.js index 4c53c13d..378dbeba 100644 --- a/commands/search/giphy.js +++ b/commands/search/giphy.js @@ -21,19 +21,17 @@ module.exports = class GiphyCommand extends Command { async run(msg, args) { const { query } = args; - try { - const { body } = await snekfetch - .get('http://api.giphy.com/v1/gifs/search') - .query({ - q: query, - api_key: GIPHY_KEY, - rating: msg.channel.nsfw ? 'r' : 'pg' - }); - if (!body.data.length) throw new Error('No Results.'); - const random = Math.floor(Math.random() * body.data.length); - return msg.say(body.data[random].images.original.url); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + const { body } = await snekfetch + .get('http://api.giphy.com/v1/gifs/search') + .query({ + q: query, + api_key: GIPHY_KEY, + rating: msg.channel.nsfw ? 'r' : 'pg' + }); + if (!body.data.length) { + return msg.say('No Results.'); } + const random = Math.floor(Math.random() * body.data.length); + return msg.say(body.data[random].images.original.url); } }; diff --git a/commands/search/github.js b/commands/search/github.js index b4f1d17d..bce9e9ed 100644 --- a/commands/search/github.js +++ b/commands/search/github.js @@ -34,21 +34,21 @@ module.exports = class GithubCommand extends Command { .setTitle(body.full_name) .setDescription(body.description) .setThumbnail(body.owner.avatar_url) - .addField('Creation Date', + .addField('❯ Creation Date', moment(body.created_at).format('MMMM Do YYYY'), true) - .addField('Last Updated On', + .addField('❯ Last Updated On', moment(body.updated_at).format('MMMM Do YYYY'), true) - .addField('Stargazers', + .addField('❯ Stargazers', body.stargazers_count, true) - .addField('Watchers', + .addField('❯ Watchers', body.watchers_count, true) - .addField('Open Issues', + .addField('❯ Open Issues', body.open_issues_count, true) - .addField('Language', + .addField('❯ Language', body.language, true); return msg.embed(embed); } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + return msg.say(err.message); } } }; diff --git a/commands/search/google.js b/commands/search/google.js index 75eb4e5f..a385125b 100644 --- a/commands/search/google.js +++ b/commands/search/google.js @@ -23,19 +23,17 @@ module.exports = class GoogleCommand extends Command { async run(msg, args) { const { query } = args; const message = await msg.say('Searching...'); - try { - const { text } = await snekfetch - .get('https://www.google.com/search') - .query({ - q: query - }); - const $ = cheerio.load(text); - let href = $('.r').first().find('a').first().attr('href'); - if (!href) throw new Error('No Results.'); - href = querystring.parse(href.replace('/url?', '')); - return message.edit(href.q); - } catch (err) { - return message.edit(`${err.name}: ${err.message}`); + const { text } = await snekfetch + .get('https://www.google.com/search') + .query({ + q: query + }); + const $ = cheerio.load(text); + let href = $('.r').first().find('a').first().attr('href'); + if (!href) { + return msg.say('No Results.'); } + href = querystring.parse(href.replace('/url?', '')); + return message.edit(href.q); } }; diff --git a/commands/search/konachan.js b/commands/search/konachan.js index 96912807..0eecde46 100644 --- a/commands/search/konachan.js +++ b/commands/search/konachan.js @@ -22,17 +22,15 @@ module.exports = class KonachanCommand extends Command { async run(msg, args) { const { query } = args; - try { - const { body } = await snekfetch - .get('https://konachan.net/post.json') - .query({ - tags: `${query ? `${query} ` : ''}order:random`, - limit: 1 - }); - if (!body.length) throw new Error('No Results.'); - return msg.say(`${query ? `Result for ${query}:` : 'Random Image:'} https:${body[0].file_url}`); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + const { body } = await snekfetch + .get('https://konachan.net/post.json') + .query({ + tags: `${query ? `${query} ` : ''}order:random`, + limit: 1 + }); + if (!body.length) { + return msg.say('No Results.'); } + return msg.say(`${query ? `Result for ${query}:` : 'Random Image:'} https:${body[0].file_url}`); } }; diff --git a/commands/search/lmgtfy.js b/commands/search/lmgtfy.js index 2ddc3718..e22f2e95 100644 --- a/commands/search/lmgtfy.js +++ b/commands/search/lmgtfy.js @@ -12,7 +12,7 @@ module.exports = class LMGTFYCommand extends Command { key: 'query', prompt: 'What would you like to the link to search for?', type: 'string', - parse: query => encodeURIComponent(query) + parse: (query) => encodeURIComponent(query) } ] }); diff --git a/commands/search/manga.js b/commands/search/manga.js index b3ad39fc..7b64faf4 100644 --- a/commands/search/manga.js +++ b/commands/search/manga.js @@ -1,6 +1,7 @@ const Command = require('../../structures/Command'); const { RichEmbed } = require('discord.js'); const snekfetch = require('snekfetch'); +const { cleanXML } = require('../../util/Util'); const { promisifyAll } = require('tsubaki'); const xml = promisifyAll(require('xml2js')); const { ANIMELIST_LOGIN } = process.env; @@ -32,14 +33,7 @@ module.exports = class MangaCommand extends Command { q: query }); const { manga } = await xml.parseStringAsync(text); - const synopsis = manga.entry[0].synopsis[0].substr(0, 2000) - .replace(/(
)/g, '') - .replace(/(')/g, '\'') - .replace(/(—)/g, '—') - .replace(/(")/g, '"') - .replace(/(&)/g, '&') - .replace(/(")/g, '"') - .replace(/(\[i\]|\[\/i\])/g, '*'); + const synopsis = cleanXML(manga.entry[0].synopsis[0].substr(0, 2000)); const embed = new RichEmbed() .setColor(0x2D54A2) .setAuthor('My Anime List', 'https://i.imgur.com/R4bmNFz.png') @@ -47,17 +41,17 @@ module.exports = class MangaCommand extends Command { .setThumbnail(manga.entry[0].image[0]) .setTitle(`${manga.entry[0].title[0]} (English: ${manga.entry[0].english[0] || 'N/A'})`) .setDescription(synopsis) - .addField('Type', + .addField('❯ Type', `${manga.entry[0].type[0]} - ${manga.entry[0].status[0]}`, true) - .addField('Volumes / Chapters', + .addField('❯ Volumes / Chapters', `${manga.entry[0].volumes[0]} / ${manga.entry[0].chapters[0]}`, true) - .addField('Start Date', + .addField('❯ Start Date', manga.entry[0].start_date[0], true) - .addField('End Date', + .addField('❯ End Date', manga.entry[0].end_date[0], true); return msg.embed(embed); } catch (err) { - return msg.say('Error: No Results.'); + return msg.say('No Results.'); } } }; diff --git a/commands/search/map.js b/commands/search/map.js index 7b07cf28..0791cdd8 100644 --- a/commands/search/map.js +++ b/commands/search/map.js @@ -16,10 +16,12 @@ module.exports = class MapCommand extends Command { label: 'zoom level', prompt: 'What would you like the zoom level for the map to be? Limit 1-20.', type: 'integer', - validate: zoom => { - if (zoom < 21 && zoom > 0) + validate: (zoom) => { + if (zoom < 21 && zoom > 0) { return true; - return 'Please enter a zoom value from 1-20'; + } else { + return 'Please enter a zoom value from 1-20'; + } } }, { @@ -33,19 +35,14 @@ module.exports = class MapCommand extends Command { async run(msg, args) { const { zoom, query } = args; - try { - const { body } = await snekfetch - .get('https://maps.googleapis.com/maps/api/staticmap') - .query({ - center: query, - zoom, - size: '500x500', - key: GOOGLE_KEY - }); - return msg.say({ files: [{ attachment: body, name: 'map.png' }] }) - .catch(err => msg.say(`${err.name}: ${err.message}`)); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); - } + const { body } = await snekfetch + .get('https://maps.googleapis.com/maps/api/staticmap') + .query({ + center: query, + zoom, + size: '500x500', + key: GOOGLE_KEY + }); + return msg.say({ files: [{ attachment: body, name: 'map.png' }] }); } }; diff --git a/commands/search/neopet.js b/commands/search/neopet.js index 35e17b2f..f1f51109 100644 --- a/commands/search/neopet.js +++ b/commands/search/neopet.js @@ -21,20 +21,18 @@ module.exports = class NeopetCommand extends Command { async run(msg, args) { const { query } = args; - try { - const { text } = await snekfetch - .get('http://www.sunnyneo.com/petimagefinder.php') - .query({ - name: query, - size: 5, - mood: 1 - }); - const $ = cheerio.load(text); - const link = $('textarea').first().text(); - if (!link.includes('cp')) throw new Error('Invalid Pet Name.'); - return msg.say(link); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + const { text } = await snekfetch + .get('http://www.sunnyneo.com/petimagefinder.php') + .query({ + name: query, + size: 5, + mood: 1 + }); + const $ = cheerio.load(text); + const link = $('textarea').first().text(); + if (!link.includes('cp')) { + return msg.say('Invalid Pet Name.'); } + return msg.say(link); } }; diff --git a/commands/search/osu.js b/commands/search/osu.js index 4803904f..d857b45f 100644 --- a/commands/search/osu.js +++ b/commands/search/osu.js @@ -23,46 +23,44 @@ module.exports = class OsuCommand extends Command { async run(msg, args) { const { query } = args; - try { - const { body } = await snekfetch - .get('https://osu.ppy.sh/api/get_user') - .query({ - k: OSU_KEY, - u: query, - type: 'string' - }); - if (!body.length) throw new Error('No Results.'); - const embed = new RichEmbed() - .setColor(0xFF66AA) - .setAuthor('osu!', 'https://i.imgur.com/EmnUp00.png') - .setURL('https://osu.ppy.sh/') - .addField('Username', - body[0].username, true) - .addField('ID', - body[0].user_id, true) - .addField('Level', - body[0].level, true) - .addField('Accuracy', - body[0].accuracy, true) - .addField('Rank', - body[0].pp_rank, true) - .addField('Play Count', - body[0].playcount, true) - .addField('Country', - body[0].country, true) - .addField('Ranked Score', - body[0].ranked_score, true) - .addField('Total Score', - body[0].total_score, true) - .addField('SS', - body[0].count_rank_ss, true) - .addField('S', - body[0].count_rank_s, true) - .addField('A', - body[0].count_rank_a, true); - return msg.embed(embed); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + const { body } = await snekfetch + .get('https://osu.ppy.sh/api/get_user') + .query({ + k: OSU_KEY, + u: query, + type: 'string' + }); + if (!body.length) { + return msg.say('No Results.'); } + const embed = new RichEmbed() + .setColor(0xFF66AA) + .setAuthor('osu!', 'https://i.imgur.com/EmnUp00.png') + .setURL('https://osu.ppy.sh/') + .addField('❯ Username', + body[0].username, true) + .addField('❯ ID', + body[0].user_id, true) + .addField('❯ Level', + body[0].level, true) + .addField('❯ Accuracy', + body[0].accuracy, true) + .addField('❯ Rank', + body[0].pp_rank, true) + .addField('❯ Play Count', + body[0].playcount, true) + .addField('❯ Country', + body[0].country, true) + .addField('❯ Ranked Score', + body[0].ranked_score, true) + .addField('❯ Total Score', + body[0].total_score, true) + .addField('❯ SS', + body[0].count_rank_ss, true) + .addField('❯ S', + body[0].count_rank_s, true) + .addField('❯ A', + body[0].count_rank_a, true); + return msg.embed(embed); } }; diff --git a/commands/search/rule34.js b/commands/search/rule34.js index 951a8c7e..b19679e2 100644 --- a/commands/search/rule34.js +++ b/commands/search/rule34.js @@ -23,21 +23,19 @@ module.exports = class Rule34Command extends Command { async run(msg, args) { const { query } = args; - try { - const { text } = await snekfetch - .get('https://rule34.xxx/index.php') - .query({ - page: 'dapi', - s: 'post', - q: 'index', - tags: query, - limit: 1 - }); - const { posts } = await xml.parseStringAsync(text); - if (posts.$.count === '0') throw new Error('No Results.'); - return msg.say(`Result for ${query}: https:${posts.post[0].$.file_url}`); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + const { text } = await snekfetch + .get('https://rule34.xxx/index.php') + .query({ + page: 'dapi', + s: 'post', + q: 'index', + tags: query, + limit: 1 + }); + const { posts } = await xml.parseStringAsync(text); + if (posts.$.count === '0') { + return msg.say('No Results.'); } + return msg.say(`Result for ${query}: https:${posts.post[0].$.file_url}`); } }; diff --git a/commands/search/soundcloud.js b/commands/search/soundcloud.js index cc2b2aa7..1154ae22 100644 --- a/commands/search/soundcloud.js +++ b/commands/search/soundcloud.js @@ -23,33 +23,31 @@ module.exports = class SoundCloudCommand extends Command { async run(msg, args) { const { query } = args; - try { - const { body } = await snekfetch - .get('https://api.soundcloud.com/tracks') - .query({ - q: query, - client_id: SOUNDCLOUD_KEY - }); - if (!body.length) throw new Error('No Results.'); - const embed = new RichEmbed() - .setColor(0xF15A22) - .setAuthor('SoundCloud', 'https://i.imgur.com/lFIz7RU.png') - .setTitle(body[0].title) - .setURL(body[0].permalink_url) - .setThumbnail(body[0].artwork_url) - .addField('Artist', - body[0].user.username) - .addField('Download Count', - body[0].download_count, true) - .addField('Comment Count', - body[0].comment_count, true) - .addField('Playback Count', - body[0].playback_count, true) - .addField('Favorited Count', - body[0].favoritings_count, true); - return msg.embed(embed); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + const { body } = await snekfetch + .get('https://api.soundcloud.com/tracks') + .query({ + q: query, + client_id: SOUNDCLOUD_KEY + }); + if (!body.length) { + return msg.say('No Results.'); } + const embed = new RichEmbed() + .setColor(0xF15A22) + .setAuthor('SoundCloud', 'https://i.imgur.com/lFIz7RU.png') + .setTitle(body[0].title) + .setURL(body[0].permalink_url) + .setThumbnail(body[0].artwork_url) + .addField('❯ Artist', + body[0].user.username) + .addField('❯ Download Count', + body[0].download_count, true) + .addField('❯ Comment Count', + body[0].comment_count, true) + .addField('❯ Playback Count', + body[0].playback_count, true) + .addField('❯ Favorited Count', + body[0].favoritings_count, true); + return msg.embed(embed); } }; diff --git a/commands/search/urban.js b/commands/search/urban.js index e8285bbd..b08f54c3 100644 --- a/commands/search/urban.js +++ b/commands/search/urban.js @@ -22,24 +22,22 @@ module.exports = class UrbanCommand extends Command { async run(msg, args) { const { query } = args; - try { - const { body } = await snekfetch - .get('http://api.urbandictionary.com/v0/define') - .query({ - term: query - }); - if (!body.list.length) throw new Error('No Results.'); - const embed = new RichEmbed() - .setColor(0x32a8f0) - .setAuthor('Urban Dictionary', 'https://i.imgur.com/fzFuuL7.png') - .setURL(body.list[0].permalink) - .setTitle(body.list[0].word) - .setDescription(body.list[0].definition.substr(0, 2000)) - .addField('Example', - body.list[0].example.substr(0, 2000) || 'None'); - return msg.embed(embed); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + const { body } = await snekfetch + .get('http://api.urbandictionary.com/v0/define') + .query({ + term: query + }); + if (!body.list.length) { + return msg.say('No Results.'); } + const embed = new RichEmbed() + .setColor(0x32a8f0) + .setAuthor('Urban Dictionary', 'https://i.imgur.com/fzFuuL7.png') + .setURL(body.list[0].permalink) + .setTitle(body.list[0].word) + .setDescription(body.list[0].definition.substr(0, 2000)) + .addField('❯ Example', + body.list[0].example.substr(0, 2000) || 'None'); + return msg.embed(embed); } }; diff --git a/commands/search/wattpad.js b/commands/search/wattpad.js index 064c14d6..310e9a63 100644 --- a/commands/search/wattpad.js +++ b/commands/search/wattpad.js @@ -24,37 +24,37 @@ module.exports = class WattpadCommand extends Command { async run(msg, args) { const { query } = args; - try { - const { body } = await snekfetch - .get('https://api.wattpad.com:443/v4/stories') - .query({ - query, - limit: 1 - }) - .set({ Authorization: `Basic ${WATTPAD_KEY}` }); - if (!body.stories.length) throw new Error('No Results.'); - const embed = new RichEmbed() - .setColor(0xF89C34) - .setAuthor('Wattpad', 'https://i.imgur.com/Rw9vRQB.png') - .setURL(body.stories[0].url) - .setTitle(body.stories[0].title) - .setDescription(body.stories[0].description.substr(0, 2000)) - .setThumbnail(body.stories[0].cover) - .addField('Created On', - moment(body.stories[0].createDate).format('MMMM Do YYYY'), true) - .addField('Author', - body.stories[0].user, true) - .addField('Parts', - body.stories[0].numParts, true) - .addField('Reads', - body.stories[0].readCount, true) - .addField('Votes', - body.stories[0].voteCount, true) - .addField('Comments', - body.stories[0].commentCount, true); - return msg.embed(embed); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + const { body } = await snekfetch + .get('https://api.wattpad.com:443/v4/stories') + .query({ + query, + limit: 1 + }) + .set({ + Authorization: `Basic ${WATTPAD_KEY}` + }); + if (!body.stories.length) { + return msg.say('No Results.'); } + const embed = new RichEmbed() + .setColor(0xF89C34) + .setAuthor('Wattpad', 'https://i.imgur.com/Rw9vRQB.png') + .setURL(body.stories[0].url) + .setTitle(body.stories[0].title) + .setDescription(body.stories[0].description.substr(0, 2000)) + .setThumbnail(body.stories[0].cover) + .addField('❯ Created On', + moment(body.stories[0].createDate).format('MMMM Do YYYY'), true) + .addField('❯ Author', + body.stories[0].user, true) + .addField('❯ Parts', + body.stories[0].numParts, true) + .addField('❯ Reads', + body.stories[0].readCount, true) + .addField('❯ Votes', + body.stories[0].voteCount, true) + .addField('❯ Comments', + body.stories[0].commentCount, true); + return msg.embed(embed); } }; diff --git a/commands/search/weather.js b/commands/search/weather.js index 7f9971d5..de9b739b 100644 --- a/commands/search/weather.js +++ b/commands/search/weather.js @@ -22,46 +22,44 @@ module.exports = class WeatherCommand extends Command { async run(msg, args) { const { query } = args; - try { - const { body } = await snekfetch - .get('https://query.yahooapis.com/v1/public/yql') - .query({ - q: `select * from weather.forecast where u=\'f\' AND woeid in (select woeid from geo.places(1) where text="${query}")`, - format: 'json' - }); - if (!body.query.count) throw new Error('Location Not Found.'); - const embed = new RichEmbed() - .setColor(0x0000FF) - .setAuthor(body.query.results.channel.title, 'https://i.imgur.com/2MT0ViC.png') - .setURL(body.query.results.channel.link) - .setTimestamp() - .addField('City', - body.query.results.channel.location.city, true) - .addField('Country', - body.query.results.channel.location.country, true) - .addField('Region', - body.query.results.channel.location.region, true) - .addField('Condition', - body.query.results.channel.item.condition.text, true) - .addField('Temperature', - `${body.query.results.channel.item.condition.temp}°F`, true) - .addField('Humidity', - body.query.results.channel.atmosphere.humidity, true) - .addField('Pressure', - body.query.results.channel.atmosphere.pressure, true) - .addField('Rising', - body.query.results.channel.atmosphere.rising, true) - .addField('Visibility', - body.query.results.channel.atmosphere.visibility, true) - .addField('Wind Chill', - body.query.results.channel.wind.chill, true) - .addField('Wind Direction', - body.query.results.channel.wind.direction, true) - .addField('Wind Speed', - body.query.results.channel.wind.speed, true); - return msg.embed(embed); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + const { body } = await snekfetch + .get('https://query.yahooapis.com/v1/public/yql') + .query({ + q: `select * from weather.forecast where u=\'f\' AND woeid in (select woeid from geo.places(1) where text="${query}")`, + format: 'json' + }); + if (!body.query.count) { + return msg.say('Location Not Found.'); } + const embed = new RichEmbed() + .setColor(0x0000FF) + .setAuthor(body.query.results.channel.title, 'https://i.imgur.com/2MT0ViC.png') + .setURL(body.query.results.channel.link) + .setTimestamp() + .addField('❯ City', + body.query.results.channel.location.city, true) + .addField('❯ Country', + body.query.results.channel.location.country, true) + .addField('❯ Region', + body.query.results.channel.location.region, true) + .addField('❯ Condition', + body.query.results.channel.item.condition.text, true) + .addField('❯ Temperature', + `${body.query.results.channel.item.condition.temp}°F`, true) + .addField('❯ Humidity', + body.query.results.channel.atmosphere.humidity, true) + .addField('❯ Pressure', + body.query.results.channel.atmosphere.pressure, true) + .addField('❯ Rising', + body.query.results.channel.atmosphere.rising, true) + .addField('❯ Visibility', + body.query.results.channel.atmosphere.visibility, true) + .addField('❯ Wind Chill', + body.query.results.channel.wind.chill, true) + .addField('❯ Wind Direction', + body.query.results.channel.wind.direction, true) + .addField('❯ Wind Speed', + body.query.results.channel.wind.speed, true); + return msg.embed(embed); } }; diff --git a/commands/search/wikipedia.js b/commands/search/wikipedia.js index c8b87a26..035f1fd6 100644 --- a/commands/search/wikipedia.js +++ b/commands/search/wikipedia.js @@ -22,28 +22,26 @@ module.exports = class WikipediaCommand extends Command { async run(msg, args) { const { query } = args; - try { - const { body } = await snekfetch - .get('https://en.wikipedia.org/w/api.php') - .query({ - action: 'query', - prop: 'extracts', - format: 'json', - titles: query, - exintro: '', - explaintext: '', - redirects: '', - formatversion: 2 - }); - if (body.query.pages[0].missing) throw new Error('No Results.'); - const embed = new RichEmbed() - .setColor(0xE7E7E7) - .setTitle(body.query.pages[0].title) - .setAuthor('Wikipedia', 'https://i.imgur.com/a4eeEhh.png') - .setDescription(body.query.pages[0].extract.substr(0, 2000).replace(/[\n]/g, '\n\n')); - return msg.embed(embed); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + const { body } = await snekfetch + .get('https://en.wikipedia.org/w/api.php') + .query({ + action: 'query', + prop: 'extracts', + format: 'json', + titles: query, + exintro: '', + explaintext: '', + redirects: '', + formatversion: 2 + }); + if (body.query.pages[0].missing) { + return msg.say('No Results.'); } + const embed = new RichEmbed() + .setColor(0xE7E7E7) + .setTitle(body.query.pages[0].title) + .setAuthor('Wikipedia', 'https://i.imgur.com/a4eeEhh.png') + .setDescription(body.query.pages[0].extract.substr(0, 2000).replace(/[\n]/g, '\n\n')); + return msg.embed(embed); } }; diff --git a/commands/search/youtube.js b/commands/search/youtube.js index 6d5c6f02..e86010c7 100644 --- a/commands/search/youtube.js +++ b/commands/search/youtube.js @@ -23,27 +23,25 @@ module.exports = class YouTubeCommand extends Command { async run(msg, args) { const { query } = args; - try { - const { body } = await snekfetch - .get('https://www.googleapis.com/youtube/v3/search') - .query({ - part: 'snippet', - type: 'video', - maxResults: 1, - q: query, - key: GOOGLE_KEY - }); - if (!body.items.length) throw new Error('No Results.'); - const embed = new RichEmbed() - .setColor(0xDD2825) - .setTitle(body.items[0].snippet.title) - .setDescription(body.items[0].snippet.description) - .setAuthor(`YouTube - ${body.items[0].snippet.channelTitle}`, 'https://i.imgur.com/hkUafwu.png') - .setURL(`https://www.youtube.com/watch?v=${body.items[0].id.videoId}`) - .setThumbnail(body.items[0].snippet.thumbnails.default.url); - return msg.embed(embed); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + const { body } = await snekfetch + .get('https://www.googleapis.com/youtube/v3/search') + .query({ + part: 'snippet', + type: 'video', + maxResults: 1, + q: query, + key: GOOGLE_KEY + }); + if (!body.items.length) { + return msg.say('No Results.'); } + const embed = new RichEmbed() + .setColor(0xDD2825) + .setTitle(body.items[0].snippet.title) + .setDescription(body.items[0].snippet.description) + .setAuthor(`YouTube - ${body.items[0].snippet.channelTitle}`, 'https://i.imgur.com/hkUafwu.png') + .setURL(`https://www.youtube.com/watch?v=${body.items[0].id.videoId}`) + .setThumbnail(body.items[0].snippet.thumbnails.default.url); + return msg.embed(embed); } }; diff --git a/commands/search/yu-gi-oh.js b/commands/search/yu-gi-oh.js index 6bf40559..93503cd7 100644 --- a/commands/search/yu-gi-oh.js +++ b/commands/search/yu-gi-oh.js @@ -15,7 +15,7 @@ module.exports = class YuGiOhCommand extends Command { key: 'query', prompt: 'What card would you like to get data for?', type: 'string', - parse: text => encodeURIComponent(text) + parse: (text) => encodeURIComponent(text) } ] }); @@ -23,32 +23,31 @@ module.exports = class YuGiOhCommand extends Command { async run(msg, args) { const { query } = args; - try { - const { body } = await snekfetch - .get(`http://yugiohprices.com/api/card_data/${query}`); - if (body.status === 'fail') throw new Error('No Results.'); - const embed = new RichEmbed() - .setColor(0xBE5F1F) - .setTitle(body.data.name) - .setDescription(body.data.text) - .setAuthor('Yu-Gi-Oh!', 'https://i.imgur.com/7gPm9Rr.png') - .addField('Card Type', - body.data.card_type, true); - if (body.data.card_type === 'monster') { - embed.addField('Type', - body.data.type, true) - .addField('Attribute', - body.data.family, true) - .addField('ATK', - body.data.atk, true) - .addField('DEF', - body.data.def, true) - .addField('Level', - body.data.level, true); - } - return msg.embed(embed); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); + const { body } = await snekfetch + .get(`http://yugiohprices.com/api/card_data/${query}`); + if (body.status === 'fail') { + return msg.say('No Results.'); } + const embed = new RichEmbed() + .setColor(0xBE5F1F) + .setTitle(body.data.name) + .setDescription(body.data.text) + .setAuthor('Yu-Gi-Oh!', 'https://i.imgur.com/7gPm9Rr.png') + .addField('❯ Card Type', + body.data.card_type, true); + if (body.data.card_type === 'monster') { + embed + .addField('❯ Type', + body.data.type, true) + .addField('❯ Attribute', + body.data.family, true) + .addField('❯ ATK', + body.data.atk, true) + .addField('❯ DEF', + body.data.def, true) + .addField('❯ Level', + body.data.level, true); + } + return msg.embed(embed); } }; diff --git a/commands/settings/clear-setting.js b/commands/settings/clear-setting.js index 246237ac..e063770d 100644 --- a/commands/settings/clear-setting.js +++ b/commands/settings/clear-setting.js @@ -15,9 +15,12 @@ module.exports = class ClearSettingCommand extends Command { key: 'setting', prompt: 'What setting do you want to clear?', type: 'string', - validate: setting => { - if (settings.includes(setting)) return true; - return `Please enter one of the following: ${settings.join(', ')}.`; + validate: (setting) => { + if (settings.includes(setting)) { + return true; + } else { + return `Please enter one of the following: ${settings.join(', ')}.`; + } } } ] diff --git a/commands/settings/member-message.js b/commands/settings/member-message.js index 6aca7c82..93bd71c5 100644 --- a/commands/settings/member-message.js +++ b/commands/settings/member-message.js @@ -16,18 +16,24 @@ module.exports = class MemberMsgCommand extends Command { key: 'type', prompt: 'Which message would you like to change? Please enter either `joinMsg` or `leaveMsg`.', type: 'string', - validate: type => { - if (['joinMsg', 'leaveMsg'].includes(type)) return true; - return 'Please enter either `joinMsg` or `leaveMsg`.'; + validate: (type) => { + if (['joinMsg', 'leaveMsg'].includes(type)) { + return true; + } else { + return 'Please enter either `joinMsg` or `leaveMsg`.'; + } } }, { key: 'message', prompt: 'What should be sent to the channel? Use , , and as placeholders.', type: 'string', - validate: message => { - if (message.length < 150) return true; - return 'Invalid Message. Message must be under 150 characters.'; + validate: (message) => { + if (message.length < 150) { + return true; + } else { + return 'Invalid Message. Message must be under 150 characters.'; + } } } ] diff --git a/commands/settings/setting-list.js b/commands/settings/setting-list.js index 84e6c4e4..4efb8a4a 100644 --- a/commands/settings/setting-list.js +++ b/commands/settings/setting-list.js @@ -13,7 +13,6 @@ module.exports = class SettingListCommand extends Command { } run(msg) { - const staffRole = msg.guild.settings.get('staffRole', false); const modLog = msg.guild.settings.get('modLog', false); const memberLog = msg.guild.settings.get('memberLog', false); const singleRole = msg.guild.settings.get('singleRole', false); @@ -22,14 +21,13 @@ module.exports = class SettingListCommand extends Command { return msg.say(stripIndents` **Prefix:** ${msg.guild.commandPrefix} **Invite Guard:** ${msg.guild.settings.get('inviteGuard', false)} - **Staff Role:** ${staffRole ? (msg.guild.roles.has(staffRole) ? msg.guild.roles.get(staffRole).name : 'Missing') : 'None'} - **Mod Channel:** ${modLog ? (msg.guild.channels.has(modLog) ? msg.guild.channels.get(modLog).name : 'Missing') : 'None'} - **Starboard:** ${starboard ? (msg.guild.channels.has(starboard) ? msg.guild.channels.get(starboard).name : 'Missing') : 'None'} - **Join Role:** ${joinRole ? (msg.guild.roles.has(joinRole) ? msg.guild.roles.get(joinRole).name : 'Missing') : 'None'} - **Member Channel:** ${memberLog ? (msg.guild.channels.has(memberLog) ? msg.guild.channels.get(memberLog).name : 'Missing') : 'None'} + **Mod Channel:** ${modLog ? msg.guild.channels.has(modLog) ? msg.guild.channels.get(modLog).name : 'Missing' : 'None'} + **Starboard:** ${starboard ? msg.guild.channels.has(starboard) ? msg.guild.channels.get(starboard).name : 'Missing' : 'None'} + **Join Role:** ${joinRole ? msg.guild.roles.has(joinRole) ? msg.guild.roles.get(joinRole).name : 'Missing' : 'None'} + **Member Channel:** ${memberLog ? msg.guild.channels.has(memberLog) ? msg.guild.channels.get(memberLog).name : 'Missing' : 'None'} **Join Message:** ${msg.guild.settings.get('joinMsg', 'Welcome ! (Default)')} **Leave Message:** ${msg.guild.settings.get('leaveMsg', 'Bye ... (Default)')} - **Single Role:** ${singleRole ? (msg.guild.roles.has(singleRole) ? msg.guild.roles.get(singleRole).name : 'Missing') : 'None'} + **Single Role:** ${singleRole ? msg.guild.roles.has(singleRole) ? msg.guild.roles.get(singleRole).name : 'Missing' : 'None'} `); } }; diff --git a/commands/settings/staff-role.js b/commands/settings/staff-role.js deleted file mode 100644 index 6758cf5c..00000000 --- a/commands/settings/staff-role.js +++ /dev/null @@ -1,27 +0,0 @@ -const Command = require('../../structures/Command'); - -module.exports = class StaffRoleCommand extends Command { - constructor(client) { - super(client, { - name: 'staff-role', - group: 'settings', - memberName: 'staff-role', - description: 'Sets the role that can use Mod Commands without perms.', - guildOnly: true, - userPermissions: ['ADMINISTRATOR'], - args: [ - { - key: 'role', - prompt: 'What role should be staff?', - type: 'role' - } - ] - }); - } - - run(msg, args) { - const { role } = args; - msg.guild.settings.set('staffRole', role.id); - return msg.say(`Server Staff role set to ${role.name}.`); - } -}; diff --git a/commands/textedit/binary.js b/commands/textedit/binary.js index e5949bed..bfe7467e 100644 --- a/commands/textedit/binary.js +++ b/commands/textedit/binary.js @@ -12,11 +12,14 @@ module.exports = class BinaryCommand extends Command { key: 'text', prompt: 'What text would you like to convert to binary?', type: 'string', - validate: text => { - if (this.binary(text).length < 2000) return true; - return 'Your text is too long.'; + validate: (text) => { + if (this.binary(text).length < 2000) { + return true; + } else { + return 'Your text is too long.'; + } }, - parse: text => this.binary(text) + parse: (text) => this.binary(text) } ] }); @@ -28,7 +31,7 @@ module.exports = class BinaryCommand extends Command { } binary(text) { - return unescape(encodeURIComponent(text)).split('').map(str => { + return unescape(encodeURIComponent(text)).split('').map((str) => { const converted = str.charCodeAt(0).toString(2); return `${'00000000'.slice(converted.length)}${converted}`; }).join(''); diff --git a/commands/textedit/cow-say.js b/commands/textedit/cow-say.js index c28204c6..efe7c722 100644 --- a/commands/textedit/cow-say.js +++ b/commands/textedit/cow-say.js @@ -13,9 +13,12 @@ module.exports = class CowsayCommand extends Command { key: 'text', prompt: 'What text would you like the cow to say?', type: 'string', - validate: text => { - if (text.length < 1500) return true; - return 'Invalid Text. Text must be under 1500 characters.'; + validate: (text) => { + if (text.length < 1500) { + return true; + } else { + return 'Invalid Text. Text must be under 1500 characters.'; + } } } ] diff --git a/commands/textedit/morse.js b/commands/textedit/morse.js index 73300bbc..3584e45f 100644 --- a/commands/textedit/morse.js +++ b/commands/textedit/morse.js @@ -14,11 +14,14 @@ module.exports = class MorseCommand extends Command { key: 'text', prompt: 'What text would you like to convert to morse?', type: 'string', - validate: text => { - if (letterTrans(text, dictionary, ' ').length < 1999) return true; - return 'Your text is too long.'; + validate: (text) => { + if (letterTrans(text, dictionary, ' ').length < 1999) { + return true; + } else { + return 'Your text is too long.'; + } }, - parse: text => letterTrans(text.toLowerCase(), dictionary, ' ') + parse: (text) => letterTrans(text.toLowerCase(), dictionary, ' ') } ] }); diff --git a/commands/textedit/pirate.js b/commands/textedit/pirate.js index cec84e0d..ffa03ee7 100644 --- a/commands/textedit/pirate.js +++ b/commands/textedit/pirate.js @@ -14,11 +14,14 @@ module.exports = class PirateCommand extends Command { key: 'text', prompt: 'What text would you like to convert to pirate?', type: 'string', - validate: text => { - if (wordTrans(text, dictionary).length < 1999) return true; - return 'Your text is too long.'; + validate: (text) => { + if (wordTrans(text, dictionary).length < 1999) { + return true; + } else { + return 'Your text is too long.'; + } }, - parse: text => wordTrans(text, dictionary) + parse: (text) => wordTrans(text, dictionary) } ] }); diff --git a/commands/textedit/repeat.js b/commands/textedit/repeat.js index d6420cf7..d5f9c738 100644 --- a/commands/textedit/repeat.js +++ b/commands/textedit/repeat.js @@ -12,7 +12,7 @@ module.exports = class RepeatCommand extends Command { key: 'text', prompt: 'What text would you like to repeat over and over and over and over?', type: 'string', - parse: text => text.repeat(2000).substr(0, 1999) + parse: (text) => text.repeat(2000).substr(0, 1999) } ] }); diff --git a/commands/textedit/reverse.js b/commands/textedit/reverse.js index 052b7f5a..27872b3c 100644 --- a/commands/textedit/reverse.js +++ b/commands/textedit/reverse.js @@ -12,7 +12,7 @@ module.exports = class ReverseCommand extends Command { key: 'text', prompt: 'What text would you like to reverse?', type: 'string', - parse: text => text.split('').reverse().join('') + parse: (text) => text.split('').reverse().join('') } ] }); diff --git a/commands/textedit/temmie.js b/commands/textedit/temmie.js index 2884d0c1..d9280519 100644 --- a/commands/textedit/temmie.js +++ b/commands/textedit/temmie.js @@ -14,11 +14,14 @@ module.exports = class TemmieCommand extends Command { key: 'text', prompt: 'What text would you like to convert to Temmie speak?', type: 'string', - validate: text => { - if (wordTrans(text, dictionary).length < 1999) return true; - return 'Your text is too long.'; + validate: (text) => { + if (wordTrans(text, dictionary).length < 1999) { + return true; + } else { + return 'Your text is too long.'; + } }, - parse: text => wordTrans(text, dictionary) + parse: (text) => wordTrans(text, dictionary) } ] }); diff --git a/commands/textedit/translate.js b/commands/textedit/translate.js index c7706c49..21c5ef63 100644 --- a/commands/textedit/translate.js +++ b/commands/textedit/translate.js @@ -23,22 +23,28 @@ module.exports = class TranslateCommand extends Command { key: 'to', prompt: 'Which language is being translated to?', type: 'string', - validate: to => { - if (codes[to.toLowerCase()]) return true; - return 'Invalid Language Code. Use `help translate` for a list of codes.'; + validate: (to) => { + if (codes[to.toLowerCase()]) { + return true; + } else { + return 'Invalid Language Code. Use `help translate` for a list of codes.'; + } }, - parse: to => to.toLowerCase() + parse: (to) => to.toLowerCase() }, { key: 'from', prompt: 'Which language is being translated from?', type: 'string', - validate: from => { - if (codes[from.toLowerCase()]) return true; - return 'Invalid Language Code. Use `help translate` for a list of codes.'; + default: '', + validate: (from) => { + if (codes[from.toLowerCase()]) { + return true; + } else { + return 'Invalid Language Code. Use `help translate` for a list of codes.'; + } }, - parse: from => from.toLowerCase(), - default: '' + parse: (from) => from.toLowerCase() } ] }); @@ -46,24 +52,20 @@ module.exports = class TranslateCommand extends Command { async run(msg, args) { const { text, to, from } = args; - try { - const { body } = await snekfetch - .get('https://translate.yandex.net/api/v1.5/tr.json/translate') - .query({ - key: YANDEX_KEY, - text, - lang: from ? `${from}-${to}` : to - }); - const lang = body.lang.split('-'); - const embed = new RichEmbed() - .setColor(0x00AE86) - .addField(`From: ${codes[lang[0]]}`, - text) - .addField(`To: ${codes[lang[1]]}`, - body.text[0]); - return msg.embed(embed); - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); - } + const { body } = await snekfetch + .get('https://translate.yandex.net/api/v1.5/tr.json/translate') + .query({ + key: YANDEX_KEY, + text, + lang: from ? `${from}-${to}` : to + }); + const lang = body.lang.split('-'); + const embed = new RichEmbed() + .setColor(0x00AE86) + .addField(`❯ From: ${codes[lang[0]]}`, + text) + .addField(`❯ To: ${codes[lang[1]]}`, + body.text[0]); + return msg.embed(embed); } }; diff --git a/commands/textedit/upside-down.js b/commands/textedit/upside-down.js index 44397208..7817e166 100644 --- a/commands/textedit/upside-down.js +++ b/commands/textedit/upside-down.js @@ -15,7 +15,7 @@ module.exports = class UpsideDownCommand extends Command { key: 'text', prompt: 'What text would you like to flip upside-down?', type: 'string', - parse: text => letterTrans(text, dictionary) + parse: (text) => letterTrans(text, dictionary) } ] }); diff --git a/commands/textedit/webhook.js b/commands/textedit/webhook.js index 17072040..e85e71d7 100644 --- a/commands/textedit/webhook.js +++ b/commands/textedit/webhook.js @@ -23,20 +23,12 @@ module.exports = class WebhookCommand extends Command { }); } - hasPermission(msg) { - return this.client.isOwner(msg.author); - } - async run(msg, args) { const { content } = args; - try { - msg.delete(); - await snekfetch - .post(WEBHOOK_URL) - .send({ content }); - return null; - } catch (err) { - return msg.say(`${err.name}: ${err.message}`); - } + msg.delete(); + await snekfetch + .post(WEBHOOK_URL) + .send({ content }); + return null; } }; diff --git a/commands/textedit/zalgo.js b/commands/textedit/zalgo.js index 2b1a325e..47bb0541 100644 --- a/commands/textedit/zalgo.js +++ b/commands/textedit/zalgo.js @@ -13,11 +13,14 @@ module.exports = class ZalgoCommand extends Command { key: 'text', prompt: 'What text would you like to convert to zalgo?', type: 'string', - validate: text => { - if (text.length < 500) return true; - return 'Invalid Text. Text must be under 500 characters.'; + validate: (text) => { + if (text.length < 500) { + return true; + } else { + return 'Invalid Text. Text must be under 500 characters.'; + } }, - parse: text => zalgo(text) + parse: (text) => zalgo(text) } ] }); diff --git a/commands/userinfo/avatar.js b/commands/userinfo/avatar.js index 880cb394..98a9f772 100644 --- a/commands/userinfo/avatar.js +++ b/commands/userinfo/avatar.js @@ -11,14 +11,15 @@ module.exports = class AvatarCommand extends Command { { key: 'user', prompt: 'Which user would you like to get the avatar of?', - type: 'user' + type: 'user', + default: '' } ] }); } run(msg, args) { - const { user } = args; + const user = args.user || msg.author; return msg.say(user.avatarURL('webp', 2048) || user.displayAvatarURL); } }; diff --git a/commands/userinfo/user-info.js b/commands/userinfo/user-info.js index 6ed3b78c..631e7f10 100644 --- a/commands/userinfo/user-info.js +++ b/commands/userinfo/user-info.js @@ -1,8 +1,7 @@ const Command = require('../../structures/Command'); const { RichEmbed } = require('discord.js'); -const { stripIndents } = require('common-tags'); const moment = require('moment'); -require('moment-duration-format'); +const { statuses, colors } = require('../../assets/json/user-info'); module.exports = class UserInfoCommand extends Command { constructor(client) { @@ -18,54 +17,30 @@ module.exports = class UserInfoCommand extends Command { { key: 'member', prompt: 'Which user would you like to get info on?', - type: 'member' + type: 'member', + default: '' } ] }); } run(msg, args) { - const { member } = args; - let stat; - let color; - switch(member.user.presence.status) { - case 'online': - stat = '<:online:313956277808005120> Online'; - color = 0x00AE86; - break; - case 'idle': - stat = '<:away:313956277220802560> Idle'; - color = 0xFFFF00; - break; - case 'dnd': - stat = '<:dnd:313956276893646850> Do Not Disturb'; - color = 0xFF0000; - break; - case 'offline': - stat = '<:offline:313956277237710868> Offline'; - color = 0x808080; - break; - } + const member = args.member || msg.member; + const status = member.user.presence.status; const embed = new RichEmbed() - .setColor(color) + .setColor(colors[status]) .setThumbnail(member.user.displayAvatarURL) - .addField('Name', + .addField('❯ Name', member.user.tag, true) - .addField('ID', + .addField('❯ ID', member.id, true) - .addField('Discord Join Date', - stripIndents` - ${moment(member.user.createdTimestamp).format('MMMM Do YYYY h:mm:ss A')} - ${moment.duration(Date.now() - member.user.createdTimestamp).format('y[ years], M[ months], w[ weeks, and ]d[ days]')} ago. - `) - .addField('Server Join Date', - stripIndents` - ${moment(member.joinedTimestamp).format('MMMM Do YYYY h:mm:ss A')} - ${moment.duration(Date.now() - member.joinedTimestamp).format('y[ years], M[ months], w[ weeks, and ]d[ days]')} ago. - `) - .addField('Status', - stat, true) - .addField('Playing', + .addField('❯ Discord Join Date', + moment(member.user.createdAt).format('MMMM Do YYYY h:mm:ss A')) + .addField('❯ Server Join Date', + moment(member.joinedTimestamp).format('MMMM Do YYYY h:mm:ss A')) + .addField('❯ Status', + statuses[status], true) + .addField('❯ Playing', member.user.presence.game ? member.user.presence.game.name : 'None', true); return msg.embed(embed); } diff --git a/commands/util/help.js b/commands/util/help.js index da9ceca3..32f4c3a7 100644 --- a/commands/util/help.js +++ b/commands/util/help.js @@ -37,17 +37,19 @@ module.exports = class HelpCommand extends Command { **Group:** ${commands[0].group.name} ${commands[0].details || ''} `); - } else return msg.say(`Could not identify command. Use \`${msg.usage(null)}\` to view a list of commands you can use.`); + } else { + return msg.say(`Could not identify command. Use \`${msg.usage(null)}\` to view a list of commands you can use.`); + } } else { const embed = new RichEmbed() .setTitle(!showAll ? `Commands Available in ${msg.guild ? msg.guild.name : 'this DM'}` : 'All Commands') .setDescription(`Use \`${msg.usage('')}\` to view detailed information about a specific command.`) .setColor(0x00AE86); for (const group of this.client.registry.groups.values()) { - embed.addField(group.name, - showAll ? - group.commands.map(c => c.name).join(', ') : - group.commands.filter(c => c.isUsable(msg)).map(c => c.name).join(', ') || 'None Available'); + embed.addField(`❯ ${group.name}`, + showAll + ? group.commands.map((c) => c.name).join(', ') + : group.commands.filter((c) => c.isUsable(msg)).map((c) => c.name).join(', ') || 'None Available'); } try { await msg.direct({ embed }); diff --git a/commands/util/info.js b/commands/util/info.js index 14063643..4526b9c8 100644 --- a/commands/util/info.js +++ b/commands/util/info.js @@ -1,6 +1,5 @@ const Command = require('../../structures/Command'); const { RichEmbed } = require('discord.js'); -const { oneLine } = require('common-tags'); const { version } = require('../../package'); const moment = require('moment'); require('moment-duration-format'); @@ -23,27 +22,24 @@ module.exports = class InfoCommand extends Command { const memory = await this.client.shard.broadcastEval('Math.round(process.memoryUsage().heapUsed / 1024 / 1024)'); const embed = new RichEmbed() .setColor(0x00AE86) - .setFooter(oneLine` - ©2017 dragonfire535#8081 | - Created ${moment.duration(Date.now() - this.client.user.createdTimestamp).format('y[ years], M[ months], w[ weeks, and ]d[ days]')} ago! - `) - .addField('Servers', + .setFooter('©2017 dragonfire535#8081') + .addField('❯ Servers', guilds.reduce((prev, val) => prev + val, 0), true) - .addField('Shards', + .addField('❯ Shards', this.client.options.shardCount, true) - .addField('Commands', + .addField('❯ Commands', this.client.registry.commands.size, true) - .addField('Source Code', + .addField('❯ Source Code', '[View Here](https://github.com/dragonfire535/xiaobot)', true) - .addField('Memory Usage', + .addField('❯ Memory Usage', `${memory.reduce((prev, val) => prev + val, 0)}MB`, true) - .addField('Uptime', + .addField('❯ Uptime', moment.duration(this.client.uptime).format('d[d]h[h]m[m]s[s]'), true) - .addField('Version', + .addField('❯ Version', `v${version}`, true) - .addField('Node Version', + .addField('❯ Node Version', process.version, true) - .addField('Library', + .addField('❯ Library', '[discord.js](https://github.com/hydrabolt/discord.js)[-commando](https://github.com/Gawdl3y/discord.js-commando)', true); return msg.embed(embed); } diff --git a/commands/util/shard-info.js b/commands/util/shard-info.js index cef992bc..eec8fd32 100644 --- a/commands/util/shard-info.js +++ b/commands/util/shard-info.js @@ -18,9 +18,12 @@ module.exports = class ShardInfoCommand extends Command { key: 'shard', prompt: 'Which Shard would you like to get data for?', type: 'integer', - validate: shard => { - if (shard < this.client.options.shardCount && shard > -1) return true; - return 'Invalid Shard ID'; + validate: (shard) => { + if (shard < this.client.options.shardCount && shard > -1) { + return true; + } else { + return 'Invalid Shard ID'; + } } } ] @@ -35,11 +38,11 @@ module.exports = class ShardInfoCommand extends Command { const embed = new RichEmbed() .setTitle(`Shard ${shard}`) .setColor(0x00AE86) - .addField('Servers', + .addField('❯ Servers', guilds[shard], true) - .addField('Memory Usage', + .addField('❯ Memory Usage', `${memory[shard]}MB`, true) - .addField('Uptime', + .addField('❯ Uptime', moment.duration(uptime[shard]).format('d[d]h[h]m[m]s[s]'), true); return msg.embed(embed); } diff --git a/package.json b/package.json index 4a8ec80d..8293b7ac 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "xiaobot", - "version": "21.4.7", + "version": "22.0.0", "description": "A Discord Bot", "main": "Shard.js", "scripts": { @@ -23,12 +23,12 @@ "postgresql", "cleverbot" ], - "author": "dragonfire535", + "author": "dragonfire535 ", "license": "ISC", "bugs": { "url": "https://github.com/dragonfire535/xiaobot/issues" }, - "homepage": "http://dragonfire535.weebly.com/xiaobot.html", + "homepage": "https://github.com/dragonfire535/xiaobot#readme", "engines": { "node": "8.0.0" }, diff --git a/providers/Sequelize.js b/providers/Sequelize.js index 85cab50e..7f93f793 100644 --- a/providers/Sequelize.js +++ b/providers/Sequelize.js @@ -93,29 +93,33 @@ class SequelizeProvider extends SettingProvider { .set('commandPrefixChange', (guild, prefix) => this.set(guild, 'prefix', prefix)) .set('commandStatusChange', (guild, command, enabled) => this.set(guild, `cmd-${command.name}`, enabled)) .set('groupStatusChange', (guild, group, enabled) => this.set(guild, `grp-${group.id}`, enabled)) - .set('guildCreate', guild => { + .set('guildCreate', (guild) => { const settings = this.settings.get(guild.id); if (!settings) return; this.setupGuild(guild.id, settings); }) - .set('commandRegister', command => { + .set('commandRegister', (command) => { for (const [guild, settings] of this.settings) { if (guild !== 'global' && !client.guilds.has(guild)) continue; this.setupGuildCommand(client.guilds.get(guild), command, settings); } }) - .set('groupRegister', group => { + .set('groupRegister', (group) => { for (const [guild, settings] of this.settings) { if (guild !== 'global' && !client.guilds.has(guild)) continue; this.setupGuildGroup(client.guilds.get(guild), group, settings); } }); - for (const [event, listener] of this.listeners) client.on(event, listener); + for (const [event, listener] of this.listeners) { + client.on(event, listener); + } } destroy() { // Remove all listeners from the client - for (const [event, listener] of this.listeners) this.client.removeListener(event, listener); + for (const [event, listener] of this.listeners) { + this.client.removeListener(event, listener); + } this.listeners.clear(); } @@ -137,14 +141,18 @@ class SequelizeProvider extends SettingProvider { { guild: guild !== 'global' ? guild : '0', settings: JSON.stringify(settings) }, { where: { guild: guild !== 'global' ? guild : '0' } } ); - if (guild === 'global') this.updateOtherShards(key, val); + if (guild === 'global') { + this.updateOtherShards(key, val); + } return val; } async remove(guild, key) { guild = this.constructor.getGuildID(guild); const settings = this.settings.get(guild); - if (!settings || typeof settings[key] === 'undefined') return undefined; + if (!settings || typeof settings[key] === 'undefined') { + return undefined; + } const val = settings[key]; settings[key] = undefined; @@ -152,7 +160,9 @@ class SequelizeProvider extends SettingProvider { { guild: guild !== 'global' ? guild : '0', settings: JSON.stringify(settings) }, { where: { guild: guild !== 'global' ? guild : '0' } } ); - if (guild === 'global') this.updateOtherShards(key, undefined); + if (guild === 'global') { + this.updateOtherShards(key, undefined); + } return val; } @@ -170,18 +180,27 @@ class SequelizeProvider extends SettingProvider { * @private */ setupGuild(guild, settings) { - if (typeof guild !== 'string') throw new TypeError('The guild must be a guild ID or "global".'); + if (typeof guild !== 'string') { + throw new TypeError('The guild must be a guild ID or "global".'); + } guild = this.client.guilds.get(guild) || null; // Load the command prefix if (typeof settings.prefix !== 'undefined') { - if (guild) guild._commandPrefix = settings.prefix; - else this.client._commandPrefix = settings.prefix; + if (guild) { + guild._commandPrefix = settings.prefix; + } else { + this.client._commandPrefix = settings.prefix; + } } // Load all command/group statuses - for (const command of this.client.registry.commands.values()) this.setupGuildCommand(guild, command, settings); - for (const group of this.client.registry.groups.values()) this.setupGuildGroup(guild, group, settings); + for (const command of this.client.registry.commands.values()) { + this.setupGuildCommand(guild, command, settings); + } + for (const group of this.client.registry.groups.values()) { + this.setupGuildGroup(guild, group, settings); + } } /** @@ -194,7 +213,9 @@ class SequelizeProvider extends SettingProvider { setupGuildCommand(guild, command, settings) { if (typeof settings[`cmd-${command.name}`] === 'undefined') return; if (guild) { - if (!guild._commandsEnabled) guild._commandsEnabled = {}; + if (!guild._commandsEnabled) { + guild._commandsEnabled = {}; + } guild._commandsEnabled[command.name] = settings[`cmd-${command.name}`]; } else { command._globalEnabled = settings[`cmd-${command.name}`]; @@ -211,7 +232,9 @@ class SequelizeProvider extends SettingProvider { setupGuildGroup(guild, group, settings) { if (typeof settings[`grp-${group.id}`] === 'undefined') return; if (guild) { - if (!guild._groupsEnabled) guild._groupsEnabled = {}; + if (!guild._groupsEnabled) { + guild._groupsEnabled = {}; + } guild._groupsEnabled[group.id] = settings[`grp-${group.id}`]; } else { group._globalEnabled = settings[`grp-${group.id}`]; diff --git a/structures/Command.js b/structures/Command.js index 9c81f5fa..5b4e539d 100644 --- a/structures/Command.js +++ b/structures/Command.js @@ -7,33 +7,29 @@ class XiaoCommand extends Command { this.ownerOnly = info.ownerOnly; this.nsfw = info.nsfw; this.clientPermissions = info.clientPermissions; - this.allowStaff = info.allowStaff; this.userPermissions = info.userPermissions; } hasPermission(msg) { - if (this.ownerOnly) { - if (!this.client.isOwner(msg.author)) return 'This Command can only be used by the bot owner.'; + if (this.ownerOnly && !this.client.isOwner(msg.author)) { + return 'This Command can only be used by the bot owner.'; } - if (this.nsfw) { - if (!msg.channel.nsfw) return 'This Command can only be used in NSFW Channels.'; + if (this.nsfw && !msg.channel.nsfw) { + return 'This Command can only be used in NSFW Channels.'; } if (msg.channel.type !== 'dm') { if (this.clientPermissions) { for (const permission of this.clientPermissions) { - if (!msg.channel.permissionsFor(this.client.user).has(permission)) + if (!msg.channel.permissionsFor(this.client.user).has(permission)) { return `This Command requires the \`${permission}\` Permission.`; + } } } - const staffRole = msg.guild.settings.get('staffRole'); - if (staffRole && this.allowStaff) { - if (!msg.member.roles.has(staffRole)) - return `This Command can only be used by the \`${msg.guild.roles.get(staffRole).name}\` role.`; - } - if (this.userPermissions && (this.allowStaff ? !msg.member.roles.has(staffRole) : true)) { + if (this.userPermissions) { for (const permission of this.userPermissions) { - if (!msg.channel.permissionsFor(msg.author).has(permission)) + if (!msg.channel.permissionsFor(msg.author).has(permission)) { return `You do not have the \`${permission}\` Permission.`; + } } } } diff --git a/structures/CommandoClient.js b/structures/CommandoClient.js index d2671897..9245950e 100644 --- a/structures/CommandoClient.js +++ b/structures/CommandoClient.js @@ -4,6 +4,7 @@ const Database = require('./PostgreSQL'); class CommandoClient extends Client { constructor(options) { super(options); + this.database = Database.db; Database.start(); diff --git a/structures/PostgreSQL.js b/structures/PostgreSQL.js index 56e421a3..d3659f5e 100644 --- a/structures/PostgreSQL.js +++ b/structures/PostgreSQL.js @@ -9,14 +9,14 @@ class Database { static start() { database.authenticate() - .then(() => console.log('[Database] Connection has been established successfully.')) - .then(() => console.log('[Database] Synchronizing...')) + .then(() => console.log('[DATABASE] Connection has been established successfully.')) + .then(() => console.log('[DATABASE] Synchronizing...')) .then(() => database.sync() - .then(() => console.log('[Database] Synchronizing complete!')) - .catch(err => console.error(`[Database] Error synchronizing: ${err}`)) + .then(() => console.log('[DATABASE] Synchronizing complete!')) + .catch(err => console.error(`[DATABASE] Error synchronizing: ${err}`)) ) - .then(() => console.log('[Database] Ready!')) - .catch(err => console.error(`[Database] Unable to connect: ${err}`)); + .then(() => console.log('[DATABASE] Ready!')) + .catch(err => console.error(`[DATABASE] Unable to connect: ${err}`)); } } diff --git a/structures/Stats.js b/structures/Stats.js index 778213e4..403e2977 100644 --- a/structures/Stats.js +++ b/structures/Stats.js @@ -2,21 +2,28 @@ const snekfetch = require('snekfetch'); const { CARBON_KEY, DBOTS_KEY } = process.env; class Stats { - static dBots(server_count, id) { + static dBots(count, id) { snekfetch .post(`https://bots.discord.pw/api/bots/${id}/stats`) - .set({ Authorization: DBOTS_KEY }) - .send({ server_count }) - .then(() => console.log('[Carbon] Successfully posted to Carbon.')) - .catch(err => console.error(`[Carbon] Failed to post to Carbon. ${err}`)); + .set({ + Authorization: DBOTS_KEY + }) + .send({ + server_count: count + }) + .then(() => console.log('[CARBON] Successfully posted to Carbon.')) + .catch(err => console.error(`[CARBON] Failed to post to Carbon. ${err}`)); } - static carbon(servercount) { + static carbon(count) { snekfetch .post('https://www.carbonitex.net/discord/data/botdata.php') - .send({ key: CARBON_KEY, servercount }) - .then(() => console.log('[DBots] Successfully posted to DBots.')) - .catch(err => console.error(`[DBots] Failed to post to DBots. ${err}`)); + .send({ + key: CARBON_KEY, + servercount: count + }) + .then(() => console.log('[DBOTS] Successfully posted to Discord Bots.')) + .catch(err => console.error(`[DBOTS] Failed to post to Discord Bots. ${err}`)); } } diff --git a/structures/Util.js b/structures/Util.js new file mode 100644 index 00000000..932c634a --- /dev/null +++ b/structures/Util.js @@ -0,0 +1,13 @@ +class Util { + static cleanXML(str) { + return str + .replace(/(
)/g, '') + .replace(/(')/g, '\'') + .replace(/(—)/g, '—') + .replace(/("|")/g, '"') + .replace(/(&)/g, '&') + .replace(/(\[i\]|\[\/i\])/g, '*'); + } +} + +module.exports = Util;