This site has been archived and made available for preservation purposes. No edits can be made.

Command processor

(Difference between revisions)
Return to current revision
  1.  
    This script uses OnPlayerChat and processes chat input given by players if the first character is a forward slash.
    [h="2"] Code [/h]
    [highlight=cpp]
    #include "vaultscript.h"
    #include <cstdlib>
    #include <cstring>

    using namespace vaultmp;

    State VAULTSCRIPT OnPlayerChat(ID player, RawString message) noexcept
    {
    // it's a command if the first character is a /
    if (*message == '/')
    {
    // we can safely tokenize because we won't send the message
    std::vector<String> tokens;
    RawString cmd = std::strtok(message + 1, " ");

    // collecting tokens
    while (cmd)
    {
    tokens.emplace_back(cmd);
    cmd = std::strtok(nullptr, " ");
    }

    if (!tokens.empty())
    {
    // Player object
    Player pplayer(player);

    if (!tokens[0].compare("additem"))
    {
    // baseID given?
    if (tokens.size() > 1)
    {
    // get the hexadecimal baseID of the item
    Base item = static_cast<Base>(std::strtoul(tokens[1].c_str(), nullptr, 16));
    // give item to player with notification
    pplayer.AddItem(item, 1, 100.0, False);
    }
    }
    // more commands...
    else
    {
    // send error message
    std::strncpy(message, String("Unrecognized command: " + tokens[0]).c_str(), static_cast<size_t>(Index::MAX_CHAT_LENGTH));
    return True;
    }
    }

    return False;
    }

    return True;
    }
    [/highlight]
    [highlight=c]
    public OnPlayerChat(ID, message{})
    {
  2. -
    new str{MAX_CHAT_LENGTH};
  3. +
    new str{MAXVAULTCHAT_LENGTH};
  4.  
    if(message{0} == '/' && strlen(message)>1)
    {
    new delim = strfind(message," "),
    params{MAX_MESSAGE_LENGTH},
    len = strlen(message);
    strmid(str,message,1,delim==-1?len:delim);
    if(delim>1) strmid(params,message,delim+1,len);
    if(!strcmp(str,"additem"))
    {
    AddItem(ID,strval(params),1,100.0,Bool:true);
    return 0;
    }
    strformat(str,sizeof(str),true,"SERVER: The command \"/%s\" does not exist",str);
    ChatMessage(ID,str);
    return 0;
    }
    return 1;
    }
    [/highlight]

    [category]Script examples[/category]