Getting started
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:
- Pre-hook. Your code that runs first.
- Response. The reply the bot sends.
- 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#
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 runsPre-hook#
Use the pre-hook to get data ready for the reply. Anything you make here can go in the reply with { }.
roll = randomNumber(1, 6)Response:
{user.mention} rolled a {roll}!You can also build the whole reply from code. See Response functions.
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.
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.
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.
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(...).
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.