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 को फोटो सन्दर्भले म्यासेजलाई अप्रचलित चिह्न लगाउँछ।
estimated_time_to_regain_access दिने प्रतिक्रिया हेडर, जसले सीमामा परेका कल फेरि चल्न कति मिनेट लाग्छ भन्ने बताउँछ।
Page ले प्राप्त गरेको म्यासेजको जवाफका लागि messaging_type, 24 घण्टाको विन्डोभित्र पठाइएको।
निजी जवाफले कमेन्ट गर्ने व्यक्तिलाई कसरी सम्बोधन गर्छ, त्यही /{page-id}/messages एन्डपोइन्ट मार्फत।
उदाहरण चलाउनुअघि के चाहिन्छ?
Page ID र त्यही Page को एक्सेस टोकन, जुन लामो समय चल्ने user टोकनमार्फत /me/accounts बाट पढिन्छ, साथमा requests सहितको Python 3, वा Node.js 18 वा त्यसभन्दा नयाँ, जसको built-in fetch ले कुनै प्याकेज चाहिँदैन। प्रत्येक काम टोकनमा त्यसको अनुमति र Page मा त्यसको कार्य चाहिन्छ, र उदाहरणहरूले Graph API v26.0 कल गर्छन्:
Python मा पोस्ट र फोटो कसरी प्रकाशित गर्ने?
एउटा सहायक फङ्सनसहित, जसलाई पछिका उदाहरणहरूले पुनः प्रयोग गर्छन्: graph() ले Page को टोकन थप्छ, GET प्यारामिटर query string मा र POST फिल्ड JSON मा पठाउँछ, जसरी Meta का आफ्नै उदाहरणहरूमा हुन्छ, र Meta को error object लाई 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 काम गरोस्, र क्लाइन्ट लाइब्रेरीको सट्टा built-in fetch। फोटो कलले url र caption पठाउँछ, जुन photos edge को 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 ले नयाँ पहिले ल्याउँछ, त्यसपछि कमेन्टको आफ्नै comments edge मा म्यासेज पोस्ट गरेर 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 मा कमेन्ट कसरी पढ्ने र जवाफ कसरी दिने?
उही दुई कल, URL object ले query string बनाउँदै: 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 मा म्यासेज वेबहुकबाट आएको व्यक्तिको Page-scoped ID, messaging_type RESPONSE र text राखिन्छ। उदाहरणले पुनः प्रयास गर्न नलायक दुई अस्वीकृति समात्छ: 24 घण्टाको विन्डो बन्द भएको बेला error 10 सँग subcode 2534022 वा 2018278, र व्यक्ति उपलब्ध नभएको बेला 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 मा उही request body, 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, र since र until विन्डो UNIX सेकेन्डमा; एउटा request ले बढीमा 90 दिन समेट्छ। तीनवटा मेट्रिकले Meta ले हटाएकाहरूको ठाउँ लिएका छन्: page_media_view ले page_impressions को, page_total_media_view_unique ले page_impressions_unique को, र page_follows ले page_fans को ठाउँमा, जबकि page_post_engagements ले reactions, comments र shares गन्छ।
# 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 मा वेबहुक हस्ताक्षर कसरी प्रमाणित गर्ने?
कच्चा अनुरोध बडी र app secret बाट X-Hub-Signature-256 पुनः गणना गर्नुहोस्, त्यसपछि दुई मानलाई constant time मा तुलना गर्नुहोस्। Meta ले प्रत्येक POST लाई payload को HMAC-SHA256 ले हस्ताक्षर गर्छ, App Dashboard को basic settings को App Secret ले कुञ्जी बनाएर, र sha256= पछि लेख्छ। बडी JSON parse गर्नुअघि bytes का रूपमा पठाउनुहोस्: 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 मा बडी parse नगरी राख्छ। timingSafeEqual ले फरक लम्बाइका इनपुटमा त्रुटि फाल्छ, त्यसैले लम्बाइको परीक्षण पहिले चल्छ। छिट्टै 200 फर्काउनुहोस् र काम पछि गर्नुहोस्, किनकि Meta ले असफल डेलिभरी पुनः पठाउँछ र घटना दुई पटक पठाउन सक्छ; verification पृष्ठले कुनै पनि घटनाअघि आउने 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 base फर्काउँछ। प्रत्येक कामको टुल:
सामान्य गल्तीहरू
- Page का एन्डपोइन्टमा user टोकनबाट कल गर्नु। तिनीहरूमध्ये धेरैले Page को आफ्नै टोकन चाहन्छन्, र user वा app टोकनबाट गरिएका कल Page को सट्टा user वा app को दर सीमामा गणना हुन्छन्।
- एउटै text लगातार दुई पटक प्रकाशित गर्नु। Meta ले लगातार दोहोरिएका पोस्ट 506 त्रुटिसँग अस्वीकार गर्छ, त्यसैले पुनः चल्ने काममा सामग्री फरक हुनुपर्छ वा पोस्ट छोड्नुपर्छ।
- दैनिक अद्वितीय दर्शकहरू जोड्नु। page_total_media_view_unique ले हरेक अवधिमा अद्वितीय दर्शक गन्छ, त्यसैले दैनिक मानहरूको योग महिनासँग मिल्दैन; यसको सट्टा period days_28 माग्नुहोस्।
- Page को टोकन browser वा app मा पठाउनु। यी कल सर्भरमा बस्नुपर्छ, जहाँ टोकन क्लाइन्ट पढ्न सक्ने जोसुकैको पहुँचबाहिर रहन्छ।
प्रति जडान प्रति महिना US$ 9 देखि US$ 0.75 सम्म, जडान थप्दै जाँदा घट्दै, पहिलो 3 दिन निःशुल्क।
बारम्बार सोधिने प्रश्नहरू
Facebook Pages API लाई कल गर्न मलाई SDK चाहिन्छ?
पर्दैन। Graph API HTTPS मा JSON हो, त्यसैले Python का अनुरोध र Node.js 18 वा त्यसभन्दा नयाँमा built-in 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 ID app-scoped हुन्छन् र Messenger Platform सँग काम गर्दैनन्।
easyCoexistence ले Facebook Page का लागि कति लाग्छ?
जडान भएको प्रत्येक Page एउटा जडान गनिन्छ, प्रति जडान प्रति महिना US$ 9 देखि US$ 0.75 सम्म, तपाईंसँग कति छन् भन्ने आधारमा, र पहिलो 3 दिन निःशुल्क छ; MCP टुलहरू यसैसँग आउँछन्।
पढ्दै जानुहोस्
दुई मिनेटमै आफ्नो पहिलो च्यानल जडान गर्नुहोस्।
प्लेटफर्मको समीक्षा कुर्नुपर्दैन। WhatsApp, Instagram, TikTok वा अर्को च्यानल जडान गर्नुहोस्, अनि आफ्नो AI लाई पोस्ट गर्न, जवाफ दिन वा रिपोर्ट बनाउन भन्नुहोस् र काम भइरहेको हेर्नुहोस्।
- 3 दिन निःशुल्क
- जुनसुकै बेला रद्द गर्नुहोस्
- आधिकारिक एपीआई मात्र
- 24/7 निगरानी
प्रमाणीकरण गरिएको