Skip to content

Commit

Permalink
Tiny optimization, fix /apod for videos and add re-eval on edit.
Browse files Browse the repository at this point in the history
  • Loading branch information
retrixe committed Nov 5, 2018
1 parent 11f8e92 commit 5644b87
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 28 deletions.
56 changes: 44 additions & 12 deletions server/bot/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,12 +112,16 @@ export default class CommandParser {
client: Client // eslint-disable-line no-undef
tempDB: DB // eslint-disable-line no-undef
db: Db // eslint-disable-line no-undef
evaluatedMessages: string[] // eslint-disable-line no-undef

constructor (client: Client, tempDB: DB, db: Db) {
this.commands = {}
this.client = client
this.tempDB = tempDB
this.db = db
this.evaluatedMessages = []
this.onMessage = this.onMessage.bind(this)
this.onMessageUpdate = this.onMessageUpdate.bind(this)
}

registerCommand = (command: IveBotCommand) => { // eslint-disable-line no-undef
Expand Down Expand Up @@ -161,38 +165,66 @@ export default class CommandParser {
}

async onMessage (message: Message) {
if (!message.content.split(' ')[0].startsWith('/')) {
if (!message.content.startsWith('/')) {
botCallback(message, this.client, this.tempDB, this.db)
return // Don't process it if it's not a command.
}
const commandExec = message.content.split(' ')[0].substr(1).toLowerCase()
// Webhook and bot protection.
try { if (message.author.bot) return } catch (e) { return }
// Check for the commands in this.commands.
// Check for the command in this.commands.
const keys = Object.keys(this.commands)
for (let i = 0; i < keys.length; i++) {
if (commandExec === keys[i]) {
if (commandExec === keys[i] || (
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 {
await this.executeCommand(this.commands[keys[i]], message)
} catch (e) {
try { await this.executeCommand(this.commands[keys[i]], message) } 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)
console.error(e)
}
return
} else if (
}
}
botCallback(message, this.client, this.tempDB, this.db)
}

// For evaluating messages which weren't evaluated.
async onMessageUpdate (message: Message, oldMessage?: Message) {
// We won't bother with a lot of messages..
if (!message.content.startsWith('/')) return
else if (this.evaluatedMessages.includes(message.id)) return
else if (!oldMessage || Date.now() - message.timestamp > 30000) return
else if (message.editedTimestamp - message.timestamp > 30000) return
// Proceed to evaluate.
const commandExec = message.content.split(' ')[0].substr(1).toLowerCase()
// Webhook and bot protection.
try { if (message.author.bot) return } catch (e) { return }
// Check for the command in this.commands.
const keys = Object.keys(this.commands)
for (let i = 0; i < keys.length; i++) {
if (commandExec === keys[i] || (
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 {
await this.executeCommand(this.commands[keys[i]], message)
} catch (e) {
try { await this.executeCommand(this.commands[keys[i]], message) } 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)
console.error(e)
}
return
}
}
botCallback(message, this.client, this.tempDB, this.db)
}
}
36 changes: 20 additions & 16 deletions server/bot/commands/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,28 +123,32 @@ export const handleApod: Command = {
])
if (date.isValid()) {
const dateStr = date.format('YYYY-MM-DD')
// Fetch a picture.
try {
const { url, title, explanation } = await (await fetch(
// Fetch a picture or video.
try { // eslint-disable-next-line camelcase
const { media_type, url, title, explanation } = await (await fetch(
`https://api.nasa.gov/planetary/apod?api_key=${NASAtoken}&date=${dateStr}`
)).json()
return {
content: '**' + title + '**\n' + explanation,
embed: { image: { url }, color: 0x2361BE }
}
)).json() // eslint-disable-next-line camelcase
return media_type === 'video'
? `**${title}**\n${explanation}\n${url.split('embed/').join('watch?v=')}`
: {
content: `**${title}**\n${explanation}`,
embed: { image: { url }, color: 0x2361BE }
}
} catch (err) { return `Something went wrong 👾 Error: ${err}` }
} else if (args.length) {
return 'Invalid date.'
}
// Fetch a picture.
try {
const { hdurl, title, explanation } = await (await fetch(
// Fetch a picture or video.
try { // eslint-disable-next-line camelcase
const { media_type, url, hdurl, title, explanation } = await (await fetch(
`https://api.nasa.gov/planetary/apod?api_key=${NASAtoken}`
)).json()
return {
content: '**' + title + '**\n' + explanation,
embed: { image: { url: hdurl }, color: 0x2361BE }
}
)).json() // eslint-disable-next-line camelcase
return media_type === 'video'
? `**${title}**\n${explanation}\n${url.split('embed/').join('watch?v=')}`
: {
content: `**${title}**\n${explanation}`,
embed: { image: { url: hdurl }, color: 0x2361BE }
}
} catch (err) { return `Something went wrong 👾 Error: ${err}` }
}
}
Expand Down
1 change: 1 addition & 0 deletions server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ MongoClient.connect(mongoURL === 'dotenv' ? process.env.MONGO_URL : mongoURL, {
// Register the commandParser.
const commandParser = new CommandParser(client, tempDB, db)
client.on('messageCreate', commandParser.onMessage)
client.on('messageUpdate', commandParser.onMessageUpdate)
// Register all commands in bot/commands onto the CommandParser.
readdir('./server/bot/commands', (err, commandFiles) => {
// Handle any errors.
Expand Down

0 comments on commit 5644b87

Please sign in to comment.