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 मेट्रिक्स वाचते, आणि प्रत्येक वेबहुकवरील X-Hub-Signature-256 तपासण्यासाठी मूळ बॉडीचा HMAC-SHA256 मोजतात.
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 संदर्भात तिथे मेसेज अप्रचलित म्हणून चिन्हांकित आहे.
Response हेडर, ज्यातील estimated_time_to_regain_access मध्ये थ्रॉटल झालेले कॉल पुन्हा कधी चालतील त्याची मिनिटे दिली जातात.
Page ला आलेल्या मेसेजला उत्तरासाठी messaging_type, जे 24 तासांच्या विंडोमध्ये पाठवले जाते.
खाजगी उत्तर कमेंट करणाऱ्या व्यक्तीला कसे संबोधते, तेही त्याच /{page-id}/messages एंडपॉइंटद्वारे.
उदाहरणे चालवण्यापूर्वी काय लागते?
Page ID आणि त्या Page चे ॲक्सेस टोकन, जे दीर्घकालीन user token वापरून /me/accounts मधून वाचले जाते, तसेच Python 3 आणि requests पॅकेज, किंवा Node.js 18 किंवा नंतरची आवृत्ती, जिच्या अंगभूत fetch ला कोणत्याही पॅकेजची गरज नाही. प्रत्येक कामाला टोकनवर त्याची परवानगी आणि Page वर त्याचा टास्क लागतो, आणि ही उदाहरणे Graph API v26.0 वापरतात:
Python मध्ये पोस्ट आणि फोटो कसे प्रकाशित कराल?
एक हेल्पर वापरून, जो पुढील उदाहरणे पुन्हा वापरतात: graph() Page टोकन जोडते, GET पॅरामीटर्स query string मध्ये आणि POST फील्ड्स JSON स्वरूपात पाठवते, जसे Meta च्या स्वतःच्या उदाहरणांमध्ये केले आहे, आणि Meta चा एरर ऑब्जेक्ट GraphError मध्ये रूपांतरित करते, ज्यात code आणि error_subcode असतात. तात्पुरत्या आणि रेट-लिमिट कोडसाठीच ते थांबून पुन्हा प्रयत्न करते, आणि 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 देऊन उत्तर देते, तर फीड कॉल फक्त पोस्टचा 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 कमेंट IDs वगळतो, आणि उत्तर देण्यासाठी 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 मध्ये कमेंट कसे वाचाल आणि त्यांना उत्तर कसे द्याल?
तेच दोन कॉल, query string URL object तयार करतो: fields, filter आणि order सह GET, नंतर /{comment-id}/comments वर POST. fields मध्ये मागितलेला can_reply_privately सांगतो की Page त्या कमेंट करणाऱ्याला अजूनही खाजगी उत्तर पाठवू शकते का, आणि ते खालील Messenger उदाहरणापूर्वी जाणून घेणे उपयुक्त आहे. ज्या कमेंट्सना उत्तर दिले, त्यांचे IDs जपून ठेवा, म्हणजे पुन्हा चालवल्यावर दोनदा उत्तर जाणार नाही.
// 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 वेबहुकमधून मिळणारा त्या व्यक्तीचा Page-scoped ID, messaging_type RESPONSE आणि text ठेवला जातो. उदाहरण दोन नकार पकडते ज्यांना पुन्हा प्रयत्न करणे योग्य नाही: 24 तासांची विंडो बंद झाल्यास error 10 सह subcode 2534022 किंवा 2018278, आणि व्यक्ती उपलब्ध नसल्यास 551. private_reply() recipient.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 insights कसे वाचाल?
/{page-id}/insights वर GET, स्वल्पविरामाने वेगळी केलेली मेट्रिक यादी, 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 insights कसे वाचाल?
तोच कॉल, since आणि until Date.now() वरून सेकंदांत मोजलेले. प्रत्येक मेट्रिक नाव, period आणि 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 कच्च्या विनंती बॉडी आणि app secret वरून पुन्हा मोजा, नंतर दोन्ही constant time तुलनेत तपासा. Meta प्रत्येक POST वर पेलोडच्या HMAC-SHA256ने स्वाक्षरी करते, App डॅशबोर्ड मधील basic सेटिंग्ज वरील App Secret वापरून, आणि ती sha256= नंतर लिहिते. बॉडी bytes म्हणून पाठवा, कोणत्याही JSON parsing आधी: Django मधील request.body आणि FastAPI मधील await request.body() दोन्ही Meta ने स्वाक्षरी केलेले bytes देतात.
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 त्या route वर ती पार्स न करता ठेवते. 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 एंडपॉइंट्सना user टोकनने कॉल करणे. त्यांतील बहुतेकांना Page चेच स्वतःचे टोकन हवे असते, आणि user किंवा app टोकनने केलेले कॉल Page च्या ऐवजी त्या रेट लिमिट्सवर मोजले जातात.
- सलग एकसारखी पोस्ट दोनदा प्रकाशित करणे. Meta सलग डुप्लिकेट पोस्ट एरर 506 सह नाकारते, त्यामुळे पुन्हा चालणाऱ्या कामाने मजकूर बदलला पाहिजे किंवा पोस्ट वगळली पाहिजे.
- दररोजचे अद्वितीय दर्शक जोडणे. page_total_media_view_unique प्रत्येक period मध्ये अद्वितीय दर्शक मोजते, त्यामुळे रोजची मूल्ये महिन्याला बेरीज होत नाहीत; त्याऐवजी 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 कुठून येतो?
messages वेबहुकमधून: प्रत्येक messaging इव्हेंटमधील sender.id ही त्या व्यक्तीची Page-scoped ID आहे, जी त्या व्यक्तीसाठी आणि Page साठी अद्वितीय असते. Facebook Login मधील user IDs app-scoped असतात आणि Messenger Platform सोबत चालत नाहीत.
Facebook Page साठी easyCoexistence किती खर्च येतो?
प्रत्येक कनेक्टेड Page एक कनेक्शन मोजला जातो, प्रति कनेक्शन दरमहा US$ 9 ते US$ 0.75, तुमच्याकडे किती आहेत त्यानुसार, आणि पहिले 3 दिवस मोफत आहेत; MCP टूल्स त्यासोबतच येतात.
पुढे वाचा
तुमचे पहिले चॅनेल दोन मिनिटांत कनेक्ट करा.
कोणत्याही प्लॅटफॉर्म पुनरावलोकनाची वाट पाहावी लागत नाही. WhatsApp, Instagram, TikTok किंवा दुसरे चॅनेल कनेक्ट करा, मग तुमच्या AI ला पोस्ट करायला, उत्तर द्यायला किंवा रिपोर्ट द्यायला सांगा आणि ते काम करताना पाहा.
- 3 दिवस मोफत
- कधीही रद्द करा
- फक्त अधिकृत एपीआय
- 24/7 देखरेख
पडताळले: