התחברותהתחילו תקופת ניסיון
easyCoexistence ממשקי API רשמיים

Facebook Pages API ב-Python וב-Node.js: דוגמאות עובדות

Python ו-Node.js קוראים ל-Facebook Pages API כבקשות HTTPS רגילות אל graph.facebook.com/v26.0, עם אסימון גישה (Access Token) של העמוד: POST /{page-id}/feed ו-POST /{page-id}/photos מפרסמים, /{post-id}/comments קורא ומשיב לתגובות, POST /{page-id}/messages משיב ב-Messenger, GET /{page-id}/insights קורא מדדים, וחתימת HMAC-SHA256 של הגוף הגולמי בודקת את X-Hub-Signature-256 בכל וובהוק (Webhook) שמגיע.

easyCoexistence מעניקה לעמוד מחובר את המשימות האלה ככלי MCP, כגון publish_facebook_post, reply_to_comment, send_social_dm וגם get_social_insights, מעבירה את האירועים שלה חתומים בכותרת X-EC-Signature, ומוסרת לקוד שלכם את מזהה העמוד ואת בסיס ה-API דרך get_social_credentials.

caption

הפרמטר text של תמונת עמוד; בתיעוד התמונות של Meta מסומן שם הפרמטר message כמיושן.

X-Business-Use-Case-Usage

כותרת תגובה, שבתוכה estimated_time_to_regain_access נותנת את מספר הדקות עד שקריאות מוגבלות יחזרו לפעול.

RESPONSE

השדה messaging_type לתשובה על הודעה שהעמוד קיבל, הנשלחת בתוך חלון 24 השעות.

recipient.comment_id

איך תגובה פרטית פונה למי שהגיב, דרך אותה נקודת הקצה /{page-id}/messages.

מה הדוגמאות צריכות לפני שהן רצות?

מזהה העמוד (Page 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() מוסיפה את אסימון העמוד, שולחת פרמטרים בשאילתת הכתובת ושדות בגוף הבקשה כ-JSON, כמו בדוגמאות של 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 של נקודת הקצה photos; 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 משמיטה את מזהי התגובות, ולהשיב דורש את ההרשאה 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. השדה can_reply_privately, שמבוקש בפרמטר fields, מציין אם העמוד עדיין יכול לשלוח לאותו מגיב תשובה פרטית, וזה שווה לדעת לפני הדוגמה של Messenger שלמטה. שמרו את מזהי התגובות שאליהן כבר השבתם, כדי שהרצה חוזרת לא תשיב פעמיים.

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

איך שולחים תשובה ב-Messenger עם Python?

POST אל /{page-id}/messages, כאשר recipient.id הוא מזהה Page-scoped של האדם מוובהוק ההודעות, messaging_type הוא RESPONSE, והטקסט הוא תוכן ההודעה. הדוגמה תופסת את שתי הדחיות שאין טעם לנסות שוב: שגיאה 10 עם subcode 2534022 או 2018278 כשחלון של 24 שעות נסגר, ושגיאה 551 כשהאדם אינו זמין. private_reply() שם את recipient.comment_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})

איך שולחים תשובה ב-Messenger עם Node.js?

אותו גוף בקשה ב-JavaScript, עם השדות recipient, messaging_type, message, הנשלחים כ-JSON על ידי graph(). 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 וחלון זמן (since, until) בשניות UNIX; בקשה אחת מכסה עד 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() בשניות. כל מדד חוזר עם השם שלו, עם period שלו ועם רשימה בשם 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?

מחשבים מחדש את X-Hub-Signature-256 מגוף הבקשה הגולמי ומסוד האפליקציה, ואז משווים בין השניים בזמן קבוע. Meta חותמת כל POST עם HMAC-SHA256 של ה-payload, באמצעות המפתח App Secret שבהגדרות הבסיס ב-App Dashboard, וכותבת את התוצאה אחרי sha256=. מעבירים את הגוף כ-bytes, לפני כל פענוח JSON: request.body ב-Django וגם await request.body() ב-FastAPI מחזירים את הבתים ש-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?

הבדיקה זהה, עם 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 או הסוכן שלכם מפעילים על עמוד מחובר, כשהאסימון נשמר ב-easyCoexistence. אסימוני עמוד אינם נמסרים לעולם, ולכן הדוגמאות למעלה רצות על אסימון מאפליקציית Meta שלכם; get_social_credentials מחזיר את המזהה של העמוד ואת בסיס ה-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 ימים ראשונים בחינם.

שאלות נפוצות

האם צריך SDK כדי לקרוא ל-Facebook Pages API?

לא. Graph API הוא ממשק HTTPS עם JSON, לכן מספיקים בקשות ב-Python, וגם fetch מובנה ב-Node.js 18 ומעלה, כפי שהדוגמאות בעמוד הזה מראות.

האם אותו קוד יכול לפרסם ליותר מעמוד אחד?

כן. /me/accounts מחזיר אסימון נפרד לכל עמוד, לכן שומרים אסימון אחד לכל עמוד ומעבירים את PAGE_ID ואת PAGE_TOKEN המתאימים. קריאות שנעשות עם אסימון עמוד נספרות במגבלת הקצב של אותו עמוד.

מאיפה מגיע ה-PSID לתשובה ב-Messenger?

מוובהוק ההודעות: sender.id בכל אירוע messaging הוא מזהה ה-Page-scoped של האדם, ייחודי לאותו אדם ולאותו עמוד. מזהי משתמש שמגיעים מ-Facebook Login הם ברמת האפליקציה, ולכן אינם מתאימים לשימוש בפלטפורמת ההודעות.

כמה עולה easyCoexistence לעמוד Facebook?

כל עמוד מחובר נספר כחיבור אחד, ב-US$ 9 עד US$ 0.75 לחיבור בחודש לפי מספר החיבורים שיש לכם, עם 3 הימים הראשונים בחינם; כלי ה-MCP כלולים במחיר.

המשיכו לקרוא

מדריך Facebook Pages API לשנת 2026: מהאפליקציה שלכם ועד הפוסט הראשוןמסלול Facebook Pages API לשנת 2026, צעד אחר צעד: אפליקציית Meta, Facebook Login for Business, הרשאות, אסימון עמוד, פוסט ראשון, Messenger, וובהוקים (Webhook).אימות וובהוק (Webhook) של Facebook: hub.challenge ו-X-Hub-Signature-256אימות וובהוק של Facebook: מחזירים את hub.challenge כאשר hub.verify_token תואם, ואז בודקים את X-Hub-Signature-256 בכל אירוע עם סוד האפליקציה.מדדי Facebook Page Insights ב-2026: אילו עובדים ואילו Meta הוציאה משימושאילו מדדי Facebook Page Insights עובדים בסוף 2026 ואילו הוצאו משימוש על ידי Meta, עם התאריכים: page_impressions, page_fans, מדדי הגעה ועוד.הודעות תגית ב-Messenger בשנת 2026: מה דף Facebook יכול לשלוח אחרי חלון 24 השעותמה דף Facebook יכול לשלוח אחרי חלון 24 השעות של Messenger ב-2026: HUMAN_AGENT, CUSTOMER_FEEDBACK, שלוש תגיות שהופסקו והתחליפים שלהן.למה חיבור ה-API לעמוד Facebook מפסיק לעבוד, ואיך לשמור עליו פעילהסיבות המתועדות לכך שאסימון או וובהוק (Webhook) של עמוד Facebook מפסיקים לעבוד, השגיאה שכל אחת מחזירה, איך מזהים מוקדם ואיך מתחברים מחדש לעמוד.שינויים ב-Graph API של Facebook ב-2026: מה הפסיק לעבוד ומה לעשותשינויי Graph API ב-Facebook ב-2026, מהחדש לישן: v26.0 והגרסאות שפרשו, שינויי פרוטוקול, מדדי Page ותגיות הודעה שפרשו, ותיקון לכל אחד.

מחברים את הערוץ הראשון שלכם תוך שתי דקות.

בלי לחכות לאישורים של הפלטפורמות. מחברים את WhatsApp, Instagram, TikTok או ערוץ אחר, מבקשים מה-AI לפרסם, להשיב או להפיק דוח, ורואים אותו עובד.

  • 3 ימי ניסיון חינם
  • ביטול בכל עת
  • רק ממשקי API רשמיים
  • ניטור 24/7

נבדק ב-