Python और Node.js में Facebook Pages API: काम करने वाले उदाहरण
Python और Node.js, Facebook Pages API को graph.facebook.com/v26.0 पर Page के एक्सेस टोकन के साथ सामान्य HTTPS अनुरोधों के रूप में कॉल करते हैं: POST /{page-id}/feed और /{page-id}/photos प्रकाशित करते हैं, /{post-id}/comments कमेंट पढ़ता और उनका जवाब देता है, POST /{page-id}/messages Messenger में जवाब देता है, GET /{page-id}/insights मेट्रिक्स पढ़ता है, और रॉ बॉडी का HMAC-SHA256 हर वेबहुक पर X-Hub-Signature-256 की जाँच करता है।
easyCoexistence कनेक्टेड Page को ये काम MCP टूल के रूप में देता है, publish_facebook_post और reply_to_comment से send_social_dm और get_social_insights तक; अपने इवेंट X-EC-Signature से हस्ताक्षरित करके आगे भेजता है, और अपने कोड को get_social_credentials के ज़रिए Page का ID और API बेस देता है।
Page फ़ोटो का text पैरामीटर; Meta के photos रेफ़रेंस में वहाँ मैसेज को अब उपयोग न होने वाला चिह्नित किया गया है।
जवाब का हेडर, जिसका estimated_time_to_regain_access बताता है कि सीमा पर रोकी गई कॉल कितने मिनट बाद फिर काम करेंगी।
वह messaging_type जो Page को मिले मैसेज के जवाब के लिए है, जो 24 घंटे की विंडो के भीतर भेजा जाता है।
निजी जवाब यह तय करता है कि कमेंट करने वाले व्यक्ति को कैसे संबोधित किया जाए, उसी /{page-id}/messages एंडपॉइंट के माध्यम से।
उदाहरण चलने से पहले क्या चाहिए?
Page ID और उस Page का एक्सेस टोकन, जो लंबे समय वाले यूज़र टोकन से /me/accounts में पढ़ा जाता है, साथ में Python 3 और requests, या Node.js 18 या बाद का, जिसका बिल्ट-इन fetch किसी पैकेज की ज़रूरत नहीं रखता। हर काम के लिए टोकन पर उसकी अनुमति और Page पर उसका टास्क भी चाहिए, और उदाहरण Graph API v26.0 को कॉल करते हैं:
Python में पोस्ट और फ़ोटो कैसे प्रकाशित करें?
एक सहायक फ़ंक्शन के साथ, जिसे बाद के सभी उदाहरण दोबारा इस्तेमाल करते हैं: 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 में ये कैसे प्रकाशित होते हैं?
उसी सहायक फ़ंक्शन से Node.js 18 या बाद के संस्करण में, .mjs फ़ाइल के रूप में सहेजकर ताकि top-level await काम करे, और किसी क्लाइंट लाइब्रेरी की जगह बिल्ट-इन fetch के साथ। फ़ोटो कॉल url और caption भेजती है, जो photos एज का text फ़ील्ड है; Meta उसका जवाब फ़ोटो की id और उस Page पोस्ट की 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 से सबसे नए पहले, फिर Page के रूप में कमेंट के अपने 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 backNode.js में कमेंट कैसे पढ़ें और उनका जवाब कैसे दें?
वही दो कॉल, 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 का जवाब कैसे भेजें?
POST /{page-id}/messages, जिसमें recipient.id मैसेज वेबहुक से मिली व्यक्ति की Page-scoped ID है, messaging_type RESPONSE और text। उदाहरण वे दो अस्वीकृतियाँ पकड़ता है जिन्हें दोबारा कोशिश करने लायक नहीं माना गया: गड़बड़ी 10 का सबकोड 2534022 या 2018278, जब 24 घंटे की विंडो बंद हो चुकी हो, और 551, जब व्यक्ति उपलब्ध न हो। private_reply() ID की जगह recipient.comment_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 में, जिसमें 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 इनसाइट कैसे पढ़ें?
GET /{page-id}/insights, कॉमा से अलग मेट्रिक की सूची, period=day, और UNIX सेकंड में since और until विंडो के साथ; एक अनुरोध 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() से सेकंड में निकाले जाते हैं। हर मेट्रिक अपने नाम, अवधि और 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 में वेबहुक सिग्नेचर कैसे सत्यापित करें?
कच्ची रिक्वेस्ट बॉडी और ऐप सीक्रेट से X-Hub-Signature-256 दोबारा गणना करें, फिर दोनों की तुलना स्थिर समय में करें। Meta हर POST पर पेलोड के HMAC-SHA256 से हस्ताक्षर करता है, जो App Dashboard की बेसिक सेटिंग में 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 में वेबहुक सिग्नेचर कैसे सत्यापित करें?
वही जाँच 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 या आपका अपना एजेंट कनेक्टेड Page पर कॉल करता है, टोकन easyCoexistence के पास रहता है। Page टोकन कभी सौंपे नहीं जाते, इसलिए ऊपर के उदाहरण आपके अपने Meta ऐप के टोकन पर चलते हैं; get_social_credentials Page की ID और Graph API बेस लौटाता है। हर काम का टूल:
आम गड़बड़ियाँ
- Page एंडपॉइंट को यूज़र टोकन से कॉल करना। इनमें से ज़्यादातर Page का अपना टोकन माँगते हैं, और यूज़र या ऐप टोकन से की गई कॉल Page की रेट लिमिट के बजाय उन्हीं की रेट लिमिट में गिनी जाती हैं।
- एक के बाद एक वही टेक्स्ट दो बार प्रकाशित करना। Meta लगातार एक जैसी पोस्ट को गड़बड़ी 506 से ठुकराता है, इसलिए दोबारा चलने वाले काम को कंटेंट बदलना होगा या पोस्ट छोड़नी होगी।
- दैनिक अनोखे दर्शकों को जोड़ना। page_total_media_view_unique हर अवधि में अनोखे दर्शक गिनता है, इसलिए दैनिक मान योग नहीं होते; इसके बजाय period days_28 माँगें।
- Page टोकन को ब्राउज़र या ऐप में भेजना। ये कॉल सर्वर पर होनी चाहिए, जहाँ टोकन उस किसी की पहुँच से बाहर रहे जो क्लाइंट पढ़ सकता है।
हर कनेक्शन के लिए प्रति माह 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 का एक रखें और मेल खाते PAGE_ID और PAGE_TOKEN पास करें; Page टोकन से की गई कॉल उसी Page की रेट लिमिट में गिनी जाती हैं।
Messenger के जवाब के लिए PSID कहाँ से आता है?
मैसेज वेबहुक से: हर messaging इवेंट में sender.id व्यक्ति की Page-scoped ID है, जो उस व्यक्ति और Page के लिए अनोखी है। Facebook Login के यूज़र ID ऐप-scoped होते हैं और Messenger Platform के साथ काम नहीं करते।
Facebook Page के लिए easyCoexistence कितना खर्च होता है?
हर कनेक्टेड Page एक कनेक्शन गिना जाता है, जिसकी कीमत कुल कनेक्शन की संख्या पर निर्भर करते हुए प्रति कनेक्शन प्रति माह US$ 9 से US$ 0.75 तक है, और पहले 3 दिन मुफ़्त हैं; MCP टूल इसी में शामिल हैं।
पढ़ना जारी रखें
दो मिनट में अपना पहला चैनल कनेक्ट करें।
किसी प्लैटफ़ॉर्म की समीक्षा का इंतज़ार नहीं। WhatsApp, Instagram, TikTok या कोई और चैनल कनेक्ट करें, फिर अपने AI से पोस्ट करने, जवाब देने या रिपोर्ट बनाने को कहें और उसे काम करते देखें।
- 3 दिन मुफ़्त
- कभी भी रद्द करें
- सिर्फ़ आधिकारिक एपीआई
- 24/7 निगरानी
इस तारीख को सत्यापित