Skip to main content
Level: Beginner · Tags: AI, WhatsApp, Telegram, Guardrails Features shown: AI autoresponder · business-scoped persona · text and function triggers · slash commands · /reset of the AI history · cost and latency settings · terminal simulator

Prerequisites

  • Node.js 22.12 or newer.
  • An Anthropic API key in the ANTHROPIC_API_KEY environment variable (or another model provider, see below). Never write the key in the code.

The bot

How it works

  • Order of handlers. Commands, bot.when() triggers and flows always run before the AI. aiPlugin registers a catch-all autoresponder that only sees the text messages nothing else handled, so “hours” and “agent” are answered by your code, not by the model.
  • The persona is the guardrail. It names one business, lists what the bot may talk about and says how to decline. Since January 2026 WhatsApp only allows AI in service of a business, never as a general-purpose assistant (see WhatsApp AI policy).
  • A deterministic guardrail. A function trigger answers messages longer than 500 characters itself, so a pasted essay never becomes a paid model call. Add any rule you can check in code the same way.
  • Cost and latency. model, maxTokens and context.maxMessages keep every answer small. timeoutMs (60 s by default) bounds each call; a failed call answers the built-in “⚠️ I can’t answer right now…” text instead of crashing.
  • /reset. aiPlugin adds its own /reset, which clears the chat’s AI history. It is plugged after slashCommandsPlugin, so its /reset wins.

Try it

This is a run of the code above in the terminal simulator. The AI answers come from a scripted model in the test that runs this page (packages/ai/tests/docs-examples-ai.test.ts); a real model words them differently.

Other model providers

Install the SDK of the provider and change the aiPlugin options; the rest of the bot stays the same.OpenAI (npm install openai, key in OPENAI_API_KEY):
Gemini (npm install @google/genai, key in GEMINI_API_KEY):
Ollama on your machine (no package, no key; run ollama pull llama3.1 first):
The full list (and the OpenAI-compatible presets) is in Choose a provider.

Run it on WhatsApp or Telegram

node bot.js prints a QR code: scan it with WhatsApp (Linked devices) and write to that number from another phone. For Telegram, install @botmesh/telegram and start the factory with new TelegramProvider({ token: process.env.TELEGRAM_TOKEN ?? '' }) instead (see Or connect Telegram).

Next steps