chat-commander
Version:
chat command parser engine
49 lines (37 loc) • 1.05 kB
JavaScript
const Promise = require("bluebird")
const Group = require("./group")
class Commander extends Group {
constructor(sep = "/") {
super("", sep)
}
get allCommands() {
return this._buildCommands()
}
findCommand(message) {
const text = message.trim().toLowerCase()
const commands = this.allCommands
const names = Object.keys(commands)
const name = names.find(name => text.match(new RegExp("^" + name, "i")))
if (!name) return {}
return {
command: commands[name],
request: message.trim().replace(new RegExp("^" + name + "\\s*", "i"), ""),
name: name
}
}
execute(message, context) {
// split / find command
const parsed = message.command? message: this.findCommand(message)
// no command found
if (!parsed.command) return Promise.reject("commander")
const request = parsed.command.parse(parsed.request, context)
return Promise.try(() => parsed.command.call(request, context))
}
static get commands() {
return {
help: require("./commands/help")
}
}
}
module.exports = Commander