# העברת צ'אט מהבוט שלכם לאדם, והחזרה לבוט

> זיהוי לקוח ב-WhatsApp שרוצה נציג, העברת הצ'אט לצוות עם סיכום, שיוך לאדם, השתקת תשובות הבוט וה-AI בזמן שאדם משיב, והחזרה לבוט כשהפנייה טופלה.

בוט עונה מהר על שאלות פשוטות. יש צ'אטים שדורשים אדם: החזר כספי, תלונה, הזמנה שהשתבשה, או לקוח שפשוט כותב "אפשר לדבר עם מישהו?".

במדריך הזה הבוט שלכם מעביר צ'אט כזה לצוות שלכם, ומחזיר אותו לבוט כשהצוות סיים.

**מה הלקוח רואה:** הוא מבקש נציג, והבוט עונה "תודה! אדם מהצוות שלנו יענה לכם כאן בקרוב." מכאן ואילך רק הצוות שלכם עונה, באותו צ'אט של WhatsApp. אף תשובת בוט ואף תשובת AI לא נכנסת באמצע.

**מה אתם רואים:** הצ'אט ב-Inbox של app2email, משויך לאדם אחד בצוות שלכם, עם הערה פנימית שמסבירה למה הבוט העביר את הצ'אט ומה הלקוח ביקש. ה-webhook שלכם מקבל אירוע על כל שינוי: מי הבעלים של הצ'אט, למי הוא משויך, ומתי הוא סומן כטופל.

## איך זה עובד

לכל שיחה (אחת לכל איש קשר) יש **בעלים**. הבעלים קובע מי עונה לאיש הקשר הזה כרגע. מגדירים אותו בקריאה אחת, `PUT /conversations/{contact}/owner`:

| `owner` | משמעות | מה קורה |
| --- | --- | --- |
| `""` (ריק) | ניתוב רגיל | התשובה האוטומטית של המספר, אוטומציות צ'אט, תשובות AI וסוכן ה-A2A / OpenClaw פועלים כפי שהגדרתם. |
| `agent` | אוטומציה היא הבעלים | סימון לכל מערכת אחרת: "אוטומציה מטפלת באיש הקשר הזה". תשובות AI שותקות, כי הן עונות רק לשיחה בלי בעלים. |
| `human` | אדם הוא הבעלים | התשובה האוטומטית של app2email וסוכן ה-A2A / OpenClaw לא נוגעים באיש הקשר, וגם תשובות AI לא. הצוות משיב. |
| `paused` | התשובות האוטומטיות מושהות | כמו `human` לגבי התשובה האוטומטית, סוכן ה-A2A / OpenClaw ותשובות AI. |

העברה בדואר אלקטרוני ממשיכה כרגיל, בלי קשר לבעלים, כך שמי שמקבל את הודעות WhatsApp במייל ימשיך לקבל אותן.

ההעברה במדריך הזה עובדת כך:

1. לקוח כותב למספר שלכם. ה-webhook מקבל `message.received`.
2. הבוט קורא את השיחה (`GET /conversations/{contact}`). אם אדם כבר הוא הבעלים, הבוט לא עושה דבר.
3. אם הלקוח מבקש נציג, הבוט מגדיר את הבעלים כ-`human` עם `reason` ו-`summary`, מודיע ללקוח שאדם יענה, משייך את הצ'אט למישהו בצוות ומוסיף הערה פנימית.
4. אדם משיב מה-Inbox, מהמייל או דרך ה-API.
5. כשהצוות מסמן את הצ'אט כטופל, הבוט מחזיר את הבעלים ל-`""` ועונה שוב להודעה הבאה. `until_minutes` יכול גם להחזיר את הצ'אט לבד אחרי זמן שהגדרתם.

<Note>
ה-webhook שלכם עדיין מקבל כל אירוע של המספר, גם `message.received` לצ'אט שאדם הוא הבעלים שלו. התשובה האוטומטית של app2email, סוכן ה-A2A / OpenClaw ותשובות AI בודקים את הבעלים בעצמם. **הבוט שלכם חייב לבדוק אותו גם הוא**, לפני כל תשובה.
</Note>

## מה צריך

- **מספר WhatsApp מחובר ל-app2email**, בתוכנית בתשלום ופעיל. בלי תוכנית כל קריאה עונה 403 `plan_not_allowed`; שירות מושהה עונה 403 `service_not_live`. ראו [תחילת העבודה](https://www.app2email.com/docs/onboarding).
- **בוט שמקבל הודעות ב-webhook.** אם אין לכם עדיין, [בניית צ'אטבוט WhatsApp עם ה-API](/guides/how-to-whatsapp-chatbot) מכין אחד (מנהרה, `POST /webhooks`, סוד חתימה). המדריך הזה מוסיף לו את ההעברה.
- **מפתח API** מ[דף מפתח ה-API](https://www.app2email.com/dashboard/apikey) עם ההרשאות האלה:

| Scope | לשם מה היא משמשת כאן |
| --- | --- |
| `messages:send` | קביעת הבעלים (`PUT /conversations/{contact}/owner`), שיוך הצ'אט (`PUT /conversations/{contact}/assignee`), סימון כטופל (`PUT /conversations/{contact}/status`), הוספת הערה (`POST /conversations/{contact}/notes`), שליחת הודעה ללקוח (`POST /messages`) |
| `messages:read` | קריאת שיחה אחת (`GET /conversations/{contact}`), רשימת השיחות, הצוות (`GET /team/members`) וההערות |
| `webhooks:manage` | רישום ה-webhook פעם אחת (`POST /webhooks`), או הוספתו בדף מפתח ה-API |

- **לשיוך, להערות ולסימון פתוח / טופל:** ה-Inbox של הצוות. הוא כלול בתוכנית Trial ובתוכנית Professional. בתוכניות אחרות הקריאות האלה עונות 403 `team_inbox_not_in_plan`; הבעלים עצמו עובד בכל תוכנית בתשלום.

<Tip>
**ניסיון.** ה-**instant sandbox** לא דורש חשבון: `POST https://api.app2email.com/v1/account/sandbox` (בלי מפתח, בלי גוף) או הכלי `create_sandbox` של שרת ה-MCP לניהול `https://api.app2email.com/mcp/manage` מחזירים מפתח למספר הדמו `12025550100`. הלקוח המדומה שלו `12025550105` מבקש נציג, כך שאפשר לבדוק את הזיהוי. ב-instant sandbox יש `PUT /conversations/{contact}/owner`, `GET /conversations`, `POST /messages` ו-`GET /events` (את האירועים קוראים שם, אין שם webhooks). קריאות הצוות (חברים, שיוך, סטטוס, הערות) עונות שם 403 `not_in_instant_sandbox`. פרטים: [Sandbox](/api/sandbox).
</Tip>

<Warning>
**מפתח sandbox על המספר שלכם** לא שולח כלום ל-WhatsApp, אבל הבעלים, המשויך, הסטטוס וההערות הם **שינויים אמיתיים** בשיחות שלכם, גם עם מפתח sandbox. בדקו את הקריאות האלה על איש קשר שלכם, למשל על הטלפון שלכם.
</Warning>

## העברה, שלב אחר שלב

בכל בקשה, `YOUR_NUMBER` הוא מספר ה-WhatsApp שממנו שולחים: קידומת מדינה קודם, ספרות בלבד. איש הקשר הוא מספר הלקוח (עם קידומת מדינה) או מזהה המשתמש שלו בתוך העסק (כמו `AU.1234567890123456`), ה-`from` או ה-`from_user_id` של האירוע.

<Steps>
  <Step title="קריאה של מי הבעלים של הצ'אט">
    `GET /conversations/{contact}` (הרשאה `messages:read`) מראה לכם את הבעלים, אם אפשר לשלוח עכשיו תשובה חופשית, ואם יש תשובות מייל שממתינות. קראו לו לפני כל תשובה של הבוט שלכם.

    <CodeGroup>

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

    ```javascript Node.js
    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678", {
      headers: { Authorization: `Bearer ${process.env.API_KEY}` },
    });
    const conv = await res.json();
    console.log(conv.owner, conv.window_open);
    ```

    ```python Python
    import os, requests

    res = requests.get("https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678",
                       headers={"Authorization": f"Bearer {os.environ['API_KEY']}"}, timeout=10)
    conv = res.json()
    print(conv.get("owner"), conv.get("window_open"))
    ```

    </CodeGroup>

    **מה מקבלים בחזרה** (צ'אט שאדם הוא הבעלים שלו):

    ```json
    {
      "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-22T01:05:44Z",
      "last_inbound_at": "2026-11-21T01:20:44Z",
      "last_outbound_at": "2026-11-21T01:12:09Z",
      "messages": 12,
      "owner": "human",
      "owner_set_at": "2026-11-21T01:21:00Z",
      "owner_set_by": "api:Support bot",
      "owner_reason": "customer asked for a person",
      "owner_summary": "Wants to move the delivery to Monday.",
      "held_replies": false,
      "conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_..."
    }
    ```

    | שדה | מה הוא אומר לבוט שלכם |
    | --- | --- |
    | `owner` | `""` ניתוב רגיל, `agent`, `human` או `paused`. עונים רק כש-`""` (או `agent`, אם `agent` הוא הסימון של הבוט שלכם) |
    | `owner_set_by` | מי קבע אותו, למשל `api:Support bot` (שם המפתח) |
    | `owner_reason`, `owner_summary` | מה נמסר עם ההעברה |
    | `owner_until` | מתי הבעלים הזמני מסתיים. זמן שעבר פירושו שוב `""` |
    | `owner_set` | מה נקבע, גם אחרי ש-`owner_until` עבר |
    | `window_state`, `window_open` | `open`: אפשר לשלוח תשובה חופשית עכשיו. `closed`: רק תבנית מאושרת |
    | `window_closes_at` | השעה המדויקת שבה החלון נסגר |
    | `held_replies` | `true`: תשובות מייל ממתינות עד שאיש הקשר ילחץ על "הצג תשובה", כי חלון 24 השעות נסגר |

    שדה בלי ערך לא מופיע בתשובה, כך שצ'אט עם ניתוב רגיל עשוי לא לכלול שום שדה `owner_*`. איש קשר שמעולם לא כתב מקבל 404 `conversation_not_found`.
  </Step>
  <Step title="שימו לב שהלקוח רוצה נציג">
    הבוט שלכם מחליט על כך לפי האירוע `message.received`. שלושה סימנים עובדים היטב:

    - **מילים** בהודעת טקסט: "אדם", "בן אדם", "מישהו", "צוות", "מנהל".
    - **כפתור.** הציעו "דברו עם נציג" ככפתור תגובה עם מזהה משלכם. הלחיצה מגיעה עם `type` `interactive` ו-`interactive.id`.
    - **הבוט שלכם תקוע**, למשל הלקוח קיבל את התפריט פעמיים ברציפות, או שלח תמונה או הודעה קולית שהבוט לא מסוגל לקרוא.

    לחיצה על כפתור תגובה מגיעה כך:

    ```json
    {
      "id": "evt_Pa3k9m2Lw8Rt5Yp1Zs012",
      "type": "message.received",
      "created": "2026-11-21T01:20:44.000Z",
      "number": "4976659348270",
      "data": {
        "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
        "from": "61412345678",
        "from_user_id": "AU.1234567890123456",
        "name": "John",
        "type": "interactive",
        "text": "Talk to a person",
        "interactive": {
          "type": "button_reply",
          "id": "person",
          "title": "Talk to a person"
        },
        "conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_SAMPLEk3XbQ9rTzP2mW",
        "timestamp": "2026-11-21T01:20:44.000Z"
      }
    }
    ```

    הכפתור עצמו הוא הודעה אינטראקטיבית רגילה, שנשלחת בתוך חלון 24 השעות:

    ```json
    {
      "to": "61412345678",
      "type": "interactive",
      "interactive": {
        "type": "button",
        "body": { "text": "What would you like to do?" },
        "action": {
          "buttons": [
            { "type": "reply", "reply": { "id": "track", "title": "Track my order" } },
            { "type": "reply", "reply": { "id": "person", "title": "Talk to a person" } }
          ]
        }
      }
    }
    ```

    משתמשים בתשובות AI (העוזר של app2email) במקום בבוט שלכם? הוא מזהה זאת בעצמו ומעביר: ראו [תשובות AI מעבירות לבד](#ai-answers-hand-over-by-themselves).
  </Step>
  <Step title="העברת הצ'אט לאדם">
    `PUT /conversations/{contact}/owner` (הרשאה `messages:send`) עם `"owner": "human"`:

    | שדה | חובה | מה לשים |
    | --- | --- | --- |
    | `owner` | כן | `human`. גם `agent`, `paused`, או `""` לחזרה לרגיל |
    | `reason` | לא | הסיבה, במשפט קצר (עד 200 תווים), למשל `customer asked for a person` |
    | `summary` | לא | על מה הצ'אט עד עכשיו, עבור מי שמשתלט עליו (עד 2000 תווים). גם מי שקורא את הודעות WhatsApp במייל מקבל אותו |
    | `until_minutes` | לא | 1 עד 43200. אחרי מספר הדקות הזה הבעלים חוזר ל-`""` מעצמו |

    <CodeGroup>

    ```bash cURL
    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": 480}'
    ```

    ```javascript Node.js
    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/owner", {
      method: "PUT",
      headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json" },
      body: JSON.stringify({
        owner: "human",
        reason: "customer asked for a person",
        summary: "Wants to move the delivery to Monday.",
        until_minutes: 480,
      }),
    });
    console.log(res.status, await res.json());
    ```

    ```python Python
    res = requests.put(
        "https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/owner",
        headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
        json={"owner": "human", "reason": "customer asked for a person",
              "summary": "Wants to move the delivery to Monday.", "until_minutes": 480},
        timeout=10,
    )
    print(res.status_code, res.json())
    ```

    </CodeGroup>

    **מה מקבלים בחזרה** (200): השיחה המעודכנת, עם אותם שדות כמו בשלב 1.

    ```json
    {
      "success": true,
      "request_id": "own3r",
      "conversation": {
        "contact": "61412345678",
        "identity_type": "phone",
        "phone": "61412345678",
        "name": "John",
        "window_state": "open",
        "window_open": true,
        "window_closes_at": "2026-11-22T01:05:44Z",
        "messages": 12,
        "owner": "human",
        "owner_set": "human",
        "owner_set_at": "2026-11-21T01:21:00Z",
        "owner_set_by": "api:Support bot",
        "owner_reason": "customer asked for a person",
        "owner_summary": "Wants to move the delivery to Monday.",
        "owner_until": "2026-11-21T09:21:00Z",
        "held_replies": false,
        "conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_..."
      }
    }
    ```

    מעכשיו התשובה האוטומטית של app2email, סוכן ה-A2A / OpenClaw ותשובות AI לא נוגעים באיש הקשר הזה, וכל ה-webhook של המספר מקבל את `conversation.owner_changed`. קביעה חוזרת של אותו בעלים לא מזיקה, לכן ניסיון חוזר של הקריאה בטוח.

    <Tip>
    בחרו את `until_minutes` לפי שעות הפעילות שלכם. עם 480 (8 שעות) צ'אט שאף אחד לא לקח חוזר לבוט מעצמו. השמיטו אותו כדי להשאיר את הצ'אט אצל הצוות שלכם, עד שמישהו יחזיר אותו.
    </Tip>
  </Step>
  <Step title="עדכון הלקוח">
    כל עוד חלון 24 השעות פתוח (`window_open` הוא true, וכך זה, כי הלקוח רק כתב), שלחו טקסט חופשי קצר עם `POST /messages`. תנו לו `Idempotency-Key` שנבנה מ-`message_id` של הלקוח, כך שניסיון חוזר לעולם לא ישלח אותו פעמיים.

    <CodeGroup>

    ```bash 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: handoff-wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=" \
      -d '{"to": "61412345678", "type": "text", "text": {"body": "Thanks! A person from our team will answer you here soon."}}'
    ```

    ```javascript Node.js
    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": `handoff-${messageId}`,
      },
      body: JSON.stringify({
        to: "61412345678",
        type: "text",
        text: { body: "Thanks! A person from our team will answer you here soon." },
      }),
    });
    ```

    ```python Python
    requests.post(
        "https://api.app2email.com/v1/YOUR_NUMBER/messages",
        headers={"Authorization": f"Bearer {os.environ['API_KEY']}", "Idempotency-Key": f"handoff-{message_id}"},
        json={"to": "61412345678", "type": "text",
              "text": {"body": "Thanks! A person from our team will answer you here soon."}},
        timeout=10,
    )
    ```

    </CodeGroup>

    **מה מקבלים בחזרה** (200):

    ```json
    {
      "success": true,
      "request_id": "kxrkf",
      "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBI5QTNDQTVCM0Q0Q0Q2RTY3RTgA",
      "status": "accepted",
      "type": "text",
      "from": "4976659348270",
      "to": "61412345678",
      "window_closes_at": "2026-11-22T01:05:44Z",
      "conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_..."
    }
    ```

    החלון נסגר? אז השליחה עונה 422 `outside_24h_window`, ורק תבנית מאושרת יכולה להגיע ללקוח.
  </Step>
  <Step title="שיוך הצ'אט למישהו בצוות">
    `GET /team/members` (הרשאה `messages:read`) מציג מי יכול לקחת שיחה: הבעלים של המספר והחברים שמורשים להשיב (אי אפשר לשייך צופים).

    ```bash
    curl https://api.app2email.com/v1/YOUR_NUMBER/team/members \
      -H "Authorization: Bearer YOUR_API_KEY"
    ```

    **מה מקבלים בחזרה:**

    ```json
    {
      "success": true,
      "request_id": "t3amx",
      "members": [
        { "user_id": "a8d2k4m6p1q3r5s", "name": "Ava", "email": "ava@example.com", "role": "owner", "away": false, "in_rotation": false },
        { "user_id": "k3x9q2m7p4z8w1v", "name": "Ben", "email": "ben@example.com", "role": "member", "away": false, "in_rotation": true }
      ],
      "count": 2,
      "auto_assign": "round_robin"
    }
    ```

    `away: true` פירושו שכלל השיוך האוטומטי מדלג על האדם הזה לעת עתה; `in_rotation: true` פירושו שהחלוקה לסירוגין (round robin) נותנת לו שיחות.

    ואז `PUT /conversations/{contact}/assignee` (הרשאה `messages:send`). `assignee` מקבל:

    - `user_id` או `email` מהרשימה,
    - `"auto"`: כלל השיוך האוטומטי של המספר בוחר (לסירוגין בין החברים שבחרתם, או חזרה לאדם שענה אחרון). עם הכלל `off` שום דבר לא משתנה,
    - `""`: אף אחד.

    <CodeGroup>

    ```bash cURL
    curl -X PUT https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/assignee \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{"assignee": "auto"}'
    ```

    ```javascript Node.js
    const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/assignee", {
      method: "PUT",
      headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json" },
      body: JSON.stringify({ assignee: "auto" }), // or "k3x9q2m7p4z8w1v", or "ben@example.com"
    });
    console.log(await res.json());
    ```

    ```python Python
    res = requests.put(
        "https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/assignee",
        headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
        json={"assignee": "auto"},  # or "k3x9q2m7p4z8w1v", or "ben@example.com"
        timeout=10,
    )
    print(res.json())
    ```

    </CodeGroup>

    **מה מקבלים בחזרה:**

    ```json
    {
      "success": true,
      "request_id": "as1gn",
      "conversation": {
        "contact": "61412345678",
        "conversation_id": 1234,
        "name": "John",
        "assignee": "k3x9q2m7p4z8w1v",
        "assignee_name": "Ben",
        "assigned_at": "2026-11-21T01:21:01.000Z",
        "assigned_by": "auto",
        "status": "open",
        "status_at": null,
        "status_by": null
      }
    }
    ```

    בן מקבל התראת push (אם הפעיל התראות), ה-Inbox מציג שורת פעילות כמו `API (Support bot) assigned this to Ben`, וכל ה-webhook מקבל את `conversation.assigned`.

    הבעלים והמשויך הם שני שדות נפרדים: הבעלים קובע אם התשובות האוטומטיות נשארות בצד, והמשויך קובע איזה אדם בצוות אחראי על הצ'אט.
  </Step>
  <Step title="השארת הערה לצוות">
    `POST /conversations/{contact}/notes` (הרשאה `messages:send`) מוסיף הערה פנימית: הצוות רואה אותה בשרשור ה-Inbox כהערה צהובה, בסדר הזמנים יחד עם ההודעות. הלקוח לא רואה אותה לעולם. 1 עד 4000 תווים.

    <CodeGroup>

    ```bash cURL
    curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/notes \
      -H "Authorization: Bearer YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{"text": "Bot handover: customer asked for a person. Order 1234, wants to move the delivery to Monday."}'
    ```

    ```javascript Node.js
    await fetch("https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/notes", {
      method: "POST",
      headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json" },
      body: JSON.stringify({ text: "Bot handover: customer asked for a person. Order 1234, wants to move the delivery to Monday." }),
    });
    ```

    ```python Python
    requests.post(
        "https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/notes",
        headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
        json={"text": "Bot handover: customer asked for a person. Order 1234, wants to move the delivery to Monday."},
        timeout=10,
    )
    ```

    </CodeGroup>

    **מה מקבלים בחזרה:**

    ```json
    {
      "success": true,
      "request_id": "n0te1",
      "contact": "61412345678",
      "conversation_id": 1234,
      "note": {
        "id": 88,
        "kind": "note",
        "text": "Bot handover: customer asked for a person. Order 1234, wants to move the delivery to Monday.",
        "actor": "api:Support bot",
        "actor_name": "API (Support bot)",
        "assignee": null,
        "assignee_name": null,
        "at": "2026-11-21T01:21:02.000Z"
      }
    }
    ```

    הערה אינה idempotent: ניסיון חוזר מוסיף הערה שנייה. הוסיפו אותה פעם אחת לכל העברה (הקוד למטה עושה זאת אחרי שהבעלים נקבע, ולא מנסה שוב).
  </Step>
</Steps>

## בזמן שאדם מטפל בצ'אט

- **הצוות שלכם משיב** מה-Inbox ב[לוח הבקרה](https://www.app2email.com/dashboard), מהמייל (כשהעברת מייל פעילה: היא ממשיכה לפעול בלי קשר לבעלים), או דרך ה-API עם `POST /messages`.
- **הבוט שלכם שותק.** הוא קורא את `owner` לפני כל תשובה, ולא עושה דבר כש-`human` או `paused`.
- **התשובה האוטומטית של app2email וסוכן ה-A2A / OpenClaw** לא נוגעים באיש הקשר. לסוכן ה-A2A / OpenClaw זה תלוי בהגדרה `a2a.respect_owner` של המספר (פעילה כברירת מחדל; `GET /settings/number` מראה אותה).
- **תשובות AI** עונות ללקוח רק כשלשיחה אין בעלים, אף אפליקציה או אוטומציה לא ענתה, וה-AI המובנה של WhatsApp לא מחזיק בצ'אט.
- **חלון 24 השעות עדיין נספר.** תשובה חופשית של אדם עובדת רק כשהחלון פתוח. תשובת מייל שנשלחה אחרי שהחלון נסגר נשמרת: `held_replies` הוא `true` ב-`GET /conversations/{contact}` עד שאיש הקשר לוחץ "הצג תשובה". אחרי החלון, רק תבנית מאושרת מתחילה שוב את הצ'אט.

`GET /conversations?assignee=k3x9q2m7p4z8w1v&status=open` (הרשאה `messages:read`) מציג את הצ'אטים הפתוחים של אדם אחד; `assignee=none` מציג את הלא-משויכים. לכל רשומה יש `owner` (לא מופיע בניתוב רגיל), `assignee`, `assignee_name`, `status` ו-`window_open`.

## החזרת הצ'אט לבוט

יש שלוש דרכים, ואפשר להשתמש בכולן:

1. **באופן מפורש**, עם `PUT /conversations/{contact}/owner` ו-`"owner": ""`. אדם יכול גם לשנות את הבעלים בלוח הבקרה (האירוע אז אומר `set_by` `dashboard`).
2. **לפי זמן**, עם `until_minutes` מההעברה. אחריו `owner` מציג שוב `""`, ו-`owner_set` עדיין מראה מה נקבע.
3. **כשהצוות מסמן את הצ'אט כטופל.** `PUT /conversations/{contact}/status` עם `"status": "solved"` (או "Solved" ב-Inbox) שולח `conversation.status_changed`; הבוט שלכם מגיב לו בהגדרת הבעלים ל-`""`.

<CodeGroup>

```bash cURL
# Mark it solved (it leaves the Inbox's Open view)
curl -X PUT https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/status \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"status": "solved"}'

# Back to normal routing: the bot answers again
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": "", "reason": "solved by the team"}'
```

```javascript Node.js
const headers = { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json" };
const base = "https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678";

await fetch(`${base}/status`, { method: "PUT", headers, body: JSON.stringify({ status: "solved" }) });
await fetch(`${base}/owner`, { method: "PUT", headers, body: JSON.stringify({ owner: "", reason: "solved by the team" }) });
```

```python Python
base = "https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678"
headers = {"Authorization": f"Bearer {os.environ['API_KEY']}"}

requests.put(f"{base}/status", headers=headers, json={"status": "solved"}, timeout=10)
requests.put(f"{base}/owner", headers=headers, json={"owner": "", "reason": "solved by the team"}, timeout=10)
```

</CodeGroup>

**מה מקבלים בחזרה** מקריאת הסטטוס:

```json
{
  "success": true,
  "request_id": "s0lvd",
  "conversation": {
    "contact": "61412345678",
    "conversation_id": 1234,
    "name": "John",
    "assignee": "k3x9q2m7p4z8w1v",
    "assignee_name": "Ben",
    "assigned_at": "2026-11-21T01:21:01.000Z",
    "assigned_by": "auto",
    "status": "solved",
    "status_at": "2026-11-21T02:15:00.000Z",
    "status_by": "api:Support bot"
  }
}
```

הודעה חדשה מאיש הקשר פותחת שוב שיחה טופלה מעצמה (`conversation.status_changed` עם `by` `contact`). שליחת תשובה לא משנה את הסטטוס.

<Warning>
אל תיקחו צ'אט מאדם מיוזמתכם. החזירו אותו רק על סימן שהצוות הסכים לו (טופל, זמן שנקבע, או החלטה של אדם). `owner_set_by` אומר לכם מי קבע את הבעלים.
</Warning>

## קוד ההעברה המלא

הקוד מוסיף את ההעברה לבוט של [בניית צ'אטבוט WhatsApp עם ה-API](/guides/how-to-whatsapp-chatbot). הוא מאמת את החתימה, מדלג על אירועים שכבר טופלו, שותק כל עוד אדם הוא הבעלים של הצ'אט, מעביר לפי בקשה, ומחזיר את הצ'אט כשהצוות מסמן אותו כטופל. לפני הכול הגדירו את `NUMBER` (מספר ה-WhatsApp שלכם, ספרות), `API_KEY` ו-`WEBHOOK_SECRET` (הערך `whsec_...` של ה-webhook שלכם).

<Tabs>
  <Tab title="Node.js (Express)">

```javascript handoff.mjs
// Node.js 18 or newer.  npm install express   then   node handoff.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 ASKS_FOR_PERSON = /\b(human|person|someone|staff|manager)\b/i;
const done = new Set(); // handled event ids: use a database table or Redis in production

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 || res.status === 429) throw new Error(`${code} ${json.request_id}`);
    console.warn(method, path, code, json.error?.how_to_fix, json.request_id);
    return json;
  }
}

const later = (promise, what) => promise.catch((err) => console.error(`${what} failed:`, err.message));

function wantsPerson(m) {
  return m.interactive?.id === "person" || m.button?.payload === "person" ||
         (m.type === "text" && ASKS_FOR_PERSON.test(m.text ?? ""));
}

async function handOver(m, conv) {
  const to = m.from || m.from_user_id;
  const contact = encodeURIComponent(to);
  const reason = "customer asked for a person";
  const summary = `${conv.name ?? "The customer"} wrote: "${(m.text ?? "").slice(0, 300)}"`;
  // 1. The owner first: from now on no automatic answer reaches this contact. A failure here is retried.
  await api("PUT", `/conversations/${contact}/owner`, { owner: "human", reason, summary, until_minutes: 480 });
  // 2. The rest is best effort: logged, never retried, so nothing is done twice.
  if (conv.window_open) {
    await later(api("POST", "/messages", { to, type: "text",
      text: { body: "Thanks! A person from our team will answer you here soon." } }, `handoff-${m.message_id}`), "message");
  }
  await later(api("PUT", `/conversations/${contact}/assignee`, { assignee: "auto" }), "assign");
  await later(api("POST", `/conversations/${contact}/notes`, { text: `Bot handover: ${reason}. ${summary}` }), "note");
}

async function onMessage(m) {
  const contact = encodeURIComponent(m.from || m.from_user_id);
  const conv = await api("GET", `/conversations/${contact}`);
  if (conv.owner && conv.owner !== "agent") return; // a person has it, or it is paused: stay quiet
  if (wantsPerson(m)) return handOver(m, conv);
  // ... your bot's normal answer goes here (see the chatbot guide)
}

async function onSolved(d) {
  const contact = encodeURIComponent(d.contact);
  const conv = await api("GET", `/conversations/${contact}`);
  if (conv.owner === "human") {
    await api("PUT", `/conversations/${contact}/owner`, { owner: "", reason: "solved by the team" });
  }
}

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 || done.has(event.id)) return res.sendStatus(200);
  try {
    const d = event.data;
    if (event.type === "message.received") await onMessage(d);
    if (event.type === "conversation.status_changed" && d.status === "solved") await onSolved(d);
    if (event.type === "conversation.owner_changed") {
      console.log(`${d.contact}: ${d.previous_owner || "normal"} -> ${d.owner || "normal"} (${d.set_by ?? "?"})`);
    }
    if (event.type === "ai.handover") console.log(`AI handed ${d.contact} to the team: ${d.reason}`);
    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(`handoff bot on http://localhost:${PORT}/webhook`));
```

  </Tab>
  <Tab title="Python (Flask)">

```python handoff.py
# Python 3.9 or newer.  pip install flask requests   then   flask --app handoff run --port 3000
import hashlib, hmac, json, os, re, time
from urllib.parse import quote
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}"
ASKS_FOR_PERSON = re.compile(r"\b(human|person|someone|staff|manager)\b", re.I)
done = set()  # handled event ids: use a database table or Redis in production

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 res.status_code == 429:
            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 later(what, *args, **kwargs):
    try:
        api(*args, **kwargs)
    except Exception as err:  # best effort: logged, never retried
        print(what, "failed:", err)

def wants_person(m):
    return ((m.get("interactive") or {}).get("id") == "person"
            or (m.get("button") or {}).get("payload") == "person"
            or (m.get("type") == "text" and ASKS_FOR_PERSON.search(m.get("text") or "")))

def hand_over(m, conv):
    to = m.get("from") or m.get("from_user_id")
    contact = quote(to, safe="")
    reason = "customer asked for a person"
    summary = f'{conv.get("name") or "The customer"} wrote: "{(m.get("text") or "")[:300]}"'
    # 1. The owner first: from now on no automatic answer reaches this contact. A failure here is retried.
    api("PUT", f"/conversations/{contact}/owner",
        {"owner": "human", "reason": reason, "summary": summary, "until_minutes": 480})
    # 2. The rest is best effort, so nothing is done twice.
    if conv.get("window_open"):
        later("message", "POST", "/messages", {"to": to, "type": "text",
              "text": {"body": "Thanks! A person from our team will answer you here soon."}},
              idempotency_key=f"handoff-{m['message_id']}")
    later("assign", "PUT", f"/conversations/{contact}/assignee", {"assignee": "auto"})
    later("note", "POST", f"/conversations/{contact}/notes", {"text": f"Bot handover: {reason}. {summary}"})

def on_message(m):
    contact = quote(m.get("from") or m.get("from_user_id"), safe="")
    conv = api("GET", f"/conversations/{contact}")
    if conv.get("owner") and conv.get("owner") != "agent":
        return  # a person has it, or it is paused: stay quiet
    if wants_person(m):
        return hand_over(m, conv)
    # ... your bot's normal answer goes here (see the chatbot guide)

def on_solved(d):
    contact = quote(d["contact"], safe="")
    conv = api("GET", f"/conversations/{contact}")
    if conv.get("owner") == "human":
        api("PUT", f"/conversations/{contact}/owner", {"owner": "", "reason": "solved by the team"})

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") or event["id"] in done:
        return "", 200
    d = event.get("data", {})
    try:
        if event["type"] == "message.received":
            on_message(d)
        elif event["type"] == "conversation.status_changed" and d.get("status") == "solved":
            on_solved(d)
        elif event["type"] == "conversation.owner_changed":
            print(f'{d["contact"]}: {d.get("previous_owner") or "normal"} -> {d.get("owner") or "normal"} ({d.get("set_by")})')
        elif event["type"] == "ai.handover":
            print(f'AI handed {d["contact"]} to the team: {d.get("reason")}')
    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
```

  </Tab>
</Tabs>

**למה זה בנוי כך:**

- הבעלים נקבע **קודם**. אם הקריאה הזו נכשלת עם 5xx או הגבלת קצב, הבוט עונה 503 ו-app2email שולח את האירוע שוב מאוחר יותר; עוד לא נעשה דבר אחר, כך שהניסיון החוזר מתחיל נקי.
- אחרי שהבעלים נקבע, ההודעה, השיוך וההערה הם **במאמץ מיטבי (best effort)**: כישלון נרשם ביומן ולא מנוסה שוב. ניסיון חוזר של כל האירוע ימצא `owner` `human` ויעצור בבדיקה, כך שהשלבים האלה בכל מקרה לא ירוצו פעמיים.
- `"assignee": "auto"` משתמש בכלל השיוך האוטומטי של המספר. בלי ה-Inbox של הצוות בתוכנית הוא עונה 403 `team_inbox_not_in_plan`, שנרשם ביומן; ההעברה עצמה עדיין עובדת.
- החזרת הצ'אט על "טופל" נוגעת רק בבעלים `human`. צ'אט ב-`paused` נשאר מושהה.

## התוצאה

ב-WhatsApp הלקוח רואה את ההודעה שלו, אחריה "תודה! אדם מהצוות שלנו יענה לכם כאן בקרוב.", ואחר כך התשובה של אדם מהצוות שלכם. ב-Inbox הצ'אט משויך לבן, וההערה הצהובה מופיעה בראש ההעברה.

ה-webhook שלכם מקבל את האירועים האלה, כל אחד במעטפה הרגילה (`id`, `type`, `created`, `number`, `data`), והסוג גם בכותרת `X-App2email-Event`:

| אירוע | מתי |
| --- | --- |
| `conversation.owner_changed` | הבעלים השתנה: human, agent, paused או חזר לרגיל; או שסוכן ה-AI של WhatsApp לקח את השיחה או העביר אותה הלאה (בעלים `whatsapp_ai`) |
| `conversation.assigned` | הצ'אט הועבר לאדם בצוות, או לאף אחד: ב-Inbox, לפי כלל השיוך האוטומטי, אוטומציה, תשובת AI או ה-API |
| `conversation.note_added` | נוספה הערה פנימית (לעולם לא נשלחת לאיש הקשר) |
| `conversation.status_changed` | הצ'אט סומן כטופל, או נפתח שוב (על ידי אדם, ה-API, או הודעה חדשה מאיש הקשר) |
| `ai.handover` | תשובות AI העבירו צ'אט לאדם: הודעת ההעברה נשלחה והבעלים הפך ל-`human` |
| `message.status` | הודעת "אדם יענה לכם" נשלחה, נמסרה ונקראה |

**אדם השתלט** (`conversation.owner_changed`):

```json
{
  "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
  "type": "conversation.owner_changed",
  "created": "2026-11-21T01:21:00.000Z",
  "number": "4976659348270",
  "data": {
    "contact": "61412345678",
    "owner": "human",
    "reason": "customer asked for a person",
    "summary": "John wrote: \"Can I talk to a person about my delivery?\"",
    "until": "2026-11-21T09:21:00.000Z",
    "set_by": "api",
    "timestamp": "2026-11-21T01:21:00.000Z"
  }
}
```

**חזרה לבוט** (אותו אירוע, הבעלים ריק):

```json
{
  "id": "evt_Xq3k9m2Lw8Rt5Yp1Zs07",
  "type": "conversation.owner_changed",
  "created": "2026-11-21T02:15:01.000Z",
  "number": "4976659348270",
  "data": {
    "contact": "61412345678",
    "owner": "",
    "previous_owner": "human",
    "reason": "solved by the team",
    "set_by": "api",
    "timestamp": "2026-11-21T02:15:01.000Z"
  }
}
```

**שויך** (`conversation.assigned`):

```json
{
  "id": "evt_Team3k9m2Lw8Rt5Yp1Z01",
  "type": "conversation.assigned",
  "created": "2026-11-21T01:21:01.000Z",
  "number": "4976659348270",
  "data": {
    "contact": "61412345678",
    "conversation_id": 1234,
    "assignee": "k3x9q2m7p4z8w1v",
    "assignee_name": "Ben",
    "previous_assignee": null,
    "by": "auto",
    "timestamp": "2026-11-21T01:21:01.000Z"
  }
}
```

**טופל** (`conversation.status_changed`):

```json
{
  "id": "evt_Team3k9m2Lw8Rt5Yp1Z02",
  "type": "conversation.status_changed",
  "created": "2026-11-21T02:15:00.000Z",
  "number": "4976659348270",
  "data": {
    "contact": "61412345678",
    "conversation_id": 1234,
    "status": "solved",
    "previous_status": "open",
    "by": "dashboard:ben@example.com",
    "timestamp": "2026-11-21T02:15:00.000Z"
  }
}
```

`by` ו-`set_by` אומרים מי ביצע את השינוי: `dashboard:<email>`, `api:<key name>` או `api`, `automation: <rule>`, `ai`, `auto` (כלל השיוך האוטומטי), או `contact` (הודעה חדשה פתחה את הצ'אט מחדש).

<Note>
המסמך לא אומר שנשלח אירוע כש-`until_minutes` נגמר. אל תסתמכו על אירוע לכך: קראו את `owner` עם `GET /conversations/{contact}` לפני כל תשובה, כפי שעושה הקוד למעלה.
</Note>

<a id="ai-answers-hand-over-by-themselves"></a>

## תשובות AI מעבירות לבד

אם המספר משתמש ב**תשובות AI** (העוזר של app2email, בתוכנית Professional ובתקופת ה-trial) במקום בבוט שלכם, ההעברה מובנית. העוזר מעביר את הצ'אט לאדם כשהמידע שלו לא מכסה את השאלה, כשהלקוח מבקש אדם, או כשהבקשה דורשת את הצוות. הוא שולח את הודעת ההעברה, מגדיר את הבעלים ל-`human`, ושולח `ai.handover`:

```json
{
  "id": "evt_Ai3k9m2Lw8Rt5Yp1Zs002",
  "type": "ai.handover",
  "created": "2026-11-21T01:00:00.000Z",
  "number": "4976659348270",
  "data": {
    "contact": "61412345678",
    "conversation_id": 1234,
    "message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBI5QTNDQTVCM0Q0Q0Q2RTY3RTgA",
    "text": "Thanks, a person from our team will reply soon.",
    "reason": "the customer asks for a refund",
    "model": "claude-haiku-5-5",
    "owner": "human",
    "timestamp": "2026-11-21T01:00:00.000Z"
  }
}
```

`message_id` הוא null כשלא הצליחה לשלוח את הודעת ההעברה. הטקסט שהלקוח מקבל הוא `handover_text` ב-`GET /ai-answers/settings` (ריק פירושו ברירת המחדל; `handover_text_sent` מראה מה נשלח). משנים אותו עם `PUT /ai-answers/settings` (הרשאה `settings:manage`, לא עם מפתח sandbox).

גם כללי אוטומציה בצ'אט יכולים להעביר: "העבר לאדם" הוא אחד הצעדים שלהם, לצד שיוך, סימון כטופל והוספת הערה.

## לתת לסוכן AI לבצע את ההעברה

לשרת ה-MCP `https://api.app2email.com/mcp/conversations` יש את הקריאות של המדריך הזה ככלים, עם אותו מפתח `Authorization: Bearer`: `get_conversation`, `get_conversation_messages`, `set_conversation_owner`, `list_team_members`, `assign_conversation`, `set_conversation_status`, `add_conversation_note`, `list_conversation_notes`. לשרת המלא `https://api.app2email.com/mcp` יש אותן גם כן. ראו [לתת לסוכן AI להפעיל את ה-WhatsApp שלכם עם MCP](/guides/how-to-ai-agent-mcp) ו-[MCP](/api/mcp).

הכלל לסוכנים זהה לכלל לבוט שלכם: הגדירו `human` עם `reason` קצר ו-`summary` כשאיש הקשר מבקש אדם או כשהסוכן לא יכול לעזור, ואל תחזירו צ'אט (`agent` או `""`) שאדם לקח, אלא אם המשתמש ביקש זאת.

## רשימת בדיקה לפני עלייה לאוויר

<Check>
**בדקו כל אירוע.** הכותרת `X-App2email-Signature` היא `t=<unix seconds>,v1=<hex>`: ה-HMAC-SHA256 של `t`, נקודה והגוף הגולמי, עם סוד החתימה של ה-webhook (`whsec_...`, כולל הקידומת) כמפתח. בדקו כל `v1=` (יש שניים כל עוד סוד ישן נשמר אחרי שינוי סוד), השוו בזמן קבוע, ודחו `t` ישן (הקוד למעלה מאפשר 5 דקות). גם `X-Hub-Signature-256` (`sha256=` וה-HMAC-SHA256 של הגוף הגולמי, כפי ש-Meta חותמת) קיים, רק עם הסוד הנוכחי. עוד: [Webhooks](/api/webhooks).
</Check>

<Check>
**ענו מהר וסננו כפולים.** החזירו 2xx תוך 10 שניות; הפניות לא נעקבות. אירוע שנכשל נשלח שוב אחרי 10 שניות, דקה, 5 דקות, 30 דקות, 1, 2, 4, 8 ו-16 שעות. ה-`id` של האירוע (גם ב-`X-App2email-Delivery`) זהה בכל ניסיון חוזר: שמרו את המזהים שטיפלתם בהם לפחות יומיים, במסד נתונים או ב-Redis ולא בזיכרון.
</Check>

<Check>
**בדקו את הבעלים לפני כל תשובה.** ענו רק כש-`owner` הוא `""` (או סימון ה-`agent` שלכם). אירועים יכולים להגיע באיחור או לא לפי הסדר, לכן קראו את השיחה במקום לסמוך על ה-`conversation.owner_changed` האחרון שראיתם, וסדרו את האירועים לפי `data.timestamp`.
</Check>

<Check>
**העבירו פעם אחת.** קבעו קודם את הבעלים; חזרה על הקריאה בטוחה. שלחו את ההודעה "אדם יענה לכם" עם `Idempotency-Key` שנבנה מ-`message_id` של הלקוח (אותו מפתח בתוך 24 שעות לא נשלח שוב; התשובה חוזרת עם `Idempotent-Replayed: true`). הערות ו-`"assignee": "auto"` אינם idempotent: הריצו אותם פעם אחת.
</Check>

<Check>
**כבדו את מגבלת הקצב.** לכל תשובה יש `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` (שניות עד שהמכסה מתמלאת שוב) ו-`X-RateLimit-Policy`. מעל המגבלה: 429 `rate_limited` עם כותרת `Retry-After` ו-`error.retry_after_seconds`; המתינו את הזמן הזה, ואז נסו שוב. עוד: [מגבלות](/api/limits).
</Check>

<Check>
**שימו לב לחלון 24 השעות.** ההודעה "אדם יענה לכם" של הבוט והתשובות של הצוות הן הודעות חופשיות: הן עובדות רק בתוך 24 שעות מההודעה האחרונה של הלקוח (app2email עוצר 15 דקות מוקדם; `window_closes_at` הוא השעה המדויקת). אחרי זה, רק תבנית מאושרת. אם אדם לוקח צ'אט באיחור, בדקו קודם את `window_open`.
</Check>

<Check>
**כבדו הסרה מרשימת התפוצה.** רשימת ה-Do Not Call לא חלה על תשובות חופשיות, כי הלקוח כתב אליכם. החריג: כשההודעה האחרונה שלו הייתה הסרה עצמה, תשובה עונה 403 `recipient_opted_out` עד שהוא יכתוב שוב. `contact.opted_out` מודיע לכם מתי זה קורה.
</Check>

<Check>
**מענה אחד לכל מספר.** התשובה האוטומטית, אוטומציות הצ'אט, תשובות AI והבוט שלכם רואים את אותן הודעות. החליטו מי עונה. בעלים מסוג `agent` שומר על תשובות AI מרחק כל עוד הבוט שלכם מטפל באיש קשר.
</Check>

<Check>
**כתבו סיכומים לאנשים.** ה-`summary` מגיע לאנשים שקוראים את הודעות WhatsApp במייל, וההערה נקראת ב-Inbox. שמרו אותם קצרים ושימושיים: מספר ההזמנה, מה הלקוח רוצה, מה הבוט כבר ניסה. לעולם אל תכניסו בהם סודות או פרטי תשלום.
</Check>

<Check>
**הרשאות מינימליות.** ההעברה צריכה `messages:send` ו-`messages:read`. שמרו את המפתח בשרת שלכם, לעולם לא בדף אינטרנט או ביומן. אפשר להגביל מפתח לכתובות ה-IP של השרת שלכם, לתת לו תקרה יומית, או להגדיר לו תפוגה.
</Check>

## אם זה לא עובד

| מה אתם רואים | למה | תיקון |
| --- | --- | --- |
| 400 `invalid_owner` | `owner` אינו `""`, `agent`, `human` או `paused` | שלחו למשל `{"owner": "human", "reason": "customer asked for a person"}`; שאר השדות אופציונליים |
| 400 `invalid_json` | הגוף אינו JSON תקין | בדקו מרכאות, פסיקים וסוגריים |
| 400 `invalid_phone` | איש הקשר בכתובת אינו מספר או מזהה משתמש בתוך העסק | השתמשו במספר המלא, עם קידומת מדינה קודם, או ב-`from_user_id` |
| 404 `conversation_not_found` | עוד אין שיחה עם איש קשר זה | שיחה עם מזהה משתמש בתוך העסק נפתחת כשאיש הקשר כותב למספר |
| 400 `invalid_assignee` | `assignee` אינו מזהה משתמש, אימייל, `auto` או `""` | קחו `user_id` או `email` מ-`GET /team/members` |
| 422 `not_a_member` | האדם הזה אינו בעלים המספר או חבר שמורשה להשיב (אי אפשר לשייך צופים) | `GET /team/members` מציג מי ניתן לשייך |
| 400 `invalid_conversation_status` | `status` אינו `open` או `solved` | שלחו `{"status": "solved"}` או `{"status": "open"}` |
| 400 `invalid_conversation_note` | ההערה ריקה או ארוכה מ-4000 תווים | שלחו `{"text": "..."}` עם 1 עד 4000 תווים |
| 403 `team_inbox_not_in_plan` | שיוך, הערות ופתוח / טופל אינם בתוכנית של המספר | הם כלולים בתוכנית Trial ו-Professional; הבעלים עובד בלעדיהם |
| 503 `team_database_pending` | ה-Inbox של הצוות ממתין לעדכון מסד נתונים בצד app2email | נסו שוב מאוחר יותר; כל השאר עובד כרגיל |
| 403 `insufficient_scope` | למפתח חסרה הרשאה (`details.required_scope`) | השתמשו במפתח עם `messages:send` ו-`messages:read` |
| 403 `not_in_instant_sandbox` | למספר הדמו אין את הקריאה הזו (קריאות הצוות, למשל) | השתמשו במפתח sandbox על המספר שלכם, או במפתח רגיל |
| 403 `plan_not_allowed`, `service_not_live` | אין תוכנית בתשלום, או שהשירות לא פעיל | בחרו תוכנית; שירות מושהה חוזר לפעילות עם "Go Live" בדף ההגדרות |
| 422 `outside_24h_window` | הלקוח כתב לאחרונה לפני יותר מ-24 שעות | שלחו במקום זאת תבנית מאושרת |
| 403 `recipient_opted_out` | ההודעה האחרונה של הלקוח הייתה ההסרה | אל תשיבו עד שהוא יכתוב שוב |
| 429 `rate_limited` | יותר מדי קריאות למפתח הזה | המתינו `Retry-After` שניות, ואז נסו שוב |
| הבוט עדיין עונה אחרי ההעברה | הבוט שלכם לא בודק את `owner`, או שמשיב אחר פועל על המספר | קראו את `GET /conversations/{contact}` לפני כל תשובה; בדקו את התשובה האוטומטית, האוטומציות ותשובות ה-AI בלוח הבקרה |
| סוכן ה-A2A / OpenClaw עדיין עונה | ההגדרה `a2a.respect_owner` של המספר כבויה | `GET /settings/number` מראה אותה; היא פעילה כברירת מחדל |

לכל תשובה יש `request_id`. `GET /requests/{request_id}` מראה מה נרשם עבורה (שגיאות ובקשות ששינו משהו, נשמרות 30 יום), וגם support@app2email.com יכול למצוא אותה. כל הקודים: [שגיאות](/api/errors).

## שאלות נפוצות

<AccordionGroup>
  <Accordion title="מה ההבדל בין human ל-paused?">
    לתשובות האוטומטיות של app2email אין הבדל: בשני המקרים התשובה האוטומטית, סוכן ה-A2A / OpenClaw ותשובות AI לא נוגעים באיש הקשר. השתמשו ב-`human` כשאדם מטפל בצ'אט, וב-`paused` כשאתם רוצים רק שהתשובות האוטומטיות ייעצרו לאיש הקשר הזה לזמן מה, למשל בזמן שאתם בודקים משהו. שניהם יכולים להסתיים מעצמם עם `until_minutes`.
  </Accordion>
  <Accordion title="מה המשמעות של agent, והאם הבוט שלכם צריך לקבוע אותו?">
    `agent` אומר שאוטומציה היא הבעלים של איש הקשר. זה סימון לכל השאר, והוא שומר על תשובות AI מרחק (הן עונות רק לשיחה בלי בעלים). קבעו אותו אם כמה מערכות צופות באותו מספר, ואתם רוצים שיראו שהבוט שלכם באמצע עניין עם איש הקשר הזה. החזירו `""` כשהבוט מסיים.
  </Accordion>
  <Accordion title="מה זה בעלים whatsapp_ai?">
    סוכן ה-AI המובנה של WhatsApp מחזיק בשיחה. `conversation.owner_changed` מודיע לכם מתי הוא לוקח את הצ'אט או מעביר אותו הלאה (`set_by` `whatsapp`, עם `handover` `control_taken` או `control_passed`). בזמן שהוא מחזיק בצ'אט, תשובה נשלחת רק אחרי שהוא מעביר את השיחה הלאה.
  </Accordion>
  <Accordion title="אפשר להעביר לפני שהלקוח כתב אי פעם?">
    כן, למספר טלפון: למספר שמעולם לא יצר קשר נוצרת רשומת שיחה, כך שאפשר לקבוע קודם את הבעלים. מזהה משתמש בתוך העסק דורש שאיש הקשר יכתוב קודם (אחרת 404 `conversation_not_found`).
  </Accordion>
  <Accordion title="אפשר לבדוק את הזיהוי בלי מספר WhatsApp?">
    כן. ה-instant sandbox (`POST https://api.app2email.com/v1/account/sandbox`, בלי מפתח, בלי גוף) נותן מפתח (`a2es_...`, תקף 7 ימים) למספר הדמו `12025550100`. הלקוח המדומה שלו `12025550105` מבקש אדם. קראו את האירועים עם `GET /events?wait=25` וקבעו את הבעלים עם `PUT /conversations/{contact}/owner`; קריאות הצוות לא קיימות שם. שום דבר לא מגיע ל-WhatsApp.
  </Accordion>
  <Accordion title="אפשר לקבל את האירועים בלי כתובת ציבורית?">
    כן: `GET /events?wait=25` (הרשאה `messages:read`) מחזיר את אותם אירועים שה-webhook מקבל, עם אותו `id`. שמרו את ה-`cursor` של התשובה והעבירו אותו כ-`after` בקריאה הבאה. [בניית צ'אטבוט WhatsApp עם ה-API](/guides/how-to-whatsapp-chatbot) מראה את הלולאה.
  </Accordion>
  <Accordion title="איך רואים מה קרה בצ'אט?">
    `GET /conversations/{contact}/notes?include_activity=true` (הרשאה `messages:read`) מציג את ההערות, מהישנה לחדשה, עם שורות הפעילות (`assigned`, `unassigned`, `solved`, `reopened`) כשמוסיפים `include_activity=true`. `GET /conversations/{phone}/messages` מציג את ההודעות בשני הכיוונים.
  </Accordion>
</AccordionGroup>

## מדריכי ה-how-to נוספים

<CardGroup cols={2}>
  <Card title="בניית צ'אטבוט WhatsApp עם ה-API" href="/guides/how-to-whatsapp-chatbot">
    קבלו הודעות ב-webhook חתום, וענו להן מהקוד שלכם.
  </Card>
  <Card title="שליחת הודעות על הזמנות ותורים עם תבניות" href="/guides/how-to-order-notifications">
    תבניות שירות מאושרות לאישורים ותזכורות, עם סטטוס מסירה.
  </Card>
  <Card title="שליחת שידור שיווקי שמכבד הסכמות (opt-in)" href="/guides/how-to-marketing-broadcast">
    תבנית אחת לרשימה או לקטע, עם רישומי הסכמה ורשימת Do Not Call.
  </Card>
  <Card title="לתת לסוכן AI להפעיל את ה-WhatsApp שלכם עם MCP" href="/guides/how-to-ai-agent-mcp">
    חברו את Claude או סוכן אחר למספר שלכם עם מפתחות מוגבלים ואישורים.
  </Card>
  <Card title="בקשת תשלום בתוך צ'אט WhatsApp" href="/guides/how-to-payment-links">
    שלחו קישור תשלום בצ'אט וקבלו עדכון כששולם.
  </Card>
</CardGroup>

[כל מדריכי ה-how-to](https://www.app2email.com/docs#how-to)
