Skip to content

Commit

Permalink
Finish re-eval on error for all commands.
Browse files Browse the repository at this point in the history
- /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.
  • Loading branch information
retrixe committed May 4, 2021
1 parent 9d84d7a commit 1b0369a
Show file tree
Hide file tree
Showing 7 changed files with 62 additions and 61 deletions.
14 changes: 8 additions & 6 deletions server/bot/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
36 changes: 18 additions & 18 deletions server/bot/commands/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <robot, monster, head, cat, human> <text to robohash>'
return { content: 'Correct usage: /robohash <robot, monster, head, cat, human> <text to robohash>', error: true }
}
}
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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]}`
Expand Down Expand Up @@ -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}`
Expand Down Expand Up @@ -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 } }
}
}

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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(', ')}:**`,
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 } }
}
}

Expand Down Expand Up @@ -654,15 +654,15 @@ 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. <https://xkcd.com/${res[1].id}>` : ''
const res3 = res[2] ? `\n3. <https://xkcd.com/${res[2].id}>` : ''
return `**Top results:**\n1. ${res1}${res2}${res3}`
} 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()
Expand All @@ -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]
}
Expand Down
10 changes: 5 additions & 5 deletions server/bot/commands/games.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)]}`
}
Expand Down Expand Up @@ -128,10 +128,10 @@ export const handleRepeat: Command = {
const number = +args.shift()
if (isNaN(number)) return 'Correct usage: /repeat <number of times> <string to 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(' ') }
Expand Down Expand Up @@ -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)}`
}
Expand All @@ -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 }
}
}
}
Expand Down
12 changes: 6 additions & 6 deletions server/bot/commands/gunfight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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] = {
Expand Down Expand Up @@ -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']
Expand Down
4 changes: 2 additions & 2 deletions server/bot/commands/help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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 }
}
}
}
7 changes: 3 additions & 4 deletions server/bot/commands/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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 }
}
}
}
Expand All @@ -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 {
Expand Down
Loading

0 comments on commit 1b0369a

Please sign in to comment.