app2email API الأثمنة

التوثيق

ابنِ chatbot WhatsApp بـ API

استقبل رسائل WhatsApp عبر webhook موقع، جاوب على الأسئلة العادية من الكود ديالك، وحوّل المحادثة لشي واحد من الفريق ملي الزبون يطلب ذلك.

فهاد الدليل غادي تبني بوت صغير ديال WhatsApp كيجاوب على أسئلة ديال أوقات الخدمة والأثمان، وكيحوّل المحادثة لشي واحد من الفريق ملي الزبون يطلب ذلك.

شنو كيشوف الزبون: كيكتب لرقم WhatsApp ديالكم، رسالتو كتاخد علامات زرقا، كيبان "يكتب..."، والجواب كيوصل بعد ثانية. ملي يكتب "ممكن نهدر مع شي واحد؟"، البوت كيقول أن شخص غادي يجاوب، ومن بعدها غير الفريق ديالكم كيجاوب.

شنو كتشوف انت: كل رسالة وكل جواب فـ Inbox ديال app2email وفـ سجل النشاط (Activity Log)، علامات التسليم والقراءة ديال كل جواب كأحداث فالـ webhook، وملخص ديال المحادثة ملي البوت يحوّلها.

البوت أقل من 100 سطر ديال Node.js (Express) ولا Python (Flask). كيتشيك على توقيع الـ webhook، كيتجاوز الأحداث اللي عالجها من قبل، كيعاود المحاولة بأمان، وكيحترم نافذة الرد ديال 24 ساعة.

كيفاش كيخدم

  1. زبون كيصيفط رسالة لرقم WhatsApp ديالكم.
  2. app2email كيصيفط POST موقّع بالحدث message.received للرابط ديالكم.
  3. الكود ديالكم كيتشيك على التوقيع، كيشوف المحادثة (واش شي واحد من الفريق ماسكها؟ واش نافذة الرد مفتوحة؟)، كيعلّم الرسالة بأنها مقروءة مع مؤشر الكتابة، وكيصيفط الجواب بـ POST /messages.
  4. app2email كيصيفط أحداث message.status ملي الجواب يتصيفط، يتسلّم ويتقرا.

الرابط ديالكم خاصو يجاوب بـ 2xx فـ 10 ثواني. إلا ما جاوبش، app2email كيعاود صيفط نفس الحدث من بعد، فالانقطاع القصير ما كيضيّعش والو.

شنو خاصك

  • رقم WhatsApp مربوط بـ app2email، فباقة مدفوعة وشغال (LIVE). بلا باقة، كل طلب كيجاوب 403 plan_not_allowed؛ الخدمة الموقوفة كتجاوب 403 service_not_live. شوف البداية.
  • API key من صفحة مفاتيح API بهاد الصلاحيات:
الصلاحيةعلاش البوت خاصو
messages:sendيصيفط الأجوبة (POST /messages)، يعلّم الرسائل مقروءة (POST /messages/read)، يحوّل المحادثة لشخص (PUT /conversations/{contact}/owner)
messages:readيقرا المحادثة: المالك ونافذة الرد (GET /conversations/{contact})
webhooks:manageيسجّل الـ webhook مرة وحدة (POST /webhooks). تقدر تزيدو كذلك من صفحة مفتاح API فقسم Webhooks، بلا كود
  • عنوان https عام للـ webhook. فحاسوبك، tunnel كيعطيك واحد (الخطوة 2 تحت).
  • template موافق عليه بلا placeholders، للجواب النادر اللي كيمشي بعد ما تسالي نافذة الرد (شوف نافذة 24 ساعة).
Tip

جرّب قبل ما تخدم بالحقيقي. sandbox key (مفتاح فيه علامة sandbox، كتصنعها فصفحة مفتاح API) كيدير كل التشيكات على رقمكم انتو وما كيصيفط والو لـ WhatsApp: الأجوبة فيها "sandbox": true، وmessage ids كتبدا بـ wamid.SANDBOX.، وأحداث message.status كتوصل. بلا حساب خالص، الـ instant sandbox كيعطيك key لرقم التجربة 12025550100 مع زبناء مزيفين: POST https://api.app2email.com/v1/account/sandbox (بلا key، بلا body) ولا الأداة create_sandbox ديال سيرفر Management MCP. ما عندوش webhooks: اقرا الأحداث بـ GET /events?wait=25 (شوف الأسئلة الشائعة). التفاصيل: Sandbox.

جهّز فـ أربع خطوات

  1. 1. تشيك على المفتاح ديالك

    GET /me كيخدم مع أي key صالح، وكيبين الصلاحيات والحدود ديالو. فكل طلب، YOUR_NUMBER هو رقم WhatsApp اللي كتصيفط منو: كود الدولة أولا، أرقام فقط.

    cURL
    curl https://api.app2email.com/v1/YOUR_NUMBER/me \
      -H "Authorization: Bearer YOUR_API_KEY"
    Node.js
    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/me", {
      headers: { Authorization: `Bearer ${process.env.API_KEY}` },
    });
    console.log(await res.json());
    Python
    import os, requests
    
    res = requests.get("https://api.app2email.com/v1/YOUR_NUMBER/me",
                       headers={"Authorization": f"Bearer {os.environ['API_KEY']}"}, timeout=10)
    print(res.json())

    شنو كترجع:

    {
      "success": true,
      "request_id": "a7k3p",
      "key_valid": true,
      "api_version": "v1",
      "number": "4976659348270",
      "plan": "standard_5000",
      "service_status": "LIVE",
      "key": { "name": "WhatsApp bot", "scopes": ["messages:read", "messages:send"], "ip_allow": "" },
      "limits": { "max_numbers_per_request": 1000, "requests_per_second": 20, "burst": 50, "rate_limit_mode": "enforce", "webhooks_max": 5 }
    }

    service_status خاصو يكون LIVE، وkey.scopes خاصو يبيّن الصلاحيات اللي فالجدول فوق (ولا * للوصول الكامل).

  2. 2. عطي الكومبيوتر ديالك عنوان عام

    app2email كيقدر غير يصيفط الأحداث لعنوان https عام. وأنت كتطور، tunnel كيوصّل واحد لحاسوبك. شغّل البوت على البورت 3000 (الكود تحت)، ومن بعد فterminal ثاني:

    # ngrok (https://ngrok.com)
    ngrok http 3000
    
    # or Cloudflare's cloudflared, no account needed for a quick tunnel
    cloudflared tunnel --url http://localhost:3000

    كلاهما كيطبعو عنوان https بحال https://a1b2-203-0-113-7.ngrok-free.app. رابط الـ webhook ديالك هو هاد العنوان زائد /webhook. الـ tunnel السريع ممكن يعطيك عنوان جديد كل مرة كيبدا: حدّث الـ webhook بـ PATCH /webhooks/{id} وurl جديد ملي يوقع هادشي.

    ما عندكش tunnel؟ GET /events?wait=25 كيجيب نفس الأحداث بلا عنوان عام (شوف الأسئلة الشائعة).

  3. 3. سجّل الـ webhook

    طلب وحدة. الجواب فيه سر التوقيع (whsec_...) اللي كيوقّع كل حدث: خبيه مع المفتاح ديالك، مثلا فمتغير بيئة WEBHOOK_SECRET.

    cURL
    curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/webhooks \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{"url": "https://a1b2-203-0-113-7.ngrok-free.app/webhook"}'
    Node.js
    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/webhooks", {
      method: "POST",
      headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json" },
      body: JSON.stringify({ url: "https://a1b2-203-0-113-7.ngrok-free.app/webhook" }),
    });
    const { webhook } = await res.json();
    console.log(webhook.id, webhook.secret);
    Python
    import os, requests
    
    res = requests.post("https://api.app2email.com/v1/YOUR_NUMBER/webhooks",
                        headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
                        json={"url": "https://a1b2-203-0-113-7.ngrok-free.app/webhook"}, timeout=10)
    webhook = res.json()["webhook"]
    print(webhook["id"], webhook["secret"])

    شنو كترجع (201 Created؛ مختصر: الجواب كيبين كذلك كل أنواع الأحداث فـ events):

    {
      "success": true,
      "request_id": "w8hk2",
      "webhook": {
        "id": "wh_a1b2c3d4e5f6g7h8",
        "url": "https://a1b2-203-0-113-7.ngrok-free.app/webhook",
        "secret": "whsec_...",
        "created": "2026-11-21T09:00:00.000Z",
        "active": true,
        "format": "app2email"
      }
    }

    تسجيل نفس الرابط مرة أخرى كيجاوب 200 بنفس الـ id ونفس السر، فالطلب آمن تعاودو. الرقم عندو 5 webhooks كحد أقصى، وكل webhook كيوصلو كل الأحداث: الكود ديالك كيختار الأنواع اللي كيعالجها بـ type، وكيجاوب 2xx على الباقي. خلّي format على app2email (الافتراضي) فهاد الدليل.

  4. 4. صيفط حدث تجريبي

    POST /webhooks/{id}/test كيصيفط حدث موقّع نموذجي فالحال، وكيقولك واش الرابط ديالك جاوب. بـ {"type": "message.received"} كتاخد النموذج ديال هاد الحدث.

    curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/webhooks/wh_a1b2c3d4e5f6g7h8/test \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{"type": "message.received"}'

    شنو كترجع (مختصر):

    {
      "success": true,
      "request_id": "t3ws9",
      "delivered": true,
      "http_status": 200,
      "response_ms": 38
    }

    delivered: true معناه أن الرابط ديالك جاوب 2xx فـ 10 ثواني. الحدث التجريبي فيه "test": true والـ header X-App2email-Test: true، وجهة الاتصال ديالو مزيفة، فالبوت تحت كيتشيك على التوقيع ويسجل الحدث وما كيجاوبش عليه. حتى 30 تجربة فالساعة لكل رقم. من بعد، صيفط رسالة حقيقية لرقمكم من تليفونكم: البوت غادي يجاوب.

الأربع طلبات اللي كيدير البوت

كل طلب كيمشي لـ https://api.app2email.com/v1/YOUR_NUMBER مع Authorization: Bearer YOUR_API_KEY.

1. اقرا شنو صيفط الزبون

هادي هي body ديال حدث message.received اللي كيوصل للرابط ديالك (رسالة نصية):

{
  "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
  "type": "message.received",
  "created": "2026-11-06T01:00:00.000Z",
  "number": "4976659348270",
  "data": {
    "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
    "from": "61412345678",
    "name": "Sample Contact",
    "type": "text",
    "text": "What are your opening hours?",
    "conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_SAMPLEk3XbQ9rTzP2mW",
    "timestamp": "2026-11-06T01:00:00.000Z",
    "from_user_id": "AU.1234567890123456"
  }
}
  • id (وكذلك فـ header X-App2email-Delivery) نفسو فكل إعادة: هو اللي كتعاود تشيك بيه.
  • data.from هو رقم الزبون. الزبون اللي كيستعمل اسم مستخدم فـ WhatsApp ممكن يجي بـ from_user_id وبلا رقم؛ هاد الـ id كيخدم فين ما يخدم الرقم.
  • data.type هو text، image، audio، interactive (ضغطة على زر رد ولا سطر فقائمة، مع interactive.id)، button (زر رد ديال template، مع button.payload)، وغيرهم. البوت كيجاوب على النص والضغطات، والباقي كيخليه للفريق.

2. شوف المحادثة

GET /conversations/{contact} (صلاحية messages:read) كيقولك شكون كيتعامل مع المحادثة، وواش ممكن تصيفط جواب حر دابا.

curl https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678 \
  -H "Authorization: Bearer YOUR_API_KEY"

شنو كترجع:

{
  "success": true,
  "request_id": "c9slm",
  "contact": "61412345678",
  "identity_type": "phone",
  "phone": "61412345678",
  "name": "John",
  "window_state": "open",
  "window_open": true,
  "window_closes_at": "2026-11-07T00:45:00Z",
  "last_inbound_at": "2026-11-06T01:00:00Z",
  "messages": 12,
  "owner": "",
  "conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_..."
}

owner خاوي معناه التعامل العادي. ملي يكون human ولا paused شي واحد من الفريق ماسك المحادثة والبوت ساكت؛ whatsapp_ai معناه أن وكيل الذكاء الاصطناعي ديال WhatsApp ماسكها.

3. بيّن العلامات الزرقا و"يكتب..."

POST /messages/read (صلاحية messages:send) كيعلّم الرسالة مقروءة، ومع "typing": true كيبيّن مؤشر الكتابة حتى 25 ثانية، ولا حتى يوصل جوابك. هادا مجاني: ما كيتحسبش على الباقة، وما كيتقيّدش بنافذة 24 ساعة.

curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/messages/read \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=", "typing": true}'

شنو كترجع:

{
  "success": true,
  "request_id": "k2rdq",
  "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
  "status": "read",
  "typing_indicator": true
}

4. صيفط الجواب

POST /messages (صلاحية messages:send) بـ "type": "text" كيصيفط رسالة حرة لزبون واحد ملي نافذة الرد مفتوحة.

الجزءشنو تحط
لمنto: رقم الزبون (data.from)، ولا from_user_id ديالو
أي رسالةtype: text للجواب العادي. خارج النافذة: template
شنو كيقولtext.body: الجواب ديالك. text.preview_url: true باش يبان معاينة الرابط
المفتاح ديالكالـ header Authorization: Bearer YOUR_API_KEY
بلا تكرارالـ header Idempotency-Key: قيمة فريدة لهاد الجواب، مثلا text- مع message_id ديال الزبون. نفس الطلب بنفس المفتاح فـ 24 ساعة ما كيتصيفطش مرة أخرى
cURL
curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/messages \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: text-wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=" \
  -d '{"to": "61412345678", "type": "text", "text": {"body": "We are open Monday to Friday, 9 am to 5 pm.", "preview_url": false}}'
Node.js
const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/messages", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.API_KEY}`,
    "Content-Type": "application/json",
    "Idempotency-Key": `text-${messageId}`,
  },
  body: JSON.stringify({
    to: "61412345678",
    type: "text",
    text: { body: "We are open Monday to Friday, 9 am to 5 pm.", preview_url: false },
  }),
});
console.log(res.status, await res.json());
Python
res = requests.post(
    "https://api.app2email.com/v1/YOUR_NUMBER/messages",
    headers={"Authorization": f"Bearer {os.environ['API_KEY']}", "Idempotency-Key": f"text-{message_id}"},
    json={"to": "61412345678", "type": "text",
          "text": {"body": "We are open Monday to Friday, 9 am to 5 pm.", "preview_url": False}},
    timeout=10,
)
print(res.status_code, res.json())

شنو كترجع (200):

{
  "success": true,
  "request_id": "kxrkf",
  "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
  "status": "accepted",
  "type": "text",
  "from": "4976659348270",
  "to": "61412345678",
  "window_closes_at": "2026-11-07T00:45:00Z",
  "conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_...",
  "contacts": [{ "input": "61412345678", "wa_id": "61412345678" }]
}

accepted معناه أن WhatsApp قبل الرسالة. واش توصلات وتقرات، غادي يجي من بعد على شكل أحداث message.status. الطلب المتكرر بنفس Idempotency-Key كيرجع نفس الجواب بالـ header Idempotent-Replayed: true، وما كيتصيفطش أي شي مرتين.

ملي كيفشل، الجواب فيه success: false وerror. قرر حسب error.code، ماشي حسب نص الرسالة:

{
  "success": false,
  "request_id": "q2v8n",
  "error": {
    "code": "outside_24h_window",
    "message": "The contact has not written to this number in the last 24 hours (or never), so only a template message can be sent.",
    "how_to_fix": "Send an approved template message instead (\"type\": \"template\"). When the contact answers, normal messages work again for 24 hours.",
    "documentation_url": "https://www.app2email.com/docs/api/errors#outside_24h_window",
    "is_retriable": false
  }
}

الطلبات الكثيرة كتجاوب 429 rate_limited مع header Retry-After:

HTTP/1.1 429 Too Many Requests
Retry-After: 2
X-RateLimit-Limit: 50
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 2

{"success": false, "request_id": "r5lmt", "error": {"code": "rate_limited", "message": "Too many requests for this key.", "how_to_fix": "Wait, then send again.", "documentation_url": "https://www.app2email.com/docs/api/errors#rate_limited", "is_retriable": true, "retry_after_seconds": 2}}

عطي المحادثة لشي واحد من الفريق

ملي الزبون يطلب شخص، PUT /conversations/{contact}/owner (صلاحية messages:send) بـ "owner": "human"، وreason قصيرة وsummary. الرد التلقائي ديال app2email والوكلاء الآخرين كيسكتو على الجهة، الناس اللي كيوصلهم الكلام بالإيميل كيشوفو الملخص، وكل webhook ديال الرقم كيوصلو conversation.owner_changed. until_minutes كيخليه مؤقت: من بعد، المحادثة كترجع للتعامل العادي وحدها.

curl -X PUT https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/owner \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"owner": "human", "reason": "customer asked for a person", "summary": "Wants to move the delivery to Monday.", "until_minutes": 240}'

الجواب فيه conversation المحدّثة (بنفس الحقول ديال GET /conversations/{contact}).

البوت الكامل

الجوج نسخ كيديرو نفس الشي: كيتشيكو على التوقيع، كيتجاوزو أحداث التجربة والأحداث اللي تعالجات، كيتجاوزو المحادثات اللي شي واحد من الفريق ماسكها، كيعلّمو مقروء مع مؤشر الكتابة، كيحوّلو ملي الزبون يقول "شخص"، كيجاوبو على الكلمات المفتاحية، وكيرجعو لـ template ملي النافذة تسالات. عطي ثلاث متغيرات بيئة قبل: NUMBER (رقم WhatsApp ديالكم، أرقام)، وAPI_KEY، وWEBHOOK_SECRET (القيمة whsec_... ديال الخطوة 3).

Node.js (Express)
bot.mjs
// Node.js 18 or newer.  npm install express   then   node bot.mjs
import crypto from "node:crypto";
import express from "express";

const { NUMBER, API_KEY, WEBHOOK_SECRET, PORT = 3000 } = process.env;
const API = `https://api.app2email.com/v1/${NUMBER}`;
const FALLBACK = { name: "hello_world", language: { code: "en_US" } }; // an approved template without placeholders
const RETRY_LATER = new Set(["rate_limited", "whatsapp_rate_limit", "too_many_messages_to_recipient"]);
const done = new Set(); // handled event ids: use a database table or Redis in production

const ANSWERS = [
  [/\b(hours?|open|opening|closed)\b/i, "We are open Monday to Friday, 9 am to 5 pm, and Saturday 10 am to 2 pm."],
  [/\b(prices?|cost|how much)\b/i, "A standard service is $49, an express service $79. Full list: https://example.com/prices"],
];
const HUMAN = /\b(human|person|someone|staff)\b/i;
const MENU = "Hi! I can tell you our opening hours or our prices. Type 'person' to talk to the team.";

function verify(raw, header, secret) {
  const t = /(?:^|,)\s*t=(\d+)/.exec(header ?? "")?.[1];
  const v1 = [...(header ?? "").matchAll(/(?:^|,)\s*v1=([0-9a-f]+)/g)].map((m) => m[1]); // two during a secret change
  if (!t || v1.length === 0 || Math.abs(Date.now() / 1000 - Number(t)) > 300) return false;
  const expected = crypto.createHmac("sha256", secret).update(t + ".").update(raw).digest("hex");
  return v1.some((v) => v.length === expected.length && crypto.timingSafeEqual(Buffer.from(v), Buffer.from(expected)));
}

async function api(method, path, body, idempotencyKey) {
  for (let attempt = 1; ; attempt++) {
    const res = await fetch(API + path, {
      method,
      signal: AbortSignal.timeout(4000),
      headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json",
                 ...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}) },
      body: body ? JSON.stringify(body) : undefined,
    });
    const json = await res.json();
    if (res.ok) return json;
    const code = json.error?.code;
    const wait = Number(res.headers.get("Retry-After") ?? 1);
    if (code === "rate_limited" && attempt < 3 && wait <= 3) { await new Promise((r) => setTimeout(r, wait * 1000)); continue; }
    if (res.status >= 500 || RETRY_LATER.has(code)) throw new Error(`${code} ${json.request_id}`);
    console.warn(method, path, code, json.error?.how_to_fix, json.request_id);
    return json;
  }
}

async function reply(to, windowOpen, body, inReplyTo) {
  if (windowOpen) {
    const sent = await api("POST", "/messages", { to, type: "text", text: { body } }, `text-${inReplyTo}`);
    if (sent.error?.code !== "outside_24h_window") return sent;
  }
  return api("POST", "/messages", { to, type: "template", template: FALLBACK }, `tpl-${inReplyTo}`);
}

async function handle(m) {
  if (!["text", "interactive", "button"].includes(m.type)) return; // photos, voice notes ...: for the team
  const contact = encodeURIComponent(m.from || m.from_user_id);
  const text = m.interactive?.id || m.button?.payload || m.text || "";
  const conv = await api("GET", `/conversations/${contact}`);
  if (["human", "paused", "whatsapp_ai"].includes(conv.owner)) return; // someone else has this chat
  await api("POST", "/messages/read", { message_id: m.message_id, typing: true });
  const open = conv.window_open !== false;
  if (HUMAN.test(text)) {
    await api("PUT", `/conversations/${contact}/owner`, {
      owner: "human", reason: "customer asked for a person", summary: text.slice(0, 300), until_minutes: 240 });
    return reply(m.from || m.from_user_id, open, "Thanks! A person from our team will answer you here soon.", m.message_id);
  }
  const hit = ANSWERS.find(([pattern]) => pattern.test(text));
  return reply(m.from || m.from_user_id, open, hit ? hit[1] : MENU, m.message_id);
}

const app = express();
app.post("/webhook", express.raw({ type: "application/json" }), async (req, res) => {
  if (!verify(req.body, req.get("X-App2email-Signature"), WEBHOOK_SECRET)) return res.sendStatus(401);
  const event = JSON.parse(req.body);
  if (event.test) { console.log("test event ok:", event.type); return res.sendStatus(200); }
  if (event.type !== "message.received" || done.has(event.id)) return res.sendStatus(200);
  try {
    await handle(event.data);
    done.add(event.id); // only after it worked: a failed event comes again
    res.sendStatus(200);
  } catch (err) {
    console.error("not handled, app2email will send it again:", event.id, err.message);
    res.sendStatus(503);
  }
});
app.listen(PORT, () => console.log(`bot on http://localhost:${PORT}/webhook`));
Python (Flask)
bot.py
# Python 3.9 or newer.  pip install flask requests   then   flask --app bot run --port 3000
import hashlib, hmac, json, os, re, time
import requests
from flask import Flask, request

NUMBER, API_KEY, SECRET = os.environ["NUMBER"], os.environ["API_KEY"], os.environ["WEBHOOK_SECRET"]
API = f"https://api.app2email.com/v1/{NUMBER}"
FALLBACK = {"name": "hello_world", "language": {"code": "en_US"}}  # an approved template without placeholders
RETRY_LATER = {"rate_limited", "whatsapp_rate_limit", "too_many_messages_to_recipient"}
done = set()  # handled event ids: use a database table or Redis in production

ANSWERS = [
    (re.compile(r"\b(hours?|open|opening|closed)\b", re.I), "We are open Monday to Friday, 9 am to 5 pm, and Saturday 10 am to 2 pm."),
    (re.compile(r"\b(prices?|cost|how much)\b", re.I), "A standard service is $49, an express service $79. Full list: https://example.com/prices"),
]
HUMAN = re.compile(r"\b(human|person|someone|staff)\b", re.I)
MENU = "Hi! I can tell you our opening hours or our prices. Type 'person' to talk to the team."

def verify(raw: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
    t = re.search(r"(?:^|,)\s*t=(\d+)", header or "")
    v1 = re.findall(r"(?:^|,)\s*v1=([0-9a-f]+)", header or "")  # two during a secret change
    if not t or not v1 or abs(time.time() - int(t.group(1))) > tolerance:
        return False
    expected = hmac.new(secret.encode(), t.group(1).encode() + b"." + raw, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(v, expected) for v in v1)

def api(method, path, body=None, idempotency_key=None):
    headers = {"Authorization": f"Bearer {API_KEY}"}
    if idempotency_key:
        headers["Idempotency-Key"] = idempotency_key
    for attempt in (1, 2, 3):
        res = requests.request(method, API + path, json=body, headers=headers, timeout=4)
        data = res.json()
        if res.ok:
            return data
        code = data.get("error", {}).get("code")
        wait = int(res.headers.get("Retry-After", "1"))
        if code == "rate_limited" and attempt < 3 and wait <= 3:
            time.sleep(wait)
            continue
        if res.status_code >= 500 or code in RETRY_LATER:
            raise RuntimeError(f"{code} {data.get('request_id')}")
        print("not done:", method, path, code, data.get("error", {}).get("how_to_fix"), data.get("request_id"))
        return data

def reply(to, window_open, body, in_reply_to):
    if window_open:
        sent = api("POST", "/messages", {"to": to, "type": "text", "text": {"body": body}}, f"text-{in_reply_to}")
        if sent.get("error", {}).get("code") != "outside_24h_window":
            return sent
    return api("POST", "/messages", {"to": to, "type": "template", "template": FALLBACK}, f"tpl-{in_reply_to}")

def handle(m):
    if m.get("type") not in ("text", "interactive", "button"):
        return  # photos, voice notes ...: for the team
    contact = m.get("from") or m.get("from_user_id")
    text = (m.get("interactive") or {}).get("id") or (m.get("button") or {}).get("payload") or m.get("text") or ""
    conv = api("GET", f"/conversations/{contact}")
    if conv.get("owner") in ("human", "paused", "whatsapp_ai"):
        return  # someone else has this chat
    api("POST", "/messages/read", {"message_id": m["message_id"], "typing": True})
    window_open = conv.get("window_open") is not False
    if HUMAN.search(text):
        api("PUT", f"/conversations/{contact}/owner", {"owner": "human", "reason": "customer asked for a person",
                                                       "summary": text[:300], "until_minutes": 240})
        return reply(contact, window_open, "Thanks! A person from our team will answer you here soon.", m["message_id"])
    answer = next((a for pattern, a in ANSWERS if pattern.search(text)), MENU)
    return reply(contact, window_open, answer, m["message_id"])

app = Flask(__name__)

@app.post("/webhook")
def webhook():
    raw = request.get_data()
    if not verify(raw, request.headers.get("X-App2email-Signature"), SECRET):
        return "bad signature", 401
    event = json.loads(raw)
    if event.get("test"):
        print("test event ok:", event["type"])
        return "", 200
    if event["type"] != "message.received" or event["id"] in done:
        return "", 200
    try:
        handle(event["data"])
    except Exception as err:
        print("not handled, app2email will send it again:", event["id"], err)
        return "", 503
    done.add(event["id"])  # only after it worked: a failed event comes again
    return "", 200

علاش كيتبنى بهاد الشكل:

  • التوقيع كيتشيك عليه فوق الـ body الخام قبل ما يتقرا أي parser (express.raw، request.get_data()).
  • الحدث كيتعلّم "معالج" غير بعد ما الجواب يتصيفط. إلا فشل طلب بـ 5xx ولا rate limit، البوت كيجاوب 503 وapp2email كيعاود صيفط الحدث من بعد (بعد 10 ثواني، 1 دقيقة، 5 دقايق ...). Idempotency-Key كيضمن أن إعادة المحاولة ما تصيفطش نفس الجواب مرتين، حتى ملي المحاولة الأولى وصلات حتى للصيفط.
  • 429 rate_limited القصير كيتسنّى داخل الطلب (3 ثواني كحد أقصى، باش حد 10 ثواني يبقى). أي شي أطول كيرجع لإعادات app2email.
  • الأخطاء اللي ما كتتبدلش بإعادة المحاولة (template بسمية غالطة، صلاحية ناقصة) كتتسجل مع how_to_fix وrequest_id، والحدث كيجاوب 200 باش ما يرجعش.
  • FALLBACK هو hello_world لأن الـ instant sandbox كيعندو. على رقمكم انتو، حط الاسم واللغة ديال واحد من الـ templates الموافق عليها ديالكم (GET /templates كيعطيهم، وكل واحد فيه example_request كامل).

شنو كيوقع فـ WhatsApp

  1. الزبون كيكتب "ما هي أوقات الخدمة ديالكم؟".
  2. رسالتو كتاخد علامات زرقا، وكيبان "يكتب...".
  3. الجواب كيوصل. فـ Inbox وفـ سجل النشاط كتشوف الرسالتين.
  4. الـ webhook ديالكم كيوصلو message.status ديال الجواب: sent، من بعد delivered، من بعد read.
{
  "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs02",
  "type": "message.status",
  "created": "2026-11-06T01:00:03.000Z",
  "number": "4976659348270",
  "data": {
    "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
    "to": "61412345678",
    "status": "delivered",
    "timestamp": "2026-11-06T01:00:03.000Z",
    "sent_by": "api",
    "whatsapp_status": "delivered"
  }
}

الجواب اللي فشل كيجي على شكل message.status بـ status: "failed" وerror (code هو كود Meta، وerror_code ديال app2email)، وكذلك على شكل message.failed.

ملي الزبون يكتب "ممكن نهدر مع شي واحد؟"، كيوصلو "شخص من الفريق ديالنا غادي يجاوبك هنا قريب"، والـ webhook ديالكم كيوصلو:

{
  "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs03",
  "type": "conversation.owner_changed",
  "created": "2026-11-06T01:02:00.000Z",
  "number": "4976659348270",
  "data": {
    "contact": "61412345678",
    "owner": "human",
    "previous_owner": "",
    "reason": "customer asked for a person",
    "summary": "can I talk to a person?",
    "until": "2026-11-06T05:02:00.000Z",
    "set_by": "api",
    "timestamp": "2026-11-06T01:02:00.000Z"
  }
}

شخص من الفريق كيجاوب من Inbox، من الإيميل، ولا عبر API. البوت كيشوف المالك human فالرسالة الجاية وكيسكت.

الرجوع للبوت: بعد until_minutes المالك كيرجع خاوي وحدو. شي واحد يقدر يرجع المحادثة قبل بـ PUT /conversations/{contact}/owner و{"owner": ""}، وهادشي كيصيفط conversation.owner_changed من جديد. ما ترجعش المحادثة من الكود ديالك والشخص ماسكها.

نافذة 24 ساعة

WhatsApp كيخليك تصيفط رسائل حرة (نص، صور، أزرار) لمدة 24 ساعة من آخر رسالة ديال الزبون. app2email كيوقف 15 دقيقة قبل؛ window_closes_at هو الوقت الدقيق. من بعد، غير template موافق عليه يقدر يبدا المحادثة من جديد.

البوت اللي كيجاوب فـ ثواني غالبا كيبقى داخل النافذة. الأمر كيهم ملي الحدث يتوصل متأخر: المحاولات كتستمر حوالي 32 ساعة، فالجواب على رسالة من البارح ممكن يحتاج template. البوت كيتشيك على window_open قبل ما يكتب، وكيبقى كيرجع لـ template ملي الصيفط يجاوب 422 outside_24h_window.

قائمة Do Not Call ما كتطبقش على الأجوبة الحرة، حيت الزبون هو اللي كتب ليكم. الاستثناء: ملي تكون آخر رسالة ديالو هي الاعتراض نفسو، الجواب كيجاوب 403 recipient_opted_out حتى يكتب من جديد.

قائمة التحقق قبل الإنتاج

Done

تشيك على كل حدث. الـ header X-App2email-Signature بحال t=<unix seconds>,v1=<hex>: الـ HMAC-SHA256 ديال النص t، نقطة، والـ body الخام، بسر الـ webhook (whsec_... مع البادئة) كمفتاح. تشيك على كل v1= (كاينين جوج لمدة ملي كيبقى السر القديم محفوظ بعد POST /webhooks/{id}/rotate-secret مع keep_old_for_hours)، قارن بطريقة constant time، وارفض t قديم من 5 دقايق. X-Hub-Signature-256 (sha256= و HMAC-SHA256 ديال الـ body الخام، بحال ما كيوقع Meta) كاين كذلك إلا كان الكود ديالك كيتشيك على webhooks ديال Meta؛ ما فيهش وقت وكيعتمد غير على السر الحالي.

Done

جاوب بسرعة. رجّع 2xx فـ 10 ثواني. الـ redirects ما كيتتبعوش. للخدمة الثقيلة (قاعدة بيانات، نموذج AI)، خزّن الحدث، جاوب 200، وعالجو من queue كتعاود المحاولة بوحدها.

Done

عاود ما تعالجش نفس الحدث. خزّن id ديال الحدث (X-App2email-Delivery) ديال كل حدث عالجتي على الأقل يومين: المحاولات كتستمر حوالي 32 ساعة. خزّنو فقاعدة بيانات ولا Redis، ماشي فالذاكرة، ملي عندك أكثر من process. الأحداث ممكن توصل بترتيب غالط: استعمل data.timestamp، ماشي الترتيب اللي وصلو فيه.

Done

صيفط كل جواب مرة وحدة. عطي كل POST /messages Idempotency-Key مبني على message_id ديال الزبون. نفس المفتاح ونفس الـ body فـ 24 ساعة: الجواب الأول كيرجع بـ Idempotent-Replayed: true. نفس المفتاح بـ body مختلف: 422 idempotency_key_reused. 409 idempotency_request_in_progress: استنى وعاود بنفس المفتاح.

Done

احترم الحدود. كل جواب فيه X-RateLimit-Limit وX-RateLimit-Remaining وX-RateLimit-Reset (الثواني حتى يرجع كامل) وX-RateLimit-Policy؛ GET /me كيبين limits ديال المفتاح ديالك. ملي تعديت الحد: 429 rate_limited مع Retry-After وerror.retry_after_seconds. حدود WhatsApp ديالو (429 whatsapp_rate_limit، too_many_messages_to_recipient) كتحتاج دقايق، ماشي ثواني. 429 monthly_limit_reached وdaily_cap_reached ما يسواش نعاودو دابا (retry_after_seconds كيقول حتى متى): قول لشي واحد من الفريق.

Done

خلّي الـ webhook شغال. من بعد 20 حدث متتالي ما توصلوش فأول 4 محاولات (فمدة 24 ساعة على الأقل)، app2email كيطفي الـ webhook. GET /webhooks/{id}/deliveries?status=failed كيبين شنو فشل وعلاش؛ PATCH /webhooks/{id} بـ {"active": true} كيشغلو من جديد، وPOST /webhooks/{id}/deliveries/{event_id}/redeliver كيصيفط حدث وحدة من جديد.

Done

خلّي الناس وحدهم ملي شي واحد من الفريق ماسك المحادثة. تشيك على owner قبل كل جواب (human، paused وwhatsapp_ai معناهم: ما تجاوبش)، وحوّل ملي الزبون يطلب.

Done

جواب واحد لكل رقم. الرد التلقائي (أول جواب كياخدو جهة جديدة)، أتمتات المحادثة وأجوبة الـ AI كيشوفو كل الرسائل. تشيك على لوحة التحكم باش جهة جديدة ما تاخدش جوابين أول.

Done

تعامل مع نص الزبون كمعطيات. الزبون هو اللي كيكتبو. ما تشغلوش كأمر أبدا، وإلا صيفطتيه لنموذج AI، خلّيه بعيد على التعليمات ديالك.

Done

أدنى صلاحية. مفتاح البوت خاصو messages:send وmessages:read غير. خليه فالسيرفر، وما تحطوهش فصفحة ويب ولا فـ log. المفتاح يقدر يتحدد على عناوين IP ديال السيرفر، يكون عندو سقف يومي، ولا يتسالى.

إلا ما خدمش

اللي كتشوفعلاشالحل
البوت ديالك كيجاوب 401 على كل حدثالتوقيع ما كيتطابقشاستعمل سر whsec_... ديال هاد الـ webhook مع البادئة؛ تشيك على الـ body الخام قبل أي JSON parser؛ تشيك على ساعة السيرفر (t خاصو يكون فـ 5 دقايق)
401 missing_api_key، invalid_api_key، api_key_revokedلا كاين مفتاح، مفتاح غالط، ولا قديمصيفط Authorization: Bearer YOUR_API_KEY بمفتاح مكتوب فصفحة مفاتيح API، ورقم هاد المفتاح فالرابط
403 insufficient_scopeالمفتاح ناقصو صلاحية (details.required_scope)صنع مفتاح فيه messages:send وmessages:read (وكذلك webhooks:manage باش تسجل الـ webhook)
403 plan_not_allowed، service_not_liveما كاينش باقة مدفوعة، ولا الخدمة موقوفةاختار باقة؛ الخدمة الموقوفة كتشغل بـ "Go Live" فصفحة Settings
422 invalid_webhook_urlالرابط ماشي عنوان https عاماستعمل عنوان https ديال الـ tunnel ولا السيرفر ديالك، مع المسار (/webhook)
409 webhook_url_in_usewebhook آخر ديال الرقم عندو نفس الرابطبدّل ذاك الـ webhook بـ PATCH، ولا امسح واحد
400 too_many_webhooksالرقم عندو 5 webhooksامسح واحد ما بقاش كتستعملو
422 outside_24h_windowالزبون كتب ليكم قبل أكثر من 24 ساعةصيفط template موافق عليه
404 template_not_found، 422 template_not_approvedسمية الـ template ولا اللغة ديالو غالطين، ولا ما تواففقش عليه بعداختار واحد من GET /templates بحالة APPROVED
422 template_parameters_invalidالـ template الاحتياطي فيه placeholdersاستعمل واحد بلا placeholders، ولا عمّرهم كيما كيبين example_request
403 recipient_opted_outآخر رسالة ديال الزبون كانت الاعتراضما تجاوبوش حتى يكتب من جديد
429 rate_limitedطلبات بزاف لهاد المفتاحاستنى Retry-After ثانية، من بعد عاود
429 whatsapp_rate_limit، too_many_messages_to_recipientحد WhatsAppوقف دقايق
429 too_many_testsأكثر من 30 حدث تجريبي فالساعةاستنى، ولا جرب برسالة من تليفونك
403 not_in_instant_sandboxرقم التجربة ما عندوش هاد الطلب (الـ webhooks، مثلا)استعمل GET /events هناك، ولا sandbox key على رقمك انتا
ما كيوصلش ولا حدثالـ webhook مطفي، ولا عنوان الـ tunnel تبدلGET /webhooks كيبين active وآخر توصيل؛ PATCH بالـ url الجديد، ولا {"active": true}

كل جواب فيه request_id. GET /requests/{id} كيبين شنو تسجل ليه، وsupport@app2email.com يقدر يلقاه كذلك. كل الأكواد: Errors.

طرق أخرى باش تجاوب الزبناء

  • أجوبة الـ AI: مساعد app2email كيجاوب من موقعكم، ومن PDFs والملاحظات ديالكم، وكيحوّل المحادثة لشخص ملي ما يقدرش يعاون (باقة Professional وTrial). كيصيفط ai.answered وai.handover. كيجاوب الزبون غير ملي المحادثة ما عندهاش مالك، ولا جاوب تطبيق ولا أتمتة، فخلّي جواب واحد لكل رقم. شوف إعدادات أجوبة الـ AI.
  • وكيل AI عبر MCP: سيرفر MCP https://api.app2email.com/mcp عندو نفس الطلبات كأدوات (send_text، mark_read، get_conversation، set_conversation_owner، list_events، wait_for_message ...). شوف خلّي وكيل AI يدير WhatsApp ديالك بـ MCP وMCP.
  • التحويل بتفصيل أكثر: حوّل المحادثة من البوت لشخص وراجعها.

الأسئلة الشائعة

واش نقدر نبني ونجرب هادشي بلا رقم WhatsApp؟

إيه. POST https://api.app2email.com/v1/account/sandbox (بلا key، بلا body) كيعطيك instant sandbox key (a2es_...، صالح 7 أيام) لرقم التجربة 12025550100. الزبناء المزيفين عندو: أفا (12025550101، كتجاوب على كل رسالة)، وإيڤ (12025550105، كتطلب شخص). عندو GET /conversations/{contact}، وPUT /conversations/{contact}/owner، وPOST /messages وGET /events، فمنطق البوت ديالك كيخدم هناك، وعندو template hello_world اللي كيتستعمل كاحتياطي. ما عندوش webhooks: اقرا الأحداث بـ GET /events. POST /messages/read ما كاينش هناك كذلك؛ كيجاوب 403 not_in_instant_sandbox، والبوت كيسجلو وكيكمّل. والو ما كيوصل لـ WhatsApp.

واش نقدر نستقبل الرسائل بلا عنوان عام؟

إيه: GET /events?wait=25 (صلاحية messages:read) كيبقى الجواب معلّق حتى يوصل حدث، حتى 25 ثانية. كل حدث هو نفس JSON اللي كيوصل للـ webhook، بنفس id. خلّي cursor ديال الجواب، وصيفطو كـ after فالطلب الجاي؛ تجاوز الـ ids اللي عالجتي، حيت بعد جواب ضايع الحدث ممكن يجي مرة أخرى. types=message.received كيعطيك غير الرسائل الواصلة. أول طلب كيشغّل feed ديال الرقم؛ الأحداث كتبقى 72 ساعة.

let after = "now";
for (;;) {
  const page = await api("GET", `/events?wait=25&types=message.received&after=${after}`);
  for (const event of page.events ?? []) if (!done.has(event.id)) { await handle(event.data); done.add(event.id); }
  after = page.cursor ?? after;
}
واش الزبون يقدر يضغط على أزرار بدل ما يكتب؟

إيه، فنافذة 24 ساعة. صيفط "type": "interactive" بحتى 3 أزرار رد، ولا قائمة حتى 10 سطور. عطي الأزرار الـ ids اللي البوت كيفهمها، والضغطة كتوصل كـ message.received بـ type interactive وinteractive.id:

{
  "to": "61412345678",
  "type": "interactive",
  "interactive": {
    "type": "button",
    "body": { "text": "What would you like to know?" },
    "action": {
      "buttons": [
        { "type": "reply", "reply": { "id": "hours", "title": "Opening hours" } },
        { "type": "reply", "reply": { "id": "prices", "title": "Prices" } },
        { "type": "reply", "reply": { "id": "person", "title": "Talk to a person" } }
      ]
    }
  }
}
شنو كيكلّف كل جواب؟

كل جواب كيصيفطو البوت كيتحسب كرسالة وحدة من باقة app2email ديالكم. العلامة كمقروءة ومؤشر الكتابة مجانيين. Meta كتحسب عليكم مباشرة: الأجوبة فالنافذة هي رسائل خدمة (أول 1,000 فالشهر لكل رقم مجانية)، والـ templates كتتحسب بكل رسالة. GET /usage كيبين شنو تستعمل وشنو باقي فهاد الشهر، مع فئات Meta فـ meta_pricing.

شنو كيوقع مع الصور والتسجيلات الصوتية والملفات؟

كيوصلو كـ message.received بـ type بحال image، audio، document وغيرهم، ومعاهم media_url: app2email كيحتفظ بنسخة، وكتتقدم بـ GET /media/{message_id}. البوت فوق كيخليهم للفريق؛ تقدر كذلك تحوّل المحادثة فالحين ملي يوصل واحد منهم.

كيفاش شي واحد من الفريق كيجاوب، وكيفاش نرجع المحادثة للبوت؟

من Inbox فلوحة التحكم، من الإيميل (ملي يكون تحويل الإيميل مفعّل)، ولا عبر API. المحادثة كترجع للبوت ملي until_minutes يسالي، ولا قبل بـ PUT /conversations/{contact}/owner و{"owner": ""}.

واش نقدر نجيب صيغة Meta ديال الـ webhook بدلها؟

إيه: الـ webhook بـ "format": "meta" كيوصلو اللي جاي من WhatsApp بـ body ديال Meta نفسو (entry[].changes[])، موقّع بنفس الطريقة. الأحداث ديال app2email، بحال conversation.owner_changed، كتبقى بالغلاف ديال app2email. هاد الدليل كيستعمل الصيغة الافتراضية app2email.

علاش بعض الزبناء ما عندهمش رقم تليفون فالحدث؟

WhatsApp كيتحول لأسماء المستخدمين مع معرّفات مرتبطة بالنشاط (بحال AU.1234567890123456). الحدث كيكون عندو from_user_id وبلا from. حط المعرّف فـ to: كيخدم فين ما يخدم الرقم، بما فيها /conversations/{contact}. البوتات فوق كتدير هادشي.

أدلة أخرى

كل أدلة How-To