Skip to main content
Level: Intermediate · Tags: WhatsApp, User data, Conversations Features shown: user data (ctx.user) · namespaces · async conversations · validation and maxAttempts · MemoryStore with a file · slash commands

Prerequisites

  • Node.js 22.12 or newer and an empty folder with "type": "module" in its package.json (Getting started).

The complete bot

How it works

  1. A conversation as a function. bot.conversation(name, fn, { trigger }) is the async form of a flow: plain ifs and variables decide what to ask. Its ctx is the full message context, so ctx.user works directly.
  2. Per-user memory. ctx.user is a profile keyed by the sender, the same in their DM and in every group. ns('orders') keeps this feature’s keys apart from the rest of the profile, and /forget clears only them.
  3. Per-conversation state. code and last live only while the conversation runs; what must outlive it goes to ctx.user. orders.update({ last, followed }) writes both keys in one call.
  4. Validation. validate rejects unknown order numbers with a hint, and maxAttempts: 3 ends the conversation after three wrong answers.
  5. Surviving restarts. MemoryStore({ file }) saves profiles and checkpoints to orders.json every minute and when the bot stops, and loads them on start. Nothing stops the bot on Ctrl+C by itself, so the start block calls bot.stop() on SIGINT: without it, changes from the last minute are lost. Use SQLite or Redis when several processes share the data.
From outside a handler (a webhook from your shop, a scheduled job) the same profile is bot.user(userId), for example await bot.user(userId).ns('orders').get('followed') to find who to notify when an order ships.

Try it

:as bob switches to another user (in their own DM), and :reset restarts the bot from the factory:

Run it on WhatsApp or Telegram

node bot.js shows a QR code: scan it from WhatsApp → Linked devices. For Telegram, install @botmesh/telegram and swap the provider in the start block for new TelegramProvider({ token: process.env.TELEGRAM_TOKEN ?? '' }), as in Or connect Telegram.

Next steps