diff --git a/main.js b/main.js index 400b19c91..125b1af5e 100644 --- a/main.js +++ b/main.js @@ -40,6 +40,8 @@ process.on('unhandledRejection', (err) => { const nexusOptions = { user_key: process.env.NEXUSSTATS_USER_KEY || undefined, user_secret: process.env.NEXUSSTATS_USER_SECRET || undefined, + api_url: process.env.NEXUS_API_OVERRIDE || undefined, + auth_url: process.env.NEXUS_AUTH_OVERRIDE || undefined, ignore_limiter: true, }; diff --git a/package.json b/package.json index 0e7d24d80..6ec67cb91 100644 --- a/package.json +++ b/package.json @@ -38,7 +38,7 @@ "pad-left": "^2.1.0", "ping": "^0.2.2", "raven": "^2.1.2", - "request-promise": "^4.2.1", + "request-promise": "^4.2.2", "right-pad": "^1.0.1", "sql-template-strings": "^2.2.2", "warframe-location-query": "0.0.3", @@ -53,7 +53,7 @@ "eslint-plugin-jsx-a11y": "^2.2.3", "eslint-plugin-react": "^6.6.0", "ink-docstrap": "^1.3.0", - "jsdoc": "^3.5.4", + "jsdoc": "^3.5.5", "mocha": "^3.5.3", "rewire": "^2.5.2", "sinon": "^1.17.6", diff --git a/src/CommandHandler.js b/src/CommandHandler.js index 27cb81437..fb9dd6e9a 100644 --- a/src/CommandHandler.js +++ b/src/CommandHandler.js @@ -71,7 +71,7 @@ class CommandHandler { return null; } }) - .filter(c => c !== null); + .filter(c => c !== null); this.commands = commands.filter(c => !c.isInline); @@ -94,16 +94,16 @@ class CommandHandler { async handleCommand(message) { let content = message.content; const botping = `@${message.guild ? - message.guild.members.get(this.bot.client.user.id).displayName : - this.bot.client.user.username}`; + message.guild.members.get(this.bot.client.user.id).displayName : + this.bot.client.user.username}`; const botPingId = `<@${this.bot.client.user.id}>`; - const { prefix, allowCustom, allowInline } = await this.bot.settings + const ctx = await this.bot.settings .getCommandContext(message.channel); let checkOnlyInlines = false; - const notStartWithPrefix = !content.startsWith(prefix) + const notStartWithPrefix = !content.startsWith(ctx.prefix) && !content.startsWith(botping) && !content.startsWith(botPingId); if (notStartWithPrefix) { - if (allowInline && this.inlineCommands.length > 0) { + if (ctx.allowInline && this.inlineCommands.length > 0) { checkOnlyInlines = true; } else { return; @@ -113,14 +113,14 @@ class CommandHandler { let commands = []; if (checkOnlyInlines) { commands = this.inlineCommands; - } else if (allowCustom) { + } else if (ctx.allowCustom) { commands = this.commands.concat(this.customCommands); } else { commands = this.commands; } - if (content.startsWith(prefix)) { - content = content.replace(prefix, ''); + if (content.startsWith(ctx.prefix)) { + content = content.replace(ctx.prefix, ''); } if (content.startsWith(botping)) { content = content.replace(new RegExp(`${botping}\\s+`, 'i'), ''); @@ -135,13 +135,14 @@ class CommandHandler { commands.forEach(async (command) => { if (command.regex.test(content) && !done) { const canAct = await this.checkCanAct(command, messageWithStrippedContent, - allowCustom, allowInline); + ctx.allowCustom, ctx.allowInline); if (canAct) { this.logger.debug(`Matched ${command.id}`); - const status = await command.run(messageWithStrippedContent); - const canReact = message && (message.channel.type === 'dm' || + ctx.message = messageWithStrippedContent; + const status = await command.run(messageWithStrippedContent, ctx); + const canReact = (message.channel.type === 'dm' || (message.channel.permissionsFor(this.bot.client.user.id) - .has(['ADD_REACTIONS', 'VIEW_CHANNEL', 'SEND_MESSAGES', 'EMBED_LINKS']))) && !command.isInline; + .has(['ADD_REACTIONS', 'VIEW_CHANNEL', 'SEND_MESSAGES', 'EMBED_LINKS']))) && !command.isInline; switch (status) { case this.statuses.SUCCESS: if (canReact) { @@ -156,7 +157,6 @@ class CommandHandler { case this.statuses.NO_ACCESS: default: break; - } done = true; } diff --git a/src/Tracker.js b/src/Tracker.js index f67b5c1a7..dba60daf9 100644 --- a/src/Tracker.js +++ b/src/Tracker.js @@ -3,24 +3,24 @@ const request = require('request-promise'); const config = { - updateInterval: process.env.TRACKERS_UPDATE_INTERVAL || 3660000, - carbon: { - token: process.env.DISCORD_CARBON_TOKEN, - }, - botsDiscordPw: { - token: process.env.DISCORD_BOTS_WEB_TOKEN, - id: process.env.DISCORD_BOTS_WEB_USER, - }, - cachet: { - metricId: process.env.CACHET_BOT_METRIC_ID, - host: process.env.CACHET_HOST, - token: process.env.CACHET_TOKEN, - heartbeat: process.env.CACHET_HEARTBEAT || 600000, - }, - botsDiscordOrg: { - token: process.env.DISCORD_BOTS_ORG_TOKEN, - id: process.env.DISCORD_BOTS_ORG_ID - }, + updateInterval: process.env.TRACKERS_UPDATE_INTERVAL || 3660000, + carbon: { + token: process.env.DISCORD_CARBON_TOKEN, + }, + botsDiscordPw: { + token: process.env.DISCORD_BOTS_WEB_TOKEN, + id: process.env.DISCORD_BOTS_WEB_USER, + }, + cachet: { + metricId: process.env.CACHET_BOT_METRIC_ID, + host: process.env.CACHET_HOST, + token: process.env.CACHET_TOKEN, + heartbeat: process.env.CACHET_HEARTBEAT || 600000, + }, + botsDiscordOrg: { + token: process.env.DISCORD_BOTS_ORG_TOKEN, + id: process.env.DISCORD_BOTS_ORG_ID, + }, }; /** @@ -116,8 +116,8 @@ class Tracker { this.logger.error(`Error updating bots.discord.pw. Token: ${config.botsDiscordPw.token} | User: ${config.botsDiscordPw.id} | Error Code: ${err.statusCode}`); } } - } - + } + /** * Updates discordbots.org if the corresponding token is provided * @param {number} guildsLen number of guilds that this bot is present on diff --git a/src/bot.js b/src/bot.js index cd300b0a6..a0ac7a901 100644 --- a/src/bot.js +++ b/src/bot.js @@ -121,6 +121,12 @@ class Genesis { this.channelTimeout = 300000; + /** + * Discord.js API + * @type {Discord} + */ + this.discord = Discord; + /** * The logger object * @type {Logger} @@ -375,7 +381,7 @@ class Genesis { .replace(/\$username/ig, guildMember.displayName) .replace(/\$usermention/ig, guildMember) .replace(/\$timestamp/ig, new Date().toLocaleString()), - false, false); + false, false); } }); } diff --git a/src/commands/Builds/AddBuild.js b/src/commands/Builds/AddBuild.js index e4574a5ba..e8276fe71 100644 --- a/src/commands/Builds/AddBuild.js +++ b/src/commands/Builds/AddBuild.js @@ -26,7 +26,7 @@ class AddBuild extends Command { const matches = message.strippedContent.match(this.regex)[1]; const params = (matches || '').split('|'); if (params.length < 1) { - // let them know there's not enough params + // let them know there's not enough params return this.messageManager.statuses.FAILURE; } // save params based on order diff --git a/src/commands/Builds/SetField.js b/src/commands/Builds/SetField.js index 285341b85..dabfa8de4 100644 --- a/src/commands/Builds/SetField.js +++ b/src/commands/Builds/SetField.js @@ -36,15 +36,13 @@ class AddBuild extends Command { let image; if (build && (build.owner_id === message.author.id || message.author.id === this.bot.owner)) { if (type === 'all') { - title = params[1]; - body = params[2]; - image = params[3]; + [, title, body, image] = params; } else if (type === 'title') { - title = params[1]; + [, title] = params; } else if (type === 'body') { - body = params[1]; + [, body] = params; } else if (type === 'image') { - image = params[1]; + [, image] = params; } else { return this.failure(message, buildId); } @@ -55,8 +53,10 @@ class AddBuild extends Command { // save params based on order const status = await this.bot.settings.setBuildFields(buildId, { title, body, image }); if (status) { - this.messageManager.embed(message, new BuildEmbed(this.bot, - await this.bot.settings.getBuild(buildId)), true, true); + this.messageManager.embed(message, new BuildEmbed( + this.bot, + await this.bot.settings.getBuild(buildId), + ), true, true); return this.messageManager.statuses.SUCCESS; } return this.failure(message, buildId); diff --git a/src/commands/Core/Help.js b/src/commands/Core/Help.js index 570962dde..e76769779 100644 --- a/src/commands/Core/Help.js +++ b/src/commands/Core/Help.js @@ -37,8 +37,8 @@ class Help extends Command { this.sendCoreEmbed(message, prefix); if (message.channel.type === 'dm' || message.channel - .permissionsFor(message.author) - .has('MANAGE_ROLES_OR_PERMISSIONS')) { + .permissionsFor(message.author) + .has('MANAGE_ROLES_OR_PERMISSIONS')) { this.sendSettingsEmbed(message, prefix); } this.sendWorldStateEmbed(message, prefix); @@ -52,56 +52,56 @@ class Help extends Command { sendHelpEmbed(message, prefix) { const commands = this.commandHandler.commands.filter(c => - !c.ownerOnly && + !c.ownerOnly && !/core/ig.test(c.id) && !(/warframe/ig.test(c.id)) && !/settings/ig.test(c.id)) - .map(c => c.usages.map(u => ({ - name: `${prefix}${c.call} ${u.parameters.map(p => `<${p}>`).join(u.separator ? u.separator : ' ')}`, - value: u.description, - inline: false, - } + .map(c => c.usages.map(u => ({ + name: `${prefix}${c.call} ${u.parameters.map(p => `<${p}>`).join(u.separator ? u.separator : ' ')}`, + value: u.description, + inline: false, + } ))); this.sendEmbedForCommands(message, commands, 'Help!', 0x00ff00); } sendOwnerOnlyEmbed(message, prefix) { const ownerCommands = this.commandHandler.commands.filter(c => c.ownerOnly) - .map(c => c.usages.map(u => ({ - name: `${prefix}${c.call} ${u.parameters.map(p => `<${p}>`).join(u.separator ? u.separator : ' ')}`, - value: u.description, - inline: false, - }))); + .map(c => c.usages.map(u => ({ + name: `${prefix}${c.call} ${u.parameters.map(p => `<${p}>`).join(u.separator ? u.separator : ' ')}`, + value: u.description, + inline: false, + }))); this.sendEmbedForCommands(message, ownerCommands, 'Owner Only', 0xff0000); } sendCoreEmbed(message, prefix) { const commands = this.commandHandler.commands.filter(c => !c.ownerOnly && /core/ig.test(c.id)) - .map(c => c.usages.map(u => ({ - name: `${prefix}${c.call} ${u.parameters.map(p => `<${p}>`).join(u.separator ? u.separator : ' ')}`, - value: u.description, - inline: false, - }))); + .map(c => c.usages.map(u => ({ + name: `${prefix}${c.call} ${u.parameters.map(p => `<${p}>`).join(u.separator ? u.separator : ' ')}`, + value: u.description, + inline: false, + }))); this.sendEmbedForCommands(message, commands, 'Core Commands', 0x000000); } sendWorldStateEmbed(message, prefix) { const commands = this.commandHandler.commands.filter(c => !c.ownerOnly && /warframe.worldstate/ig.test(c.id)) - .map(c => c.usages.map(u => ({ - name: `${prefix}${c.call} ${u.parameters.map(p => `<${p}>`).join(u.separator ? u.separator : ' ')}`, - value: u.description, - inline: false, - }))); + .map(c => c.usages.map(u => ({ + name: `${prefix}${c.call} ${u.parameters.map(p => `<${p}>`).join(u.separator ? u.separator : ' ')}`, + value: u.description, + inline: false, + }))); this.sendEmbedForCommands(message, commands, 'Warframe Commands - Worldstate', 0x4068BD); } sendWarframeEmbed(message, prefix) { const commands = this.commandHandler.commands.filter(c => !c.ownerOnly && /warframe.(?!worldstate)/ig.test(c.id)) - .map(c => c.usages.map(u => ({ - name: `${prefix}${c.call} ${u.parameters.map(p => `<${p}>`).join(u.separator ? u.separator : ' ')}`, - value: u.description, - inline: false, - }))); + .map(c => c.usages.map(u => ({ + name: `${prefix}${c.call} ${u.parameters.map(p => `<${p}>`).join(u.separator ? u.separator : ' ')}`, + value: u.description, + inline: false, + }))); this.sendEmbedForCommands(message, commands, 'Warframe Commands - Utility', 0x4068BD); } diff --git a/src/commands/Core/Ping.js b/src/commands/Core/Ping.js index ba462240b..e2de4db33 100644 --- a/src/commands/Core/Ping.js +++ b/src/commands/Core/Ping.js @@ -77,7 +77,8 @@ class Ping extends Command { title: 'PONG', type: 'rich', fields: [ - { name: `Response time (shard ${this.bot.shardId + 1} of ${this.bot.shardCount})`, + { + name: `Response time (shard ${this.bot.shardId + 1} of ${this.bot.shardCount})`, value: `${afterSend - now}ms`, }, ...results, diff --git a/src/commands/Ondemand/Armor.js b/src/commands/Ondemand/Armor.js index 1f70253f3..640c1cff8 100644 --- a/src/commands/Ondemand/Armor.js +++ b/src/commands/Ondemand/Armor.js @@ -78,8 +78,10 @@ class Armor extends Command { armorString = this.armorSimple(parseInt(armor, 10)); } else { this.logger.debug('Entered 3-param armor'); - armorString = this.armorFull(parseFloat(armor), parseFloat(baseLevel), - parseFloat(currentLevel)); + armorString = this.armorFull( + parseFloat(armor), parseFloat(baseLevel), + parseFloat(currentLevel), + ); } const embed = { diff --git a/src/commands/Ondemand/EarthCycle.js b/src/commands/Ondemand/EarthCycle.js index 61c30a1b0..990ea6e91 100644 --- a/src/commands/Ondemand/EarthCycle.js +++ b/src/commands/Ondemand/EarthCycle.js @@ -22,8 +22,9 @@ class EarthCycle extends Command { * @returns {string} success status */ async run(message) { - const ws = await this.bot.caches.pc.getDataJson() - await this.messageManager.embed(message, new EarthCycleEmbed(this.bot, ws.earthCycle), true, true); + const ws = await this.bot.caches.pc.getDataJson(); + const embed = new EarthCycleEmbed(this.bot, ws.earthCycle); + await this.messageManager.embed(message, embed, true, true); return this.messageManager.statuses.SUCCESS; } } diff --git a/src/commands/Ondemand/Efficiency.js b/src/commands/Ondemand/Efficiency.js index aa27972c0..0ea6900b5 100644 --- a/src/commands/Ondemand/Efficiency.js +++ b/src/commands/Ondemand/Efficiency.js @@ -22,9 +22,11 @@ class Efficiency extends Command { * @returns {string} success status */ async run(message) { - this.messageManager.sendFile(message, - `Operator ${message.author.toString()}, the efficiency table, at your request.`, - this.efficiencyChart, 'efficiency.png', true); + this.messageManager.sendFile( + message, + `Operator ${message.author.toString()}, the efficiency table, at your request.`, + this.efficiencyChart, 'efficiency.png', true, + ); return this.messageManager.statuses.SUCCESS; } } diff --git a/src/commands/Ondemand/Mod.js b/src/commands/Ondemand/Mod.js index 09cf792b3..79821d41d 100644 --- a/src/commands/Ondemand/Mod.js +++ b/src/commands/Ondemand/Mod.js @@ -32,7 +32,7 @@ class Mod extends Command { return this.messageManager.statuses.FAILURE; } const searchJson = await warframe.getSearchList({ query, limit: 1 }); - const id = searchJson.items[0].id; + const { item: { id } } = searchJson.items; const detailsJson = await warframe.getArticleDetails({ ids: [id] }); let thumbUrl = detailsJson.items[`${id}`].thumbnail; thumbUrl = thumbUrl ? thumbUrl.replace(/\/revision\/.*/, '') : 'https://i.imgur.com/11VCxbq.jpg'; diff --git a/src/commands/Ondemand/Pricecheck.js b/src/commands/Ondemand/Pricecheck.js index 839615c0b..fb56889cd 100644 --- a/src/commands/Ondemand/Pricecheck.js +++ b/src/commands/Ondemand/Pricecheck.js @@ -37,7 +37,7 @@ class PriceCheck extends Command { const sentMessage = await message.channel.send('', { embed: inProgressEmbed }); const result = await this.bot.nexusQuerier.priceCheckQueryAttachment(item); const embed = new PriceCheckEmbed(this.bot, result, item); - sentMessage.edit('', { embed }); + sentMessage.edit('', { embed }); return embed.color === 0xff55ff ? this.messageManager.statuses.FAILURE : this.messageManager.statuses.SUCCESS; } catch (error) { diff --git a/src/commands/Ondemand/Raid.js b/src/commands/Ondemand/Raid.js index 3e6fb34ac..ae00cca8b 100644 --- a/src/commands/Ondemand/Raid.js +++ b/src/commands/Ondemand/Raid.js @@ -40,8 +40,10 @@ class Raid extends Command { const platform = await this.bot.settings.getChannelSetting(message.channel, 'platform'); const url = encodeURI(`https://api.trials.wf/api/player/${platform.toLowerCase()}/${query}/completed`); const data = await (new Fetcher(url)).httpGet(); - this.messageManager.embed(message, new RaidEmbed(this.bot, - data, query, platform.toLowerCase()), true, true); + this.messageManager.embed(message, new RaidEmbed( + this.bot, + data, query, platform.toLowerCase(), + ), true, true); return this.messageManager.statuses.SUCCESS; } } diff --git a/src/commands/Ondemand/WhereIs.js b/src/commands/Ondemand/WhereIs.js index 6b82117a8..048d8f53c 100644 --- a/src/commands/Ondemand/WhereIs.js +++ b/src/commands/Ondemand/WhereIs.js @@ -81,8 +81,10 @@ class Whereis extends Command { .reduce((a, b) => (a.length > b.length ? a : b)) : ''; query = toTitleCase(query.trim()); createGroupedArray(results, 60).forEach((group, index) => { - const embed = new WhereisEmbed(this.bot, createGroupedArray(group, 4), - query, longestName.length, longestRelic.length); + const embed = new WhereisEmbed( + this.bot, createGroupedArray(group, 4), + query, longestName.length, longestRelic.length, + ); if (index === 0) { sentMessage.edit('', { embed }); } else { diff --git a/src/commands/Owner/Servers.js b/src/commands/Owner/Servers.js index 116b857b2..8aaea37d8 100644 --- a/src/commands/Owner/Servers.js +++ b/src/commands/Owner/Servers.js @@ -27,7 +27,7 @@ class Servers extends Command { fileContents.push(`"${guild.name}","${guild.owner.user.username}#${guild.owner.user.discriminator}","${guild.id}"`); }); - await this.messageManager.sendFileToAuthor(message, new Buffer(fileContents.join('\n'), 'ascii'), 'servers.csv', true); + await this.messageManager.sendFileToAuthor(message, Buffer.from(fileContents.join('\n'), 'ascii'), 'servers.csv', true); return this.messageManager.statuses.SUCCESS; } } diff --git a/src/commands/Roles/RemoveRole.js b/src/commands/Roles/RemoveRole.js index 1940d7cbd..c93e92f95 100644 --- a/src/commands/Roles/RemoveRole.js +++ b/src/commands/Roles/RemoveRole.js @@ -55,8 +55,8 @@ class RemoveRole extends Command { const filteredRoles = roles.filter(storedRole => role.id === storedRole.id); if (filteredRoles.length > 0) { this.removeAndCommitRoles(message, roles - .filter(storedRole => filteredRoles[0].id !== storedRole.id) - .map(unSelectedRole => unSelectedRole.id), filteredRoles[0]); + .filter(storedRole => filteredRoles[0].id !== storedRole.id) + .map(unSelectedRole => unSelectedRole.id), filteredRoles[0]); return this.messageManager.statuses.SUCCESS; } await this.sendRoleNotAvailable(message); diff --git a/src/commands/Roles/Roles.js b/src/commands/Roles/Roles.js index 009e78033..7cff75b71 100644 --- a/src/commands/Roles/Roles.js +++ b/src/commands/Roles/Roles.js @@ -35,15 +35,19 @@ class Roles extends Command { const groupedRoles = createGroupedArray(roles, 20); const metaGroups = createGroupedArray(groupedRoles, 4); metaGroups.forEach((metaGroup) => { - this.messageManager.embed(message, + this.messageManager.embed( + message, new RolesEmbed(this.bot, metaGroup, prefix, longest.length), - true, true); + true, true, + ); }); return this.messageManager.statuses.SUCCESS; } - await this.messageManager.embed(message, - new RolesEmbed(this.bot, [], prefix, 0), - true, true); + await this.messageManager.embed( + message, + new RolesEmbed(this.bot, [], prefix, 0), + true, true, + ); return this.messageManager.statuses.FAILURE; } } diff --git a/src/commands/Rooms/Create.js b/src/commands/Rooms/Create.js index 7506a7b79..725461231 100644 --- a/src/commands/Rooms/Create.js +++ b/src/commands/Rooms/Create.js @@ -4,7 +4,7 @@ const Command = require('../../Command.js'); const useable = ['room', 'raid', 'team']; -const vulgar = []; +const vulgar = ['n[i!1]gg[e3]r', 'n[i!1]gg[ua]', 'h[i!1]tl[e3]r', 'n[a@]z[i!1]', '[©ck]un[t7]', 'fu[©c]k', '[©c]umm', 'f[a@4]g', 'd[i!1]ck', 'c[o0]ck', 'boner', 'sperm', 'gay', 'gooch', 'jizz', 'pussy', 'penis', 'r[i!1]mjob', 'schlong', 'slut', 'wank', 'whore', 'sh[i!1]t', 'sex', 'fuk', 'heil', 'porn', 'suck', 'rape', 'scrotum']; /** * Gets the list of users from the mentions in the call @@ -27,12 +27,12 @@ function getUsersForCall(message) { } let authorIncluded = false; users.forEach((user) => { - if (user.id === message.author.id) { - authorIncluded = true; - } + if (user.id === message.author.id) { + authorIncluded = true; + } }); if (!authorIncluded) { - users.push(message.author); + users.push(message.author); } return users; } @@ -46,7 +46,7 @@ class Create extends Command { */ constructor(bot) { super(bot, 'rooms.create', 'create', 'Create a temporary room.'); - this.regex = new RegExp(`^${this.call}\\s?(room|raid|team)?(\\w|-)?(?:\-n(.+))?`, 'i'); + this.regex = new RegExp(`^${this.call}\\s?(room|raid|team)?(\\w|-)?(?:-n(.+))?`, 'i'); this.usages = [ { description: 'Display instructions for creating temporary rooms', parameters: [] }, @@ -58,7 +58,7 @@ class Create extends Command { description: 'Create temporary text and voice channels for the calling user and any mentioned users/roles.', parameters: ['room | raid | team', 'users and/or role'], }, - { + { description: 'Create temporary text and voice channels for the calling user and any mentioned users/roles, with a custom name', parameters: ['room | raid | team', 'users and/or role', '-n name'], }, @@ -74,14 +74,14 @@ class Create extends Command { * @returns {string} success status */ async run(message) { - const channelNameRegex = new RegExp('-n\\s+(.+)', 'ig'); + const channelNameRegex = new RegExp('-n\\s+(.+)', 'ig'); const type = message.strippedContent.match(this.regex)[1]; - const namingResults = message.strippedContent.match(channelNameRegex); + const namingResults = message.strippedContent.match(channelNameRegex); let optName = (namingResults ? namingResults[0] : '') - .replace('-n ', ''); - if (vulgar.length) { - optName = optName.replace(new RegExp(`(${vulgar.join('|')})`, 'ig'), ''); //remove vulgar - } + .replace('-n ', ''); + if (vulgar.length) { + optName = optName.replace(new RegExp(`(${vulgar.join('|')})`, 'ig'), ''); // remove vulgar + } const createPrivateChannelAllowed = parseInt(await this.bot.settings.getChannelSetting(message.channel, 'createPrivateChannel'), 10); if (createPrivateChannelAllowed) { if (type) { @@ -113,7 +113,7 @@ class Create extends Command { } let msg = ''; if (users.length > 10) { - // notify caller that there's too many users if role is more than 10 people. + // notify caller that there's too many users if role is more than 10 people. msg = 'you are trying to send an invite to too many people, please keep the total number under 10'; } else { msg = 'that room already exists.'; @@ -122,10 +122,12 @@ class Create extends Command { return this.messageManager.statuses.FAILURE; } } else { - this.messageManager.reply(message, '```haskell\n' + + this.messageManager.reply( + message, '```haskell\n' + 'Sorry, you need to specify what you want to create. Right now these are available to create:' + `\n* ${useable.join('\n* ')}\n\`\`\`` - , true, false); + , true, false, + ); return this.messageManager.statuses.FAILURE; } } @@ -165,17 +167,17 @@ class Create extends Command { // create voice channel perms overwritePromises.push(voiceChannel.overwritePermissions(everyoneId, { CONNECT: false, - VIEW_CHANNEL: false, + VIEW_CHANNEL: false, })); // allow bot to manage channels overwritePromises.push(textChannel.overwritePermissions(this.bot.client.user.id, { VIEW_CHANNEL: true, - SEND_MESSAGES: true, + SEND_MESSAGES: true, })); overwritePromises.push(voiceChannel.overwritePermissions(this.bot.client.user.id, { VIEW_CHANNEL: true, - CREATE_INSTANT_INVITE: true, + CREATE_INSTANT_INVITE: true, CONNECT: true, SPEAK: true, MUTE_MEMBERS: true, @@ -194,7 +196,7 @@ class Create extends Command { })); overwritePromises.push(voiceChannel.overwritePermissions(user.id, { VIEW_CHANNEL: true, - CONNECT: true, + CONNECT: true, SPEAK: true, USE_VAD: true, })); diff --git a/src/commands/Rooms/RoomCreation.js b/src/commands/Rooms/RoomCreation.js index 8d8733249..d3950507a 100644 --- a/src/commands/Rooms/RoomCreation.js +++ b/src/commands/Rooms/RoomCreation.js @@ -8,7 +8,7 @@ class AllowPrivateRoom extends Command { this.usages = [ { description: 'Change if the bot is allowed to create private channels', parameters: ['private rooms enabled'] }, ]; - this.regex = new RegExp('^allow\\s?private\\s?rooms?\\s?(on|off)?$', 'i'); + this.regex = new RegExp(`^${this.call}\\s?(on|off)?$`, 'i'); this.requiresAuth = true; this.allowDM = false; } @@ -37,11 +37,7 @@ class AllowPrivateRoom extends Command { return this.messageManager.statuses.FAILURE; } enable = enable.trim(); - let enableResponse = false; - if (enable === 'on') { - enableResponse = true; - } - await this.bot.settings.setGuildSetting(message.guild, 'createPrivateChannel', enableResponse); + await this.bot.settings.setGuildSetting(message.guild, 'createPrivateChannel', enable === 'on'); this.messageManager.notifySettingsChange(message, true, true); return this.messageManager.statuses.SUCCESS; } diff --git a/src/commands/Settings/AllowCustomCommands.js b/src/commands/Settings/AllowCustomCommands.js index 2d9b62f35..9ec6caa50 100644 --- a/src/commands/Settings/AllowCustomCommands.js +++ b/src/commands/Settings/AllowCustomCommands.js @@ -49,12 +49,13 @@ class AllowCustomCommands extends Command { * @returns {Array} channel ids to enable commands in */ getChannel(channelsParam, message) { - let channel = message.channel; + let { channel } = message; if (typeof channelsParam === 'string') { // handle it for strings if (channelsParam !== 'here') { channel = this.bot.client.channels.get(channelsParam.trim()); } else if (channelsParam === 'here') { + // eslint-disable-next-line prefer-destructuring channel = message.channel; } } diff --git a/src/commands/Settings/AllowInlineCommands.js b/src/commands/Settings/AllowInlineCommands.js index c4b09aa37..04436cfc6 100644 --- a/src/commands/Settings/AllowInlineCommands.js +++ b/src/commands/Settings/AllowInlineCommands.js @@ -49,12 +49,13 @@ class AllowInlineCommands extends Command { * @returns {Array} channel ids to enable commands in */ getChannel(channelsParam, message) { - let channel = message.channel; + let { channel } = message; if (typeof channelsParam === 'string') { // handle it for strings if (channelsParam !== 'here') { channel = this.bot.client.channels.get(channelsParam.trim()); } else if (channelsParam === 'here') { + // eslint-disable-next-line prefer-destructuring channel = message.channel; } } diff --git a/src/commands/Settings/DeleteAfterRespond.js b/src/commands/Settings/DeleteAfterRespond.js index d2a257c0e..d0801e887 100644 --- a/src/commands/Settings/DeleteAfterRespond.js +++ b/src/commands/Settings/DeleteAfterRespond.js @@ -76,12 +76,13 @@ class RespondToSettings extends Command { * @returns {Array} channel ids to enable commands in */ getChannel(channelsParam, message) { - let channel = message.channel; + let { channel } = message; if (typeof channelsParam === 'string') { // handle it for strings if (channelsParam !== 'here') { channel = this.bot.client.channels.get(channelsParam.trim()); } else if (channelsParam === 'here') { + // eslint-disable-next-line prefer-destructuring channel = message.channel; } } diff --git a/src/commands/Settings/Disable.js b/src/commands/Settings/Disable.js index 4cb6f577a..582019ab1 100644 --- a/src/commands/Settings/Disable.js +++ b/src/commands/Settings/Disable.js @@ -10,8 +10,10 @@ class Disable extends Command { this.usages = [ { description: 'Disable a command for a role in a channel or channels', parameters: ['command id> in for )?|here|\\*)(?:\\s+for\\s((?:\\<\\@\\&?)?\\d+(?:\\>)?|\\*))?)?)?`, - 'i'); + this.regex = new RegExp( + `^${this.call}(?:\\s+(\\w*\\.*\\w*\\.*\\w*\\*?)(?:\\s+in\\s+((?:\\<\\#)?\\d+(?:\\>)?|here|\\*)(?:\\s+for\\s((?:\\<\\@\\&?)?\\d+(?:\\>)?|\\*))?)?)?`, + 'i', + ); this.blacklistable = false; this.requiresAuth = true; this.allowDM = false; @@ -29,7 +31,7 @@ class Disable extends Command { if (params[1]) { channels = this.getChannels(message.mentions.channels.length > 0 - ? message.mentions.channels : params[1].trim().replace(/<|>|#/ig, ''), message); + ? message.mentions.channels : params[1].trim().replace(/<|>|#/ig, ''), message); } else { channels = [message.channel]; } @@ -38,8 +40,10 @@ class Disable extends Command { let target = {}; if (params[2] || message.mentions.roles.array().length > 0 || message.mentions.users.array().length > 0) { - target = this.getTarget(params[2], message.mentions ? message.mentions.roles : [], - message.mentions ? message.mentions.users : [], message); + target = this.getTarget( + params[2], message.mentions ? message.mentions.roles : [], + message.mentions ? message.mentions.users : [], message, + ); } else { target = message.guild.roles.find('name', '@everyone'); } @@ -50,10 +54,10 @@ class Disable extends Command { for (const channel of channels) { if (target.type === 'Role') { results.push(this.bot.settings - .setChannelPermissionForRole(channel, target, command, 0)); + .setChannelPermissionForRole(channel, target, command, 0)); } else { results.push(this.bot.settings - .setChannelPermissionForMember(channel, target, command, 0)); + .setChannelPermissionForMember(channel, target, command, 0)); } } } @@ -61,7 +65,7 @@ class Disable extends Command { // notify info embed const infoEmbed = new EnableInfoEmbed(this.bot, 0, [commands, channels, target.toString()]); const respondToSettings = await this.bot.settings - .getChannelSetting(message.channel, 'respond_to_settings'); + .getChannelSetting(message.channel, 'respond_to_settings'); if (respondToSettings) { this.messageManager.embed(message, infoEmbed, true, false); } @@ -121,11 +125,13 @@ class Disable extends Command { */ getTarget(targetParam, roleMentions, userMentions, message) { let target; + const roleMention = roleMentions.first(); + const userMention = userMentions.first(); if (roleMentions.array().length > 0) { - target = roleMentions.array()[0]; + target = roleMention; target.type = 'Role'; } else if (userMentions.array().length > 0) { - target = userMentions.array()[0]; + target = userMention; target.type = 'User'; } else { const userTarget = this.bot.client.users.get(targetParam); diff --git a/src/commands/Settings/Enable.js b/src/commands/Settings/Enable.js index 096bd679e..c65e44159 100644 --- a/src/commands/Settings/Enable.js +++ b/src/commands/Settings/Enable.js @@ -10,8 +10,10 @@ class Enable extends Command { this.usages = [ { description: 'Enable a command for a role in a channel or channels', parameters: ['command id> in for )?|here|\\*)(?:\\s+for\\s((?:\\<\\@\\&?)?\\d+(?:\\>)?|\\*))?)?)?`, - 'i'); + this.regex = new RegExp( + `^${this.call}(?:\\s+(\\w*\\.*\\w*\\.*\\w*\\*?)(?:\\s+in\\s+((?:\\<\\#)?\\d+(?:\\>)?|here|\\*)(?:\\s+for\\s((?:\\<\\@\\&?)?\\d+(?:\\>)?|\\*))?)?)?`, + 'i', + ); this.requiresAuth = true; this.blacklistable = false; this.allowDM = false; @@ -29,7 +31,7 @@ class Enable extends Command { if (params[1]) { channels = this.getChannels(message.mentions.channels.length > 0 - ? message.mentions.channels : params[1].trim().replace(/<|>|#/ig, ''), message); + ? message.mentions.channels : params[1].trim().replace(/<|>|#/ig, ''), message); } else { channels = [message.channel]; } @@ -37,8 +39,10 @@ class Enable extends Command { let target = {}; if (params[2] || message.mentions.roles.array().length > 0 || message.mentions.users.array().length > 0) { - target = this.getTarget(params[2], message.mentions ? message.mentions.roles : [], - message.mentions ? message.mentions.users : [], message); + target = this.getTarget( + params[2], message.mentions ? message.mentions.roles : [], + message.mentions ? message.mentions.users : [], message, + ); } else { target = message.guild.roles.find('name', '@everyone'); } @@ -48,10 +52,10 @@ class Enable extends Command { for (const channel of channels) { if (target.type === 'Role') { results.push(this.bot.settings - .setChannelPermissionForRole(channel, target, command, 1)); + .setChannelPermissionForRole(channel, target, command, 1)); } else { results.push(this.bot.settings - .setChannelPermissionForMember(channel, target, command, 1)); + .setChannelPermissionForMember(channel, target, command, 1)); } } } @@ -59,7 +63,7 @@ class Enable extends Command { // notify info embed const infoEmbed = new EnableInfoEmbed(this.bot, 1, [commands, channels, target.toString()]); const respondToSettings = await this.bot.settings - .getChannelSetting(message.channel, 'respond_to_settings'); + .getChannelSetting(message.channel, 'respond_to_settings'); if (respondToSettings) { this.messageManager.embed(message, infoEmbed, true, false); } @@ -119,11 +123,13 @@ class Enable extends Command { */ getTarget(targetParam, roleMentions, userMentions, message) { let target; + const roleMention = roleMentions.first(); + const userMention = userMentions.first(); if (roleMentions.array().length > 0) { - target = roleMentions.array()[0]; + target = roleMention; target.type = 'Role'; } else if (userMentions.array().length > 0) { - target = userMentions.array()[0]; + target = userMention; target.type = 'User'; } else { const userTarget = this.bot.client.users.get(targetParam); diff --git a/src/commands/Settings/GetCommandIds.js b/src/commands/Settings/GetCommandIds.js index 66b27de3a..20ad08d0e 100644 --- a/src/commands/Settings/GetCommandIds.js +++ b/src/commands/Settings/GetCommandIds.js @@ -30,7 +30,7 @@ class GetCommandIds extends Command { if (message.channel.type !== 'dm') { this.messageManager.reply(message, 'Check your direct messages for more information.', true, true); } - this.messageManager.sendFileToAuthor(message, new Buffer(fileContents.join('\n'), 'ascii'), 'command_ids.csv', true); + this.messageManager.sendFileToAuthor(message, Buffer.from(fileContents.join('\n'), 'ascii'), 'command_ids.csv', true); return this.messageManager.statuses.SUCCESS; } } diff --git a/src/commands/Settings/Language.js b/src/commands/Settings/Language.js index 8429abbec..be14d5d03 100644 --- a/src/commands/Settings/Language.js +++ b/src/commands/Settings/Language.js @@ -45,12 +45,13 @@ class Language extends Command { * @returns {Array} channel ids to enable commands in */ getChannel(channelsParam, message) { - let channel = message.channel; + let { channel } = message; if (typeof channelsParam === 'string') { // handle it for strings if (channelsParam !== 'here') { channel = this.bot.client.channels.get(channelsParam.trim()); } else if (channelsParam === 'here') { + // eslint-disable-next-line prefer-destructuring channel = message.channel; } } diff --git a/src/commands/Settings/Platform.js b/src/commands/Settings/Platform.js index 7b69ddf7c..605b0dd88 100644 --- a/src/commands/Settings/Platform.js +++ b/src/commands/Settings/Platform.js @@ -43,12 +43,13 @@ class Platform extends Command { * @returns {Array} channel ids to enable commands in */ getChannel(channelsParam, message) { - let channel = message.channel; + let { channel } = message; if (typeof channelsParam === 'string') { // handle it for strings if (channelsParam !== 'here') { channel = this.bot.client.channels.get(channelsParam.trim()); } else if (channelsParam === 'here') { + // eslint-disable-next-line prefer-destructuring channel = message.channel; } } diff --git a/src/commands/Settings/Prefix.js b/src/commands/Settings/Prefix.js index 9ccaeeb5a..d4e793e0d 100644 --- a/src/commands/Settings/Prefix.js +++ b/src/commands/Settings/Prefix.js @@ -11,8 +11,10 @@ class Prefix extends Command { this.usages = [ { description: 'Change this channel\'s platform', parameters: ['prefix (up to 3 characters)'] }, ]; - this.regex = new RegExp(`^${this.call}(?:\\s+(.+))?`, - 'i'); + this.regex = new RegExp( + `^${this.call}(?:\\s+(.+))?`, + 'i', + ); this.requiresAuth = true; } diff --git a/src/commands/Settings/RespondToSettings.js b/src/commands/Settings/RespondToSettings.js index fa8d4b90d..2ac55a3b6 100644 --- a/src/commands/Settings/RespondToSettings.js +++ b/src/commands/Settings/RespondToSettings.js @@ -48,12 +48,13 @@ class RespondToSettings extends Command { * @returns {Array} channel ids to enable commands in */ getChannel(channelsParam, message) { - let channel = message.channel; + let { channel } = message; if (typeof channelsParam === 'string') { // handle it for strings if (channelsParam !== 'here') { channel = this.bot.client.channels.get(channelsParam.trim()); } else if (channelsParam === 'here') { + // eslint-disable-next-line prefer-destructuring channel = message.channel; } } diff --git a/src/commands/Settings/SetPing.js b/src/commands/Settings/SetPing.js index 281d1fad9..4363d5aba 100644 --- a/src/commands/Settings/SetPing.js +++ b/src/commands/Settings/SetPing.js @@ -2,8 +2,7 @@ const Command = require('../../Command.js'); const trackFunctions = require('../../TrackFunctions.js'); -const eventTypes = require('../../resources/trackables.json').eventTypes; -const rewardTypes = require('../../resources/trackables.json').rewardTypes; +const { eventTypes, rewardTypes } = require('../../resources/trackables.json'); class SetPing extends Command { constructor(bot) { @@ -29,8 +28,10 @@ class SetPing extends Command { if (!eventsAndItems.length) { const prefix = await this.bot.settings.getChannelSetting(message.channel, 'prefix'); - this.messageManager.embed(message, - trackFunctions.getTrackInstructionEmbed(message, prefix, this.call), true, true); + this.messageManager.embed( + message, + trackFunctions.getTrackInstructionEmbed(message, prefix, this.call), true, true, + ); return this.messageManager.statuses.FAILURE; } const results = []; @@ -51,7 +52,7 @@ class SetPing extends Command { } const prefix = await this.bot.settings.getChannelSetting(message.channel, 'prefix'); this.messageManager.embed(message, trackFunctions - .getTrackInstructionEmbed(message, prefix, this.call), true, true); + .getTrackInstructionEmbed(message, prefix, this.call), true, true); return this.messageManager.statuses.FAILURE; } } diff --git a/src/commands/Settings/Settings.js b/src/commands/Settings/Settings.js index 1d85a4a79..b37e53f56 100644 --- a/src/commands/Settings/Settings.js +++ b/src/commands/Settings/Settings.js @@ -57,8 +57,10 @@ class Settings extends Command { const tokenGroups = createGroupedArray(tokens, 6); // eslint-disable-next-line no-loop-func tokenGroups.forEach((tokenGroup) => { - const embed = new SettingsEmbed(this.bot, channel, - createGroupedArray(tokenGroup, 3), lastIndex); + const embed = new SettingsEmbed( + this.bot, channel, + createGroupedArray(tokenGroup, 3), lastIndex, + ); this.messageManager.embed(message, embed); }); } @@ -83,8 +85,8 @@ class Settings extends Command { // Guild Pings const guildPings = await this.bot.settings.getPingsForGuild(message.guild); const pingParts = guildPings - .filter(obj => obj.thing && obj.text) - .map(obj => `**${obj.thing}**: ${obj.text}`); + .filter(obj => obj.thing && obj.text) + .map(obj => `**${obj.thing}**: ${obj.text}`); if (pingParts.length > 0) { // add them all guildTokens.push('\n**Pings per Item:**'); @@ -96,7 +98,7 @@ class Settings extends Command { // Guild Permissions const guildPermissions = await this.bot.settings.permissionsForGuild(message.guild); const guildParts = guildPermissions - .map(obj => `**${obj.command}** ${obj.isAllowed ? 'allowed' : 'denied'} for ${this.evalAppliesTo(obj.type, obj.appliesToId, message)}`); + .map(obj => `**${obj.command}** ${obj.isAllowed ? 'allowed' : 'denied'} for ${this.evalAppliesTo(obj.type, obj.appliesToId, message)}`); if (guildParts.length > 0) { guildTokens.push('\n**Guild Permissions:**'); @@ -108,8 +110,10 @@ class Settings extends Command { const tokenGroups = createGroupedArray(guildTokens, 30); // eslint-disable-next-line no-loop-func tokenGroups.forEach((tokenGroup) => { - const embed = new SettingsEmbed(this.bot, message.channel, - createGroupedArray(tokenGroup, 15), lastIndex + 1); + const embed = new SettingsEmbed( + this.bot, message.channel, + createGroupedArray(tokenGroup, 15), lastIndex + 1, + ); this.messageManager.embed(message, embed); lastIndex += 1; }); diff --git a/src/commands/Settings/Track.js b/src/commands/Settings/Track.js index 7fd25a2c9..cac5ecb22 100644 --- a/src/commands/Settings/Track.js +++ b/src/commands/Settings/Track.js @@ -4,8 +4,7 @@ const Command = require('../../Command.js'); const trackFunctions = require('../../TrackFunctions.js'); const allTrackables = require('../../resources/trackables.json'); -const eventTypes = allTrackables.eventTypes; -const rewardTypes = allTrackables.rewardTypes; +const { eventTypes, rewardTypes } = allTrackables; /** * Track an event or item @@ -34,9 +33,9 @@ class Track extends Command { return this.failure(message); } trackables.events = trackables.events - .filter((elem, pos) => trackables.events.indexOf(elem) === pos); + .filter((elem, pos) => trackables.events.indexOf(elem) === pos); trackables.items = trackables.items - .filter((elem, pos) => trackables.items.indexOf(elem) === pos); + .filter((elem, pos) => trackables.items.indexOf(elem) === pos); const channelParam = message.strippedContent.match(roomId) ? message.strippedContent.match(roomId)[0].trim().replace(/<|>|#/ig, '') : undefined; const channel = this.getChannel(channelParam, message); @@ -54,8 +53,10 @@ class Track extends Command { async failure(message) { const prefix = await this.bot.settings.getChannelSetting(message.channel, 'prefix'); - this.messageManager.embed(message, - trackFunctions.getTrackInstructionEmbed(message, prefix, this.call), true, true); + this.messageManager.embed( + message, + trackFunctions.getTrackInstructionEmbed(message, prefix, this.call), true, true, + ); return this.messageManager.statuses.FAILURE; } @@ -66,12 +67,13 @@ class Track extends Command { * @returns {Array} channel ids to enable commands in */ getChannel(channelsParam, message) { - let channel = message.channel; + let { channel } = message; if (typeof channelsParam === 'string') { // handle it for strings if (channelsParam !== 'here') { channel = this.bot.client.channels.get(channelsParam.trim()); } else if (channelsParam === 'here') { + // eslint-disable-next-line prefer-destructuring channel = message.channel; } } diff --git a/src/commands/Settings/Untrack.js b/src/commands/Settings/Untrack.js index 4994e09d7..8ff94849e 100644 --- a/src/commands/Settings/Untrack.js +++ b/src/commands/Settings/Untrack.js @@ -3,8 +3,7 @@ const Command = require('../../Command.js'); const trackFunctions = require('../../TrackFunctions.js'); -const eventTypes = require('../../resources/trackables.json').eventTypes; -const rewardTypes = require('../../resources/trackables.json').rewardTypes; +const { eventTypes, rewardTypes } = require('../../resources/trackables.json'); /** * Untrack an event or item @@ -33,9 +32,9 @@ class Untrack extends Command { return this.failure(message); } trackables.events = trackables.events - .filter((elem, pos) => trackables.events.indexOf(elem) === pos); + .filter((elem, pos) => trackables.events.indexOf(elem) === pos); trackables.items = trackables.items - .filter((elem, pos) => trackables.items.indexOf(elem) === pos); + .filter((elem, pos) => trackables.items.indexOf(elem) === pos); const channelParam = message.strippedContent.match(roomId) ? message.strippedContent.match(roomId)[0].trim().replace(/<|>|#/ig, '') : undefined; const channel = this.getChannel(channelParam, message); @@ -54,8 +53,10 @@ class Untrack extends Command { async failure(message) { const prefix = await this.bot.settings.getChannelSetting(message.channel, 'prefix'); - this.messageManager.embed(message, - trackFunctions.getTrackInstructionEmbed(message, prefix, this.call), true, true); + this.messageManager.embed( + message, + trackFunctions.getTrackInstructionEmbed(message, prefix, this.call), true, true, + ); return this.messageManager.statuses.FAILURE; } @@ -66,12 +67,13 @@ class Untrack extends Command { * @returns {Array} channel ids to enable commands in */ getChannel(channelsParam, message) { - let channel = message.channel; + let { channel } = message; if (typeof channelsParam === 'string') { // handle it for strings if (channelsParam !== 'here') { channel = this.bot.client.channels.get(channelsParam.trim()); } else if (channelsParam === 'here') { + // eslint-disable-next-line prefer-destructuring channel = message.channel; } } diff --git a/src/commands/Silly/Corgi.js b/src/commands/Silly/Corgi.js index 1820ba465..a5569d31a 100644 --- a/src/commands/Silly/Corgi.js +++ b/src/commands/Silly/Corgi.js @@ -22,13 +22,12 @@ class Corgi extends Command { * @returns {string} success status */ async run(message) { - const corgi = await corggit(); - if (corgi) { - await this.messageManager.sendMessage(message, corgi.url, true, true); - return this.messageManager.statuses.SUCCESS; - } else { - return this.messageManager.statuses.FAILURE; - } + const corgi = await corggit(); + if (corgi) { + await this.messageManager.sendMessage(message, corgi.url, true, true); + return this.messageManager.statuses.SUCCESS; + } + return this.messageManager.statuses.FAILURE; } } diff --git a/src/commands/Silly/Joke.js b/src/commands/Silly/Joke.js index af384c511..d8c49de13 100644 --- a/src/commands/Silly/Joke.js +++ b/src/commands/Silly/Joke.js @@ -2,53 +2,52 @@ const Command = require('../../Command.js'); -const jokes = ["Saryn. Want some STD?", - "Mesa. Ya'll bow down to the cowgirl.", - "Mag. Plenty of things she can pull.", - "Volt. Doing it fast and clean.", - "Ash. Thrust, thrust, thrust your blade...", - "Loki. Always good and prepared for every occasion.", - "Rhino. Protection first, charging later.", - "Chroma. THIS IS A STRICTLY SCALIE HOUSEHOLD.", - "Valkyr. Ropes, whips, and claws have never been THIS FUN.", - "Oberon. Everybody gets some of him.", - "Frost. Don't mind your frozen balls. Just chill.", - "Vauban. Throws balls around. What else is there to say?", - "Trinity. A dish best eaten from inbetween.", - "Nyx. Domination at its finest.", - "Excalibur. Starting out strong, last one to finish.", - "Inaros. POCKET SAND.", - "Equinox. Can't love yourself better than this.", - "Atlas. Prepare for some fistin'.", - "Nova. Prepare your body to be basted by explosions.", - "Wukong. WHY WON'T YOU FINISH?!", - "Nezha. Not to be confused with Hatsune Miku.", - "Ivara. Tugging on your hips with these dashwires.", - "Opticor, Lanka, Snipetron, Punchthrough. Maximum penetration.", - "Phage. Several strokes and your ultimate weapon's ready to go again.", - "Braton. A first timer's best friend.", - "Vectis. Top quality wood.", - "Grakata. You just need to let out more money shots!", - "Atterax. If normal punching and contact just isn't your type.", - "Prova. Compensation's always an option.", - "Kohm. Don't tell me you didn't read that one a different way. I know.", - "Stug. Every lady would want some of those blobs of life.", - "Prime Gear. Technically normal. They just got the golden shower.", - "Boltor. Perfect for an alternative on 'nailing'."] - -const cleanJokes = ["Prova. Compensation's always an option.","Clem. Clem. Grakaaaataaaaaa.", - "Zephyr. Will take you to the heavens. Does not accept normies. BAKAAAAAWWWWWWWWWWW!", - "Banshee. Prepare your earplugs when you're tuning her out.", - "Excalibur. Cut with the grain.", - "Lacera. Morning, neighbor! Trim your hedges.", - "Sydon. If you think a pitchfork's not enough to start a riot.", - "Latron. Pop some bottlecaps for your brand new trophy.", - "Excalibur Umbra. CRAWLING IN MY SKIN, THESE WOUNDS THEY WILL NOT HEAL-", - "Mios. Just think of it like a visit to the dentist.", - "Excalibur Prime, how's that forma on your face?", - "Vauban. Why did you make the bouncy castle from hell?", - "Badder than a ceramic dagger fight over primed reach", - "You should feel bad about that. Let me rub your face in it to help."] +const jokes = ['Saryn. Want some STD?', + "Mesa. Ya'll bow down to the cowgirl.", + 'Mag. Plenty of things she can pull.', + 'Volt. Doing it fast and clean.', + 'Ash. Thrust, thrust, thrust your blade...', + 'Loki. Always good and prepared for every occasion.', + 'Rhino. Protection first, charging later.', + 'Chroma. THIS IS A STRICTLY SCALIE HOUSEHOLD.', + 'Valkyr. Ropes, whips, and claws have never been THIS FUN.', + 'Oberon. Everybody gets some of him.', + "Frost. Don't mind your frozen balls. Just chill.", + 'Vauban. Throws balls around. What else is there to say?', + 'Trinity. A dish best eaten from inbetween.', + 'Nyx. Domination at its finest.', + 'Excalibur. Starting out strong, last one to finish.', + 'Inaros. POCKET SAND.', + "Equinox. Can't love yourself better than this.", + "Atlas. Prepare for some fistin'.", + 'Nova. Prepare your body to be basted by explosions.', + "Wukong. WHY WON'T YOU FINISH?!", + 'Nezha. Not to be confused with Hatsune Miku.', + 'Ivara. Tugging on your hips with these dashwires.', + 'Opticor, Lanka, Snipetron, Punchthrough. Maximum penetration.', + "Phage. Several strokes and your ultimate weapon's ready to go again.", + "Braton. A first timer's best friend.", + 'Vectis. Top quality wood.', + 'Grakata. You just need to let out more money shots!', + "Atterax. If normal punching and contact just isn't your type.", + "Prova. Compensation's always an option.", + "Kohm. Don't tell me you didn't read that one a different way. I know.", + 'Stug. Every lady would want some of those blobs of life.', + 'Prime Gear. Technically normal. They just got the golden shower.', + "Boltor. Perfect for an alternative on 'nailing'.", + "Prova. Compensation's always an option.", 'Clem. Clem. Grakaaaataaaaaa.', + 'Zephyr. Will take you to the heavens. Does not accept normies. BAKAAAAAWWWWWWWWWWW!', + "Banshee. Prepare your earplugs when you're tuning her out.", + 'Excalibur. Cut with the grain.', + 'Lacera. Morning, neighbor! Trim your hedges.', + "Sydon. If you think a pitchfork's not enough to start a riot.", + 'Latron. Pop some bottlecaps for your brand new trophy.', + 'Excalibur Umbra. CRAWLING IN MY SKIN, THESE WOUNDS THEY WILL NOT HEAL-', + 'Mios. Just think of it like a visit to the dentist.', + "Excalibur Prime, how's that forma on your face?", + 'Vauban. Why did you make the bouncy castle from hell?', + 'Badder than a ceramic dagger fight over primed reach', + 'You should feel bad about that. Let me rub your face in it to help.']; /** * Tell a joke @@ -69,7 +68,7 @@ class Jokes extends Command { * @returns {string} success status */ async run(message) { - this.messageManager.sendMessage(message, `\`\`\`haskell\n${cleanJokes[Math.floor(Math.random()*cleanJokes.length)]}\n\`\`\``, true, true); + this.messageManager.sendMessage(message, `\`\`\`haskell\n${jokes[Math.floor(Math.random() * jokes.length)]}\n\`\`\``, true, true); return this.messageManager.statuses.SUCCESS; } } diff --git a/src/commands/Utilities/ServerInfo.js b/src/commands/Utilities/ServerInfo.js index ce927bd9b..77da3a788 100644 --- a/src/commands/Utilities/ServerInfo.js +++ b/src/commands/Utilities/ServerInfo.js @@ -15,8 +15,8 @@ class ServerInfo extends Command { } async run(message) { - const guild = message.guild; - if (!message.guild) { + const { guild } = message; + if (!guild) { this.messageManager.reply(message, 'Operator, this is a DM, you can\'t do that!', false, false); return this.messageManager.statuses.FAILURE; } diff --git a/src/commands/Utilities/UserInfo.js b/src/commands/Utilities/UserInfo.js index 2244630d0..ec90eb984 100644 --- a/src/commands/Utilities/UserInfo.js +++ b/src/commands/Utilities/UserInfo.js @@ -22,11 +22,12 @@ class UserInfo extends Command { let member; let mention; if (message.mentions.users) { + const { a, b } = message.mentions.users.array(); if (message.mentions.users.array().length > 1 && message.mentions.users.array()[0].id === this.bot.client.id) { - mention = message.mentions.users.array()[1]; + mention = b; } else { - mention = message.mentions.users.array()[0]; + mention = a; } } @@ -47,8 +48,8 @@ class UserInfo extends Command { .filter(guild => guild.members.get(user.id)); const guilds = guildsWithUser.length > 25 ? - guildsWithUser.splice(0, 24) : - guildsWithUser; + guildsWithUser.splice(0, 24) : + guildsWithUser; const embed = new UserInfoEmbed(this.bot, guilds, user, member, message); this.messageManager.embed(message, embed, true, false); return this.messageManager.statuses.SUCCESS; diff --git a/src/commands/Worldstate/Alerts.js b/src/commands/Worldstate/Alerts.js index bf37d1eea..f16d66547 100644 --- a/src/commands/Worldstate/Alerts.js +++ b/src/commands/Worldstate/Alerts.js @@ -21,8 +21,8 @@ class Alerts extends Command { const platform = platformParam || await this.bot.settings.getChannelSetting(message.channel, 'platform'); const ws = await this.bot.caches[platform.toLowerCase()].getDataJson(); const alerts = ws.alerts.filter(a => !a.expired); - await this.messageManager.embed(message, - new AlertEmbed(this.bot, alerts, platform), true, false); + await this.messageManager + .embed(message, new AlertEmbed(this.bot, alerts, platform), true, false); return this.messageManager.statuses.SUCCESS; } } diff --git a/src/commands/Worldstate/Baro.js b/src/commands/Worldstate/Baro.js index d1629d750..2f672df0d 100644 --- a/src/commands/Worldstate/Baro.js +++ b/src/commands/Worldstate/Baro.js @@ -20,8 +20,8 @@ class Baro extends Command { const platformParam = message.strippedContent.match(this.regex)[1]; const platform = platformParam || await this.bot.settings.getChannelSetting(message.channel, 'platform'); const ws = await this.bot.caches[platform.toLowerCase()].getDataJson(); - await this.messageManager.embed(message, - new VoidTraderEmbed(this.bot, ws.voidTrader, platform), true, false); + await this.messageManager + .embed(message, new VoidTraderEmbed(this.bot, ws.voidTrader, platform), true, false); return this.messageManager.statuses.SUCCESS; } } diff --git a/src/commands/Worldstate/ConclaveChallenges.js b/src/commands/Worldstate/ConclaveChallenges.js index ae0b0062b..041e230ce 100644 --- a/src/commands/Worldstate/ConclaveChallenges.js +++ b/src/commands/Worldstate/ConclaveChallenges.js @@ -39,7 +39,7 @@ class ConclaveChallenges extends Command { } const platform = platformParam || await this.bot.settings.getChannelSetting(message.channel, 'platform'); const ws = await this.bot.worldStates[platform].getData(); - const conclaveChallenges = ws.conclaveChallenges; + const { conclaveChallenges } = ws; const embed = new ConclaveChallengeEmbed(this.bot, conclaveChallenges, category, platform); await this.messageManager.embed(message, embed, true, false); return this.messageManager.statuses.SUCCESS; diff --git a/src/commands/Worldstate/Construction.js b/src/commands/Worldstate/Construction.js index 7dbc07533..e0b738163 100644 --- a/src/commands/Worldstate/Construction.js +++ b/src/commands/Worldstate/Construction.js @@ -21,8 +21,8 @@ class Construction extends Command { const platform = platformParam || await this.bot.settings .getChannelSetting(message.channel, 'platform'); const ws = await this.bot.caches[platform.toLowerCase()].getDataJson(); - await this.messageManager.embed(message, new EventEmbed(this.bot, - ws.constructionProgress, platform.toUpperCase()), true, true); + const embed = new EventEmbed(this.bot, ws.constructionProgress, platform.toUpperCase()); + await this.messageManager.embed(message, embed, true, true); return this.messageManager.statuses.SUCCESS; } } diff --git a/src/commands/Worldstate/Enemies.js b/src/commands/Worldstate/Enemies.js index 0f42969c1..08ac433e7 100644 --- a/src/commands/Worldstate/Enemies.js +++ b/src/commands/Worldstate/Enemies.js @@ -20,8 +20,10 @@ class Enemies extends Command { const platformParam = message.strippedContent.match(this.regex)[1]; const platform = platformParam || await this.bot.settings.getChannelSetting(message.channel, 'platform'); const ws = await this.bot.caches[platform.toLowerCase()].getDataJson(); - await this.messageManager.embed(message, - new EnemyEmbed(this.bot, ws.persistentEnemies, platform), true, false); + await this.messageManager.embed( + message, + new EnemyEmbed(this.bot, ws.persistentEnemies, platform), true, false, + ); return this.messageManager.statuses.SUCCESS; } } diff --git a/src/commands/Worldstate/Event.js b/src/commands/Worldstate/Event.js index 20daf8f70..a82ab589e 100644 --- a/src/commands/Worldstate/Event.js +++ b/src/commands/Worldstate/Event.js @@ -24,14 +24,18 @@ class Event extends Command { if (ws.events.length > 0) { const results = []; ws.events.forEach((event) => { - results.push(this.messageManager.embed(message, - new EventEmbed(this.bot, event, platform.toUpperCase()), true, true)); + results.push(this.messageManager.embed( + message, + new EventEmbed(this.bot, event, platform.toUpperCase()), true, true, + )); }); await Promise.all(results); return this.messageManager.statuses.SUCCESS; } - await this.messageManager.embed(message, new EventEmbed(this.bot, - undefined, platform.toUpperCase()), true, true); + await this.messageManager.embed(message, new EventEmbed( + this.bot, + undefined, platform.toUpperCase(), + ), true, true); return this.messageManager.statuses.FAILURE; } } diff --git a/src/commands/Worldstate/FeaturedDeal.js b/src/commands/Worldstate/FeaturedDeal.js index c03f56550..3627eafda 100644 --- a/src/commands/Worldstate/FeaturedDeal.js +++ b/src/commands/Worldstate/FeaturedDeal.js @@ -21,8 +21,10 @@ class FeaturedDeal extends Command { const platform = platformParam || await this.bot.settings.getChannelSetting(message.channel, 'platform'); const ws = await this.bot.caches[platform.toLowerCase()].getDataJson(); const sales = ws.flashSales.filter(popularItem => popularItem.isFeatured); - await this.messageManager.embed(message, - new SalesEmbed(this.bot, sales, platform), true, false); + await this.messageManager.embed( + message, + new SalesEmbed(this.bot, sales, platform), true, false, + ); return this.messageManager.statuses.SUCCESS; } } diff --git a/src/commands/Worldstate/Fissures.js b/src/commands/Worldstate/Fissures.js index fe08cc202..7d5f68a11 100644 --- a/src/commands/Worldstate/Fissures.js +++ b/src/commands/Worldstate/Fissures.js @@ -21,8 +21,10 @@ class Fissures extends Command { const platform = platformParam || await this.bot.settings.getChannelSetting(message.channel, 'platform'); const ws = await this.bot.caches[platform.toLowerCase()].getDataJson(); const fissures = ws.fissures.sort((a, b) => a.tierNum > b.tierNum); - await this.messageManager.embed(message, - new FissureEmbed(this.bot, fissures, platform), true, false); + await this.messageManager.embed( + message, + new FissureEmbed(this.bot, fissures, platform), true, false, + ); return this.messageManager.statuses.SUCCESS; } } diff --git a/src/commands/Worldstate/Invasions.js b/src/commands/Worldstate/Invasions.js index 1348ef67e..ad3b43c34 100644 --- a/src/commands/Worldstate/Invasions.js +++ b/src/commands/Worldstate/Invasions.js @@ -21,8 +21,10 @@ class Invasions extends Command { const platform = platformParam || await this.bot.settings.getChannelSetting(message.channel, 'platform'); const ws = await this.bot.caches[platform.toLowerCase()].getDataJson(); const invasions = ws.invasions.filter(i => !i.completed); - await this.messageManager.embed(message, - new InvasionEmbed(this.bot, invasions, platform), true, false); + await this.messageManager.embed( + message, + new InvasionEmbed(this.bot, invasions, platform), true, false, + ); return this.messageManager.statuses.SUCCESS; } } diff --git a/src/commands/Worldstate/News.js b/src/commands/Worldstate/News.js index 6d5458d2e..8609f16c4 100644 --- a/src/commands/Worldstate/News.js +++ b/src/commands/Worldstate/News.js @@ -21,8 +21,10 @@ class News extends Command { const platform = platformParam || await this.bot.settings.getChannelSetting(message.channel, 'platform'); const ws = await this.bot.caches[platform.toLowerCase()].getDataJson(); const news = ws.news.filter(n => !n.update && !n.primeAccess); - await this.messageManager.embed(message, - new NewsEmbed(this.bot, news, undefined, platform), true, false); + await this.messageManager.embed( + message, + new NewsEmbed(this.bot, news, undefined, platform), true, false, + ); return this.messageManager.statuses.SUCCESS; } } diff --git a/src/commands/Worldstate/PopularSale.js b/src/commands/Worldstate/PopularSale.js index 24a660aaa..67ba5f98c 100644 --- a/src/commands/Worldstate/PopularSale.js +++ b/src/commands/Worldstate/PopularSale.js @@ -21,8 +21,10 @@ class PopularDeal extends Command { const platform = platformParam || await this.bot.settings.getChannelSetting(message.channel, 'platform'); const ws = await this.bot.caches[platform.toLowerCase()].getDataJson(); const sales = ws.flashSales.filter(popularItem => popularItem.isPopular); - await this.messageManager.embed(message, - new SalesEmbed(this.bot, sales, platform), true, false); + await this.messageManager.embed( + message, + new SalesEmbed(this.bot, sales, platform), true, false, + ); return this.messageManager.statuses.SUCCESS; } } diff --git a/src/commands/Worldstate/Simaris.js b/src/commands/Worldstate/Simaris.js index 6a6466c9f..fe2f17814 100644 --- a/src/commands/Worldstate/Simaris.js +++ b/src/commands/Worldstate/Simaris.js @@ -20,9 +20,11 @@ class Simaris extends Command { const platformParam = message.strippedContent.match(this.regex)[1]; const platform = platformParam || await this.bot.settings.getChannelSetting(message.channel, 'platform'); const ws = await this.bot.caches[platform.toLowerCase()].getDataJson(); - const simaris = ws.simaris; - await this.messageManager.embed(message, - new SimarisEmbed(this.bot, simaris, platform), true, false); + const { simaris } = ws; + await this.messageManager.embed( + message, + new SimarisEmbed(this.bot, simaris, platform), true, false, + ); return this.messageManager.statuses.SUCCESS; } } diff --git a/src/commands/Worldstate/Sorties.js b/src/commands/Worldstate/Sorties.js index 6f2c118c5..e11af8bce 100644 --- a/src/commands/Worldstate/Sorties.js +++ b/src/commands/Worldstate/Sorties.js @@ -24,7 +24,7 @@ class Sorties extends Command { const platformParam = message.strippedContent.match(this.regex)[1]; const platform = platformParam || await this.bot.settings.getChannelSetting(message.channel, 'platform'); const ws = await this.bot.caches[platform.toLowerCase()].getDataJson(); - const sortie = ws.sortie; + const { sortie } = ws; if (sortie.expired) { await this.messageManager.sendMessage(message, 'There is currently no sortie', true, true); return this.messageManager.statuses.FAILURE; diff --git a/src/commands/Worldstate/Syndicates.js b/src/commands/Worldstate/Syndicates.js index 06384adee..169629820 100644 --- a/src/commands/Worldstate/Syndicates.js +++ b/src/commands/Worldstate/Syndicates.js @@ -37,8 +37,10 @@ class Syndicates extends Command { } const platform = platformParam || await this.bot.settings.getChannelSetting(message.channel, 'platform'); const ws = await this.bot.caches[platform.toLowerCase()].getDataJson(); - await this.messageManager.embed(message, new SyndicateEmbed(this.bot, - ws.syndicateMissions, syndicate, platform), true, false); + await this.messageManager.embed(message, new SyndicateEmbed( + this.bot, + ws.syndicateMissions, syndicate, platform, + ), true, false); return this.messageManager.statuses.SUCCESS; } } diff --git a/src/embeds/BaseEmbed.js b/src/embeds/BaseEmbed.js index 03e855384..4612d86ea 100644 --- a/src/embeds/BaseEmbed.js +++ b/src/embeds/BaseEmbed.js @@ -4,9 +4,6 @@ * Utility class for making rich embeds */ class BaseEmbed { - /** - * @param {Genesis} bot - An instance of Genesis - */ constructor() { this.footer = { icon_url: 'https://avatars1.githubusercontent.com/u/24436369', diff --git a/src/embeds/ConclaveChallengeEmbed.js b/src/embeds/ConclaveChallengeEmbed.js index 86af1d70b..cd1051aee 100644 --- a/src/embeds/ConclaveChallengeEmbed.js +++ b/src/embeds/ConclaveChallengeEmbed.js @@ -34,6 +34,7 @@ class ConclaveChallengeEmbed extends BaseEmbed { }]; } this.title = `${platform ? `[${platform.toUpperCase()}] ` : ''}Current Challenges for category: ${category || 'none'}`; + this.url = 'https://warframe.com'; this.thumbnail = { url: 'http://i.imgur.com/KDzKPYA.png', }; diff --git a/src/embeds/NewsEmbed.js b/src/embeds/NewsEmbed.js index fe12b6381..ef18aa5c3 100644 --- a/src/embeds/NewsEmbed.js +++ b/src/embeds/NewsEmbed.js @@ -36,7 +36,7 @@ class NewsEmbed extends BaseEmbed { } this.fields = [{ name: '_ _', value }]; this.image = { url: news[0] ? news[0].imageLink : '' }; - this.footer.text += ` | [${platform.toUpperCase()}]`; + this.footer.text += ` | ${platform.toUpperCase()}`; } } diff --git a/src/embeds/SortieEmbed.js b/src/embeds/SortieEmbed.js index fe48f3caa..ecbc3c502 100644 --- a/src/embeds/SortieEmbed.js +++ b/src/embeds/SortieEmbed.js @@ -20,11 +20,11 @@ class SortieEmbed extends BaseEmbed { name: `${v.node} - ${v.missionType}`, value: v.modifier, })); - this.description = `[${platform.toUpperCase()}] Currently in-progress sortie: **${sortie.boss}**`; + this.description = `Currently in-progress sortie: **${sortie.boss}**`; this.footer.text = `${sortie.eta} remaining | ${new Date().toLocaleString()}`; } - this.title = 'Worldstate - Sortie'; + this.title = `[${platform.toUpperCase()}] Worldstate - Sortie`; this.thumbnail = { url: 'http://i.imgur.com/wWBRhaB.png', }; diff --git a/src/embeds/SyndicateEmbed.js b/src/embeds/SyndicateEmbed.js index e3590c290..c404bfca6 100644 --- a/src/embeds/SyndicateEmbed.js +++ b/src/embeds/SyndicateEmbed.js @@ -35,7 +35,7 @@ class SyndicateEmbed extends BaseEmbed { value: `Valid values: ${values.join(', ')}`, }]; } - this.description = `[${platform.toUpperCase()}] Current Missions`; + this.title = `[${platform.toUpperCase()}] Syndicate Mission Nodes`; this.thumbnail = { url: 'https://i.imgur.com/I8CjF9d.png', }; diff --git a/src/notifications/Notifier.js b/src/notifications/Notifier.js index 8bd60e5f6..9b726ba52 100644 --- a/src/notifications/Notifier.js +++ b/src/notifications/Notifier.js @@ -115,8 +115,8 @@ class Notifier { .concat(newData.voidTrader ? [`${newData.voidTrader.id}${newData.voidTrader.inventory.length}`] : []); // Send all notifications - this.updateNotified(notifiedIds, platform); - this.sendAcolytes(acolytesToNotify, platform); + await this.updateNotified(notifiedIds, platform); + await this.sendAcolytes(acolytesToNotify, platform); this.sendAlerts(alertsToNotify, platform); if (baroToNotify) { this.sendBaro(baroToNotify, platform); @@ -148,12 +148,6 @@ class Notifier { await this.sendUpdates(updatesToNotify, platform); } - async sendWithPrepend(channel, embed, type, items, deleteAfter) { - const prepend = await this.settings - .getPing(channel.guild, (items || []).concat([type])); - return this.bot.messageManager.embedToChannel(channel, embed, prepend, deleteAfter); - } - /** * Broadcast embed to all channels for a platform and type * @param {Object} embed Embed to send to a channel @@ -180,6 +174,22 @@ class Notifier { await Promise.all(results); } + async sendWithoutPrepend(channel, embed, deleteAfter) { + const ctx = await this.settings.getCommandContext(channel); + ctx.deleteAfterDuration = deleteAfter; + return this.bot.messageManager.webhook(ctx, + { embed: this.bot.messageManager.webhookWrapEmbed(embed) }); + } + + async sendWithPrepend(channel, embed, type, items, deleteAfter) { + const prepend = await this.settings + .getPing(channel.guild, (items || []).concat([type])); + const ctx = await this.settings.getCommandContext(channel); + ctx.deleteAfterDuration = deleteAfter; + return this.bot.messageManager.webhook(ctx, + { text: prepend, embed: this.bot.messageManager.webhookWrapEmbed(embed, ctx) }); + } + /** * Get the list of notified ids * @param {string} platform Platform to get notified ids for @@ -271,7 +281,7 @@ class Notifier { embed.thumbnail.url = thumb; } } catch (e) { - this.logger.error(`${e.exception.code}: ${e.exception.message}`); + // do nothing, it happens } finally { await this.broadcast(embed, platform, 'invasions', invasion.rewardTypes, 86400000); } diff --git a/src/resources/Corggit.js b/src/resources/Corggit.js index 6663c4eb2..0b94203cb 100644 --- a/src/resources/Corggit.js +++ b/src/resources/Corggit.js @@ -1,40 +1,38 @@ +'use strict'; + const rp = require('request-promise'); const DEFAULT_MULTIREDDIT = 'https://reddit.com/u/d0nkeh/m/corgi.json'; -const multiUrl = process.env.CORGI_MULTIREDDIT_URL || process.env.MULTIREDDIT_URL || DEFAULT_MULTIREDDIT; +const multiUrl = process.env.CORGI_MULTIREDDIT_URL + || process.env.MULTIREDDIT_URL || DEFAULT_MULTIREDDIT; function listPosts(uri) { return rp({ - uri: uri, + uri, json: true, headers: { - 'User-Agent': `hubot/corgi v0.5.2 (by /u/d0nkeh)` - } + 'User-Agent': 'hubot/corgi v0.5.2 (by /u/d0nkeh)', + }, }).then((data) => { - if (data.kind == 'Listing') { + if (data.kind === 'Listing') { return data.data.children; - } else { - return Promise.reject(data); } - }, (err) => { - return Promise.reject(err); - }); + return Promise.reject(data); + }, err => Promise.reject(err)); } function filter(children) { return children.map(child => child.data) - .filter(post => { - return !post.is_self + .filter(post => !post.is_self && !post.over_18 // sfw only please - && /imgur\.com|reddituploads\.com|gyfycat\.com/i.test(post.domain); - }); + && /imgur\.com|reddituploads\.com|gyfycat\.com/i.test(post.domain)); } function corggit() { return listPosts(multiUrl) .then(posts => filter(posts)) - .then(posts => { - let index = Math.floor(Math.random() * posts.length); + .then((posts) => { + const index = Math.floor(Math.random() * posts.length); return posts[index]; }); } @@ -42,4 +40,4 @@ function corggit() { corggit.filter = filter; corggit.listPosts = listPosts; -module.exports = corggit; \ No newline at end of file +module.exports = corggit; diff --git a/src/settings/Database.js b/src/settings/Database.js index 85096e6c7..4535f58c3 100644 --- a/src/settings/Database.js +++ b/src/settings/Database.js @@ -158,6 +158,14 @@ class Database { return this.db.query(query); } + async checkWebhookAndReturn(channel, setting) { + if (!/webhook/.test(setting)) { + await this.setChannelSetting(channel, setting, this.defaults[`${setting}`]); + return this.defaults[`${setting}`]; + } + return undefined; + } + /** * Get a setting for a particular channel * @param {Channel} channel channel to get the setting for @@ -170,16 +178,23 @@ class Database { if (res[0].length === 0) { if (channel.type === 'text') { await this.addGuildTextChannel(channel); - await this.setChannelSetting(channel, setting, this.defaults[`${setting}`]); - return this.defaults[`${setting}`]; + return this.checkWebhookAndReturn(channel, setting); } await this.addDMChannel(channel); - await this.setChannelSetting(channel, setting, this.defaults[`${setting}`]); - return this.defaults[`${setting}`]; + return this.checkWebhookAndReturn(channel, setting); } return res[0][0].val; } + async getChannelWebhook(channel) { + return { + avatar: await this.getChannelSetting(channel, 'webhookAvatar') || this.bot.client.user.avatarURL.replace('?size=2048', ''), + name: await this.getChannelSetting(channel, 'webhookName') || this.bot.client.user.username, + id: await this.getChannelSetting(channel, 'webhookId'), + token: await this.getChannelSetting(channel, 'webhookToken'), + }; + } + /** * Get a setting for a particular channel * @param {Channel} channel channel to get the setting for @@ -774,7 +789,13 @@ class Database { const prefix = await this.getChannelSetting(channel, 'prefix'); const allowCustom = await this.getChannelSetting(channel, 'allowCustom') === '1'; const allowInline = await this.getChannelSetting(channel, 'allowInline') === '1'; - return { prefix, allowCustom, allowInline }; + const webhook = { + id: await this.getChannelSetting(channel, 'webhookId'), + token: await this.getChannelSetting(channel, 'webhookToken'), + name: await this.getChannelSetting(channel, 'webhookName'), + avatar: await this.getChannelSetting(channel, 'webhookAvatar'), + }; + return { prefix, allowCustom, allowInline, webhook, channel }; } async getCustomCommands() { diff --git a/src/settings/MessageManager.js b/src/settings/MessageManager.js index 13091b2e7..b4960239e 100644 --- a/src/settings/MessageManager.js +++ b/src/settings/MessageManager.js @@ -4,7 +4,6 @@ * MessageManager for */ class MessaageManager { - /** * Construct a message manager for sending and managing messages * @param {Genesis} bot bot containing necessary settings @@ -14,6 +13,7 @@ class MessaageManager { this.logger = bot.logger; this.settings = bot.settings; this.owner = bot.owner; + this.discord = bot.discord; /** * Zero space whitespace character to prepend to any messages sent @@ -208,12 +208,61 @@ class MessaageManager { } } - async webhook(webhookId, embed) { - this.bot.client.fetchWebhook(webhookId).sendSlackMessage({ - username: this.bot.client.user.username, - attachments: [embed], - }) - .catch(this.logger.error); + async webhook(ctx, { text = '_ _', embed = undefined }) { + if (ctx.webhook.id && ctx.webhook.token) { + const client = new this.discord.WebhookClient(ctx.webhook.id, ctx.webhook.token); + try { + return client.send(text, embed); + } catch (e) { + this.logger.error(`Something went wrong sending webhook: ${JSON.stringify(embed)} | ${text}`); + } + } + const channelWebhook = await this.settings.getChannelWebhook(ctx.channel); + if (channelWebhook.token && channelWebhook.id) { + // eslint-disable-next-line no-param-reassign + ctx.webhook = channelWebhook; + return this.webhook(ctx, { text, embed }); + } else if (ctx.channel.permissionsFor(this.client.user.id).has('MANAGE_WEBHOOKS')) { + const webhooks = await ctx.channel.fetchWebhooks(); + let webhook; + if (webhooks.array().length > 0) { + webhook = webhooks.array()[0]; + } else { + webhook = await ctx.channel.createWebhook(this.client.user.username); + } + await this.settings.setChannelSetting(ctx.channel, 'webhookId', String(webhook.id)); + await this.settings.setChannelSetting(ctx.channel, 'webhookToken', String(webhook.token)); + await this.settings.setChannelSetting(ctx.channel, 'webhookName', this.client.user.username); + await this.settings.setChannelSetting(ctx.channel, 'webhookAvatar', this.client.user.avatarURL.replace('?size=2048', '')); + // eslint-disable-next-line no-param-reassign + ctx.webhook = webhook; + return this.webhook(ctx, { text, embed }); + } + if (ctx.message) { + if (embed) { + return Promise.all(embed.embeds.map(subEmbed => + this.embed(ctx.message, subEmbed, ctx.deleteCall, ctx.deleteResponse))); + } + return this.reply(ctx.message, text, ctx.deleteCall, ctx.deleteResponse); + } + return Promise.all(embed.embeds.map(subEmbed => + this.embedToChannel(ctx.chnnel, subEmbed, text, ctx.deleteAfterDuration))); + } + + webhookWrapEmbed(embed, ctx) { + return { + username: ctx.webhook.name || this.client.user.username, + avatarURL: ctx.webhook.avatar || this.client.user.avatarURL, + embeds: [embed], + }; + } + + webhookWrapEmbeds(embeds, ctx) { + return { + username: ctx.webhook.name || this.client.user.username, + avatarURL: ctx.webhook.avatar || this.client.user.avatarURL, + embeds, + }; } }