From 1b0369ab592a23e283aebd0311e9adb6f9ec74d7 Mon Sep 17 00:00:00 2001 From: Ibrahim Ansari Date: Tue, 4 May 2021 22:35:51 +0530 Subject: [PATCH] Finish re-eval on error for all commands. - /eval was excluded as {error:true} is unsupported. - /ocr and /paste were excluded. - API errors were also excluded. - Cooldowns were also excluded. - Moderation commands are incomplete. --- server/bot/client.ts | 14 ++++++----- server/bot/commands/api.ts | 36 ++++++++++++++-------------- server/bot/commands/games.ts | 10 ++++---- server/bot/commands/gunfight.ts | 12 +++++----- server/bot/commands/help.ts | 4 ++-- server/bot/commands/tools.ts | 7 +++--- server/bot/commands/utilities.ts | 40 ++++++++++++++++---------------- 7 files changed, 62 insertions(+), 61 deletions(-) diff --git a/server/bot/client.ts b/server/bot/client.ts index 98f1961..315f8e6 100644 --- a/server/bot/client.ts +++ b/server/bot/client.ts @@ -276,17 +276,19 @@ export default class CommandParser { if (commandExec === keys[i].toLowerCase() || ( this.commands[keys[i]].aliases && this.commands[keys[i]].aliases.includes(commandExec) )) { - // We mark the command as evaluated and schedule a removal of the ID in 30 seconds. - this.evaluatedMessages.push(message.id) - setTimeout(() => { - this.evaluatedMessages.splice(this.evaluatedMessages.findIndex(i => i === message.id), 1) - }, 30000) // Execute command. try { const executeFirst = process.hrtime() // Initial high precision time. - await this.executeCommand(this.commands[keys[i]], message) + const error = await this.executeCommand(this.commands[keys[i]], message) const executeSecond = process.hrtime(executeFirst) // Time difference. this.saveAnalytics(executeSecond, keys[i]) // Send analytics. + if (!error) { + // We mark the command as evaluated and schedule a removal of the ID in 30 seconds. + this.evaluatedMessages.push(message.id) + setTimeout(() => { + this.evaluatedMessages.splice(this.evaluatedMessages.findIndex(i => i === message.id), 1) + }, 30000) + } } catch (e) { // On error, we tell the user of an unknown error and log it for our reference. message.channel.createMessage(this.commands[keys[i]].errorMessage) diff --git a/server/bot/commands/api.ts b/server/bot/commands/api.ts index 7383006..a5f3617 100644 --- a/server/bot/commands/api.ts +++ b/server/bot/commands/api.ts @@ -201,7 +201,7 @@ export const handleRobohash: Command = { embed: { image: { url: `https://robohash.org/${text}.png?set=set5` }, color }, content: '๐Ÿค”' } } else { - return 'Correct usage: /robohash ' + return { content: 'Correct usage: /robohash ', error: true } } } } @@ -237,7 +237,7 @@ export const handleApod: Command = { } } catch (err) { return `Something went wrong ๐Ÿ‘พ Error: ${err}` } } else if (args.length) { - return 'Invalid date.' + return { content: 'Invalid date.', error: true } } // Fetch a picture or video. try { // eslint-disable-next-line camelcase @@ -271,8 +271,8 @@ export const handleDog: Command = { // If only list of breeds was asked. if (!args[1]) return `**List of breeds:** ${Object.keys(message).join(', ')}` // If list of sub-breeds was asked. - if (!message[args[1]]) return 'This breed does not exist!' - else if (message[args[1]].length === 0) return 'This breed has no sub-breeds!' + if (!message[args[1]]) return { content: 'This breed does not exist!', error: true } + else if (message[args[1]].length === 0) return { content: 'This breed has no sub-breeds!', error: true } return `**List of sub-breeds:** ${message[args[1]].join(', ')}` } catch (err) { return `Something went wrong ๐Ÿ‘พ Error: ${err}` } // Fetch a random picture for a sub-breed. @@ -286,7 +286,7 @@ export const handleDog: Command = { `http://dog.ceo/api/breed/${args.join('').toLowerCase()}/images/random` )).json()) } - if (!message || message.includes('Breed not found')) return 'This breed/sub-breed does not exist!' + if (!message || message.includes('Breed not found')) return { content: 'This breed/sub-breed does not exist!', error: true } return { embed: { image: { url: message }, color: 0x654321 }, content: `๐Ÿ• ${args[0]} ${args[1]}` @@ -345,7 +345,7 @@ export const handleUrban: Command = { } // Else, there will be an exception thrown. } catch (err) { - return 'No definition was found.' + return { content: 'No definition was found.', error: true } } } catch (e) { return `Something went wrong ๐Ÿ‘พ Error: ${e}` @@ -393,7 +393,7 @@ export const handleNamemc: Command = { } } } catch (err) { return `Something went wrong ๐Ÿ‘พ Error: ${err}` } - } catch (e) { return `Enter a valid Minecraft username (account must be premium)` } + } catch (e) { return { content: `Enter a valid Minecraft username (account must be premium)`, error: true } } } } @@ -430,15 +430,15 @@ letter code + the first letter of the currency name.` }] } } // Calculate the currencies to conver from and to, as well as the amount. - if (args.length < 2) return 'Invalid usage, use /help currency for proper usage.' + if (args.length < 2) return { content: 'Invalid usage, use /help currency for proper usage.', error: true } const from = args[0].toUpperCase() const to = args[1].toUpperCase() // Check if everything is in order. - if (from.length !== 3 || !currency.rates[from]) return 'Invalid currency to convert from.' - else if (to.length !== 3 || !currency.rates[to]) return 'Invalid currency to convert to.' + if (from.length !== 3 || !currency.rates[from]) return { content: 'Invalid currency to convert from.', error: true } + else if (to.length !== 3 || !currency.rates[to]) return { content: 'Invalid currency to convert to.', error: true } else if (!args[2]) args[2] = '1' // If no amount was provided, the amount should be one. - else if (args.length > 3) return 'Enter a single number for currency conversion.' - else if (isNaN(+args[2])) return 'Enter a proper number to convert.' + else if (args.length > 3) return { content: 'Enter a single number for currency conversion.', error: true } + else if (isNaN(+args[2])) return { content: 'Enter a proper number to convert.', error: true } // Now we convert the amount. const convertedAmount = ((currency.rates[to] / currency.rates[from]) * +args[2]) const roundedOffAmount = Math.ceil(convertedAmount * Math.pow(10, 4)) / Math.pow(10, 4) @@ -487,7 +487,7 @@ export const handleWeather: Command = { )).json() const temp = fahrenheit ? 'ยฐF' : 'ยฐC' // If the place doesn't exist.. - if (weather.cod === '404') return 'Enter a valid city >_<' + if (weather.cod === '404') return { content: 'Enter a valid city >_<', error: true } // We generate the entire embed. return { content: `**๐ŸŒ‡๐ŸŒƒ๐ŸŒ๐ŸŒ† The weather for ${args.join(', ')}:**`, @@ -560,7 +560,7 @@ export const handleDefine: Command = { if (r.error === 'No entries were found for a given inflected word' || ( r.error && r.error.startsWith('No lemma was found') )) { - return 'Did you enter a valid word? ๐Ÿ‘พ' + return { content: 'Did you enter a valid word? ๐Ÿ‘พ', error: true } } try { // Here we get the dictionary entries for the specified word. @@ -624,7 +624,7 @@ export const handleDefine: Command = { } } } catch (err) { return `Something went wrong ๐Ÿ‘พ Error: ${err}` } - } catch (e) { return 'Did you enter a valid word? ๐Ÿ‘พ' } + } catch (e) { return { content: 'Did you enter a valid word? ๐Ÿ‘พ', error: true } } } } @@ -654,7 +654,7 @@ export const handleXkcd: Command = { const res = fuse.search(args.slice(1).join(' '), { limit: 3 }).map(e => ( noimageposts.includes(e.item.id) ? { ...e.item, id: e.item.id + '(no image)' } : e.item )) - if (!res.length) return 'No results were found for your search criteria!' + if (!res.length) return { content: 'No results were found for your search criteria!', error: true } const res1 = 'https://xkcd.com/' + res[0].id const res2 = res[1] ? `\n2. ` : '' const res3 = res[2] ? `\n3. ` : '' @@ -662,7 +662,7 @@ export const handleXkcd: Command = { } catch (e) { console.error(e); return 'Failed to fetch list of xkcd comics!\nhttps://xkcd.com/1348' } } else if ( args.length > 1 || (args.length === 1 && args[0] !== 'latest' && args[0] !== 'random') - ) return 'Correct usage: /xkcd (latest|random|search) (search query if searching)' + ) return { content: 'Correct usage: /xkcd (latest|random|search) (search query if searching)', error: true } // Get the latest xkcd comic. try { const { num } = await (await fetch('http://xkcd.com/info.0.json')).json() @@ -686,7 +686,7 @@ export const handleHttpCat: Command = { if (isNaN(+args[0]) || args.length > 1) return 'Enter a valid HTTP status code!' const req = await fetch('https://http.cat/' + args[0], { method: 'HEAD' }) - if (req.status === 404) return 'Enter a valid HTTP status code!\nhttps://http.cat/404' + if (req.status === 404) return { content: 'Enter a valid HTTP status code!\nhttps://http.cat/404', error: true } return 'https://http.cat/' + args[0] } diff --git a/server/bot/commands/games.ts b/server/bot/commands/games.ts index 4b78aa6..f207cb0 100644 --- a/server/bot/commands/games.ts +++ b/server/bot/commands/games.ts @@ -33,7 +33,7 @@ export const handleChoose: Command = { }, generator: (message, args) => { // Is it used correctly? - if (message.content.split('|').length === 1) return 'Correct usage: /choose item1|item2|...' + if (message.content.split('|').length === 1) return { content: 'Correct usage: /choose item1|item2|...', error: true } const choices = args.join(' ').split('|') return `I choose: ${choices[Math.floor(Math.random() * choices.length)]}` } @@ -128,10 +128,10 @@ export const handleRepeat: Command = { const number = +args.shift() if (isNaN(number)) return 'Correct usage: /repeat ' else if (number * args.join(' ').length >= 2001) { - return 'To prevent spam, your excessive message has not been repeated.' + return { content: 'To prevent spam, your excessive message has not been repeated.', error: true } } else if ( args.join(' ') === '_' || args.join(' ') === '*' || args.join(' ') === '~' - ) return 'This is known to lag users and is disabled.' + ) return { content: 'This is known to lag users and is disabled.', error: true } // Generate the repeated string. let generatedMessage = '' for (let x = 0; x < number; x++) { generatedMessage += args.join(' ') } @@ -160,7 +160,7 @@ export const handleRandom: Command = { const number2 = +args[1] return `The number.. is.. ${Math.floor(Math.random() * (number2 - number1)) + number1}` } else if (args.length >= 1) { - return 'Correct usage: /random (optional start number) (optional end number)' + return { content: 'Correct usage: /random (optional start number) (optional end number)', error: true } } return `The number.. is.. ${Math.floor(Math.random() * 10)}` } @@ -181,7 +181,7 @@ More info here: https://mathjs.org/docs/expressions/syntax.html`, try { return `${eva(args.join(' ').split(',').join('.').split('รท').join('/').toLowerCase())}` } catch (e) { - return 'Invalid expression >_<' + return { content: 'Invalid expression >_<', error: true } } } } diff --git a/server/bot/commands/gunfight.ts b/server/bot/commands/gunfight.ts index 10a1142..2fdfc34 100644 --- a/server/bot/commands/gunfight.ts +++ b/server/bot/commands/gunfight.ts @@ -18,20 +18,20 @@ export const handleGunfight: Command = { const user = getUser(message, args[0]) // Confirm an argument was passed including one mention. if (!user) { - return 'Specify a valid user to challenge >_>' + return { content: 'Specify a valid user to challenge >_>', error: true } // It should not be a challenge to self. - } else if (user.id === message.author.id) return 'You cannot challenge yourself :P' + } else if (user.id === message.author.id) return { content: 'You cannot challenge yourself :P', error: true } // It should not be a challenge to bot itself. else if (user.id === client.user.id) { - return 'Aw, how sweet. But I don\'t play with pathetic fools who try to fool me :>' + return { content: 'Aw, how sweet. But I don\'t play with pathetic fools who try to fool me :>', error: true } // It should not be a challenge to a bot. - } else if (user.bot) return 'Noob, that person is a bot.' + } else if (user.bot) return { content: 'Noob, that person is a bot.', error: true } // Do not challenge someone already in a gunfight. // Possible gunfights. const possibleGunfight = Object.keys(tempDB.gunfight) .find((gunfight) => gunfight.split('-').includes(user.id)) - if (possibleGunfight) return 'This user is already in a fight!' + if (possibleGunfight) return { content: 'This user is already in a fight!', error: true } // Push to database. const timestamp = Date.now() tempDB.gunfight[message.author.id + '-' + user.id] = { @@ -83,7 +83,7 @@ export const handleAccept: Command = { if (Object.keys(tempDB.gunfight).filter((gunfight) => ( gunfight.split('-').includes(message.author.id) )).length > 1) { - return 'You are already in a gunfight!' + return { content: 'You are already in a gunfight!', error: true } } // Accept the challenge. const words = ['fire', 'water', 'gun', 'dot'] diff --git a/server/bot/commands/help.ts b/server/bot/commands/help.ts index 19373f5..be027e2 100644 --- a/server/bot/commands/help.ts +++ b/server/bot/commands/help.ts @@ -122,7 +122,7 @@ export const handleHelp: IveBotCommand = { // Check if requested for a specific command. if (Object.keys(commands).find(check)) { return generateDocs(commands[Object.keys(commands).find(check)]) - } else if (args.join(' ')) return 'Incorrect parameters. Run /help for general help.' + } else if (args.join(' ')) return { content: 'Incorrect parameters. Run /help for general help.', error: true } // Default help. try { const channel = await message.author.getDMChannel() @@ -139,7 +139,7 @@ export const handleHelp: IveBotCommand = { }) return 'newbie, help has been direct messaged to you โœ…' } catch { - return `I cannot DM you the help for newbies, you ${getInsult()} โŒ` + return { content: `I cannot DM you the help for newbies, you ${getInsult()} โŒ`, error: true } } } } diff --git a/server/bot/commands/tools.ts b/server/bot/commands/tools.ts index e54f6f8..5328e01 100644 --- a/server/bot/commands/tools.ts +++ b/server/bot/commands/tools.ts @@ -131,7 +131,7 @@ export const handlePing: Command = { if (args.length === 1 && testPilots.includes(message.author.id)) { try { return execSync('ping -c 1 ' + args[0], { encoding: 'utf8' }).split('\n')[1] - } catch (e) { return 'Looks like pinging the website failed.' } + } catch (e) { return { content: 'Looks like pinging the website failed.', error: true } } } // Get the time before sending the message. const startTime = Date.now() @@ -219,8 +219,7 @@ getContent/getCleanContent(messageID), createMessage(content), getReactions(mess return res !== 'undefined' ? `${'```'}${res.replace(token, '')}${'```'}` : undefined } catch (e) { message.addReaction('โŒ') - return `**Error:** -${e}` + return { content: `**Error:**\n${e}`, error: true } } } } @@ -240,7 +239,7 @@ export const handleCreationtime: Command = { let id = args[0] id = (id.length === 17 || id.length === 18) && !isNaN(+id) ? id : getIdFromMention(args[0]) if ((id.length !== 17 && id.length !== 18) || isNaN(+id)) { - return `Provide an valid ID or mention, you ${getInsult()}.` + return { content: `Provide an valid ID or mention, you ${getInsult()}.`, error: true } } return moment((new Base(id)).createdAt).format('YYYY/MM/DD, hh:mm:ss A') } else { diff --git a/server/bot/commands/utilities.ts b/server/bot/commands/utilities.ts index e0935fc..b31fb7a 100644 --- a/server/bot/commands/utilities.ts +++ b/server/bot/commands/utilities.ts @@ -24,7 +24,7 @@ export const handleServerinfo: Command = { let guild = args.length ? client.guilds.find( i => i.members.has(message.author.id) && i.id === args[0] ) : message.member.guild - if (!guild) return `Specify a valid mutual guild, ${getInsult()}.` + if (!guild) return { content: `Specify a valid mutual guild, ${getInsult()}.`, error: true } // Owner. const owner = guild.members.get(guild.ownerID) // Nitro Boosting support. @@ -102,7 +102,7 @@ export const handleUserinfo: Command = { if (!user && message.author.id === host && [18, 17].includes(toGet.length) && !isNaN(+toGet)) { try { user = await client.getRESTUser(toGet) } catch (e) { } } - if (!user) return `Specify a valid member of this guild, ${getInsult()}.` + if (!user) return { content: `Specify a valid member of this guild, ${getInsult()}.`, error: true } // Display information. const member = message.member.guild.members.get(user.id) const color = member ? (member.roles.map(i => member.guild.roles.get(i)).sort( @@ -166,7 +166,7 @@ export const handlePermissions: Command = { if (!user && message.author.id === host && [18, 17].includes(toGet.length) && !isNaN(+toGet)) { try { user = await client.getRESTUser(toGet) } catch (e) { } } - if (!user) return `Specify a valid member of this guild, ${getInsult()}.` + if (!user) return { content: `Specify a valid member of this guild, ${getInsult()}.`, error: true } // Display permission info. const member = message.member.guild.members.get(user.id) const color = member ? (member.roles.map(i => member.guild.roles.get(i)).sort( @@ -274,7 +274,7 @@ export const handleSay: Command = { ) { if (message.member && !message.member.guild.channels.get(possibleChannel) .permissionsOf(message.member.id).has('sendMessages') - ) return `**You don't have enough permissions for that, you ${getInsult()}.**` + ) return { content: `**You don't have enough permissions for that, you ${getInsult()}.**`, error: true } args.shift() if (args.join(' ') === 'pls adim me') args = ['no'] tempDB.say[message.channelMentions[0]] = ( @@ -330,7 +330,7 @@ export const handleType: Command = { ) { if (message.member && !message.member.guild.channels.get(possibleChannel) .permissionsOf(message.member.id).has('sendMessages') - ) return `**You don't have enough permissions for that, you ${getInsult()}.**` + ) return { content: `**You don't have enough permissions for that, you ${getInsult()}.**`, error: true } args.shift() if (args.join(' ') === 'pls adim me') args = ['no'] await client.sendChannelTyping(message.channelMentions[0]) @@ -383,7 +383,7 @@ export const handleRemindme: Command = { }, generator: async (message, args, { db }) => { if (args.length < 2 || !ms(args[0])) { - return 'Correct usage: /remindme