Skip to content

Instantly share code, notes, and snippets.

@zekroTJA
Created December 1, 2017 10:36
Show Gist options
  • Select an option

  • Save zekroTJA/d5c3d35abb234c4937ec09ea1c0ea93c to your computer and use it in GitHub Desktop.

Select an option

Save zekroTJA/d5c3d35abb234c4937ec09ea1c0ea93c to your computer and use it in GitHub Desktop.
discord.js - Command Parser Class
const Discord = require('discord.js')
/**
* Create instance of command parser
* @param {*string} prefix Command Prefix
* @param {*discord.Client} bot Bot Instance
*/
class CmdParser {
constructor(prefix, bot) {
this.prefix = prefix
this.bot = bot
this.type = {
ADMIN: "ADMIN",
GUILDADMIN: "GUILDADMIN",
MODERATION: "MODERATION",
FUN: "FUN",
SETTING: "SETTING"
}
this.cmds = {}
/**
* Register a command.
* @param {*function} cmdfunc Command Function
* @param {*string} invoke Command Invoke
* @param {*string[]} aliases Command Aliases
* @param {*string} description Command Description
* @param {*string} help Command Help and Usage
* @param {*CmdParser.type} type Command Type
*/
this.register = function(cmdfunc, invoke, aliases, description, help, type) {
this.cmds[invoke] = {
cmdfunc: cmdfunc,
invoke: invoke,
aliases: aliases,
description: description,
help: help,
type: type
}
}
/**
* Parse a message from a message event.
* @param {*Discord.Message} msg Message Event
*/
this.parse = function(msg) {
const cont = msg.content,
author = msg.member,
guild = msg.guild,
chan = msg.channel
if (author.id != this.bot.user.id && cont.startsWith(this.prefix)) {
// Splitting args with " " but not in quotes
// -> https://stackoverflow.com/questions/16261635/javascript-split-string-by-space-but-ignore-space-in-quotes-notice-not-to-spli#16261693
const invoke = cont.split(' ')[0].substr(this.prefix.length),
args = cont.match(/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g).slice(1)
if (invoke == "help") {
if (args.length == 0) {
var out = ""
for (var inv in this.cmds) {
var cmd = this.cmds[inv]
out += `\`${this.prefix}${cmd.invoke}\` - ${cmd.description} *(${cmd.type})*\n`
}
chan.send("", new Discord.RichEmbed().setColor(0xd2db2b).setDescription(out))
}
else {
if (invoke in this.cmds)
chan.send("", new Discord.RichEmbed().setColor(0xd2db2b).setDescription(`**USAGE:**\n${this.cmds[invoke].help}`))
else
chan.send("", new Discord.RichEmbed().setColor(0xdb3a2b).setDescription("There is no command with this invoke registered!"))
}
}
else if (invoke in this.cmds) {
console.log(`[COMMAND] (${author.user.username} @ ${guild.name}) '${cont}'`)
this.cmds[invoke].cmdfunc(msg, args)
}
}
return this
}
}
}
exports.CmdParser = CmdParser
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment