# WhatsApp، Instagram، Messenger اور Telegram کے لیے ایک میسج ماڈل

> WhatsApp، Messenger، Instagram اور Telegram سے آنے والے text ویب ہُکس کا فیلڈ بہ فیلڈ موازنہ کریں، پھر Python میں چاروں کو ایک ریکارڈ میں map کریں۔

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

WhatsApp، Messenger، Instagram اور Telegram سے آنے والے text کو ایک ریکارڈ میں map کریں: چینل، وصول کرنے والا اکاؤنٹ، بھیجنے والا، جواب کا پتہ، message ID، UTC وقت، text اور media reference۔ ہر پلیٹ فارم یہ text اپنی الگ شکل میں بھیجتا ہے۔ deduplication key چینل، اکاؤنٹ اور message ID سے بنائیں۔ Telegram پر chat ID بھی شامل کریں، کیونکہ Telegram کا `message_id` صرف اپنی chat کے اندر منفرد ہوتا ہے۔

## آنے والے چار payloads

### WhatsApp Cloud API

یہ Meta کا نمونہ business-scoped user ID (BSUID) والے صفحے سے لیا گیا ہے، وہی فیلڈز اور ویلیوز، بس کم لائنوں میں ([Business-scoped user IDs](https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids)، رسائی 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"
        }
      ]
    }
  ]
}
```

Meta کے [text message reference](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/text) والے text نمونے میں `from_user_id` کی جگہ `from` (فون نمبر) ہے۔ جن صارفین کا username ہے، Meta ان کا فون نمبر روک لیتا ہے، اور پھر `wa_id` اور `from` شامل نہیں کرتا۔ استثنا دو ہیں: پچھلے 30 دنوں میں آپ کے درمیان کوئی پیغام یا کال، ہر بزنس فون نمبر کے حساب سے، یا صارف کا آپ کی contact book میں ہونا۔ BSUIDs «انفرادی بزنس پورٹ فولیوز تک محدود ہوتی ہیں»۔ [WhatsApp usernames اور business-scoped user IDs](/academy/ur/articles/whatsapp-usernames-business-scoped-user-ids/) میں migration کی تفصیل ہے۔

### Messenger

Meta کی text مثال `messaging[]` کے اندر والا آئٹم ہے ([Messenger کا messages ویب ہُک](https://developers.facebook.com/documentation/business-messaging/messenger-platform/webhooks/webhook-events/messages)، رسائی 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>" }
  }
}
```

اسی صفحے پر attachment والی مثال اس کے گرد کا envelope دکھاتی ہے: `entry[]` کے آئٹمز، جن میں `id`، `time` اور `messaging[]` ہوتے ہیں۔ attachments بطور `message.attachments[]` آتے ہیں، اور ہر ایک میں `type` اور `payload.url` ہوتا ہے۔ `sender.id` اس شخص کی Page-scoped ID (PSID) ہے، اور `recipient.id` آپ کا Page ہے۔

### Instagram

Meta، Instagram API with Instagram Login کے لیے ایک خاکہ (template) دیتا ہے، اور وہ JSON کے طور پر parse نہیں ہوتا۔ یہاں اسے صاف کیا گیا ہے: comments اور اختیاری فیلڈز ہٹا دی گئیں، اور quotes کے بغیر لکھے وقت کے placeholders کی جگہ نمونے کے نمبر رکھے گئے ([Instagram webhook examples](https://developers.facebook.com/documentation/instagram-platform/webhooks/examples)، رسائی 2026-11-03)۔ Meta ان اوقات کی کوئی اکائی نہیں بتاتا۔ 13 ہندسوں والی ویلیوز اس نمونے کے لیے چنی گئی ہیں۔

```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" }
          }
        ]
      }
    ]
  }
]
```

موصول ہونے والے پیغام پر `sender.id` «Instagram صارف کی Instagram-scoped ID» (IGSID) ہے اور `recipient.id` آپ کا professional اکاؤنٹ ہے۔ جب آپ کا اپنا اکاؤنٹ بھیجتا ہے تو دونوں کی جگہ بدل جاتی ہے اور `is_echo` کی ویلیو `true` ہوتی ہے۔ مکمل خاکے میں `attachments[]` بھی درج ہے، `type` اور `payload.url` کے ساتھ۔

### Telegram

Bot API کا صفحہ update کی کوئی مثال نہیں دیتا۔ یہ شکل اس کے فیلڈ ٹیبلز سے بنائی گئی ہے ([Telegram Bot API](https://core.telegram.org/bots/api)، رسائی 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?"
  }
}
```

ہر update میں زیادہ سے زیادہ ایک اختیاری فیلڈ ہوتی ہے، اس لیے message update میں صرف `message` آتا ہے، اور کچھ نہیں۔ `from` «channels کو بھیجے گئے پیغامات میں خالی ہو سکتا ہے»۔ user اور chat IDs، 32 bits سے بڑی ہو سکتی ہیں لیکن ان میں «زیادہ سے زیادہ 52 significant bits» ہوتے ہیں، اس لیے انہیں 64-bit integers کے طور پر محفوظ کریں۔

## ہر چینل میں کون سی فیلڈ کہاں ہے

| | WhatsApp Cloud API | Messenger | Instagram | Telegram |
| --- | --- | --- | --- | --- |
| بھیجنے والا | `messages[].from_user_id` (BSUID) یا `from` (فون، غائب ہو سکتا ہے) | `messaging[].sender.id` (PSID) | `messaging[].sender.id` (IGSID) | `message.from.id` |
| جواب کا پتہ | فون یا BSUID | PSID | IGSID | `message.chat.id` |
| بھیجنے والے کی ID کا دائرہ | بزنس پورٹ فولیو | Page | شخص اور Instagram اکاؤنٹ | درج نہیں |
| Message ID | `messages[].id` (wamid) | `message.mid` | `message.mid` | `message_id`، ہر chat میں منفرد |
| وقت | `timestamp`، 10 ہندسوں کی string | `timestamp`، مثالوں میں 13 ہندسوں کا نمبر | `timestamp`، اکائی درج نہیں | `date`، Unix time integer |
| Text | `text.body` | `message.text` | `message.text` | `message.text`، یا media پر `caption` |
| Media | `image.id`، پھر اس media ID کو GET کریں | `attachments[].payload.url` | `attachments[].payload.url` | `photo[]` یا `document` کی `file_id`، پھر `getFile` |

Meta، WhatsApp کے `timestamp` کو «Unix timestamp جو بتاتا ہے کہ ویب ہُک کب trigger ہوا» کہتا ہے اور کوئی اکائی نہیں بتاتا۔ Meta کا کوئی صفحہ Messenger یا Instagram کی اکائی بھی نہیں بتاتا، اور Telegram صرف «Unix time» کہتا ہے۔ ہندسوں کی تعداد دیکھ کر normalize کریں۔

media references مختلف رفتار سے پرانے ہوتے ہیں۔ `GET /<MEDIA_ID>?phone_number_id=<PHONE_NUMBER_ID>` سے لیا گیا WhatsApp media URL پانچ منٹ بعد expire ہو جاتا ہے اور اس کے لیے آپ کا token چاہیے ([media](https://developers.facebook.com/documentation/business-messaging/whatsapp/business-phone-numbers/media))۔ Telegram کا file link «کم از کم 1 گھنٹے تک valid» رہتا ہے، اور download کی حد 20 MB ہے۔ Meta، Messenger یا Instagram کے attachment URLs کی کوئی مدت نہیں بتاتا، اس لیے ویب ہُک آتے ہی انہیں download کر لیں۔ [WhatsApp کے expire شدہ media URLs](/academy/ur/articles/whatsapp-cloud-api-media-download-url-expired/) میں WhatsApp والا پہلو تفصیل سے ہے۔

## چاروں کے لیے ایک ریکارڈ

```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
);
```

IDs کو text کے طور پر رکھیں، تاکہ Telegram کے integers اور Meta کی strings ایک ہی column میں آ جائیں۔ PSID، IGSID اور BSUID کے دائرے مختلف ہیں (Page، Instagram اکاؤنٹ، بزنس پورٹ فولیو)، اس لیے ایک چینل کی کوئی ID دوسرے چینل پر اس شخص کی شناخت نہیں کرتی۔ تین چینلز پر موجود ایک شخص تین rows ہے، جب تک آپ کا اپنا ڈیٹا انہیں جوڑ نہ دے۔ [گفتگو محفوظ کرنے کا database schema](/academy/ur/articles/whatsapp-conversation-storage-database-schema/) وہ WhatsApp ٹیبلز دکھاتا ہے جن میں یہ ریکارڈ ڈیٹا بھیج سکتا ہے۔

## Python میں ایک normalizer

صرف standard library۔ اسے script کے طور پر چلائیں تو یہ ہر نمونے کا ایک ریکارڈ print کرتا ہے۔ echoes پر نشان لگ جاتا ہے؛ انہیں اپنے bot تک پہنچنے سے پہلے filter کر دیں۔

```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))
```

Messenger والا نمونہ Meta کی text مثال کو attachment مثال والے envelope میں لپیٹتا ہے۔ Meta کا messages صفحہ Messenger کے لیے top-level `object` کی کوئی ویلیو نہیں دکھاتا، اس لیے code ہر اس payload کو Messenger مانتا ہے جو WhatsApp یا Instagram کا نہ ہو۔ آپ کی Page subscription جو `object` بھیجتی ہے اسے log کریں اور پھر اس branch کو سخت کریں۔

Telegram کا `photo`، «دستیاب sizes» کی ایک list ہے۔ code آخری entry رکھتا ہے، اس لیے اگر آپ کو کوئی خاص size چاہیے تو کوئی اور entry چنیں۔

Instagram، `is_echo` کو دستاویز کرتا ہے۔ اس گائیڈ کے لیے Messenger کا echo event چیک نہیں کیا گیا، اس لیے Messenger والی جانچ احتیاطاً رکھی گئی ہے۔

ایک ہی پیغام کے ایک سے زیادہ بار آنے کی توقع رکھیں۔ Meta، WhatsApp ویب ہُکس «7 دن تک» دوبارہ بھیجتا ہے ([WhatsApp ویب ہُکس کا overview](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/overview)) اور Instagram ویب ہُکس «اگلے 36 گھنٹوں کے دوران» ([Instagram ویب ہُکس کا setup](https://developers.facebook.com/documentation/instagram-platform/webhooks/setup))۔ Telegram «مناسب تعداد میں کوششوں کے بعد ہار مان لے گا» ([Telegram Bot API](https://core.telegram.org/bots/api))۔ تینوں پر رسائی 2026-11-03۔ ریکارڈ `INSERT ... ON CONFLICT (dedup_key) DO NOTHING` سے لکھیں اور کارروائی صرف تب کریں جب insert کامیاب ہو۔ [n8n کا idempotency pattern](/academy/ur/articles/n8n-duplicate-webhooks-idempotency/) یہی طریقہ ایک workflow میں دکھاتا ہے۔

## صحیح چینل پر جواب دینا

جواب کو `channel` کے حساب سے route کریں اور `reply_to` پر بھیجیں۔ ہر پلیٹ فارم کا اپنا endpoint، token اور ونڈو ہے۔

| چینل | بھیجنے کا endpoint | وصول کنندہ کی فیلڈ | ونڈو |
| --- | --- | --- | --- |
| WhatsApp Cloud API | `POST https://graph.facebook.com/v26.0/<PHONE_NUMBER_ID>/messages`، Bearer token | `to` (فون) یا `recipient` (BSUID) | صارف کے آخری پیغام سے 24 گھنٹے، اس کے بعد صرف ٹیمپلیٹس |
| Messenger | `POST https://graph.facebook.com/v26.0/<PAGE_ID>/messages?access_token=<PAGE_ACCESS_TOKEN>`، `"messaging_type": "RESPONSE"` | `recipient.id` (PSID) | زیادہ تر actions کے لیے 24 گھنٹے، Click-to-Messenger ad کے بعد 7 دن تک، message tags |
| Instagram | `POST https://graph.instagram.com/v26.0/<IG_ID>/messages`، Bearer Instagram User token | `recipient.id` (IGSID) | 24 گھنٹے، اور 7 دن کا Human Agent tag |
| Telegram | `POST https://api.telegram.org/bot<TOKEN>/sendMessage` | `chat_id` | کوئی دستاویز نہیں |

ماخذ: [WhatsApp پر پیغامات بھیجنا](https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/send-messages)، [Messenger پر پیغامات بھیجنا](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) اور [Telegram Bot API](https://core.telegram.org/bots/api)، سب پر رسائی 2026-11-03۔ اگر WhatsApp کی request میں `to` اور `recipient` دونوں ہوں تو `to` کو ترجیح ملتی ہے۔ Telegram کا `text`، 1 سے 4096 حروف لیتا ہے، اور اس کا FAQ bots سے کہتا ہے کہ ایک chat میں فی سیکنڈ ایک سے زیادہ پیغام نہ بھیجیں ([Bots FAQ](https://core.telegram.org/bots/faq))۔

ہر `channel` اور `reply_to` کے لیے آخری آنے والے پیغام کا وقت محفوظ کریں، اور ہر بار بھیجنے سے پہلے اسے چیک کریں۔ 24 گھنٹے کے بعد ونڈو کے قواعد الگ الگ ہو جاتے ہیں، جیسا کہ [WhatsApp کا error 131047](/academy/ur/articles/whatsapp-error-131047-24-hour-window-templates/)، [Messenger کے message tags](/academy/ur/articles/messenger-platform-message-tags-outside-24-hours/) اور [Instagram کا human agent tag](/academy/ur/articles/instagram-messaging-api-24-hour-window-human-agent-tag/) میں بیان ہے۔ Instagram کا setup خود [Instagram Login کے ساتھ Instagram messaging API کا setup](/academy/ur/articles/instagram-messaging-api-setup-instagram-login/) میں ہے۔

اگر آپ چاروں چینلز ایک ہی provider کے ذریعے وصول کرنا چاہتے ہیں تو Z-API Omni ایک subscription میں WhatsApp، Messenger، Instagram اور Telegram فراہم کرتا ہے۔ ویب ہُکس بغیر کسی حد کے شامل ہیں ([دستاویزات دیکھیں](https://developer.omni.z-api.io/en))۔ اس کا payload format یہاں شامل نہیں، اس لیے map کرنے سے پہلے دستاویزات دیکھ لیں۔

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

*Z-API Omni ٹیم*
