الدرس 2 · الوحدة 5: Omnichannel Integration: WhatsApp, Telegram and MCP
Connecting your agent to WhatsApp: receiving, replying and sending media
الفيديو قريبًا
Learn it with your tutor on the live board
أهم نقاط الفيديو
The salon that never sleeps
- A customer messages at 11 pm: "Can I book Friday?"
- The owner sees it at 9 am, and the slot is gone
- Your agent can answer in seconds, on WhatsApp
- Today: connect the agent so it can read and reply
What you will learn
- Receive WhatsApp messages through a webhook
- Reply with text inside the 24-hour window
- Receive and send media: photos and PDF invoices
The round trip of one message
- WhatsApp calls your webhook URL
- Your workflow hands the text to the agent
- The reply goes back through the Cloud API
layout: wide
direction: LR
components:
client: {kind: user, label: Customer}
wa: {kind: external, label: WhatsApp Cloud API}
hook: {kind: api, label: Your webhook}
agent: {kind: llm, label: AI agent}
cal: {kind: service, label: Booking calendar}
links: [client->wa, wa->hook, hook->agent, agent->cal]
steps:
- at: "Mona types her question"
show: [client, wa]
- at: "your webhook address"
show: all
- at: "follow one message"
flow: ["client>wa: Friday 5pm?", "wa>hook: POST JSON", "hook>agent: text", "agent>cal: check slot", "cal>agent: free", "agent>hook: reply", "hook>wa: send", "wa>client: Booked?"] Proving the webhook is yours
VERIFY_TOKEN = "salon-secret-42"
def verify(params):
ok = params.get("hub.mode") == "subscribe"
ok = ok and params.get("hub.verify_token") == VERIFY_TOKEN
if ok:
return 200, params["hub.challenge"]
return 403, "forbidden"
print(verify({"hub.mode": "subscribe",
"hub.verify_token": "salon-secret-42",
"hub.challenge": "1158201444"}))
print(verify({"hub.mode": "subscribe",
"hub.verify_token": "wrong",
"hub.challenge": "1"})) Reading what the customer said
payload = {"entry": [{"changes": [{"value": {
"contacts": [{"profile": {"name": "Mona"},
"wa_id": "201001234567"}],
"messages": [{"from": "201001234567",
"id": "wamid.ABC123",
"type": "text",
"text": {"body": "Can I book Friday 5pm?"}}]
}}]}]}
value = payload["entry"][0]["changes"][0]["value"]
msg = value["messages"][0]
name = value["contacts"][0]["profile"]["name"]
print(name, msg["from"], msg["type"])
print(msg["text"]["body"]) Replying, and the 24-hour rule
import json
reply = {
"messaging_product": "whatsapp",
"to": "201001234567",
"type": "text",
"text": {"body": "Hi Mona! Friday 5pm is free. Book it?"},
}
# version number: from your Meta dashboard
print("POST https://graph.facebook.com/v21.0/<PHONE_ID>/messages")
print("Authorization: Bearer <ACCESS_TOKEN>")
print(json.dumps(reply, indent=2)) Receiving a photo or a file
- Media arrives as an id, not the file
- Step 1: ask the API for a temporary URL
- Step 2: download it with your access token
- Then pass the image to a vision-capable model
Sending an invoice as a PDF
import json
# photo: "type": "image" instead of "document"
# private file: upload first, then send {"id": ...}
invoice = {
"messaging_product": "whatsapp",
"to": "201001234567",
"type": "document",
"document": {
"link": "https://example.com/inv/INV-1042.pdf",
"filename": "INV-1042.pdf",
"caption": "Your invoice: 450 EGP",
},
}
print(json.dumps(invoice, indent=2)) Common mistake: the triple reply
- Meta expects a quick 200 reply from your webhook
- A slow agent means Meta sends the event again
- Fix: answer 200 at once, process afterwards
- Save message ids and skip ones you've seen
- Ignore status events (sent, delivered, read)
Recap
- Messages reach your agent through a verified webhook
- Free-text replies only inside the 24-hour window
- Media travels as ids: fetch to read, link or upload to send
Your exercise
- Connect a WhatsApp Trigger to your test number
- Reply to any text with an agent-written answer
- If the message is a photo, describe it back
- Send yourself a sample PDF invoice
النص المكتوب
The salon that never sleeps. Picture a small hair salon. At eleven at night a client sends a WhatsApp message asking for a Friday appointment. The owner is asleep, sees it at nine the next morning, and by then the client has booked somewhere else. That happens every week to thousands of small businesses. In the last lesson you set up the official WhatsApp Business Cloud API and your message templates. Now we plug your agent into that line, so the owner's phone becomes a receptionist that answers in seconds, at any hour, and still sounds like the business.
What you will learn. Here's the plan for this lesson. First, you'll see how a WhatsApp message actually reaches your agent, using something called a webhook, and how to pull the useful parts out of it. Second, you'll send a reply back and learn the one timing rule WhatsApp enforces on every business. Third, you'll handle media in both directions: reading a photo a customer sends you, and sending them a PDF invoice. You'll see small Python snippets so you know what's happening under the hood, but every step maps to a node in tools like n8n or Make.
The round trip of one message. Let's see the whole journey before any details. A client called Mona types her question on WhatsApp. Meta's servers receive it, and they need to know where to forward it. That's your webhook address, which is just a public URL you own. A webhook works like a doorbell: instead of you checking for new messages every minute, WhatsApp rings your URL the moment one arrives. Now follow one message. WhatsApp sends it to your webhook as JSON, which is simply a text format where every value carries a label. Your workflow passes the text to the agent, the agent checks the calendar, and the reply travels back through the Cloud API to Mona's phone.
Proving the webhook is yours. Before Meta sends you a single message, it checks that the URL really belongs to you. You choose a secret word, called the verify token, and type it into the app dashboard along with your URL. Meta then calls your URL once with that token and a random number called the challenge. If the token matches, you echo the challenge back with status 200, meaning OK. If not, you refuse. In the output, the right token returns the challenge number, and the wrong one gets a 403. In n8n, the WhatsApp Trigger node does this handshake for you.
Reading what the customer said. The message arrives wrapped in several layers, so let's unwrap it slowly. Entry, then changes, then value: that's where everything useful lives. Inside value you'll find contacts, which gives you the customer's display name, and messages, which holds the sender's number, a unique message id, the type, and the text itself. Those four fields are all your agent needs to start. The number tells you who to reply to and which memory to load. The type tells you whether it's text, an image or a document. The id lets you avoid handling the same message twice, which matters later in this lesson.
Replying, and the 24-hour rule. To reply, you send a POST request, which simply means sending data to a web address. The address is the messages endpoint, the exact web address for your phone number ID, and the version number in it comes from your dashboard. You also include your access token, a password-like key from the Meta dashboard, in a line called the Authorization header. In n8n or Make, each of these is just a field in the WhatsApp or HTTP node. The body names the recipient, the type, and the text the agent wrote. Now the rule that catches everyone. You may send free text only within 24 hours of the customer's last message. That's the customer service window. Each new message from Mona opens it again for another 24 hours. Once it closes, you can only send one of the approved templates you built in lesson one, like an appointment reminder.
Receiving a photo or a file. Customers love sending pictures. A salon client sends a photo of the haircut she wants, or a shop customer sends a screenshot of a bank transfer. The webhook doesn't carry the picture itself. It carries a media id. So you make two calls. First, send that id to the API, and it returns a short-lived download URL. Second, download the file from that URL, again sending your access token. Then hand the image to a model that can see, and the agent can say, "Got it, that's a layered bob, about ninety minutes."
Sending an invoice as a PDF. Sending media uses the same messages endpoint with a different type. For an invoice, the type is document, and you give a link to the PDF, a file name the customer will see, and a short caption. For a photo, such as a before and after picture, the type is image instead. One condition matters: the link must be a public HTTPS address, meaning a secure web link that Meta can download. If your invoices are private files, upload the PDF to the media endpoint first, get back an id, and send that id in place of the link.
Worked example: book, then bill. Let's put it all together for the salon. It starts in the chat. Mona sends a photo of a hairstyle and asks for Friday at five. Next, the workflow. The webhook fires, the workflow downloads the photo, and the agent sees the style, checks the calendar, books the slot and replies with a confirmation, all inside the 24-hour window. On Friday the visit happens. Finally, the invoice. The workflow creates a PDF for four hundred and fifty pounds and sends it as a document message with a polite caption. One conversation, booked and billed, without the owner touching her phone.
Common mistake: the triple reply. Here's the mistake that embarrasses almost every first build. Your webhook waits for the agent to think, check the calendar and write a reply, which can take ten seconds or more. Meta doesn't hear back quickly, assumes delivery failed, and sends the same event again. Now the customer gets three identical answers. The fix has two parts. Acknowledge with status 200 immediately and do the work afterwards. And keep a list of message ids you've handled, skipping any repeat. Also note that delivery and read receipts hit the same URL, so ignore events with no messages field.
Recap. Let's recap. First, WhatsApp delivers every message to your webhook, after a one-time handshake with your verify token, and the useful fields sit under entry, changes and value. Second, your agent can reply with free text only within 24 hours of the customer's last message. After that, use an approved template. Third, media moves as ids. To read a photo, fetch its URL and download it with your token. To send an invoice or picture, give a public link or upload the file first. Answer fast, skip duplicates, and the owner can finally rest.
Your exercise. Now it's your turn, and you can finish this in under an hour. Using the test number from lesson one, add a WhatsApp Trigger in n8n or Make and connect it to your agent. Send yourself a text and make sure the agent replies once, not three times. Then send a photo and have the agent describe what it sees. Finally, make the workflow send you a sample PDF invoice with a caption. Keep that workflow, because next lesson we'll plug a Telegram bot into the very same agent.
استكشف الرسم المتحرك
الرسوم المتحركة نفسها التي في الفيديو، دقيقة وتفاعلية: شغّلها أو أوقفها، أو اسحب المؤشر، أو انتقل إلى أي خطوة بالسرعة التي تناسبك.
Loading the animation...
ملخص الدرس
- مشاهدة الفيديو
- Messages reach your agent through a verified webhook
- Free-text replies only inside the 24-hour window
- Media travels as ids: fetch to read, link or upload to send