1#include <CS2Kit/Commands/CommandManager.hpp>
2#include <CS2Kit/Utils/StringUtils.hpp>
9void CommandManager::Register(Command cmd)
11 _commands[StringUtils::ToLower(cmd.Name)] = std::move(cmd);
14void CommandManager::Unregister(
const std::string& name)
16 _commands.erase(StringUtils::ToLower(name));
19bool CommandManager::HandleChatMessage(Players::Player* caller,
const std::string& message)
21 if (!caller || message.empty())
24 bool hasPrefix =
false;
26 for (
const auto& prefix : _prefixes)
28 if (message.size() >= prefix.size() && message.compare(0, prefix.size(), prefix) == 0)
31 prefixLen = prefix.size();
39 auto parts = ParseArguments(message.substr(prefixLen));
43 const std::string& cmdName = parts[0];
44 std::vector<std::string> args(parts.begin() + 1, parts.end());
46 const Command* cmd = GetCommand(cmdName);
50 auto reportResult = [&](
const CommandResult& result) {
52 _resultCallback(caller, *cmd, result);
55 if (
static_cast<int>(args.size()) < cmd->MinArgs ||
56 (cmd->MaxArgs != 99 &&
static_cast<int>(args.size()) > cmd->MaxArgs))
58 std::string msg =
"Usage: " + (cmd->Usage.empty() ? cmd->Name : cmd->Usage);
59 reportResult({
false, msg});
63 if (!cmd->Permission.empty())
65 if (_permissionCallback && !_permissionCallback(caller->GetSteamID(), cmd->Permission))
67 reportResult({
false,
"You do not have permission to use this command."});
74 auto result = cmd->Handler(caller, args);
81const Command* CommandManager::GetCommand(
const std::string& name)
const
83 std::string lowerName = StringUtils::ToLower(name);
85 auto it = _commands.find(lowerName);
86 if (it != _commands.end())
89 for (
const auto& [key, cmd] : _commands)
91 if (cmd.Matches(name))
98std::vector<const Command*> CommandManager::GetAllCommands()
const
100 std::vector<const Command*> commands;
101 commands.reserve(_commands.size());
103 for (
const auto& [name, cmd] : _commands)
105 commands.push_back(&cmd);
111std::vector<std::string> CommandManager::ParseArguments(
const std::string& text)
const
113 return StringUtils::Split(text,
' ');