MessageOS
Guides

The example app

The MessageOS Kitchen Sink, a small working app that receives messages and answers with every kind of message the API sends.

The MessageOS Kitchen Sink is a small app that does what an API-only integration does: it receives reply.received, and it answers through POST /v1/messages. A person texts it, gets a menu, and taps through a tour that shows every kind of message, one at a time.

It is plain JavaScript for Node.js 20 or newer, with no dependencies to install to run it. Read it for working code, or run it against your own agent.

See what it looks like on a phone in the Kitchen Sink showcase, with a screenshot of every kind of message.

Where to get it

The code is at https://github.com/messageos/Kitchen-Sink-API-Example. The repository is public. Clone it, or copy what you need.

What it shows

The menu is a carousel with one card for each stop on the tour. Every stop ends with a button for the next stop and a Menu button, so the whole tour can be walked in order.

StopWhat the app sendsThe call behind it
MenuA carousel, one card for each stop below, each with a picture and its own buttonPOST /v1/messages with carousel
TextA plain text messagePOST /v1/messages with text
RepliesText with suggested replies, each with its own postbackData. A tap is answered with the label and the value that came backsuggestions of type reply
ActionsText with every action: open a link in the conversation, open a link in the browser, call a number, show a place, share a location, add a calendar eventsuggestions of type openUrl, dial, viewLocation, shareLocation, and createCalendarEvent
CardA rich card with a picture, a title, a description, and buttons, then a horizontal cardcard, and card.orientation
CarouselA row of cards, each with a button that names its own itemcarousel
FilesButtons to pick an image, a video, an audio file, or a PDF, then that filefile
LocationA request for the person's location. What they share is answered with its coordinates and a map buttonshareLocation, then reply.received with location
TypingThe typing indicator, a two second pause, then a messagePOST /v1/typing
ExpiryA message that expires, with a traffic typettlSeconds and trafficType
Device checkWhat this phone supportsGET /v1/capabilities

Outside the tour:

  • STOP, START, HELP, and the other keywords get no answer from the app, because MessageOS answers them.
  • A file the person sends, with or without a caption, is answered with what arrived: its media type, its file name, and the caption. The app does not download it.
  • A place the person shares, with or without words, is answered with its coordinates, the words, and a map button.
  • A tap on a button the app no longer knows is answered with the menu. A button on a card stays in the conversation for good, so an old one can be tapped long after.
  • Any other words the person types are echoed back as You said: and their words.

The app decides in that order, and it reads attachments and location before it looks at kind. A photo sent with a caption has kind text, and so does a place sent with words, so an app that reads only kind answers the caption and misses the photo.

No answer leaves the person with nothing to tap. The last message of every answer carries at least a Menu button, except the menu itself, where every card has its own.

The app reads GET /v1/whoami and skips what your agent does not have. Where richMessages is false it says so in one plain line instead of sending a card, and the same for rcsExtras and the typing, expiry, and device check stops.

Every answer is a reply: it names the person's message in inReplyTo. Up to three sends can answer one message as replies, so no stop sends more than three messages.

Run it

You need Node.js 20 or newer, a client key, and a public https address for the app, because MessageOS does not deliver events to a private or local address. On your own computer that is a public https tunnel that forwards to the app's port.

The key needs these permissions, all of which an owner or admin can give a key under Developers in the dashboard: messages:write, contacts:read, contacts:write, conversations:read, webhooks:manage, and usage:read.

The app answers every message itself, so the MessageOS assistant must not answer too, or the person gets two replies. Ask MessageOS to set your agent to API only, or pause the assistant on the Agent page of the dashboard.

The app has five settings, in a file named .env. The app and its scripts read that file themselves on Node.js 20.12 or newer. On an older Node.js 20, set the same names in your shell instead. The steps fill in the three that have no default:

SettingWhat it is
MESSAGEOS_API_URLThe API address. Leave it as https://api.messageos.ai/v1 unless MessageOS gave you another one
MESSAGEOS_API_KEYYour client key. Step 1
PUBLIC_URLThe app's own public https address, with no path. Picture and file links are built from it. Step 3
MESSAGEOS_WEBHOOK_SECRETThe signing secret of your webhook. Step 5 prints it
PORTThe port the local server listens on. The default is 3000
  1. Get the code, copy .env.example to .env, and put your key in MESSAGEOS_API_KEY.

  2. Check the key. This calls GET /v1/whoami and prints what your agent offers:

    npm run check
  3. Give the app a public https address, and put it in PUBLIC_URL. On your own computer, start a public https tunnel that forwards to the app's port, and use the address the tunnel gives you.

  4. Start the app:

    npm start
  5. In a second terminal, register the webhook. This calls POST /v1/webhooks for PUBLIC_URL and prints the signing secret once. Put it in MESSAGEOS_WEBHOOK_SECRET, then stop the app and start it again. Until then the app refuses every event, because it cannot check a signature:

    npm run setup:webhook
  6. Start a conversation. This sends the menu to one phone, with the consent record a first message needs. Until your agent is launched, the phone must be one of its testers:

    npm run send:menu -- +15555550123

Tap a card. The tap arrives at the app as reply.received, and the app answers.

npm run dev restarts the app on every change. npm test runs its tests, which need no network: they post signed events to the app and check each request it makes against a stand-in for the API. npm run typecheck checks the types, and is the one command that needs npm install first.

The app is one handler for Node's own HTTP server, so it runs on any host that runs Node.js. It also exports the same handler for a host that runs functions. There, set the same settings in the host, and use the address the host gives you as PUBLIC_URL.

How the receiver works

The app answers POST /webhooks/messageos. For every event it does five things, in this order:

  1. Reads the raw body. The signature covers the bytes as sent, so nothing parses them first.
  2. Checks the signature in constant time. It computes sha256= and the hex HMAC-SHA256 of the timestamp, a period, and the raw body, keyed with the signing secret, and compares it to x-messageos-signature with timingSafeEqual.
  3. Refuses a timestamp more than 300 seconds off, so a captured request cannot be played back later.
  4. Never acts twice on one event. It remembers the event ids it has handled. That memory is one process, so the real guard is the next one: every send uses an Idempotency-Key built from the id of the person's message and the position of the send: ks-reply-, then inboundMessageId, a dash, and a number. The key is not built from the event id, because each webhook endpoint gets its own copy of an event with its own id. A redelivered event, or a second endpoint's copy of it, asks for the same sends with the same keys, and MessageOS answers each from its record instead of sending again.
  5. Answers 2xx only when the work is done. If a send could not be completed and is worth another try, the app answers 500 and MessageOS delivers the event again. That is a 500 or above, a 429, a 409 conflict, a 409 blocked with the reason provider_busy, and a 401 or 403 while the key is wrong. A send the API refused for good, such as one to a person who opted out, is logged and the event is accepted, because the same request would get the same answer.

This is the same receiver in one file, with a few stops of the tour. It needs nothing but Node.js: save it as receiver.mjs, set MESSAGEOS_API_KEY and MESSAGEOS_WEBHOOK_SECRET, and run node receiver.mjs. It does not start without them.

import { createHmac, timingSafeEqual } from 'node:crypto';
import { createServer } from 'node:http';

const apiUrl = process.env.MESSAGEOS_API_URL ?? 'https://api.messageos.ai/v1';
const apiKey = process.env.MESSAGEOS_API_KEY;
const secret = process.env.MESSAGEOS_WEBHOOK_SECRET;
// Without the secret no event can be checked, and without the key none can be answered.
if (!secret) throw new Error('MESSAGEOS_WEBHOOK_SECRET is not set');
if (!apiKey) throw new Error('MESSAGEOS_API_KEY is not set');

// MessageOS answers these itself, so this app stays silent for them. YES is left out: it is a
// keyword only from a person who has opted out, and from anyone else it is an ordinary answer.
const keywords = new Set([
  'stop', 'stopall', 'stop all', 'unsubscribe', 'cancel', 'end', 'quit', 'revoke', 'optout', 'opt out',
  'start', 'unstop', 'join', 'subscribe', 'help', 'info',
]);
const isKeyword = (text) => keywords.has(text.trim().toLowerCase().replace(/[.!]+$/, '').replace(/\s+/g, ' '));

// A best effort guard for one process. The Idempotency-Key on each send is what makes a repeat safe.
const handled = new Set();

function verified(rawBody, timestamp, signature) {
  if (typeof timestamp !== 'string' || typeof signature !== 'string') return false;
  if (!/^\d+$/.test(timestamp) || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false;
  const digest = createHmac('sha256', secret).update(`${timestamp}.`).update(rawBody).digest('hex');
  const expected = Buffer.from(`sha256=${digest}`);
  const received = Buffer.from(signature);
  return received.length === expected.length && timingSafeEqual(received, expected);
}

// One answer to the person. `position` is the place of this send among the answers to one message.
// The key is built from the message, not from the event id, so a redelivered event sends nothing
// twice, and neither does the copy of the event that a second webhook endpoint gets.
async function reply(event, position, content) {
  const response = await fetch(`${apiUrl}/messages`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${apiKey}`,
      'Idempotency-Key': `ks-reply-${event.data.inboundMessageId}-${position}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ to: { contactId: event.data.contactId }, inReplyTo: event.data.inboundMessageId, ...content }),
  });
  if (response.ok) return;
  const { code, reason } = (await response.json().catch(() => ({}))).error ?? {};
  // This key was already used with another body, so this message was answered before.
  if (response.status === 422 && code === 'idempotency_key_reuse') return;
  // Worth another delivery of the event: MessageOS or the messaging network is busy, the first
  // request with this key is still running, or the key is wrong and can be fixed.
  const tryAgain =
    response.status >= 500 || response.status === 429 || response.status === 401 || response.status === 403 ||
    (response.status === 409 && (code === 'conflict' || reason === 'provider_busy'));
  if (tryAgain) throw new Error(`POST /messages answered ${response.status} ${reason ?? code ?? ''}`);
  // Not sent, and sending again would not change it: the person opted out, the phone cannot be
  // reached, or the body is not valid, such as buttons where rich messages are not turned on.
  console.error('not sent', response.status, code, reason ?? '');
}

const menuChips = [
  { type: 'reply', text: 'Show text', postbackData: 'ks:text' },
  { type: 'reply', text: 'Show replies', postbackData: 'ks:replies' },
];

async function answer(event) {
  const { kind, text, postbackData, location, attachments } = event.data;
  if (isKeyword(text)) return;
  // A file or a place sent with words has kind text, so these two read the fields and not kind,
  // and they come before the buttons and the typed words.
  const words = text.trim() ? `, with the words "${text.trim().slice(0, 500)}"` : '';
  if (attachments.length > 0) {
    const [file] = attachments;
    return reply(event, 1, { text: `You sent a file: ${file.mediaType}${file.fileName ? `, ${file.fileName}` : ''}${words}.`, suggestions: menuChips });
  }
  if (location) {
    return reply(event, 1, {
      text: `You shared ${location.latitude}, ${location.longitude}${words}.`,
      suggestions: [{ type: 'viewLocation', text: 'View on map', latitude: location.latitude, longitude: location.longitude }, ...menuChips],
    });
  }
  if (kind === 'chip' && postbackData === 'ks:text') {
    return reply(event, 1, { text: 'This is a plain text message.', suggestions: [{ type: 'reply', text: 'Menu', postbackData: 'ks:menu' }] });
  }
  if (kind === 'chip' && postbackData === 'ks:replies') {
    return reply(event, 1, {
      text: 'Pick one. Each button carries its own postbackData.',
      suggestions: [
        { type: 'reply', text: 'Red', postbackData: 'ks:picked:red' },
        { type: 'reply', text: 'Blue', postbackData: 'ks:picked:blue' },
      ],
    });
  }
  if (kind === 'chip' && postbackData?.startsWith('ks:picked:')) {
    const value = postbackData.slice('ks:picked:'.length);
    return reply(event, 1, { text: `You tapped ${text}. Your system received postbackData ${value}.`, suggestions: menuChips });
  }
  if (kind === 'chip' || text.trim().toLowerCase() === 'menu') {
    return reply(event, 1, { text: 'Tap a button to see that kind of message.', suggestions: menuChips });
  }
  return reply(event, 1, { text: `You said: ${text}`, suggestions: menuChips });
}

createServer(async (req, res) => {
  if (req.method !== 'POST' || req.url !== '/webhooks/messageos') return res.writeHead(404).end();

  // 1. The raw body, before any JSON parsing.
  const chunks = [];
  for await (const chunk of req) chunks.push(chunk);
  const rawBody = Buffer.concat(chunks);

  // 2. The signature, in constant time, and 3. a timestamp no more than 300 seconds off.
  if (!verified(rawBody, req.headers['x-messageos-timestamp'], req.headers['x-messageos-signature'])) {
    return res.writeHead(401).end();
  }

  const event = JSON.parse(rawBody.toString('utf8'));
  try {
    // 4. Never act twice on one event.
    if (!handled.has(event.id)) {
      if (event.type === 'reply.received') await answer(event);
      else console.log(event.type, event.id);
      handled.add(event.id);
    }
    // 5. 2xx only once the work is done. Any other status brings the event again.
    res.writeHead(200).end();
  } catch (error) {
    console.error(error);
    res.writeHead(500).end();
  }
}).listen(Number(process.env.PORT ?? 3000));

The repository splits this over a few small files. src/app.js is the handler, and src/server.js runs it as a server. The signature check, the keyword list, the conversation, and the message bodies each have a file of their own, tour.json lists the stops in order, and public/media holds the pictures, the video, the audio file, and the PDF the app sends.

What to copy

  • The five receiver steps, in any language. Webhooks has them in Node.js, Python, PHP, Ruby, Go, Java, and C#.
  • An Idempotency-Key made from inboundMessageId for every answer to a person's message, so two copies of one event send once.
  • The keyword list, so your system stays silent when MessageOS has already answered.
  • Reading GET /v1/whoami once and choosing what to send from it.

When your own system answers explains each of them.

On this page