# How a command runs

> The order things happen in when someone runs your command, and how to stop early or show an error.

A command has three parts. They run in this order every time:

1. **Pre-hook.** Your code that runs first.
2. **Response.** The reply the bot sends.
3. **Post-hook.** Your code that runs after the reply is sent.

You do not need all three. Most commands only have a Response.

## The full order

```text
1. Pre-hook runs
2. { } variables in the Response are filled in
3. The reply is sent
4. "response" becomes available
5. If you used set_view, the bot waits for the buttons to finish
6. Post-hook runs
```

## Pre-hook

Use the pre-hook to get data ready for the reply. Anything you make here can go in the reply with `{ }`.

```python
roll = randomNumber(1, 6)
```

Response:

```text
{user.mention} rolled a {roll}!
```

You can also build the whole reply from code. See [Response functions](https://ccbot.app/docs/reference/response).

```python
set_content(f"{user.mention} rolled a {randomNumber(1, 6)}!")
```

## Post-hook

The post-hook runs after the reply is in the channel. Use it for work that should happen after, like a log message or reactions on the reply.

In the post-hook you can read `response`. It is the message the bot just sent.

```python
add_reactions(response, "👍", "👎")
```

> **Note:** `response` does not exist in the pre-hook. The reply is not sent yet.

Pre-hook and post-hook share everything. A variable you make in the pre-hook is still there in the post-hook. They also share one set of [limits](https://ccbot.app/docs/concepts/limits).

## Stop with an error

Call `set_error("text")` to stop the command. The user sees your text as the error. Nothing below that line runs.

```python
if user.is_bot:
    set_error("Bots cannot use this command.")

set_content("Welcome!")
```

## Stop without a reply

Call `end()` to send no reply and skip the post-hook.

> **end() does not stop the pre-hook:** Every line after `end()` in the pre-hook still runs. The bot only checks `end()` after the pre-hook is done. To stop right away, use `set_error(...)`.

```python
if channel.name != "bot-commands":
    end()
```

## When something breaks

If your code has a mistake, the bot catches it. The error goes to the **Error Logs** page on the dashboard, under **Logs**. The user sees that something went wrong.

In the post-hook you can check what happened in the pre-hook:

| Name | True when |
|---|---|
| `pre_hook_failed` | The pre-hook raised an error. |
| `pre_hook_cooldown` | The command was on cooldown. |
| `pre_hook_error` | Holds the error from the pre-hook. |

You do not need `try` / `except` around everything. Use it only when you have a real fallback.

## Events are different

Events have only one code box, and no Response. The code must send its own messages with `send_message`. See [Events](https://ccbot.app/docs/getting-started/events).
