Skip to content

Lesson 4 of 9 · 26m

Keyboards, Callback Queries, and State Machines That Do Not Rot

Build reliable interactive flows using reply keyboards, inline keyboards, callback data, explicit state, and idempotent transitions.

Most bot bugs are not crashes. They are conversations that drift into impossible states: the user taps a button twice, restarts midway, uses an old keyboard after deployment, or answers a question you no longer remember asking. Telegram gives you UI primitives, not a workflow engine. The state machine is your job.

Know the keyboard types

Reply keyboards replace the user's normal keyboard and send visible text messages. Inline keyboards attach buttons to a specific message and produce callback queries. They solve different problems:

{
  "inline_keyboard": [[
    {"text": "Approve deploy", "callback_data": "deploy:approve:1842"},
    {"text": "Reject", "callback_data": "deploy:reject:1842"}
  ]]
}

Inline buttons are good for actions bound to an object or decision. Reply keyboards are better for guided input when free text is acceptable. Do not use a reply keyboard as a security boundary; users can type anything manually.

Callback data is a reference, not a database

Telegram callback data is tiny — historically limited to 64 bytes — and visible to the client. Put an object reference and action in it, then re-authorize server-side:

deploy:approve:1842       acceptable if deployment 1842 is reloaded and permission checked
user:42:make_admin:true   dangerous authority encoded client-side

After receiving a callback, answer it quickly. Otherwise the client shows a loading state and users tap again:

await callback_query.answer()

Use show_alert=True only when the result needs explicit attention. Excessive alerts train users to ignore them.

Model state explicitly

A state machine should name states and transitions. 'If message contains yes' is not a state machine; it is string folklore. A support ticket flow might be:

idle -> collecting_subject -> collecting_description -> confirming -> submitted
          |------------------------- cancel -----------------------|

Persist the state in your database keyed by user or chat where appropriate:

create table telegram_conversations (
  chat_id bigint not null,
  user_id bigint not null,
  flow text not null,
  state text not null,
  context jsonb not null default '{}'::jsonb,
  updated_at timestamptz not null default now(),
  primary key (chat_id, user_id, flow)
);

Store only what the flow needs. Telegram is not a filing system for secrets, payment data, or large binary payloads.

Stale messages are real inputs

Inline keyboards remain visible after deploys, restarts, and business-state changes. A button rendered yesterday can arrive tomorrow. Validate whether the referenced object is still actionable. If deployment 1842 already completed, edit the original message to remove buttons or explain that the decision is closed:

await callback_query.answer("This deployment is already closed.", show_alert=True)

Editing messages is good UX, but do not rely on edit success as a consistency mechanism. Network failure or message age can leave old UI alive.

Idempotency beats optimism

Users double-tap. Mobile networks retry. Telegram retries. Workers restart. Mutating handlers need idempotency keys or natural unique constraints. If deploy:approve:1842 arrives twice, the second execution should observe the existing approval and report success or closure rather than create two deployments.

Field notes

  • Keep callback payloads small and opaque enough that users are not encouraged to synthesize them meaningfully.
  • Always authorize privileged callbacks against current state, not the state that existed when the message rendered.
  • Answer every callback query, even if the answer is a refusal; silent taps feel broken.
  • /cancel should work from every conversational state.
  • Do not serialize entire objects into callback data. Re-fetch and validate.

Was this lesson helpful?

Sign in to rate