Skip to main content
Level: Intermediate · Tags: AI, Streaming, Telegram, Performance Features shown: streaming autoreply (stream) · strategies per channel: drafts, edits, chunks · “typing…” while generating · Telegram provider · cost and latency settings · testing streams with MockProvider

Prerequisites

  • Node.js 22.12 or newer.
  • A Telegram bot token from @BotFather in TELEGRAM_TOKEN.
  • An Anthropic API key in ANTHROPIC_API_KEY (or another model provider, see below).

The bot

How it works

  • One option. stream makes the autoresponder send the answer with ctx.stream() while the model generates it. The same code picks the best strategy for each channel:
  • cursor is shown at the end of the text while it is being written and never in the final message. canStop adds Telegram’s stop button to the draft: pressing it aborts the model request, so you stop paying for it.
  • Typing. humanizeTyping (on by default) shows “typing…” until the first words arrive.
  • Tools turn streaming off. A turn that may call tools needs the whole answer first, so with tools configured the reply is sent in one message.

Cost and latency tips

Answer the obvious without the model (commands, bot.when() triggers, flows), and see Cost and latency for the rest.

Try it

The simulator has no drafts or edits, so it shows the “chunk” strategy that WhatsApp uses: the answer arrives as sentence-sized messages. This run is scripted by the test that runs this page (packages/ai/tests/docs-examples-ai.test.ts), which also runs the bot on a mock Telegram-like provider and checks that the answer arrives as a growing draft there.

Other model providers

Every provider streams. Keep the other options as they are.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 first token arrives with no network round trip, and there is no output cap unless you set maxTokens.

Run it on Telegram or WhatsApp

Put the token and the key in a .env file next to bot.js (TELEGRAM_TOKEN=... and ANTHROPIC_API_KEY=...), run node --env-file=.env bot.js and write to your bot in Telegram. For WhatsApp, install @botmesh/baileys and start the factory with new BaileysProvider({ session: 'pantry-bot' }) instead: the same code sends the answer in chunks with “typing…”.

Next steps