CS2-Kit
C++23 library for CS2 Metamod:Source plugin development
Loading...
Searching...
No Matches
CommandManager.cpp
Go to the documentation of this file.
1#include <CS2Kit/Commands/CommandManager.hpp>
2#include <CS2Kit/Utils/StringUtils.hpp>
3
4namespace CS2Kit::Commands
5{
6
7using namespace CS2Kit::Utils;
8
9void CommandManager::Register(Command cmd)
10{
11 _commands[StringUtils::ToLower(cmd.Name)] = std::move(cmd);
12}
13
14void CommandManager::Unregister(const std::string& name)
15{
16 _commands.erase(StringUtils::ToLower(name));
17}
18
19bool CommandManager::HandleChatMessage(Players::Player* caller, const std::string& message)
20{
21 if (!caller || message.empty())
22 return false;
23
24 bool hasPrefix = false;
25 size_t prefixLen = 0;
26 for (const auto& prefix : _prefixes)
27 {
28 if (message.size() >= prefix.size() && message.compare(0, prefix.size(), prefix) == 0)
29 {
30 hasPrefix = true;
31 prefixLen = prefix.size();
32 break;
33 }
34 }
35
36 if (!hasPrefix)
37 return false;
38
39 auto parts = ParseArguments(message.substr(prefixLen));
40 if (parts.empty())
41 return false;
42
43 const std::string& cmdName = parts[0];
44 std::vector<std::string> args(parts.begin() + 1, parts.end());
45
46 const Command* cmd = GetCommand(cmdName);
47 if (!cmd)
48 return false;
49
50 auto reportResult = [&](const CommandResult& result) {
51 if (_resultCallback)
52 _resultCallback(caller, *cmd, result);
53 };
54
55 if (static_cast<int>(args.size()) < cmd->MinArgs ||
56 (cmd->MaxArgs != 99 && static_cast<int>(args.size()) > cmd->MaxArgs))
57 {
58 std::string msg = "Usage: " + (cmd->Usage.empty() ? cmd->Name : cmd->Usage);
59 reportResult({false, msg});
60 return true;
61 }
62
63 if (!cmd->Permission.empty())
64 {
65 if (_permissionCallback && !_permissionCallback(caller->GetSteamID(), cmd->Permission))
66 {
67 reportResult({false, "You do not have permission to use this command."});
68 return true;
69 }
70 }
71
72 if (cmd->Handler)
73 {
74 auto result = cmd->Handler(caller, args);
75 reportResult(result);
76 }
77
78 return true;
79}
80
81const Command* CommandManager::GetCommand(const std::string& name) const
82{
83 std::string lowerName = StringUtils::ToLower(name);
84
85 auto it = _commands.find(lowerName);
86 if (it != _commands.end())
87 return &it->second;
88
89 for (const auto& [key, cmd] : _commands)
90 {
91 if (cmd.Matches(name))
92 return &cmd;
93 }
94
95 return nullptr;
96}
97
98std::vector<const Command*> CommandManager::GetAllCommands() const
99{
100 std::vector<const Command*> commands;
101 commands.reserve(_commands.size());
102
103 for (const auto& [name, cmd] : _commands)
104 {
105 commands.push_back(&cmd);
106 }
107
108 return commands;
109}
110
111std::vector<std::string> CommandManager::ParseArguments(const std::string& text) const
112{
113 return StringUtils::Split(text, ' ');
114}
115
116} // namespace CS2Kit::Commands