登入開始免費試用
easyCoexistence 官方 API

Python 與 Node.js 的 Facebook Pages API:實作範例

Python 與 Node.js 透過純 HTTPS 請求呼叫 Facebook Pages API,請求網址為 graph.facebook.com/v26.0,並使用專頁的存取權杖:POST /{page-id}/feed 與 /{page-id}/photos 發布貼文與相片,/{post-id}/comments 讀取及回覆留言,POST /{page-id}/messages 在 Messenger 中回覆,GET /{page-id}/insights 讀取指標;每個 Webhook 的 X-Hub-Signature-256 則以原始請求主體的 HMAC-SHA256 驗證。

easyCoexistence 以 MCP 工具形式為已連接的專頁提供這些任務,由 publish_facebook_post、reply_to_comment 一直到 send_social_dm 與 get_social_insights;它會以 X-EC-Signature 簽署並轉發事件,並透過 get_social_credentials 將專頁 ID 及 API 基底交給您自己的程式碼。

caption

專頁相片的 text 參數;Meta 相片參考文件在此標示 message 已棄用。

X-Business-Use-Case-Usage

回應標頭 estimated_time_to_regain_access,顯示受限呼叫恢復前還需等待的分鐘數。

RESPONSE

messaging_type 用於回覆專頁所收到的訊息,於 24 小時回覆時限內發送。

recipient.comment_id

私下回覆如何指向留言的人,透過同一個 /{page-id}/messages 端點。

執行範例前需要準備什麼?

專頁 ID 與該專頁的存取權杖(由長效用戶權杖透過 /me/accounts 讀取),另需 Python 3 並安裝 requests,或 Node.js 18 或以上版本(其內建的 fetch 無須額外套件)。每項任務也需要權杖上的對應權限,以及用戶在專頁上的相應任務,範例呼叫的是 Graph API v26.0:

Publish a post or photoPOST /{page-id}/feed and /{page-id}/photos: pages_manage_posts, CREATE_CONTENT
Read and reply to comments/{post-id}/comments and /{comment-id}/comments: pages_manage_engagement, MODERATE
Reply in MessengerPOST /{page-id}/messages: pages_messaging, MESSAGING
Read insightsGET /{page-id}/insights: read_insights, pages_read_engagement, ANALYZE
Check a webhookX-Hub-Signature-256, with the app secret and no token

如何在 Python 中發布貼文與相片?

透過一個後續範例共用的輔助函式 graph():它會加入專頁權杖,以查詢字串傳送 GET 參數,並以 JSON 傳送 POST 欄位(與 Meta 官方範例一致)。遇到 Meta 的錯誤物件時,會將其轉為 GraphError,並帶有 code 與 error_subcode。當遇到暫時性或速率限制的錯誤代碼時,它會依 X-Business-Use-Case-Usage 標頭的要求等待並重試;其他錯誤則立即拋出。

Python: graph(), then a post and a photo
import json, os, time
import requests

GRAPH = "https://graph.facebook.com/v26.0"
PAGE_ID = os.environ["PAGE_ID"]
PAGE_TOKEN = os.environ["PAGE_TOKEN"]  # the Page's own token, from /me/accounts
RETRY = {1, 2, 4, 17, 32, 613, 80001}   # temporary or rate limited


class GraphError(Exception):
    def __init__(self, err):
        super().__init__(err.get("message"))
        self.code, self.subcode = err.get("code"), err.get("error_subcode")


def wait_seconds(response, attempt):
    usage = json.loads(response.headers.get("x-business-use-case-usage", "{}"))
    minutes = [u.get("estimated_time_to_regain_access", 0) for v in usage.values() for u in v]
    return max([60 * m for m in minutes] + [30 * 2 ** attempt])


def graph(method, path, retries=3, **fields):
    fields["access_token"] = PAGE_TOKEN
    send = {"params": fields} if method == "GET" else {"json": fields}
    for attempt in range(retries + 1):
        response = requests.request(method, f"{GRAPH}/{path}", timeout=30, **send)
        body = response.json()
        if "error" not in body:
            return body
        err = GraphError(body["error"])
        if err.code not in RETRY or attempt == retries:
            raise err
        time.sleep(wait_seconds(response, attempt))


post = graph("POST", f"{PAGE_ID}/feed", message="Open until 11pm this Friday.")
photo = graph("POST", f"{PAGE_ID}/photos",
              url="https://example.com/menu.jpg", caption="This week's menu")
print(post["id"], photo["post_id"])

如何在 Node.js 中發布?

使用同一輔助函式(Node.js 18 或以上版本),儲存為 .mjs 檔案,以便使用頂層 await;並以內建 fetch 取代客戶端程式庫。相片呼叫會傳送 url 與 caption,即相片端點的 text 欄位;Meta 會回傳相片的 id,以及承載該相片之專頁貼文的 post_id;而發布貼文的呼叫只回傳貼文的 id。

Node.js: graph(), then a post and a photo
// Node.js 18 or later, saved as an .mjs file: fetch and top-level await are built in.
const GRAPH = "https://graph.facebook.com/v26.0";
const { PAGE_ID, PAGE_TOKEN } = process.env; // the Page's own token, from /me/accounts
const RETRY = new Set([1, 2, 4, 17, 32, 613, 80001]); // temporary or rate limited

class GraphError extends Error {
  constructor(err) {
    super(err.message);
    this.code = err.code;
    this.subcode = err.error_subcode;
  }
}

function waitMs(response, attempt) {
  const usage = JSON.parse(response.headers.get("x-business-use-case-usage") ?? "{}");
  const minutes = Object.values(usage).flat().map((u) => u.estimated_time_to_regain_access ?? 0);
  return Math.max(30_000 * 2 ** attempt, ...minutes.map((m) => m * 60_000));
}

async function graph(method, path, fields = {}, retries = 3) {
  const url = new URL(`${GRAPH}/${path}`);
  const init = { method };
  const all = { ...fields, access_token: PAGE_TOKEN };
  if (method === "GET") {
    for (const [key, value] of Object.entries(all)) url.searchParams.set(key, String(value));
  } else {
    init.headers = { "Content-Type": "application/json" };
    init.body = JSON.stringify(all);
  }
  for (let attempt = 0; ; attempt++) {
    const response = await fetch(url, init);
    const body = await response.json();
    if (!body.error) return body;
    if (!RETRY.has(body.error.code) || attempt === retries) throw new GraphError(body.error);
    await new Promise((done) => setTimeout(done, waitMs(response, attempt)));
  }
}

const post = await graph("POST", `${PAGE_ID}/feed`, { message: "Open until 11pm this Friday." });
const photo = await graph("POST", `${PAGE_ID}/photos`, {
  url: "https://example.com/menu.jpg",
  caption: "This week's menu",
});
console.log(post.id, photo.post_id);

如何在 Python 中讀取並回覆留言?

讀取貼文的留言時,使用 fields,並以 filter=stream 取得所有層級的留言(依時間排序),以及 order=reverse_chronological 讓最新的排在最前;接著以專頁身分,對該留言自身的 comments 端點發送訊息以回覆。權杖必須來自可執行 MODERATE 的人,否則 Meta 會省略留言 ID;回覆時需要 pages_manage_engagement 權限。paging.next 則指向更早的內容。

Python: read a post's comments and reply to the questions
# graph() as in the first example
post_id = post["id"]  # {page-id}_{post-id}, as the publish call returned it
page = graph("GET", f"{post_id}/comments", fields="id,message,created_time,can_reply_privately",
             filter="stream", order="reverse_chronological", limit=50)
for comment in page["data"]:
    if "?" in comment.get("message", ""):
        graph("POST", f"{comment['id']}/comments",
              message="Thanks for asking! Our hours are on the Page.")
older = page.get("paging", {}).get("next")  # follow it to read further back

如何在 Node.js 中讀取並回覆留言?

兩個呼叫相同,查詢字串由 URL 物件建構:以 GET 搭配 fields、filter 與 order,再以 POST 發送至 /{comment-id}/comments。在 fields 中要求的 can_reply_privately,表示專頁是否仍可向該留言者發送私下回覆;這在下方的 Messenger 範例前值得先確認。請保存已回覆的留言 ID,以免重新執行時重複回覆。

Node.js: read a post's comments and reply to the questions
// graph() as in the first example
const postId = post.id; // {page-id}_{post-id}, as the publish call returned it
const page = await graph("GET", `${postId}/comments`, {
  fields: "id,message,created_time,can_reply_privately",
  filter: "stream",
  order: "reverse_chronological",
  limit: 50,
});
for (const comment of page.data) {
  if ((comment.message ?? "").includes("?")) {
    await graph("POST", `${comment.id}/comments`, {
      message: "Thanks for asking! Our hours are on the Page.",
    });
  }
}
const older = page.paging?.next; // follow it to read further back

如何在 Python 中發送 Messenger 回覆?

以 POST 發送至 /{page-id}/messages,其中 recipient.id 設為 Webhook 訊息事件中該用戶的專頁範圍 ID,messaging_type 為 RESPONSE,並附上 text。範例會攔截兩種不值得重試的拒絕:24 小時時限已過時的錯誤 10(子代碼 2534022 或 2018278),以及用戶無法接收時的錯誤代碼 551。private_reply() 則以 recipient.comment_id 取代 ID,用於在 7 天內對留言發送唯一一則訊息。

Python: a Messenger reply and a private reply
# graph(), GraphError and PAGE_ID as in the first example
def reply(psid, text):
    """psid: sender.id from the messages webhook, within 24 hours of the person's message."""
    try:
        return graph("POST", f"{PAGE_ID}/messages", recipient={"id": psid},
                     messaging_type="RESPONSE", message={"text": text})
    except GraphError as e:
        if (e.code == 10 and e.subcode in (2534022, 2018278)) or e.code == 551:
            return None  # the window has closed, or the person is unavailable: no retry
        raise


def private_reply(comment_id, text):
    """One Messenger message to the person who commented, within 7 days of the comment."""
    return graph("POST", f"{PAGE_ID}/messages", recipient={"comment_id": comment_id},
                 message={"text": text})

如何在 Node.js 中發送 Messenger 回覆?

以 JavaScript 發送相同的請求主體,由 graph() 以 JSON 傳送 recipient、messaging_type 與 message。Meta 接受發送時會回傳 recipient_id 與 message_id,值得與對話一併儲存。私下回覆會附帶指向原留言的連結;用戶回覆後,對話便會沿用標準的 24 小時回覆時限。

Node.js: a Messenger reply and a private reply
// graph(), GraphError and PAGE_ID as in the first example
async function reply(psid, text) {
  // psid: sender.id from the messages webhook, within 24 hours of the person's message
  try {
    return await graph("POST", `${PAGE_ID}/messages`, {
      recipient: { id: psid },
      messaging_type: "RESPONSE",
      message: { text },
    });
  } catch (e) {
    const closed =
      e instanceof GraphError && ((e.code === 10 && [2534022, 2018278].includes(e.subcode)) || e.code === 551);
    if (closed) return null; // the window has closed, or the person is unavailable: no retry
    throw e;
  }
}

function privateReply(commentId, text) {
  // one Messenger message to the person who commented, within 7 days of the comment
  return graph("POST", `${PAGE_ID}/messages`, {
    recipient: { comment_id: commentId },
    message: { text },
  });
}

如何在 Python 中讀取專頁洞察?

以 GET 發送至 /{page-id}/insights,附上以逗號分隔的指標清單、period=day,以及以 UNIX 秒數表示的 since 與 until 時段;單次請求最多涵蓋 90 天。其中三個指標取代了 Meta 已停用的指標:page_media_view 取代 page_impressions,page_total_media_view_unique 取代 page_impressions_unique,page_follows 取代 page_fans;而 page_post_engagements 計算的是反應、留言與分享。

Python: four Page metrics for the last 28 days
# graph() and PAGE_ID as in the first example
until = int(time.time())
since = until - 28 * 86400  # one request can cover up to 90 days
metrics = "page_media_view,page_total_media_view_unique,page_post_engagements,page_follows"
data = graph("GET", f"{PAGE_ID}/insights", metric=metrics, period="day", since=since, until=until)
for metric in data["data"]:
    for point in metric["values"]:
        print(metric["name"], point["end_time"][:10], point["value"])

如何在 Node.js 中讀取專頁洞察?

呼叫相同,since 與 until 以 Date.now() 換算為秒數計算。每個指標會回傳其名稱、期間,以及一個 values 清單,內含 value 與 end_time 配對,每日一組;設定 since 後,第一個 end_time 落在其後一天,因此該日資料會被包含在內。權杖需要 read_insights 與 pages_read_engagement 權限,並由具備 ANALYZE 任務的人取得。

Node.js: four Page metrics for the last 28 days
// graph() and PAGE_ID as in the first example
const until = Math.floor(Date.now() / 1000);
const since = until - 28 * 86400; // one request can cover up to 90 days
const data = await graph("GET", `${PAGE_ID}/insights`, {
  metric: "page_media_view,page_total_media_view_unique,page_post_engagements,page_follows",
  period: "day",
  since,
  until,
});
for (const metric of data.data) {
  for (const point of metric.values) {
    console.log(metric.name, point.end_time.slice(0, 10), point.value);
  }
}

如何在 Python 中驗證 Webhook 簽名?

以原始請求主體與應用程式密鑰重新計算 X-Hub-Signature-256,並以恆定時間比較兩者。Meta 會以應用程式基本設定中的密鑰作為金鑰,對每個 POST 的負載計算 HMAC-SHA256,並寫入 sha256= 之後。請以位元組形式傳入主體,且須在任何 JSON 解析之前:Django 的 request.body 與 FastAPI 的 await request.body() 都會提供 Meta 所簽署的位元組。

Python: check X-Hub-Signature-256
import hashlib, hmac, os

APP_SECRET = os.environ["APP_SECRET"].encode()  # App Dashboard, Settings, Basic


def signed_by_meta(raw_body: bytes, header: str) -> bool:
    """raw_body: the request body exactly as received. header: X-Hub-Signature-256."""
    expected = "sha256=" + hmac.new(APP_SECRET, raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected.encode(), (header or "").encode())

# Django:  signed_by_meta(request.body, request.headers.get("X-Hub-Signature-256"))
# FastAPI: signed_by_meta(await request.body(), request.headers.get("X-Hub-Signature-256"))

如何在 Node.js 中驗證 Webhook 簽名?

檢查方式相同,使用 node:crypto,並需要以 Buffer 形式取得主體:在 Express 中,express.raw 可在該路由保留未解析的主體。timingSafeEqual 在長度不同的輸入上會拋出錯誤,因此須先進行長度檢查。請盡快回傳 200,之後再處理工作,因為 Meta 會重試失敗的遞送,且可能重複發送同一事件;hub.challenge 的握手程序則在任何事件之前,於驗證頁面說明。

Node.js: check X-Hub-Signature-256
import crypto from "node:crypto";

const APP_SECRET = process.env.APP_SECRET; // App Dashboard, Settings, Basic

function signedByMeta(rawBody, header = "") {
  // rawBody: a Buffer holding the request body exactly as received. header: X-Hub-Signature-256
  const digest = crypto.createHmac("sha256", APP_SECRET).update(rawBody).digest("hex");
  const expected = Buffer.from(`sha256=${digest}`);
  const given = Buffer.from(header);
  return given.length === expected.length && crypto.timingSafeEqual(given, expected);
}

// Express: app.post("/webhook", express.raw({ type: "application/json" }), (req, res) => {
//   if (!signedByMeta(req.body, req.get("X-Hub-Signature-256"))) return res.sendStatus(401);
//   res.sendStatus(200); // then work on JSON.parse(req.body) after answering
// });

程式應處理哪些錯誤代碼?

Meta 的錯誤指南會加以區分的錯誤代碼,因為每種都需要不同的回應:權杖被拒或參數有誤時重試只會再次失敗,而受限制的呼叫在等待後即可成功。graph() 會重試暫時性與速率限制的錯誤代碼,其他錯誤則拋給呼叫方處理:

190, 102The token was refused, and the subcode says why. A new sign-in is the fix
10, 200 to 299A permission was not granted or was removed. Grant it again
4, 17, 32, 613An app, user or Page rate limit. Stop, wait, then resume gradually
80001Page calls made with a Page token are throttled; the header gives the minutes
368Blocked for policy violations. Wait, and review what was being sent
100An invalid parameter. Fix the request before sending it again
551The person is not available on Messenger. Do not retry
1, 2A temporary issue on Meta's side. Wait and retry

如何透過 easyCoexistence 執行相同的任務?

以 MCP 工具形式提供,供 Claude、ChatGPT 或您自己的 AI 代理在已連接的專頁上呼叫,權杖由 easyCoexistence 保管。專頁權杖不會交出,因此上述範例須以您自己的 Meta 應用程式所發出的權杖執行;get_social_credentials 會回傳專頁的 ID 與 Graph API 基底網址。每項任務對應的工具如下:

Publishpublish_facebook_post with message, link, image_url or video_url, now or at scheduled_at
Commentslist_social_comments, then reply_to_comment; private set to true sends the one Messenger message
Messengersend_social_dm, with recipient_id set to the sender's ID from the forwarded event
Insightsget_social_insights with metrics and a period, or object_id for one post
Eventsset_social_webhook_destination; each forward carries X-EC-Signature, made with the Page's own secret

常見錯誤

  • 以用戶權杖呼叫專頁端點。大多數端點預期使用專頁本身的權杖;以用戶或應用程式權杖發出的呼叫,會計入這些速率限制,而非專頁的限額。
  • 連續發布相同內容。Meta 會以錯誤 506 拒絕連續重複的貼文,因此重新執行的任務必須更改內容,或略過該則貼文。
  • 將每日獨立觀看人數相加。page_total_media_view_unique 計算的是每個期間的獨立觀看人數,所以每日數值相加並不等於一個月的總數;請改為要求 period days_28。
  • 將專頁權杖交付瀏覽器或應用程式。這些呼叫應在伺服器上進行,讓權杖遠離任何能讀取用戶端的人。
使用 EasyCoexistence 完成這項設定

每個連接每月 US$ 9 至 US$ 0.75,連接越多越便宜,首 3 天免費。

常見問題

呼叫 Facebook Pages API 需要 SDK 嗎?

不需要。Graph API 是以 JSON 運作的 HTTPS,因此本頁範例所示的 Python 請求與 Node.js 18 或以上版本內建的 fetch 已足夠。

同一段程式碼可以發布到多個專頁嗎?

可以。/me/accounts 會為每個專頁各回傳一組獨立權杖,因此請為每個專頁各保存一組,並傳入對應的 PAGE_ID 與 PAGE_TOKEN;以專頁權杖發出的呼叫,會計入該專頁本身的速率限制。

Messenger 回覆所用的 PSID 從哪裡來?

來自 Webhook 的 messages 事件:每個 messaging 事件中的 sender.id 即為該用戶的專頁範圍 ID,對該用戶與專頁而言是唯一的。Facebook Login 的用戶 ID 屬應用程式範圍,無法用於 Messenger Platform。

easyCoexistence 對 Facebook 專頁收費多少?

每個已連接的專頁計為一個連接,按連接數量每月收費 US$ 9 至 US$ 0.75,首 3 天免費;MCP 工具已包含在內。

繼續閱讀

兩分鐘內連接您的第一個頻道。

無需等待平台審核。連接 WhatsApp、Instagram、TikTok 或其他頻道,然後請您的 AI 發佈貼文、回覆訊息或匯報數據,並看着它運作。

  • 免費試用 3 天
  • 隨時取消
  • 只用官方 API
  • 24/7 監察

驗證日期