Python සහ Node.js හි Facebook Pages API: ක්රියාත්මක උදාහරණ
Python සහ Node.js, Page හි access token එක සමඟ graph.facebook.com/v26.0 වෙත සරල HTTPS requests ලෙස Facebook Pages API ඇමතුම් කරයි: POST /{page-id}/feed සහ /{page-id}/photos ප්රකාශනය කරයි, /{post-id}/comments comments කියවා ඒවාට පිළිතුරු දෙයි, POST /{page-id}/messages Messenger හි පිළිතුරු දෙයි, GET /{page-id}/insights metrics කියවයි, සහ එක් එක් webhook හි X-Hub-Signature-256 පරීක්ෂා කරන්නේ raw body හි HMAC-SHA256 මගිනි.
easyCoexistence මෙම කාර්යයන් connected Page එකකට MCP tools ලෙස ලබා දෙයි, publish_facebook_post සිට reply_to_comment සහ send_social_dm සහ get_social_insights දක්වා, එහි events X-EC-Signature සමඟ අත්සන් කර යවයි, සහ ඔබේ තමන්ගේ කේතයට get_social_credentials හරහා Page ID සහ API base දෙයි.
Page photo හි text parameter; Meta හි photos reference මෙය එහි deprecated ලෙස සලකුණු කරයි.
ප්රතිචාර header එක, estimated_time_to_regain_access, සීමා ඉක්මවූ calls නැවත ක්රියාත්මක වන තෙක් විනාඩි ගණන දෙයි.
Page එකට ලැබුණු පණිවිඩයකට පිළිතුරක් සඳහා messaging_type, පැය 24 කාල සීමාව තුළ යවන්න.
Comment කළ පුද්ගලයාට පෞද්ගලික reply එක යවන ආකාරය, එකම /{page-id}/messages endpoint එක හරහා.
උදාහරණ ක්රියාත්මක වීමට පෙර ඊට අවශ්ය දේවල් මොනවාද?
Page ID එකක් සහ එම Page හි access token එක, දිගුකාලීන user token එකක් සමඟ /me/accounts වෙතින් කියවා ගන්න; ඊට අමතරව Python 3 සහ requests, නැතහොත් Node.js 18 හෝ ඊට වැඩි, එහි built-in fetch සඳහා package එකක් අවශ්ය නොවේ. එක් එක් කාර්යයට token එකෙහි එහි permission එකක් සහ Page හි එහි task එකක් ද අවශ්යයි, උදාහරණ Graph API v26.0 ඇමතීමට:
Python හි post සහ photo ප්රකාශනය කරන්නේ කෙසේද?
පසුව එන උදාහරණ නැවත භාවිතා කරන එක helper එකකින්: graph() එකතු කරන්නේ Page token එක, GET parameters query string එකෙහි සහ POST fields JSON ලෙස යවයි, Meta හි තමන්ගේම උදාහරණ මෙන්, සහ Meta හි error object එක GraphError එකක් බවට හරවයි, එහි code සහ error_subcode සහිතව. තාවකාලික සහ rate-limit කේත සඳහා පමණක් රැඳී සිට නැවත උත්සාහ කරයි, X-Business-Use-Case-Usage එය ඉල්ලන තුරු, එම header එක පැමිණෙන විට; අනෙක් ඒවා වහාම දෝෂයක් ලෙස ඉහළ යවයි.
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 හි ඒවා ප්රකාශනය කරන්නේ කෙසේද?
එම එකම helper එක Node.js 18 හෝ ඊට වැඩි හි, top-level await ක්රියා කිරීමට .mjs file එකක් ලෙස සුරකින ලද, සහ client library එකක් වෙනුවට built-in fetch භාවිතයෙන්. photo call එක url සහ caption යවයි, එය photos edge එකෙහි text field එකයි; Meta පිළිතුරු දෙන්නේ photo එකෙහි id සහ photo එක දරන Page post එකෙහි post_id ලෙස, feed call එක පිළිතුරු දෙන්නේ post එකෙහි 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 හි comments කියවීමට සහ ඒවාට පිළිතුරු දීමට කෙසේද?
Post එකක comments fields සමඟ කියවන්න: filter=stream සියලු මට්ටම්වල comments කාලානුක්රමිකව සඳහා, සහ order=reverse_chronological නවතම පළමුව; ඉන්පසු comment එකේම comments edge එකට පණිවිඩයක් POST කර Page ලෙස පිළිතුරු දෙන්න. Token එක MODERATE කළ හැකි කෙනෙකුගෙන් විය යුතුයි, නැතහොත් Meta comment 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 හි comments කියවීමට සහ ඒවාට පිළිතුරු දීමට කෙසේද?
එම calls දෙකම, URL object එක query string එක සාදයි: fields, filter සහ order සමඟ GET එකක්, ඉන්පසු /{comment-id}/comments වෙත POST එකක්. fields හි ඉල්ලන can_reply_privately, Page හට එම comment කළ තැනැත්තාට තවමත් පෞද්ගලික පිළිතුරක් යැවිය හැකිද යන්න කියයි, පහත Messenger උදාහරණයට පෙර දැන ගැනීම වටී. ඔබ පිළිතුරු දුන් comments හි 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 පිළිතුරක් යවන්නේ කෙසේද?
POST /{page-id}/messages, recipient.id ලෙස messages webhook එකෙන් ලැබෙන පුද්ගලයාගේ Page-scoped ID එක, messaging_type RESPONSE සහ text සමඟ. උදාහරණය නැවත උත්සාහ කිරීම ප්රයෝජනවත් නොවන දෝෂ දෙක අල්ල ගනී: දෝෂ 10, subcode 2534022 හෝ 2018278 සමඟ, පැය 24 කාල සීමාව වැසුණු විට; සහ 551, පුද්ගලයා ලබා ගත නොහැකි විට. private_reply() recipient.comment_id ID එක වෙනුවට දමයි, comment එකකට දින 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 පිළිතුරක් යවන්නේ කෙසේද?
එම request body එකම JavaScript හි: recipient, messaging_type සහ message field එක JSON ලෙස graph() මගින් යවයි. Meta පිළිගත් යැවීමකට recipient_id සහ message_id ලෙස පිළිතුරු දෙයි, සංවාදය සමඟ ගබඩා කිරීම වටී. පෞද්ගලික පිළිතුරක් එය පිළිතුරු දෙන comment එකට ආපසු සබැඳියක් දරයි, සහ පුද්ගලයා ආපසු ලියූ විට සංවාදය සම්මත පැය 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 කියවන්නේ කෙසේද?
GET /{page-id}/insights, කොමා වලින් වෙන් කළ metrics ලැයිස්තුවක්, period=day සහ UNIX තත්පරවලින් since සහ until කාල සීමාවක්; එක් request එකකින් දින 90 දක්වා ආවරණය වේ. මෙම metrics තුනක් Meta ඉවත් කළ ඒවා වෙනුවට ආදේශ වේ: page_impressions වෙනුවට page_media_view, page_impressions_unique වෙනුවට page_total_media_view_unique, සහ page_fans වෙනුවට page_follows; page_post_engagements ප්රතික්රියා, 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 කියවන්නේ කෙසේද?
එම call එකම, since සහ until Date.now() වලින් තත්පර වලින් ගණනය කරමින්. එක් එක් metric එක එහි නම, period සහ value සහ end_time යුගල ලැයිස්තුවක් සමඟ පැමිණෙයි, දිනකට එකක්; since සෙට් කළ විට, පළමු end_time එය ඊළඟ දිනට වැටේ, එවිට එම දිනයේ දත්ත ඇතුළත් වේ. token එකට read_insights සහ pages_read_engagement අවශ්යයි, ANALYZE task එක ඇති කෙනෙකුගෙන්.
// 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 අත්සන පරීක්ෂා කරන්නේ කෙසේද?
X-Hub-Signature-256 අමු request body එකෙන් සහ App Secret එකෙන් නැවත ගණනය කර, දෙක නියත කාලයකින් සසඳන්න. Meta එක් POST එකක් payload එකේ HMAC-SHA256 සමඟ අත්සන් කරයි, App Dashboard හි මූලික සැකසුම් වලින් ලබන App Secret යතුර භාවිතයෙන්, එය sha256= ට පසුව ලියයි. body එක 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 හි webhook අත්සන පරීක්ෂා කරන්නේ කෙසේද?
එම පරීක්ෂාවම node:crypto සමඟ, body එක Buffer ලෙස අවශ්යයි: Express හි express.raw එම route එකේ එය parse නොකර තබයි. timingSafeEqual විවිධ දිගයේ inputs මත දෝෂ දමයි, එබැවින් දිග පරීක්ෂාව පළමුව ක්රියා කරයි. 200 ඉක්මනින් පිළිතුරු දී වැඩ පසුව කරන්න, Meta අසමත් delivery නැවත උත්සාහ කර event එකක් දෙවරක් යැවිය හැකි නිසා; verification පිටුව hub.challenge handshake ආවරණය කරයි, ඕනෑම event එකකට පෙර එන.
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 හි දෝෂ මාර්ගෝපදේශ වෙන් කරන ඒවා, මන්ද එක් එකකට වෙනස් ප්රතිචාරයක් අවශ්යයි: ප්රතික්ෂේප වූ token එකක් හෝ වැරදි parameter එකක් නැවත උත්සාහ කිරීම ආපසු අසමත් වේ, සීමා ඉක්මවූ call එකක් කලක් රැඳී සිට සාර්ථක වේ. graph() තාවකාලික සහ rate-limit කේත නැවත උත්සාහ කරයි, අනෙක් ඒවා ඇමතුම්කරුට හැසිරවීමට ඉහළ යවයි:
easyCoexistence හරහා එම කාර්යයන් ධාවනය කරන්නේ කෙසේද?
MCP tools ලෙස, Claude, ChatGPT හෝ ඔබේ තමන්ගේ agent සම්බන්ධිත Page එකක් මත කැඳවයි, token එක easyCoexistence විසින් තබා ගනී. Page tokens කිසි විටෙක ලබා නොදේ, එබැවින් ඉහත උදාහරණ ධාවනය වන්නේ ඔබේම Meta යෙදුමක token එකකිනි; get_social_credentials Page හි ID සහ Graph API base දෙයි. එක් එක් කාර්යයේ tool:
සාමාන්ය වැරදි
- Page endpoints වලට user token එකකින් කැඳවීම. බොහෝ ඒවා බලාපොරොත්තු වන්නේ Page හි තමන්ගේම token එකයි; user හෝ app token එකකින් කරන calls, Page හි rate limits වෙනුවට ඒවාට එරෙහිව ගණන් වේ.
- එකම පෙළ දෙවරක් යාබද ලෙස ප්රකාශනය කිරීම. Meta දෝෂ 506 සමඟ අඛණ්ඩ අනුපිටපත් post ප්රතික්ෂේප කරයි, එබැවින් නැවත ධාවනය වන කාර්යයක් අන්තර්ගතය වෙනස් කළ යුතුයි හෝ post එක මඟ හැරිය යුතුයි.
- දිනපතා අද්විතීය viewers එකතු කිරීම. page_total_media_view_unique එක් එක් කාල සීමාවේ අද්විතීය viewers ගණන් කරයි, එබැවින් දිනපතා අගයන් මාසයකට එකතු නොවේ; ඒ වෙනුවට period days_28 ඉල්ලන්න.
- Page token එක browser එකකට හෝ app එකකට යැවීම. මෙම calls server එකක තැබිය යුතුයි, එහිදී token එක client එක කියවිය හැකි ඕනෑම කෙනෙකුට ළඟා නොවේ.
එක් සම්බන්ධතාවයකට මාසිකව US$ 9 සිට US$ 0.75 දක්වා, සම්බන්ධතාවයන් එකතු කරන විට අඩු වේ, පළමු දින 3ක නොමිලේ trial කාලය සමඟ.
නිතර අසන ප්රශ්න
Facebook Pages API ඇමතීමට SDK එකක් අවශ්යද?
නැත. Graph API එක JSON සහිත HTTPS වේ, එබැවින් Python හි requests සහ Node.js 18 හෝ ඊට වැඩි හි built-in fetch ප්රමාණවත්, මෙම පිටුවේ උදාහරණ පෙන්වන පරිදි.
එම කේතය Pages කිහිපයකට post කළ හැකිද?
ඔව්. /me/accounts එක් එක් Page සඳහා වෙනම token එකක් ලබා දෙයි, එබැවින් Page එකකට එකක් තබා ගෙන, ගැළපෙන PAGE_ID සහ PAGE_TOKEN යවන්න; Page token එකකින් කරන calls, එම Page හි තමන්ගේම rate limit එකට ගණන් වේ.
Messenger පිළිතුරක් සඳහා PSID එක කොහෙන් ලැබේද?
messages webhook එකෙන්: එක් එක් messaging event එකේ 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 tools එය සමඟ පැමිණේ.
තවදුරටත් කියවන්න
ඔබේ පළමු channel එක මිනිත්තු දෙකකින් සම්බන්ධ කරන්න.
වේදිකා සමාලෝචන සඳහා බලා සිටීමට අවශ්ය නැත. WhatsApp, Instagram, TikTok හෝ වෙනත් channel එකක් සම්බන්ධ කර, පසුව ඔබේ AI හට පළ කිරීමට, ප්රතිචාර දැක්වීමට හෝ වාර්තා කිරීමට පවසා එය වැඩ කරන ආකාරය බලන්න.
- දින 3ක් නොමිලේ
- ඕනෑම වේලාවක අවලංගු කරන්න
- නිල API පමණි
- 24/7 නිරීක්ෂණය කෙරේ
සත්යාපනය කළේ