# One message model for WhatsApp, Instagram, Messenger and Telegram

> Compare inbound text webhooks from WhatsApp, Messenger, Instagram and Telegram field by field, then map all four to one record in Python.

Published 2026-11-03. Z-API Omni team.

Map inbound text from WhatsApp, Messenger, Instagram and Telegram to one record: channel, receiving account, sender, reply address, message ID, UTC time, text and media reference. Each platform delivers that text in its own shape. Build the deduplication key from channel, account and message ID. On Telegram, add the chat ID, because a Telegram `message_id` is unique only inside its chat.

## The four inbound payloads

### WhatsApp Cloud API

This is Meta's sample from the business-scoped user ID (BSUID) page, with the same fields and values on fewer lines ([Business-scoped user IDs](https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids), accessed 2026-11-03).

```json
{
  "object": "whatsapp_business_account",
  "entry": [
    {
      "id": "102290129340398",
      "changes": [
        {
          "value": {
            "messaging_product": "whatsapp",
            "metadata": {
              "display_phone_number": "15550783881",
              "phone_number_id": "106540352242922"
            },
            "contacts": [
              {
                "profile": { "name": "Sheena Nelson", "username": "realsheenanelson" },
                "user_id": "US.13491208655302741918",
                "parent_user_id": "US.ENT.11815799212886844830"
              }
            ],
            "messages": [
              {
                "from_user_id": "US.13491208655302741918",
                "from_parent_user_id": "US.ENT.11815799212886844830",
                "id": "wamid.HBgLMTY1MDM4Nzk0MzkVAgASGBQzQTRBNjU5OUFFRTAzODEwMTQ0RgA=",
                "timestamp": "1749416383",
                "type": "text",
                "text": { "body": "Does it come in another color?" }
              }
            ]
          },
          "field": "messages"
        }
      ]
    }
  ]
}
```

The text sample on Meta's [text message reference](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/text) has `from` (the phone number) in place of `from_user_id`. Meta withholds the phone number from users who have a username, and then omits `wa_id` and `from`. The exceptions are a message or call between you in the last 30 days, per business phone number, or the user being in your contact book. BSUIDs "are scoped to individual business portfolios". [WhatsApp usernames and business-scoped user IDs](/academy/articles/whatsapp-usernames-business-scoped-user-ids/) covers the migration.

### Messenger

Meta's text example is the item inside `messaging[]` ([Messenger messages webhook](https://developers.facebook.com/documentation/business-messaging/messenger-platform/webhooks/webhook-events/messages), accessed 2026-11-03).

```json
{
  "sender": { "id": "<PSID>" },
  "recipient": { "id": "<PAGE_ID>" },
  "timestamp": 1458692752478,
  "message": {
    "mid": "mid.1457764197618:41d102a3e1ae206a38",
    "text": "hello, world!",
    "quick_reply": { "payload": "<DEVELOPER_DEFINED_PAYLOAD>" }
  }
}
```

The attachment example on the same page shows the envelope around it: `entry[]` items with `id`, `time` and `messaging[]`. Attachments arrive as `message.attachments[]`, each with a `type` and `payload.url`. `sender.id` is the Page-scoped ID (PSID) of the person, and `recipient.id` is your Page.

### Instagram

Meta prints a template for the Instagram API with Instagram Login, and it does not parse as JSON. Cleaned here: comments and optional fields removed, unquoted time placeholders replaced with sample numbers ([Instagram webhook examples](https://developers.facebook.com/documentation/instagram-platform/webhooks/examples), accessed 2026-11-03). Meta documents no unit for these times. The 13-digit values were chosen for this sample.

```json
[
  {
    "object": "instagram",
    "entry": [
      {
        "id": "YOUR_APP_USERS_INSTAGRAM_USER_ID",
        "time": 1749416384000,
        "messaging": [
          {
            "sender": { "id": "SENDER_ID" },
            "recipient": { "id": "RECIPIENT_ID" },
            "timestamp": 1749416383000,
            "message": { "mid": "MESSAGE_ID", "text": "MESSAGE_TEXT" }
          }
        ]
      }
    ]
  }
]
```

On a received message, `sender.id` is "The Instagram user's Instagram-scoped ID" (IGSID) and `recipient.id` is your professional account. When your own account sends, the two swap and `is_echo` is `true`. The full template also lists `attachments[]` with `type` and `payload.url`.

### Telegram

The Bot API page prints no example update. This shape is built from its field tables ([Telegram Bot API](https://core.telegram.org/bots/api), accessed 2026-11-03).

```json
{
  "update_id": 100000001,
  "message": {
    "message_id": 42,
    "from": { "id": 123456789 },
    "chat": { "id": 123456789, "type": "private" },
    "date": 1749416383,
    "text": "Does it come in another color?"
  }
}
```

At most one optional field is present per update, so a message update carries `message` and nothing else. `from` "may be empty for messages sent to channels". User and chat IDs can exceed 32 bits but have "at most 52 significant bits", so store them as 64-bit integers.

## Where each field lives per channel

| | WhatsApp Cloud API | Messenger | Instagram | Telegram |
| --- | --- | --- | --- | --- |
| Sender | `messages[].from_user_id` (BSUID) or `from` (phone, may be omitted) | `messaging[].sender.id` (PSID) | `messaging[].sender.id` (IGSID) | `message.from.id` |
| Reply address | phone or BSUID | PSID | IGSID | `message.chat.id` |
| Sender scope | business portfolio | Page | person and Instagram account | not stated |
| Message ID | `messages[].id` (wamid) | `message.mid` | `message.mid` | `message_id`, unique per chat |
| Time | `timestamp`, 10-digit string | `timestamp`, 13-digit number in examples | `timestamp`, unit not documented | `date`, Unix time integer |
| Text | `text.body` | `message.text` | `message.text` | `message.text`, or `caption` on media |
| Media | `image.id`, then GET the media ID | `attachments[].payload.url` | `attachments[].payload.url` | `photo[]` or `document` `file_id`, then `getFile` |

Meta describes the WhatsApp `timestamp` as the "Unix timestamp indicating when the webhook was triggered" and gives no unit. Neither Meta page gives a unit for Messenger or Instagram, and Telegram says only "Unix time". Normalize by digit count.

Media references age at different speeds. A WhatsApp media URL fetched from `GET /<MEDIA_ID>?phone_number_id=<PHONE_NUMBER_ID>` expires after 5 minutes and needs your token ([media](https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/media)). A Telegram file link is "valid for at least 1 hour", with downloads capped at 20 MB. Meta documents no lifetime for Messenger or Instagram attachment URLs, so download them when the webhook arrives. [Expired WhatsApp media URLs](/academy/articles/whatsapp-cloud-api-media-download-url-expired/) has the WhatsApp side in detail.

## One record for all four

```sql
CREATE TABLE inbound_message (
  dedup_key     TEXT PRIMARY KEY,   -- channel:account:message_id
  channel       TEXT NOT NULL,      -- whatsapp | messenger | instagram | telegram
  account_id    TEXT,               -- phone_number_id, Page ID, IG account ID, bot label
  sender_id     TEXT,               -- BSUID or phone, PSID, IGSID, Telegram user ID
  sender_phone  TEXT,               -- WhatsApp only, when Meta sends it
  reply_to      TEXT,               -- where the reply goes
  message_id    TEXT NOT NULL,
  sent_at       TIMESTAMPTZ,
  body          TEXT,
  media_kind    TEXT,
  media_ref     TEXT,               -- media ID, URL or file_id
  is_echo       BOOLEAN NOT NULL DEFAULT FALSE
);
```

Keep IDs as text, so Telegram's integers and Meta's strings sit in one column. A PSID, an IGSID and a BSUID have different scopes (Page, Instagram account, business portfolio), so no ID on one channel identifies the person on another. One person on three channels is three rows until your own data links them. [The conversation storage schema](/academy/articles/whatsapp-conversation-storage-database-schema/) shows the WhatsApp tables this record can feed.

## A Python normalizer

Standard library only. Run it as a script and it prints one record per sample. Echoes are flagged; filter them before they reach your bot.

```python
import json
from datetime import datetime, timezone

def to_utc(value):
    """Unix time as int or string; 13+ digits read as milliseconds."""
    if value is None:
        return None
    digits = str(value).strip()
    seconds = int(digits) / 1000 if len(digits) >= 13 else int(digits)
    return datetime.fromtimestamp(seconds, tz=timezone.utc).isoformat()

def as_text(value):
    return None if value is None else str(value)

def record(channel, account, sender, reply_to, message_id, ts, body,
           media_kind=None, media_ref=None, is_echo=False, sender_phone=None):
    account, message_id = as_text(account), as_text(message_id)
    return {
        "dedup_key": f"{channel}:{account}:{message_id}",
        "channel": channel,
        "account_id": account,
        "sender_id": as_text(sender),
        "sender_phone": sender_phone,
        "reply_to": as_text(reply_to),
        "message_id": message_id,
        "sent_at": to_utc(ts),
        "body": body,
        "media_kind": media_kind,
        "media_ref": as_text(media_ref),
        "is_echo": is_echo,
    }

def from_whatsapp(payload):
    for entry in payload.get("entry", []):
        for change in entry.get("changes", []):
            value = change.get("value", {})
            account = value.get("metadata", {}).get("phone_number_id")
            for msg in value.get("messages", []):
                kind = msg.get("type")
                part = msg.get(kind) if isinstance(msg.get(kind), dict) else {}
                body = part.get("body") if kind == "text" else part.get("caption")
                phone = msg.get("from")
                bsuid = msg.get("from_user_id")
                yield record("whatsapp", account, bsuid or phone, phone or bsuid,
                             msg.get("id"), msg.get("timestamp"), body,
                             None if kind == "text" else kind, part.get("id"),
                             sender_phone=phone)

def from_meta_messaging(payload, channel):
    envelopes = payload if isinstance(payload, list) else [payload]
    for envelope in envelopes:
        for entry in envelope.get("entry", []):
            for event in entry.get("messaging", []):
                msg = event.get("message")
                if not msg:
                    continue  # postbacks, reads and reactions are other events
                echo = bool(msg.get("is_echo"))
                sender = event.get("sender", {}).get("id")
                recipient = event.get("recipient", {}).get("id")
                account, customer = (sender, recipient) if echo else (recipient, sender)
                first = (msg.get("attachments") or [{}])[0]
                yield record(channel, account, sender, customer, msg.get("mid"),
                             event.get("timestamp"), msg.get("text"),
                             first.get("type"), first.get("payload", {}).get("url"),
                             is_echo=echo)

def from_telegram(update, bot_label):
    msg = update.get("message")
    if not msg:
        return
    chat_id = msg["chat"]["id"]
    kind, ref = None, None
    if msg.get("photo"):
        kind, ref = "image", msg["photo"][-1]["file_id"]
    elif msg.get("document"):
        kind, ref = "file", msg["document"]["file_id"]
    yield record("telegram", bot_label, msg.get("from", {}).get("id"), chat_id,
                 f"{chat_id}:{msg['message_id']}", msg.get("date"),
                 msg.get("text") or msg.get("caption"), kind, ref)

def normalize(payload, telegram_bot_label="TELEGRAM_BOT"):
    if isinstance(payload, dict) and "update_id" in payload:
        return list(from_telegram(payload, telegram_bot_label))
    first = payload[0] if isinstance(payload, list) else payload
    kind = first.get("object")
    if kind == "whatsapp_business_account":
        return list(from_whatsapp(first))
    channel = "instagram" if kind == "instagram" else "messenger"
    return list(from_meta_messaging(payload, channel))

SAMPLES = [
    {"object": "whatsapp_business_account", "entry": [{"id": "102290129340398", "changes": [{
        "field": "messages", "value": {
            "messaging_product": "whatsapp",
            "metadata": {"display_phone_number": "15550783881", "phone_number_id": "106540352242922"},
            "messages": [{"from_user_id": "US.13491208655302741918",
                          "id": "wamid.HBgLMTY1MDM4Nzk0MzkVAgASGBQzQTRBNjU5OUFFRTAzODEwMTQ0RgA=",
                          "timestamp": "1749416383", "type": "text",
                          "text": {"body": "Does it come in another color?"}}]}}]}]},
    {"entry": [{"id": "PAGE_ID", "time": 1458692752478, "messaging": [{
        "sender": {"id": "PSID"}, "recipient": {"id": "PAGE_ID"}, "timestamp": 1458692752478,
        "message": {"mid": "mid.1457764197618:41d102a3e1ae206a38", "text": "hello, world!"}}]}]},
    [{"object": "instagram", "entry": [{"id": "IG_ACCOUNT_ID", "time": 1749416384000, "messaging": [{
        "sender": {"id": "IGSID"}, "recipient": {"id": "IG_ACCOUNT_ID"}, "timestamp": 1749416383000,
        "message": {"mid": "MESSAGE_ID", "text": "MESSAGE_TEXT"}}]}]}],
    {"update_id": 100000001, "message": {"message_id": 42, "from": {"id": 123456789},
     "chat": {"id": 123456789, "type": "private"}, "date": 1749416383,
     "text": "Does it come in another color?"}},
]

if __name__ == "__main__":
    for sample in SAMPLES:
        for row in normalize(sample):
            print(json.dumps(row))
```

The Messenger sample wraps Meta's text example in the envelope from the attachment example. Meta's messages page shows no top-level `object` value for Messenger, so the code treats any non-WhatsApp, non-Instagram payload as Messenger. Log the `object` your Page subscription sends and tighten that branch.

Telegram's `photo` is a list of "available sizes". The code keeps the last entry, so pick a different one if you need a specific size.

Instagram documents `is_echo`. Messenger's echo event was not checked for this guide, so the Messenger check is defensive.

Expect the same message more than once. Meta retries WhatsApp webhooks "for up to 7 days" ([WhatsApp webhooks overview](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/overview)) and Instagram webhooks "over the next 36 hours" ([Instagram webhooks setup](https://developers.facebook.com/documentation/instagram-platform/webhooks/setup)). Telegram will "give up after a reasonable amount of attempts" ([Telegram Bot API](https://core.telegram.org/bots/api)). All three accessed 2026-11-03. Write the record with `INSERT ... ON CONFLICT (dedup_key) DO NOTHING` and act only when the insert succeeds. [The n8n idempotency pattern](/academy/articles/n8n-duplicate-webhooks-idempotency/) shows the same idea in a workflow.

## Replying on the right channel

Route the reply by `channel` and send it to `reply_to`. Each platform has its own endpoint, token and window.

| Channel | Send endpoint | Recipient field | Window |
| --- | --- | --- | --- |
| WhatsApp Cloud API | `POST https://graph.facebook.com/v26.0/<PHONE_NUMBER_ID>/messages`, Bearer token | `to` (phone) or `recipient` (BSUID) | 24 hours from the user's last message, then templates only |
| Messenger | `POST https://graph.facebook.com/v26.0/<PAGE_ID>/messages?access_token=<PAGE_ACCESS_TOKEN>`, `"messaging_type": "RESPONSE"` | `recipient.id` (PSID) | 24 hours for most actions, up to 7 days after a Click-to-Messenger ad, message tags |
| Instagram | `POST https://graph.instagram.com/v26.0/<IG_ID>/messages`, Bearer Instagram User token | `recipient.id` (IGSID) | 24 hours, plus the 7-day Human Agent tag |
| Telegram | `POST https://api.telegram.org/bot<TOKEN>/sendMessage` | `chat_id` | none documented |

Sources: [WhatsApp send messages](https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/send-messages), [Messenger send messages](https://developers.facebook.com/documentation/business-messaging/messenger-platform/send-messages), [Instagram messaging API](https://developers.facebook.com/documentation/instagram-platform/instagram-api-with-instagram-login/messaging-api) and [Telegram Bot API](https://core.telegram.org/bots/api), all accessed 2026-11-03. If a WhatsApp request carries both `to` and `recipient`, `to` takes precedence. Telegram's `text` takes 1 to 4096 characters, and its FAQ asks bots to avoid more than one message per second in a single chat ([Bots FAQ](https://core.telegram.org/bots/faq)).

Store the time of the last inbound message per `channel` and `reply_to`, and check it before each send. The window rules diverge after 24 hours, as covered in [the WhatsApp 131047 error](/academy/articles/whatsapp-error-131047-24-hour-window-templates/), [Messenger message tags](/academy/articles/messenger-platform-message-tags-outside-24-hours/) and [the Instagram human agent tag](/academy/articles/instagram-messaging-api-24-hour-window-human-agent-tag/). Instagram setup itself is in [Instagram messaging API setup with Instagram Login](/academy/articles/instagram-messaging-api-setup-instagram-login/).

If you would rather receive all four channels through one provider, Z-API Omni carries WhatsApp, Messenger, Instagram and Telegram in one subscription. Webhooks are included without limit ([View documentation](https://developer.omni.z-api.io/en)). Its payload format is not covered here, so check the documentation before you map it.

<!-- TODO:test Omni snippet: Omni's unified webhook payload for the four channels -->

*Z-API Omni team*
