Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 37 ยท State and Storage

Conversation State and Multi-Step Dialogs

Build multi-step dialogs for Telegram and Discord bots with a finite state machine: collect answers, validate each step, allow cancel, and expire stale chats.

Some tasks do not fit in one message. "Create a poll" needs a question, then options, then a duration. "Report a bug" needs a title and details. In a command-based bot every message arrives as a separate event with no memory of the one before it, so you have to remember where each user is in the conversation.

The clean way to do that is a finite state machine (FSM): each user or chat is always in exactly one named state, and each incoming message either moves them to the next state or keeps them where they are with an error.

Why not just nested callbacks?

Telegram and Discord are event-driven. There is no "wait for the next message" call that blocks your code. Libraries offer helpers such as awaiting a reply, but these hold a promise in memory, so they die on restart, they are hard to cancel and they are hard to test. A state record is plain data: you can store it, expire it and print it.

stateDiagram-v2
    [*] --> Idle
    Idle --> AskTitle: /report
    AskTitle --> AskDetails: valid title
    AskTitle --> AskTitle: invalid title
    AskDetails --> Confirm: valid details
    Confirm --> Idle: yes (save)
    Confirm --> Idle: no / cancel
    AskTitle --> Idle: /cancel
    AskDetails --> Idle: /cancel

Each arrow is one event handled by one function. Invalid input stays in the same state.

A dialog as data

Describe each step once: the prompt, a validator and the field it fills. The engine is generic.

Node.js A generic dialog engine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Adding a new dialog means adding an array of steps, not new control flow. The valid function returns true or an error message, a convenient trick that keeps the messages next to the rules.

Sessions are per chat and per user

In a private chat, the chat ID identifies the person. In a group, many people talk at once, so key the session by chat and user: ${chatId}:${userId}. Otherwise Alice's answer could land in Bob's dialog.

Node.js Two users in one group chat

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In groups, replying to every stray message is very annoying. Ignore people who are not in a dialog.

Expiring stale dialogs

A user starts /report and walks away. Without expiry the session stays forever. Store a timestamp and treat old sessions as gone. The injected clock again keeps this testable.

Node.js Sessions that time out

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

When a session expires, say so on the next message: "That dialog timed out, send /report to start again." A silent ignore looks like a broken bot.

Persisting sessions

An in-memory Map loses dialogs on restart. For short dialogs that is usually acceptable; users just start over. For long flows (applications, onboarding), store the session as a JSON row in SQLite keyed by chat and user, as in SQLite storage for bots. Because the state is plain data, this is a two-line change: load before handling, save after.

Platform notes

  • Telegram: the dialog above is the standard approach. You can also use inline keyboards for choices, and a ForceReply reply markup so the client pre-selects the reply box.
  • Discord: prefer modals (pop-up forms with several text inputs) and select menus for multi-field input. One modal can collect title, severity and details in a single step, so a state machine is only needed for choices that depend on earlier answers. Component interactions carry a custom_id string you can use to encode the step, for example report:confirm:42. Keep it under 100 characters and never trust it as proof of identity; check the user who clicked.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main advantage of keeping dialog progress as plain data?

    A promise waiting for a reply cannot be saved or inspected. A state record can.
  2. 2. A user types invalid input in the 'severity' step. What should happen?

    Invalid input keeps the user in the same state, with a helpful message.
  3. 3. Why key a group-chat session by chatId and userId?

    Many users share a chat ID; the user ID separates their dialogs.
  4. 4. What should a bot do when a user who is not in any dialog sends a plain message in a group?

    Replying to unrelated chatter is noisy; stay silent unless a command or active dialog applies.

Summary

  • Model multi-step interactions as a finite state machine with plain-data sessions.
  • Describe steps as data (prompt, validator, field) and drive them with one generic function.
  • Invalid input keeps the same state; /cancel always works.
  • Key sessions by chat and user, ignore non-participants, and expire idle sessions.
  • Persist sessions as JSON only when losing them would hurt; use Discord modals to cut steps.

Next: Long polling vs webhooks