Handlers in the bot configuration play a pivotal role in defining how your bot responds to different Telegram event updates. A handler declares various elements that determine its behavior:
The on trigger specifies when the handler is triggered.
The trigger element is required for handler.
message: Triggers the handler on a text message or command.callback: Triggers on a button callback (part of inline-buttons and callbacks feature).context: Additional selector to trigger the handler only if the current user context is set to a specified value (context feature).preCheckout: Triggers on pre-checkout events (payments feature).postCheckout: Triggers on post-checkout events (payments feature).state: Array of state conditions, an additional filter to run the handler only if the user’s state matches these conditions (states feature).Trigger should have at least one of message, callback, context, preCheckout, postCheckout,
state and context could be added to other elements. If trigger is a string, it will be treated as
message handler, there are two identical triggers below:
bot:
handlers:
# trigger message shorthand
- on: hello
reply:
- message: Hello
bot:
handlers:
# full message trigger
- on:
message: hello
reply:
- message: hello
bot:
handlers:
# the fullest message trigger version
- on:
message:
text: hello
reply:
message: hello
The wildcard trigger is handled as a default fallback trigger after trying all other triggers:
bot:
handlers:
- on: "*"
reply:
message: Fallback message
message, callback, preCheckout, postCheckout could not be mixed together.
Example:
bot:
handlers:
- on:
message:
command: start
reply:
- message:
text: "Welcome to my bot!"
- on:
callback:
data: "button_click"
reply:
- message:
text: "You clicked a button!"
In this example, the first handler triggers on the /start command, replying with a welcome message.
The second handler triggers on a button click with the callback data “button_click” and responds accordingly.
The reply element specifies how to reply to a user event. It can include:
One handler may have multiple different reply items.
Example:
bot:
handlers:
- on:
message:
command: start
reply:
- message:
text: "Welcome to my bot!"
- image:
name: "Test image"
key: "test-image.png"
In this example, the handler replies with a welcome message and an image when triggered by the /start command.
Continue exploring to learn more about the webhook, state, context, data, and validate elements, enabling you to create versatile and dynamic bot interactions.