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 请求的原始请求体经 HMAC-SHA256 计算后,与 X-Hub-Signature-256 比对以验证签名。
easyCoexistence 为已连接的主页提供这些任务,作为 MCP 工具,从 publish_facebook_post 和 reply_to_comment 到 send_social_dm 和 get_social_insights;它会转发经 X-EC-Signature 签名的事件,并通过 get_social_credentials 将主页 ID 和 API 基础地址交给您自己的代码。
主页照片的 text 参数。Meta 的照片参考文档在此处标注 message 已弃用。
响应头 estimated_time_to_regain_access,其值为受限调用恢复可用前的预计分钟数。
回复主页收到的消息时所用的 messaging_type,须在 24 小时窗口内发送。
私密回复如何指定发表评论的用户,它通过同一个 /{page-id}/messages 端点完成。
示例运行前需要什么?
主页 ID,以及该主页的访问令牌(通过长期用户访问令牌从 /me/accounts 读取),还需要 Python 3 并安装 requests,或 Node.js 18 或更高版本(其内置 fetch 无需额外包)。每项任务还需要令牌具备相应权限,并且账户在主页上拥有对应任务,示例调用 Graph API v26.0:
如何在 Python 中发布帖子和照片?
通过一个后续示例复用的辅助函数:graph() 会添加主页访问令牌,GET 参数放入查询字符串,POST 字段以 JSON 发送(与 Meta 官方示例一致),并把 Meta 的错误对象转换为携带 code 和 error_subcode 的 GraphError。它只对临时性错误和频率限制错误码进行等待与重试,等待时长遵循 X-Business-Use-Case-Usage 响应头的要求(如果返回该头),其余错误则立即抛出。
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(即 photos 端点的 text 字段);Meta 返回照片的 id,以及承载该照片的主页帖子的 post_id,而 feed 调用只返回帖子的 id。
// 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 指向更早的结果。
# 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 读取,再对 /{comment-id}/comments 执行 POST。在 fields 中请求的 can_reply_privately 表示主页能否仍向该评论者发送私密回复,这在下面的 Messenger 示例之前值得了解。请保存已回复评论的 ID,以免重新运行时重复回复。
// 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 回复?
向 /{page-id}/messages 发送 POST,其中 recipient.id 设为来自 messages Webhook 的用户主页专属 ID,messaging_type 为 RESPONSE,并附上文本。示例会捕获两类不值得重试的拒绝:当 24 小时窗口已关闭时,错误 10 且子代码为 2534022 或 2018278;当用户不可用时,错误 551。private_reply() 会把 recipient.comment_id 替换为 ID,用于 7 天内评论允许发送的那一条消息。
# 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 小时窗口内继续。
// 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 统计反应、评论和分享。
# 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() 以秒为单位计算。每项指标返回其名称、周期,以及由 value 和 end_time 组成的 values 列表,每天一条;设置 since 后,第一个 end_time 落在其后一天,因此当天的数据也会包含在内。令牌需要 read_insights 和 pages_read_engagement,并且由具有 ANALYZE 任务的人提供。
// 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 签名?
根据原始请求体和 App Secret 重新计算 X-Hub-Signature-256,然后以恒定时间比较两者。Meta 会对每个 POST 的负载计算 HMAC-SHA256 签名,使用应用控制台基本设置中的 App Secret 作为密钥,并以 sha256= 为前缀写入。请以字节形式传入请求体,并在任何 JSON 解析之前:Django 中的 request.body 和 FastAPI 中的 await request.body() 都能得到 Meta 签名所用的字节。
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 握手。
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() 会重试临时性和频率限制的错误代码,并将其他错误抛给调用方处理:
如何通过 easyCoexistence 执行相同的任务?
作为 MCP 工具,由 Claude、ChatGPT 或您自己的智能体在已连接的主页上调用,访问令牌由 easyCoexistence 保管。主页令牌不会提供给您,因此上面的示例需使用您自己的 Meta 应用的令牌运行;get_social_credentials 会返回主页的 ID 以及 Graph API 基础地址。每项任务对应的工具:
常见错误
- 使用用户访问令牌调用主页端点。这些端点大多要求主页自身的访问令牌;使用用户或应用令牌发起的调用,会计入那些频率限制,而不是主页的限额。
- 连续发布相同文本。Meta 会以错误 506 拒绝连续重复的帖子,因此重新运行的任务必须变换内容,或跳过该帖子。
- 把每日独立观众数加总。page_total_media_view_unique 统计每个周期内的独立观众,因此每日数值相加并不等于一个月的总数;应改为请求 period days_28。
- 把主页访问令牌发送到浏览器或应用。这些调用应在服务器上进行,使令牌不被任何能读取客户端的人接触到。
每个连接每月 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 从哪里来?
来自 messages Webhook:每个 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 监控
验证时间