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

Command processor

This script uses OnPlayerChat and processes chat input given by players if the first character is a forward slash.

[top]Code

Code 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;
}
Code c:
public OnPlayerChat(ID, message{})
{
	new str{MAX_CHAT_LENGTH};
	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;
}