> For the complete documentation index, see [llms.txt](https://docs.quickclient.cc/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.quickclient.cc/extras/commands.md).

# Свои команды

Как добавить скрипту свою команду в чате с подкомандами и подсказками.

Скрипт может добавить свою команду в чат, например `.home`. `command(name)` собирает команду Quick с префиксом `.`, и она работает, пока скрипт включён. Когда скрипт выключают, команда перестаёт отвечать и пропадает из подсказок. В конце обязательно вызовите `register()`, без него команда не появится.

```java
@Override
public void activate() {
    command("home")
            .usage("<go|list>")
            .alias("h")
            .sub("go", go -> go
                    .completes(0, "base", "farm")
                    .runs(context -> context.reply("иду на " + context.arg(0))))
            .sub("list", list -> list.runs(context -> context.reply("base, farm")))
            .register();
}
```

## Как это работает

* `home` это имя команды, а `h` её второе имя, поэтому `.h go base` тоже сработает.
* У `go` и `list` свои обработчики. Подсказки `base` и `farm` появляются на первом аргументе `go`.
* `context.reply` отправляет ответ в чат игроку.

Аргументы это всё, что идёт после пути команды, разбитое по пробелам. Для `.home go base` путь `home go`, а аргумент один: `base`. Номера аргументов в подсказках считаются с нуля.

## Command

| Метод                          | Тип       | Описание                                                                          |
| ------------------------------ | --------- | --------------------------------------------------------------------------------- |
| `usage(text)`                  | `Command` | подсказка, которую Quick добавит к сообщению об ошибке, если не хватает аргумента |
| `alias(alias)`                 | `Command` | ещё одно имя для той же команды со всеми подкомандами                             |
| `runs(handler)`                | `Command` | обработчик команды; получает `CommandContext` и выполняется в потоке игры         |
| `sub(name, body)`              | `Command` | подкоманда; в `body` она описывается тем же построителем                          |
| `completes(index, options...)` | `Command` | готовые варианты подсказки для аргумента                                          |
| `completes(index, supplier)`   | `Command` | варианты от поставщика, он вызывается, пока игрок печатает                        |
| `register()`                   | `void`    | регистрирует команду вместе с алиасами                                            |

Ещё есть служебные геттеры `name()`, `aliases()`, `usage()`, `subs()`, `complete(index)`. Они только читают то, что было задано в построителе.

## CommandContext

| Метод                               | Тип             | Описание                                             |
| ----------------------------------- | --------------- | ---------------------------------------------------- |
| `label()`                           | `String`        | полный путь команды, например `home go`              |
| `args()`                            | `List<String>`  | аргументы после пути                                 |
| `argCount()`                        | `int`           | количество аргументов                                |
| `arg(index)`                        | `String`        | аргумент по номеру                                   |
| `argOr(index, fallback)`            | `String`        | аргумент, а если его нет, запасное значение          |
| `intArg(index)`, `doubleArg(index)` | `int`, `double` | аргумент в виде числа                                |
| `booleanArg(index)`                 | `boolean`       | `true/on/yes/1` и `false/off/no/0`, регистр не важен |
| `rest()`, `rest(fromIndex)`         | `String`        | аргументы одной строкой                              |
| `reply(message)`                    | `void`          | ответ в чат с пометкой, какая команда отвечает       |

Если аргумента не хватает и вызывается `arg(index)`, Quick сам выведет в чат ошибку с `usage`, и обработчик дальше не выполнится.

## Команды самого Quick

У Quick есть встроенные команды: `.script list`, `.script reload`, `.script toggle <имя>`, `.script settings <имя>`, `.script set <имя> <id> <значение>`, `.script dir`, `.script check`. Свои команды лучше называть иначе, потому что команды Quick регистрируются раньше.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.quickclient.cc/extras/commands.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
