# Commands and messages

Register commands that start with /, or listen to every message that arrives.

A plugin can handle messages in two ways:

* **Commands** run when a user sends `/command arguments`. They suit clear-cut actions, such as `/weather London`.
* **Message listeners** see every message. They suit keyword replies, statistics and the like.

Both run before the message reaches the model. A message a plugin has handled doesn't have to go to the model.

## Register a command

```python main.py
from shiritaibot.api import MessageEvent, Plugin, hook


class Weather(Plugin):
    @hook.command("weather", aliases={"forecast"})
    async def weather(self, event: MessageEvent, city: str):
        """Check the weather: /weather <city>"""
        yield event.plain_result(f"It's sunny in {city} today.")
```

`aliases` sets other names for the command, so both `/weather London` and `/forecast London` run it.

The first line of the docstring appears in `/help`, so describe how to use the command there.

## Command arguments

The text after the command is split on spaces and passed, in order, to the handler's parameters (those after `self` and `event`). Each parameter's type annotation decides how its value is converted:

| Annotation      | Conversion                                                                                       |
| --------------- | ------------------------------------------------------------------------------------------------ |
| `str`, or none  | Passed as is                                                                                     |
| `int` / `float` | Converted to a number                                                                            |
| `bool`          | `true`, `yes`, `on`, `1`, `是` and `开` are true; `false`, `no`, `off`, `0`, `否` and `关` are false |

* Parameters without a default are required. When a user leaves one out or the type doesn't match, ShiritaiBot replies with the usage, such as `Usage: /weather <city>`.
* The last `str` parameter receives all the remaining text, so for `/note remember homework tomorrow`, `async def note(self, event, text: str)` gets `remember homework tomorrow` as `text`. To collect the remaining arguments as a list, use `*args`.
* Quote an argument that contains spaces: `/remind "3 pm" meeting`.

```python main.py
@hook.command("add")
async def add(self, event: MessageEvent, a: int, b: int):
    """Add two numbers: /add 1 2"""
    return event.plain_result(str(a + b))

@hook.command("sum")
async def total(self, event: MessageEvent, *numbers: float):
    """Add them all up: /sum 1 2 3 ..."""
    return event.plain_result(str(sum(numbers)))
```

## Command groups

When a plugin has many features, put related commands in a group and call them as `/group subcommand arguments`:

```python main.py
@hook.command_group("todo")
def todo(self):
    """To-do list"""

@todo.command("add")
async def todo_add(self, event: MessageEvent, text: str):
    """Add a to-do: /todo add <text>"""
    ...

@todo.command("list")
async def todo_list(self, event: MessageEvent):
    """List to-dos: /todo list"""
    ...
```

A user who sends just `/todo` gets a list of the group's subcommands. Groups can be nested: create a subgroup with `todo.group("sub")`.

## Reply

A handler can reply in three ways. They all do the same thing: send a plain-text message to the session the command came from.

```python main.py
# 1. yield; yield several times to send several messages
yield event.plain_result("First")
yield event.plain_result("Second")

# 2. return one result, or just return a string
return "Done"

# 3. send at any point
await event.send("Looking it up, one moment…")
```

Commands run in the background for up to 10 minutes, and the bot keeps handling other messages meanwhile. Commands and their replies are saved in the session history, but they don't enter the model's context.

When a handler raises `PublicError`, its message is sent to the user as the reply, which suits expected errors such as "city not found". Any other exception only replies "The plugin command failed", with the full traceback in the log.

```python main.py
from shiritaibot.api import PublicError

if city not in CITIES:
    raise PublicError(f"Couldn't find the city “{city}”")
```

Replies are text only for now; images and other rich messages aren't supported yet.

## Limit where a command works

These decorators stack with `@hook.command` to limit when a command applies:

```python main.py
from shiritaibot.api import MessageType, Permission, Platform, hook

@hook.permission(Permission.OWNER)          # owner only; anyone else gets a notice
@hook.message_type(MessageType.PRIVATE)     # private chats only
@hook.platform(Platform.QQ)                 # QQ only
@hook.command("reset")
async def reset(self, event: MessageEvent):
    ...
```

| Decorator                 | Values                                                        |
| ------------------------- | ------------------------------------------------------------- |
| `@hook.permission(...)`   | `Permission.OWNER`, `Permission.EVERYONE`                     |
| `@hook.message_type(...)` | `MessageType.PRIVATE`, `MessageType.GROUP`, `MessageType.ALL` |
| `@hook.platform(...)`     | `Platform.QQ`, `Platform.WEB`, `Platform.ALL`                 |

## Listen to messages

Listen to ordinary messages, without a `/`, with `@hook.message_type` or `@hook.regex`:

```python main.py
@hook.regex(r"^ping$")
async def ping(self, event: MessageEvent):
    await event.send("pong")
    event.stop_event()   # don't pass it to other plugins or the model

@hook.message_type(MessageType.GROUP)
async def count(self, event: MessageEvent):
    total = await self.get_kv_data(event.group_id, 0)
    await self.put_kv_data(event.group_id, total + 1)
```

* `@hook.message_type(...)` receives every message of that type.
* `@hook.regex(pattern)` is called only when the message text matches the regular expression.

After `event.stop_event()`, later listeners don't run and the message doesn't go to the model. Without it, the message goes to the model as usual.

Group messages that neither `@` the bot nor contain a wake word reach listeners too, with `event.is_wake` set to `False`. These messages never go to the model anyway, so they're good for statistics or keyword triggers.

Listeners run by `priority`, highest first (the default is 0). Set it in the decorator, as in `@hook.regex(r"^ping$", priority=10)`. One listener may run for at most 30 seconds; move long work into a background task.

## The message event

The `event` a handler receives is a `MessageEvent`. Its most useful fields:

| Field                     | Description                                                                                                    |
| ------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `text`                    | The plain text the user sent                                                                                   |
| `session`                 | The session ID, such as `private:qq:12345`; pass it to `self.context.send_message()` to send messages yourself |
| `sender_id`               | The sender's ID                                                                                                |
| `get_sender_name()`       | The sender's nickname, or their ID when there's none                                                           |
| `platform`                | `qq` or `web`                                                                                                  |
| `group_id`                | The group number; an empty string in private chats                                                             |
| `is_group` / `is_private` | Whether it's a group / private chat                                                                            |
| `is_owner`                | Whether the sender is the owner                                                                                |
| `is_wake`                 | Whether this message wakes the bot                                                                             |
| `message_id`              | The message ID                                                                                                 |
| `segments`                | OneBot message segments, for images, @mentions and the like                                                    |
| `raw`                     | The raw event from the protocol client                                                                         |

Changing these fields doesn't change what the model sees. To add to the model's input, use [`on_llm_request`](https://shiritaibot.dev/en/docs/plugins/hooks#llm-request).

## Things to watch out for

* A plugin command can't have the same name as a built-in command (`/help`, `/status`, `/stop` and so on) or another plugin's command, or the plugin fails to load.
* Built-in commands, `stop` / `停`, `cancel` / `取消` and replies to tool approvals are always handled by ShiritaiBot itself and never reach plugins.
