[Release] Command Manager for VCMP

Started by umar4911, Jan 15, 2022, 07:28 PM

Previous topic - Next topic

umar4911

Command Manager


I had this command manager scripted long ago which I used in my old squirrel-based projects. Complete credits go to SLC as this command manager is a replica of the SqMod command manager and has a function of getting argument type made by him.




Installation

function onScriptLoad()
{
    CPlayer.rawnewmember("Authority", 1);
    dofile("CMD_Manager.nut", true);
}


function onPlayerCommand(player, cmd, arguments)
{
    local str = cmd + (arguments == null ? "" : " " + arguments);
    if(cmd != "") CMD_Manager.Run(player, player.Authority, str);
}



The code for CMD_Manager.nut can be found on the Github Repository.




Usage


Creating command

The syntax to create a command is:
CMD_Manager.Create(command, args_type, args_array, min_args, max_args, auth, protected, assoc)
Understanding the parameters

First argument is the command name.

Second are the command masks for each argument. At the moment it supports the following specifiers:

i The argument accepts integer.
f The argument accepts floating point number.
b The argument accepts boolean.
s The argument accepts string.
g This argument is a greedy argument. Anything after this argument is captured as a string and no further parsing is done.

And you can combine them if one argument accepts multiple types of values.

Let's say that your command expects integer or float for the first argument, boolean for the second, uppercase string for the third and integer, float or boolean for the fourth. Then your mask should be like:

"if|b|u|ifb"
That way the command system knows how to parse the parameters and what values to expect.

Third argument is an array of argument names.  For example, let's say I'm creating a register command with 3 arguments. I'll probably specify ["name", "password", "email"].

The fourth and fifth argument is the minimum and maximum arguments that the command needs. When calling the command you only need the minimum and the rest is optional. You can have up to 16 arguments. I believe that's a fair number.

The sixth argument defines the authority/level of the command. It is validated with the newly added player.Authority. So yea, you got yourself an easy admin system in it, just change the player's authority.
player.Authority = 5If the player's authority is equal to more than the command authority, then it is triggered.

The seventh argument defines whether you want to protect the command or validate it to the player's authority. When set to true, it checks whether the player's authority is equal to or more than the command's authority. When set to false, it skips this validation step.

The last argument is Assosicate. It defines whether to get command's  'args' in form of table or array. When set to true, values are received in table form or else in array form.


Once done, you need to bind an environment and a function with 2 parameters (player and arguments) to the command by for example,
CMD_Manager.Create().BindExec(this, function (player, args) {

});



Lets create a command sethealth
CMD_Manager.Create("sethealth", "s|i", ["Target", "HP"], 0, 2, 1, true, false).BindExec(this, function(player, args) {
    if(args.len() >= 2)
    {
        local plr = FindPlayer(args[2]);
        if(plr)
        {
            if(args[1] <= 255 && args[1] >= 0)
            {
                Message(format("%s changed the health of %s to %d", player.Name, plr.Name, args[1]));
                plr.Health = args[1];
            }
            else MessagePlayer("Health must be between 0 to 255.", player);
        }
        else MessagePlayer("Unknown player", player);
    }
    else MessagePlayer("Wrong syntax, use /sethealth <player> <hp>", player)
})
This command is set to work if the arguments passed by the player are in between 0 to 2, having authority 1. Since the Associate is defined as zero, the arguments are in form of an array. Now the same command but which Associate set to true:
CMD_Manager.Create("sethealth", "s|i", ["Target", "HP"], 0, 2, 1, true, true).BindExec(this, function(player, args) {
    if(args.rawin("Target") && args.rawin("HP"))
    {
        local plr = FindPlayer(args.Target);
        if(plr)
        {
            if(args[1] <= 255 && args[1] >= 0)
            {
                Message(format("%s changed the health of %s to %d", player.Name, plr.Name, args.HP));
                plr.Health = args.HP;
            }
            else MessagePlayer("Health must be between 0 to 255.", player);
        }
        else MessagePlayer("Unknown player", player);
    }
    else MessagePlayer("Wrong syntax, use /sethealth <player> <hp>", player)
})
The arguments are now in table form.



Error Handling:

In order to trigger errors for the commands, you need to define a BindFail function.

There are total 5 types of Errors defined in an Enum:
enum CMDErrorTypes {
    UnknownCommand,
    InsufficientAuth,
    UnsupportedArg,
    IncompleteArgs,
    SyntaxError
}

An example of BindFail function:
CMD_Manager.BindFail(this, function (type, player, cmd, msg) {

switch(type)
{
case CMDErrorTypes.UnknownCommand:
MessagePlayer("[#ffffff]Error - Command doesn't exist.", player);
break;
case CMDErrorTypes.InsufficientAuth:
MessagePlayer("[#FF3300]Error - Unauthorized Access.", player);
break;
case CMDErrorTypes.UnsupportedArg:
MessagePlayer(format("[#DDFF33]Error - Wrong type of parameter passed to command %s.", cmd), player);
break;
case CMDErrorTypes.IncompleteArgs:
MessagePlayer(format("[#FFDD33]Error - Incomplete arguments for command %s.", cmd), player);
break;
case CMDErrorTypes.SyntaxError:
MessagePlayer(format("[#ff0000]Error - [#ffffff]Command %s throwed an error: %s", cmd, msg), player);
break;
default:
print("Bind Fail called");
break;
}
})





All credits go to SLC for this post too as I stole some content of his :P





Some cool things that you can do for example:
[spoiler]
CMD_Manager.Create("cmds", "", [""], 0, 0, 1, true, true).BindExec(this, function (player, args) {
    local msg = "";
    foreach(listener in CMD_Manager.GetArray())
    {
        {
            if(msg != "") msg += ", ";
            msg += listener.Name;
        }
    }
    MessagePlayer(format("Available commands: %s", msg), player);
});

An example of having commands with the same function but different name (like wep, we)


{
    local exec = function (player, args) {
       if(args.rawin("code"))
    {
        try
        {
            local cscr = compilestring(args.code);
            cscr();
        }
        catch (e) MessagePlayer(format("Exection Error %s", e), player);
    }
    else MessagePlayer("/e ( Code )", player);
    }
    CMD_Manager.Create("e", "g", ["code"], 0, 1, 1, true, true).BindExec(this, exec);
    CMD_Manager.Create("exec", "g", ["code"], 0, 1, 1, true, true).BindExec(this, exec);
}
[/spoiler]
RT Member | Asian City Scripter | CTB Contributor | VKs Contributor | European City Contributor | EAD Scripter

habi

Nice program.
btw,
so sqmod has implemented function of adding new property to player instance. This will be very useful here and in other areas like pickup.
CPlayer.rawnewmember("Authority", 1);

.

I mean. I'm a bit sad people are still struggling with official plugin knowing fully that there are a bunch of issues with it. But I'm just glad that you're are moving away from non-scalable traditional way of implementing this. Which is, using a bunch of if/else statements (or switch case) with the same code and duplicating the same parameter validation code (if any) all over the place.

So I'll take it. Is just good seeing grow out of that bad habit. Even if not for the best reason ;D
.