Skip to main content
Level: Intermediate · Tags: WhatsApp, Telegram, i18n Features shown: locales and ctx.t() · language resolution and detect · ctx.setLang() · plural forms · translated built-in texts · before hooks · async conversations

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. Message trees. bot.locale(code, messages) registers one tree per language. Keys nest (ctx.t('order.size')) and {name} placeholders are filled from the second argument. In a bigger bot, keep each tree in its own file and import it: import en from './locales/en.json' with { type: 'json' }.
  2. Which language. For every message the bot picks the first language it serves from: the user’s stored choice, the language their client reports (Telegram sends one, WhatsApp does not), your detect function, then defaultLocale. locales: ['en', 'es'] limits it to the languages you translated. ctx.langSource says which one won.
  3. Remembering a guess. detect only looks at the current message, so the before('message') hook stores a detected language with ctx.setLang(). The messages that follow keep it, even those detect does not recognise (/cancel and 1 in the transcript).
  4. Switching. /lang es calls ctx.setLang('es'), saved in the user’s profile (ctx.user) under the key lang.
  5. Conversations. c.t() translates with the language of the latest message, so the menu labels come from the same tree. The DSL’s .choose() takes fixed labels; build menus with c.choose() in a conversation when they must be translated.
  6. Plurals. cups has zero, one and other forms; count picks one with Intl.PluralRules.
The texts the framework writes for you (/help, /cancel, timeouts, retry messages) come in English and Spanish and follow ctx.lang too: compare /cancel in the transcript.

Try it

Run it on WhatsApp or Telegram

node bot.js shows a QR code: scan it from WhatsApp → Linked devices. On Telegram, install @botmesh/telegram and swap the provider as in Or connect Telegram: the bot then also reads the language of each user’s Telegram app, before detect.

Next steps