> ## Documentation Index
> Fetch the complete documentation index at: https://www.ayrshare.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# 自動化 API 概觀

> 由互動事件觸發的 Instagram 自動化 — 當終端使用者留言、回覆限時動態、對 DM 表情回應或傳送 DM 時，觸發 DM、webhook 或電子郵件

export const PlansAvailable = ({plans = [], maxPackRequired}) => {
  let displayPlans = plans;
  if (plans && plans.length === 1) {
    const lowerCasePlan = plans[0].toLowerCase();
    if (lowerCasePlan === "business") {
      displayPlans = ["Launch", "Business", "Enterprise"];
    } else if (lowerCasePlan === "premium") {
      displayPlans = ["Premium", "Launch", "Business", "Enterprise"];
    }
  }
  return <Note>
Available on {displayPlans.length === 1 ? "the " : ""}
{displayPlans.join(", ").replace(/\b\w/g, l => l.toUpperCase())}{" "}
{displayPlans.length > 1 ? "plans" : "plan"}.

{maxPackRequired && <span onClick={() => window.open('https://www.ayrshare.com/docs/additional/maxpack', '_self')} className="flex items-center mt-2 cursor-pointer">
 <span className="px-1.5 py-0.5 rounded text-sm" style={{
    backgroundColor: '#C264B6',
    color: 'white',
    fontSize: '12px'
  }}>
   Max Pack required
 </span>
</span>}
</Note>;
};

<PlansAvailable plans={["business", "enterprise"]} maxPackRequired={false} />

<Note>
  **Beta。** Automations API 目前為 Beta 階段，我們正積極收集意見回饋。端點、payload 與限制在我們迭代的過程中可能會變動。請將意見與錯誤回報寄給 support，好讓我們能優先安排正確的改進項目。
</Note>

Automations 端點讓你可以定義規則，自動回應進入的 Instagram 互動事件。每個自動化配對一個或多個**觸發條件（trigger）**（觸發該規則的事件）與一個或多個**動作（action）**（觸發時發生的事）。單一規則可以監聽多個觸發條件並派送多個動作 — 讓同一次互動同時觸發一個進到你分析管線的 webhook，並發送一則 DM。

引擎完全在 Meta 的政策範圍內運作（不會因為追蹤而觸發 DM、不會主動對陌生人發送第一則訊息、不做大量對外發送），並沿用 Ayrshare 的每帳號速率限制、每接收者去重與具冪等性的 webhook 接收機制。

## 運作方式

<Steps>
  <Step title="建立自動化">
    透過 `POST /automations` 帶入你想要的觸發條件與動作。自動化會立即啟用。
  </Step>

  <Step title="終端使用者互動">
    有人在你的貼文留言、回覆你的限時動態、傳送 DM 或對 DM 表情回應。Meta 會將 webhook 送達 Ayrshare。
  </Step>

  <Step title="Ayrshare 比對並派送">
    引擎會查找所有符合該事件的規則，檢查每個動作的去重與你的每日 DM 上限，然後執行每個動作。DM 發送會套用 20–60 秒的抖動延遲，以符合 Instagram 的反垃圾訊息啟發式規則。
  </Step>

  <Step title="檢視實際觸發狀況">
    `GET /automations/:id/activity` 會回傳稽核紀錄 — 每一次派送嘗試、每個動作的結果，以及任何錯誤。
  </Step>
</Steps>

## 觸發條件（Triggers）

單一自動化最多可附加 **50 個觸發條件**。每個觸發條件都是以 `type` 欄位為判別欄位的可辨聯集；type 專屬的欄位位於同一層。v1 中所有觸發條件僅限於 Instagram。

| Type              | 觸發時機                | 設定                               |
| ----------------- | ------------------- | -------------------------------- |
| `comment_keyword` | 特定貼文出現符合關鍵字的留言      | `postId`（必填）；`keywords`（必填，≥1 個） |
| `story_reply`     | 使用者透過 DM 回覆限時動態     | `storyId`（選填）                    |
| `dm_reaction`     | 使用者以表情符號對你的 DM 表情回應 | `emoji`（選填 — 省略則對任何表情符號都觸發）      |
| `dm_keyword`      | 使用者傳送內文符合關鍵字的 DM    | `keywords`（必填，≥1 個）              |

關鍵字比對**不區分大小寫**，且以完整字詞比對。當事件包含任一設定的關鍵字時，即滿足關鍵字過濾的觸發條件。若在限時動態觸發條件中省略 `storyId`，會對已連結帳號的每則限時動態都觸發。

## 動作（Actions）

單一自動化最多可附加 **50 個動作**。它們會依序執行，每個結果都會記錄在該活動列上。

| Type           | 效果                                                                                          | 設定                                                   |
| -------------- | ------------------------------------------------------------------------------------------- | ---------------------------------------------------- |
| `send_dm`      | 使用[模板化訊息](#template-variables)，向觸發規則的使用者發送 Instagram DM。                                    | `message`（必填，支援模板）                                   |
| `fire_webhook` | 將自動化上下文以 POST 送到你的帳號層級 webhook URL（請透過 [`POST /hook/webhook`](/apis/webhooks/register) 設定）。 | *（無 — payload 格式固定；請見[下方](#fire_webhook-payload)）*   |
| `send_email`   | 透過平台的郵件管線將郵件排入佇列。                                                                           | `to`（必填，email）；`subject`（選填，支援模板）；`message`（必填，支援模板） |

### 每個動作的去重視窗

無論動作類型為何，每個動作都額外接受一個選填的最外層 `dedupWindowMinutes` 欄位，可為該動作覆寫**預設 7 天**的每接收者去重視窗。

* 設為 `0` 可為該動作**完全停用**去重（`fire_webhook` / `send_email` 通常會這樣，因為接收方預期收到每個事件）。
* 上限為 `525600`（一年）。

```json Action with a 24h dedup override theme={"system"}
{
  "type": "send_dm",
  "message": "Thanks {{recipient_username}}!",
  "dedupWindowMinutes": 1440
}
```

### `fire_webhook` payload

當 `fire_webhook` 執行時，會 POST 一個 JSON 主體到你的帳號層級 webhook URL：

```json theme={"system"}
{
  "automationId":      "auto_9xKp2Lm4nQ",
  "triggerId":         "trg_a1b2c3",
  "trigger":           "comment_keyword",
  "platform":          "instagram",
  "recipientId":       "17841401234567890",
  "recipientUsername": "jane_doe",
  "keyword":           "LINK",
  "timestamp":         "2026-05-12T09:14:22.000Z"
}
```

當觸發條件沒有帶入這些欄位時，`recipientUsername` 與 `keyword` 會是 `null`（例如 `dm_keyword` 在 Meta 的 payload 中不會帶 username；`story_reply` 沒有 keyword）。

## 模板變數

`send_dm.message`、`send_email.subject` 與 `send_email.message` 支援 `{{placeholder}}` 替換。**未知的預留變數會在建立/更新時被拒絕**（回傳 `473` 驗證錯誤），因此打字錯誤絕不會靜默地讓字面上的 `{{foo}}` 洩漏到對客戶顯示的訊息中。

| 預留變數                     | 對應內容                                   |
| ------------------------ | -------------------------------------- |
| `{{recipient_username}}` | 互動使用者的 Instagram handle（若 webhook 有攜帶） |
| `{{recipient_id}}`       | 互動使用者的 Instagram 參與者 ID（IGSID）         |
| `{{recipient_name}}`     | 保留欄位；在未來的資料增補來源填入之前，會解析為空字串            |
| `{{sender_username}}`    | 你已連結的 Instagram 使用者名稱                  |
| `{{sender_name}}`        | 你已連結的 Instagram 顯示名稱                   |
| `{{comment_text}}`       | 觸發規則的留言 / DM / 限時動態回覆的文字               |
| `{{comment_id}}`         | 觸發訊息的平台端 id                            |
| `{{comment_sent_at}}`    | 事件的 ISO 8601 時間戳（若有提供）                 |
| `{{matched_keyword}}`    | 比對到的關鍵字（`dm_reaction` 則為 emoji 字串）     |
| `{{platform}}`           | 平台識別碼（例如 `instagram`）                  |
| `{{trigger_type}}`       | 觸發條件類型（例如 `comment_keyword`）           |

<Note>
  **沒有 `sender_email` / `recipient_email`。** 這些是刻意不公開的 — 你的帳單 email 沒有正當理由出現在傳給陌生人的 DM 中，而且 Meta 也不會在任何 IG webhook 上提供接收者的 email。不提供這些預留變數可避免意外洩漏。
</Note>

模板範例：

```
Hey {{recipient_username}}, thanks for the comment "{{comment_text}}" — here is the link you wanted: https://example.com
```

## 速率限制與上限

| 方案         | 使用中的自動化數（每個 profile） | 每日 DM 上限（每個帳號） |
| ---------- | -------------------- | -------------- |
| Business   | 10                   | 1,000          |
| Enterprise | 50                   | 5,000          |

使用中的自動化上限是以**每個 [User Profile](/apis/profiles/overview)** 計算，而非以父帳號計算。你帳號底下的每個 profile 都各自有 Business 10 / Enterprise 50 的額度，因此一個擁有許多 profile 的帳號，可以在每個 profile 上執行相對應數量的自動化。此上限會計算使用中的自動化，並在 `POST`（建立）與 `PUT` 重新啟用（`active: false → true`）時強制執行，兩者都會回傳錯誤代碼 `470`。若你需要提高每個 profile 的上限？請[聯絡支援](mailto:support@ayrshare.com)為你的帳號調整。

**每日 DM 上限**依父 Ayrshare 帳號計算，由你所有 profile 共用，並額外設有每個 profile 的子上限，讓單一忙碌的 profile 無法耗盡整個帳號的配額。當觸及 DM 上限時，該活動列會記錄狀態為 `rate_limited`，且不會發送 DM。

單一自動化的結構性上限：**1–50 個觸發條件**、**1–50 個動作**。

Instagram 本身對每個帳號的 DM 上限約為每小時 200 則。引擎會以 20–60 秒的抖動延遲派送，以安全地維持在此門檻之下。

## 活動狀態

`GET /automations/:id/activity` 中的每一列都有最外層的 `status`，以及 `actionResults[]` 中每個動作的 `status`：

| 狀態             | 意義                                  |
| -------------- | ----------------------------------- |
| `pending`      | 剛寫入；worker 尚未取用                     |
| `in_flight`    | worker 正在派送中                        |
| `sent`         | 所有動作都成功                             |
| `failed`       | 至少一個動作失敗（且沒有動作發生驗證錯誤）               |
| `auth_error`   | Instagram 存取權杖無效；DM 沒有被重試           |
| `rate_limited` | 已達每日 DM 上限（方案層級或每個 profile）；DM 未被發送 |
| `deduplicated` | 此動作已於其去重視窗內對此接收者觸發過                 |
| `skipped`      | 在 fan-out 與派送之間，該自動化被停用或已刪除         |

`pending` 與 `in_flight` 為暫時狀態；其他皆為終態。

## 錯誤代碼

API 會回傳兩種錯誤形態：

* **業務規則錯誤**會帶有編號的自動化 `code`（例如 `{ "action": "automation", "code": 469, ... }`）。
* **驗證錯誤** — 任何格式不正確的請求主體（欄位缺失或無效、未知的模板變數、無法辨識的鍵）— 會回傳單一 **`473`** 回應，並附上 `details` 物件列出違規的欄位。`details` 是驗證器的輸出（`formErrors` 加上 `fieldErrors`）。請以 `details` 為分支依據，而非為每個條件另設代碼。在 `fieldErrors` 中，鍵是最外層的請求欄位（`triggers`、`actions`）：特定項目內部的問題（例如某個觸發條件缺少 `keywords`）會回報於該欄位（例如 `triggers`）；`formErrors` 則保留物件層級的問題，例如無法辨識的鍵。

| Code | HTTP | 意義                            |
| ---- | ---- | ----------------------------- |
| 468  | 403  | 需要 Business 或 Enterprise 方案   |
| 469  | 404  | 找不到自動化（呼叫者非擁有者時也會回傳）          |
| 470  | 429  | 已達方案層級的使用中自動化上限               |
| 471  | 400  | 此 profile 在指定平台上未連結社群帳號       |
| 472  | 403  | 你的帳號尚未啟用此功能 — 若想搶先體驗請與我們聯絡    |
| 473  | 400  | 驗證失敗（請求主體格式錯誤）— 請檢查 `details` |

## Meta 不允許的功能

有些常被要求的功能因 Meta 不允許在公開的 Instagram API 上使用，因此不支援：

* **對新粉絲自動 DM。** Instagram 不會發布「追蹤」的 webhook。
* **對陌生人主動發送第一則 DM。** Meta 要求接收者必須先發起接觸（留言、回覆、DM、表情回應），商業帳號才能傳送訊息給對方 — 而這正是這裡每個支援的觸發條件所代表的情境。
* **大量對外行銷發送。** 平台層級套用每小時 DM 上限與反濫用啟發式規則。

## 多 Profile 使用

這些端點會遵循 `profileKey` 標頭。傳入子 profile 的 key，自動化就會在該 profile 下建立/管理。速率限制會透過每個 profile 的子上限分配，因此單一講話很多的 profile 不會耗盡父帳號的配額。

## FAQ

<AccordionGroup>
  <Accordion title="我可以以新粉絲作為觸發條件嗎？">
    不行。Instagram 不會發布「追蹤」webhook，Meta 也不允許第三方 App 主動發送 DM 給尚未發起對話的使用者。每個支援的觸發條件（`comment_keyword`、`story_reply`、`dm_reaction`、`dm_keyword`）都滿足「使用者先接觸你」的要求。
  </Accordion>

  <Accordion title="如果自動化觸發時我的存取權杖無效會怎樣？">
    活動列會記錄狀態為 `auth_error`，且 DM 不會被重試。重新連結帳號後，下一次符合條件的互動就會正常觸發。
  </Accordion>

  <Accordion title="為什麼發送 DM 之前有延遲？">
    每次 `send_dm` 派送會在互動事件後 20–60 秒排程，好讓對 Instagram 的反垃圾系統看起來更自然。`fire_webhook` 與 `send_email` 動作不會套用抖動延遲。活動列的 `created` 時間戳為觸發條件比對到的時間；`completedAt` 為派送完成的時間。
  </Accordion>

  <Accordion title="活動列會永久保存嗎？">
    活動列會為了追蹤與分析而無限期保留。為了效能，`GET /automations/:id/activity` 端點僅回傳最近 30 天內的資料列。（去重機制使用自己的每個動作視窗 — 預設 7 天 — 與活動的查詢視窗無關。）
  </Accordion>

  <Accordion title="刪除自動化會一併移除其活動歷史嗎？">
    不會。刪除是軟刪除：主資料列會被標記為 `deleted`，不會再有新的派送，但既有的活動歷史仍可透過 activity 端點讀取。
  </Accordion>
</AccordionGroup>

## 端點

* [`POST /automations`](/apis/automations/create-automation) — 建立新的自動化
* [`GET /automations`](/apis/automations/list-automations) — 列出你的自動化
* [`GET /automations/:id`](/apis/automations/get-automation) — 取得一個自動化及其觸發條件與動作
* [`PUT /automations/:id`](/apis/automations/update-automation) — 部分更新；透過 `active: false` 暫停
* [`DELETE /automations/:id`](/apis/automations/delete-automation) — 軟刪除
* [`GET /automations/:id/activity`](/apis/automations/get-activity) — 游標分頁的派送稽核紀錄
