Python と Node.js で使う Facebook Pages API の実装例
Python と Node.js は、Page のアクセストークンを付けた通常の HTTPS リクエストで graph.facebook.com/v26.0 を呼び出します。POST /{page-id}/feed と /{page-id}/photos で投稿と写真を公開し、/{post-id}/comments でコメントの読み取りと返信を行います。POST /{page-id}/messages では Messenger で返信し、GET /{page-id}/insights ではメトリクスを読み取ります。また、生のボディの HMAC-SHA256 を計算して、各 Webhook の X-Hub-Signature-256 を検証します。
easyCoexistence は、接続済みの Page に対してこれらの処理を MCP ツールとして提供します。
Page の写真の text パラメータです。Meta の写真リファレンスでは、ここにある message が非推奨とされています。
estimated_time_to_regain_access を含むレスポンスヘッダーは、制限された呼び出しが再び成功するまでの分数を示します。
Page が受け取ったメッセージへの返信に使う messaging_type で、24 時間のウィンドウ内で送信します。
コメントした人宛てのプライベート返信は、同じ /{page-id}/messages エンドポイントを通じて指定します。
サンプルを実行する前に何が必要ですか?
Page ID と、その Page のアクセストークンが必要です。アクセストークンは、長期間有効なユーザートークンを使って /me/accounts から読み取ります。Python 3 と requests、または Node.js 18 以降(組み込みの fetch を使うため追加パッケージは不要)を用意してください。各処理には、トークンに付与された権限と、Page 上の対応するタスクも必要です。サンプルは Graph API v26.0 を呼び出します:
Python で投稿と写真を公開するには?
後続のサンプルが再利用する共通ヘルパーを 1 つ用意します。graph() は Page トークンを付与し、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 で投稿と写真を公開するには?
Python と同じヘルパーを Node.js 18 以降で用意します。ファイルは .mjs として保存するため、トップレベル await を使えます。クライアントライブラリの代わりに、組み込みの fetch を使います。写真の呼び出しでは url と caption を送信します。これは photos エッジの text フィールドに対応します。Meta は写真の id と、その写真を含む Page 投稿の post_id を返します。一方、フィードへの呼び出しは投稿の 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 エッジに Page として投稿します。トークンは 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 backNode.js でコメントを読み取り、返信するには?
同じ 2 つの呼び出しを使います。URL オブジェクトでクエリ文字列を組み立て、fields、filter、order を指定して GET します。その後、/{comment-id}/comments に POST します。fields に含めた can_reply_privately は、その Page がコメントした人にまだプライベート返信を送れるかを示します。後述の 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 backPython で Messenger の返信を送るには?
/{page-id}/messages に POST します。recipient.id には、messages Webhook で受け取った相手の Page スコープ ID を設定します。messaging_type は RESPONSE、本文は text です。サンプルは、再試行しても意味がない 2 種類のエラーを捕捉します。24 時間のウィンドウが閉じている場合は、error 10 で subcode が 2534022 または 2018278 です。相手が利用できない場合は 551 です。private_reply() は ID の代わりに recipient.comment_id を使います。これは、コメントに対して 7 日以内に許可される 1 通のメッセージ用です。
# 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 で送ります。recipient、messaging_type、message を graph() が JSON として送信します。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 で Page のインサイトを読み取るには?
/{page-id}/insights に GET します。metric はカンマ区切りで指定し、period=day を設定します。since と until には UNIX 秒で期間を指定します。1 回のリクエストで最大 90 日分を取得できます。Meta が廃止した指標の後継は、page_impressions から page_media_view、page_impressions_unique から page_total_media_view_unique、page_fans から page_follows です。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 で Page のインサイトを読み取るには?
呼び出しは同じで、since と until は Date.now() から秒単位で計算します。各指標には、名前、period、values のリストが返ります。values は 1 日ごとの value と end_time のペアです。since を指定すると、最初の end_time はその翌日になります。これは since の日のデータを含めるためです。トークンには 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 を再計算し、2 つを定数時間で比較します。Meta は各 POST のペイロードに対して、App Dashboard の基本設定にある App Secret をキーとした HMAC-SHA256 で署名し、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 は長さの異なる入力に対して例外を投げるため、長さの確認を先に行います。Meta は失敗した配信を再試行し、同じイベントを 2 回送ることもあるため、200 を素早く返し、処理は後で行ってください。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 で同じ処理を実行するには?
easyCoexistence が接続済みの Page 上で、Claude、ChatGPT、または独自のエージェントから呼び出せる MCP ツールとして実行します。トークンは easyCoexistence が保持します。Page のトークンは渡されないため、上記のサンプルは独自の Meta アプリのトークンで実行します。get_social_credentials は Page の ID と Graph API のベース URL を返します。各処理に対応するツールは次のとおりです:
よくある間違い
- Page のエンドポイントをユーザートークンで呼び出すこと。大半のエンドポイントは Page 自身のトークンを必要とします。ユーザーまたはアプリのトークンで行った呼び出しは、Page のレート制限ではなく、そのトークン側のレート制限に計上されます。
- 同じ本文を続けて投稿すること。Meta は連続した重複投稿をエラー 506 で拒否します。再実行されるジョブは、内容を変えるか、投稿をスキップする必要があります。
- 1 日ごとのユニーク視聴者数を足し合わせること。page_total_media_view_unique は各期間のユニークな視聴者を数えるため、日別の値を合計しても月の値にはなりません。代わりに period に days_28 を指定してください。
- Page トークンをブラウザやアプリに配布すること。これらの呼び出しはサーバー側で行うべきです。そうすれば、クライアントのコードを読める人の手にトークンが渡らないようにできます。
publish_facebook_post から reply_to_comment、send_social_dm、get_social_insights までが含まれます。また、イベントを X-EC-Signature で署名して転送し、get_social_credentials を通じて独自のコードに Page の ID と API ベースを渡します。接続 1 件あたり月額 US$ 9 から、接続を増やすほど下がり US$ 0.75 まで。最初の 3 日間は無料です。
よくある質問
Facebook Pages API を呼び出すには SDK が必要ですか?
いいえ。Graph API は JSON を使う HTTPS なので、このページのサンプルが示すように、Python の requests と、Node.js 18 以降に組み込まれた fetch で十分です。
同じコードで複数の Page に投稿できますか?
はい。/me/accounts は Page ごとに別のトークンを返すため、Page ごとに 1 つずつ保持し、対応する PAGE_ID と PAGE_TOKEN を渡してください。Page トークンで行った呼び出しは、その Page 自身のレート制限に計上されます。
Messenger の返信に使う PSID はどこから取得しますか?
messages Webhook から取得します。各 messaging イベントの sender.id が、その相手の Page スコープ ID です。この ID は相手と Page の組み合わせに固有です。Facebook Login のユーザー ID はアプリスコープのため、Messenger Platform では使えません。
Facebook Page 1 つにつき easyCoexistence の料金はいくらですか?
接続済みの Page は 1 接続として数えられ、接続数に応じて接続 1 件あたり月額 US$ 9 から US$ 0.75 までです。最初の 3 日間は無料です。MCP ツールも含まれます。
続きを読む
最初のチャンネルを 2 分で接続しましょう。
プラットフォームの審査を待つ必要はありません。WhatsApp、Instagram、TikTok などのチャンネルを接続して、AI に投稿、返信、レポートを任せてみてください。
- 3 日間無料
- いつでも解約可能
- 公式 API のみ使用
- 24/7 監視
確認日