Difference between revisions of "Ru:Commands (SourceMod Scripting)"
m |
m (little translating) |
||
Line 1: | Line 1: | ||
− | [[SourceMod]] | + | [[SourceMod]] позволяет создать вам консольные команды, похожие на [[AMX Mod X]]. Есть два главных вида консольных команд: |
− | *''' | + | *'''Серверные команды''' - Fired from one of the following input methods: |
− | ** | + | **Для консоли сервера |
− | ** | + | **Для удаленной консоли (RCON) |
− | **the ServerCommand() | + | **the ServerCommand() функция, либо из SourceMod либо[[Half-Life 2]] движка |
− | *''' | + | *'''Консольные команды''' - Fired from one of the following input methods: |
− | ** | + | **консоль клиента |
**any of the server command input methods | **any of the server command input methods | ||
− | + | Для серверных команд не существует клиентского индекса. Для консольных/клиентских команд, существует клиентский индекс, но он может быть 0 что-бы показать что команда с сервера. | |
− | + | Обратите внимание, что кнопка-бинд "commands," такие как +attack и +duck, они не консольные команды. Эти команды отдельно передаются, посколько они отдельно привязаны. | |
− | = | + | =Серверные команды= |
− | + | Как отмечалось выше, server commands are fired through the server console, whether remote, local, or through the Source engine. There is no client index associated with a server command. | |
− | + | Серверные команды регистрируются через <tt>RegServerCmd()</tt> функцию, расположенную в <tt>console.inc</tt>. При регистрации команды, вы можете записать поверх существующей команды, and thus the return value is important. | |
*<b><tt>Plugin_Continue</tt></b> - The original server command will be processed, if there was one. If the server command was created by a plugin, this has no effect. | *<b><tt>Plugin_Continue</tt></b> - The original server command will be processed, if there was one. If the server command was created by a plugin, this has no effect. | ||
*<b><tt>Plugin_Handled</tt></b> - The original server command will not be processed, if there was one. If the server command was created by a plugin, this has no effect. | *<b><tt>Plugin_Handled</tt></b> - The original server command will not be processed, if there was one. If the server command was created by a plugin, this has no effect. | ||
*<b><tt>Plugin_Stop</tt></b> - The original server command will not be processed, if there was one. Additionally, no further hooks will be called for this command until it is fired again. | *<b><tt>Plugin_Stop</tt></b> - The original server command will not be processed, if there was one. Additionally, no further hooks will be called for this command until it is fired again. | ||
− | == | + | ==Добавление серверных команд== |
− | + | Допустим, мы хотим добавить тестовую команду, что-бы показать как Half-Life 2 breaks down command arguments. Вот возможная реализация: | |
<pawn> | <pawn> | ||
public OnPluginStart() | public OnPluginStart() | ||
Line 45: | Line 45: | ||
</pawn> | </pawn> | ||
− | == | + | ==Блокирование серверных команд== |
− | + | Допустим мы хотим отключить "kickid" команду на сервере. Нет причин делать это, но для примера сойдет: | |
<pawn> | <pawn> | ||
public OnPluginStart() | public OnPluginStart() | ||
Line 59: | Line 59: | ||
</pawn> | </pawn> | ||
− | = | + | =Консольные команды= |
− | + | В отличие от серверных команд, консольные могут быть вызваны, как сервером, так и клиентом, так что callback функция получает клиентский индекс, а также количество аргументов. Если сервер использовал команду, клиентский индекс будет 0. | |
When returning the <tt>Action</tt> from the callback, the following effects will happen: | When returning the <tt>Action</tt> from the callback, the following effects will happen: |
Revision as of 06:52, 18 July 2011
SourceMod позволяет создать вам консольные команды, похожие на AMX Mod X. Есть два главных вида консольных команд:
- Серверные команды - Fired from one of the following input methods:
- Для консоли сервера
- Для удаленной консоли (RCON)
- the ServerCommand() функция, либо из SourceMod либоHalf-Life 2 движка
- Консольные команды - Fired from one of the following input methods:
- консоль клиента
- any of the server command input methods
Для серверных команд не существует клиентского индекса. Для консольных/клиентских команд, существует клиентский индекс, но он может быть 0 что-бы показать что команда с сервера.
Обратите внимание, что кнопка-бинд "commands," такие как +attack и +duck, они не консольные команды. Эти команды отдельно передаются, посколько они отдельно привязаны.
Contents
Серверные команды
Как отмечалось выше, server commands are fired through the server console, whether remote, local, or through the Source engine. There is no client index associated with a server command.
Серверные команды регистрируются через RegServerCmd() функцию, расположенную в console.inc. При регистрации команды, вы можете записать поверх существующей команды, and thus the return value is important.
- Plugin_Continue - The original server command will be processed, if there was one. If the server command was created by a plugin, this has no effect.
- Plugin_Handled - The original server command will not be processed, if there was one. If the server command was created by a plugin, this has no effect.
- Plugin_Stop - The original server command will not be processed, if there was one. Additionally, no further hooks will be called for this command until it is fired again.
Добавление серверных команд
Допустим, мы хотим добавить тестовую команду, что-бы показать как Half-Life 2 breaks down command arguments. Вот возможная реализация:
public OnPluginStart() { RegServerCmd("test_command", Command_Test) } public Action:Command_Test(args) { new String:arg[128] new String:full[256] GetCmdArgString(full, sizeof(full)) PrintToServer("Argument string: %s", full) PrintToServer("Argument count: %d", args) for (new i=1; i<=args; i++) { GetCmdArg(i, arg, sizeof(arg)) PrintToServer("Argument %d: %s", i, arg) } }
Блокирование серверных команд
Допустим мы хотим отключить "kickid" команду на сервере. Нет причин делать это, но для примера сойдет:
public OnPluginStart() { RegServerCmd("kickid", Command_KickId) } public Action:Command_Kickid(args) { return Plugin_Handled }
Консольные команды
В отличие от серверных команд, консольные могут быть вызваны, как сервером, так и клиентом, так что callback функция получает клиентский индекс, а также количество аргументов. Если сервер использовал команду, клиентский индекс будет 0.
When returning the Action from the callback, the following effects will happen:
- Plugin_Continue: The original functionality of the command (if any) will still be processed. If there was no original functionality, the client will receive "Unknown command" in their console.
- Plugin_Handled: The original functionality of the command (if any) will be blocked. If there was no functionality originally, this prevents clients from seeing "Unknown command" in their console.
- Plugin_Stop: Same as Plugin_Handled, except that this will be the last hook called.
Note that, unlike AMX Mod X, SourceMod does not allow you to register command filters. I.e., there is no equivalent to this notation:
register_clcmd("say /ff", "Command_SayFF");
This notation was removed to make our internal code simpler and faster. Writing the same functionality is easy, and demonstrated below.
Adding Commands
Adding client commands is very simple. Let's port our earlier testing command to display information about the client as well.
public OnPluginStart() { RegConsoleCmd("test_command", Command_Test) } public Action:Command_Test(client, args) { new String:arg[128] new String:full[256] GetCmdArgString(full, sizeof(full)) if (client) { new String:name[32] GetClientName(client, name, sizeof(name)) PrintToServer("Command from client: %s", name); } else { PrintToServer("Command from server."); } PrintToServer("Argument string: %s", full) PrintToServer("Argument count: %d", args) for (new i=1; i<=args; i++) { GetCmdArg(i, arg, sizeof(arg)) PrintToServer("Argument %d: %s", i, arg) } }
Hooking Commands
A common example is hooking the say command. Let's say we want to tell players whether FF is enabled when they say '/ff' in game.
Before we implement this, a common point of confusion with the 'say' command is that Half-Life 2 (and Half-Life 1), by default, send it with the text in one big quoted string. This means if you say "I like hot dogs," your command will be broken down as such:
- Argument string: "I like hot dogs"
- Argument count: 1
- Argument #1: I like hot dogs
However, if a player types this in their console: say I like yams, it will be broken up as:
- Argument string: I like yams
- Argument count: 3
- Argument #1: I
- Argument #2: like
- Argument #3: yams
Thus, to take into account both of these situations, we are going to use GetCmdArgString and manually parse the input.
public OnPluginStart() { RegConsoleCmd("say", Command_Say) } public Action:Command_Say(client, args) { new String:text[192] GetCmdArgString(text, sizeof(text)) new startidx = 0 if (text[0] == '"') { startidx = 1 /* Strip the ending quote, if there is one */ new len = strlen(text); if (text[len-1] == '"') { text[len-1] = '\0' } } if (StrEqual(text[startidx], "/ff")) { new Handle:ff = FindConVar("mp_friendlyfire") if (GetConVarInt(ff)) { PrintToConsole(client, "Friendly fire is enabled.") } else { PrintToConsole(client, "Friendly fire is disabled.") } /* Block the client's messsage from broadcasting */ return Plugin_Handled } /* Let say continue normally */ return Plugin_Continue }
Creating Admin Commands
Let's create a simple admin command which kicks another player by their full name.
public OnPluginStart() { RegAdminCmd("admin_kick", Command_Kick, ADMFLAG_KICK, "Kicks a player by name") } public Action:Command_Kick(client, args) { if (args < 1) { PrintToConsole(client, "Usage: admin_kick <name>") return Plugin_Handled } new String:name[32], maxplayers, target = -1 GetCmdArg(1, name, sizeof(name)) maxplayers = GetMaxClients() for (new i=1; i<=maxplayers; i++) { if (!IsClientConnected(i)) { continue } decl String:other[32] GetClientName(i, other, sizeof(other)) if (StrEqual(name, other)) { target = i } } if (target == -1) { PrintToConsole(client, "Could not find any player with the name: \"%s\"", name) return Plugin_Handled } ServerCommand("kickid %d", GetClientUserId(target)); return Plugin_Handled }
Immunity
In our previous example, we did not take immunity into account. Immunity is a much more complex system in SourceMod than it was in AMX Mod X, and there is no simple flag to denote its permissions. Instead, two functions are provided:
- CanAdminTarget: Tests raw AdminId values for immunity.
- CanUserTarget: Tests in-game clients for immunity.
While immunity is generally tested player versus player, it is possible you might want to check for immunity and not have a targetting client. While there is no convenience function for this yet, a good idea might be to check for either default or global immunity on the player's groups (these can be user-defined for non-player targeted scenarios).
When checking for immunity, the following heuristics are performed in this exact order:
- If the targeting AdminId is INVALID_ADMIN_ID, targeting fails.
- If the targetted AdminId is INVALID_ADMIN_ID, targeting succeeds.
- If the targeting admin has Admin_Root (ADMFLAG_ROOT), targeting succeeds.
- If the targetted admin has global immunity, targeting fails.
- If the targetted admin has default immunity, and the targeting admin belongs to no groups, targeting fails.
- If the targetted admin has specific immunity from the targeting admin via group immunities, targeting fails.
- If no conclusion is reached via the previous steps, targeting succeeds.
So, how can we adapt our function about to use immunity?
public Action:Command_Kick(client, args) { if (args < 1) { PrintToConsole(client, "Usage: admin_kick <name>") return Plugin_Handled } new String:name[32], maxplayers, target = -1 GetCmdArg(1, name, sizeof(name)) maxplayers = GetMaxClients() for (new i=1; i<=maxplayers; i++) { if (!IsClientConnected(i)) { continue } decl String:other[32] GetClientName(i, other, sizeof(other)) if (StrEqual(name, other)) { target = i } } if (target == -1) { PrintToConsole(client, "Could not find any player with the name: \"%s\"", name) return Plugin_Handled } if (!CanUserTarget(client, target)) { PrintToConsole(client, "You cannot target this client.") return Plugin_Handled } ServerCommand("kickid %d", GetClientUserId(target)) return Plugin_Handled }
Client-Only Commands
SourceMod exposes a forward that is called whenever a client executes any command string in their console, called OnClientCommand. An example of this looks like:
public Action:OnClientCommand(client, args) { new String:cmd[16] GetCmdArg(0, cmd, sizeof(cmd)); /* Get command name */ if (StrEqual(cmd, "test_command")) { /* Got the client command! Block it... */ return Plugin_Handled } return Plugin_Continue }
It is worth noting that not everything a client sends will be available through this command. Command registered via external sources in C++ may not be available, especially if they are created via CON_COMMAND in the game mod itself. For example, "say" is usually implemented this way, because it can be used by both clients and the server, and thus it does not channel through this forward.
Chat Triggers
SourceMod will automatically create chat triggers for every command you make (as of revision 900). For example, if you create a console command called "sm_megaslap," administrators will be able to type any of the following commands in say/say_team message modes:
!sm_megaslap !megaslap /sm_megaslap /megaslap
SourceMod then executes this command and its arguments as if it came from the client console.
- "!" is the default public trigger (PublicChatTrigger in configs/core.cfg) and your entry will be displayed to all clients as normal.
- "/" is the default silent trigger (SilentChatTrigger in configs/core.cfg) and your entry will be blocked from being displayed.
SourceMod will only execute commands registered with RegConsoleCmd or RegAdminCmd, and only if those commands are not already provided by Half-Life 2 or the game mod. If the command is prefixed with "sm_" then the "sm_" can be omitted from the chat trigger.
Console commands which wish to support usage as a chat trigger should not use PrintTo* natives. Instead, they should use ReplyToCommand(), which will automatically print your message either as a chat message or to the client's console, depending on the source of the command.