Tuesday 30 May 2017

Get certain part of string in javascript

I am making a Discord bot, and it has a method called addCmd, which allows me to make it modular. The problem lies where I attempt to detect the command, and see if it is valid. Currently, I am checking if the command is in the commands object. That works, but the problem lies when I'm getting arguments. The arguments list is empty. My format is !cmd arg1 arg2 arg3..., but it is currently seperated by underscores. I am passing these arguments to a function.

My code is listed here:

https://pastebin.com/UwygrkLf

var Discord = require('discord.js')
var client = new Discord.Client()
var cmds = {}
var errorlvl

var prefix = '!'
function weAreReady() {
    console.log('The bot has successfully logged in.')
}

function addCmd(name, argNumber, cmd, usage) {
    cmds[name] = {name:name,func: cmd, usage: usage,argNum: argNumber}
}

client.on('ready', weAreReady)
client.on('message', function (message) {

    if (message.content.startsWith(prefix)) {
        cmd = message.content.split(prefix).pop()
        actualcmd = cmd.split('_').pop()
        var args
        if (cmds[actualcmd] == undefined) {
            //It is not a vailid command
            console.log('invalid cmd')
            console.log('cmd: ' + actualcmd)
        } else {
            //Get to actually parsing the command
            args = cmd.split(cmd).pop().split('_')
            console.log(args)
            console.log(cmds[actualcmd].argNum)
            if (args.length === cmds[actualcmd].argNum + 1) {

                //Correct number of args
                args.unshift(message);
                cmds[actualcmd].func.apply(this, args)
            } else {

                cmds[actualcmd].usage(message)
            }


        }
    }
})

addCmd('hello', 0, function (message) {
    message.channel.send('Hello, ' + message.author.username)
    errorlvl = 0
}, function (message) {
    errorlvl = 1
    message.channel.send(message.author.username + ', the arguments are not complete. The full usage of this command is: !hello')
})
client.login('MzE4ODk2MDM5NDM4NDUwNjk5.DA5Cuw.EyshBBnXnrETKf2KPU-MKclulpg')

The code I use for separating the args from the command is:

args = cmd.split(cmd).pop().split('_')

For splitting the cmd from the prefix and the args, I use:

cmd = message.content.split(prefix).pop()
actualcmd = cmd.split('_').pop()



via Michael

No comments:

Post a Comment