Instagram API 在 Python 與 Node.js 的實用範例
Instagram API 只需要 HTTPS,因此 Python 的 requests 與 Node.js 內建的 fetch 已足夠:POST /<IG_ID>/media 後接 media_publish 即可發佈,/<IG_MEDIA_ID>/comments 與 /<IG_COMMENT_ID>/replies 用於讀取及回覆留言,/insights 回傳指標,Webhook 則以原始內容主體的 HMAC-SHA256 進行驗證。每個錯誤都附有 code 與 subcode,決定重試是否有幫助。
easyCoexistence 以 MCP 工具形式運行相同工作,供 Claude、ChatGPT 或你自己的智能代理使用,權杖則由其一方保管:publish_instagram_post、reply_to_comment、get_social_insights 及 set_social_webhook_destination,建基於 Meta 的官方 API。
最新的 Graph API 版本於 2026 年 7 月 29 日推出;v25.0 可使用至 2028 年 7 月 29 日。
Meta 建議查看影片容器 status_code 的頻率,最長不超過 5 分鐘。
一次 GET /<IG_MEDIA_ID>/comments 請求最多回傳的留言數;回覆只能透過欄位展開取得。
暫時性發佈錯誤,Meta 建議在 30 秒至 2 分鐘內重試 1 至 2 次。
X-Hub-Signature-256 的前綴,之後接以應用程式密鑰為鍵的負載 HMAC-SHA256。
示例需要什麼?
一個運行環境、一個權杖及四個值。示例透過 graph.instagram.com 上的 Instagram Login 呼叫 Instagram API;Unified Login 應用程式使用相同路徑,但改用帳戶 ID,並透過 Facebook Login 的 Graph 主機,搭配其 Business Integration System User 權杖。Python 需要 requests 套件,Webhook 另需 Flask;Node.js 則需要 18 或以上版本,以使用其內建的 fetch。
- GRAPH:https://graph.instagram.com/v26.0,即主機與 API 版本。
IG_ID:專業帳戶的 ID,即 GET /me 所回傳的user_id。- TOKEN:長期有效的 Instagram 使用者存取權杖,僅存放於伺服器。
APP_SECRET與VERIFY_TOKEN:用於驗證 Webhook 請求。
如何在 Python 中呼叫 API 及處理錯誤?
透過一個輔助函式,供下方所有 Python 示例共用。它以 access_token 傳送權杖,拋出附有 Meta 的 code、subcode 及 fbtrace_id 的 MetaError,並只重試 Meta 定義為暫時性的錯誤:code 1 及 2、限流 code 4、17 及 80002,以及 subcode 2207001、2207003、2207008 與 2207032。code 4 加上 subcode 2207051 表示疑似垃圾訊息,因此會立即停止。
import json
import time
import requests
GRAPH = "https://graph.instagram.com/v26.0"
IG_ID = "<IG_ID>" # user_id from GET /me
TOKEN = "<TOKEN>" # long-lived Instagram User access token, server side only
RETRY_CODES = {1, 2, 4, 17, 80002}
RETRY_SUBCODES = {2207001, 2207003, 2207008, 2207032}
class MetaError(Exception):
def __init__(self, error: dict, status: int):
super().__init__(error.get("message", f"HTTP {status}"))
self.code = error.get("code")
self.subcode = error.get("error_subcode")
self.fbtrace_id = error.get("fbtrace_id") # log it: Meta support asks for it
@property
def needs_new_token(self) -> bool:
return self.code in (102, 190)
@property
def retryable(self) -> bool:
if self.subcode == 2207051: # code 4 with this subcode is suspected spam: stop
return False
return self.code in RETRY_CODES or self.subcode in RETRY_SUBCODES
def wait_seconds(resp) -> int:
"""estimated_time_to_regain_access from X-Business-Use-Case-Usage, at least 60 s."""
try:
usage = json.loads(resp.headers.get("X-Business-Use-Case-Usage", "{}"))
minutes = max(e.get("estimated_time_to_regain_access", 0) for v in usage.values() for e in v)
except (ValueError, AttributeError, TypeError):
minutes = 0
return max(60, int(minutes) * 60)
def graph(method: str, path: str, attempts: int = 3, **params) -> dict:
if attempts < 1:
raise ValueError("attempts must be at least 1")
params["access_token"] = TOKEN
for attempt in range(1, attempts + 1):
resp = requests.request(method, f"{GRAPH}/{path}", params=params, timeout=30)
try:
data = resp.json()
except ValueError:
data = {}
if resp.ok and "error" not in data:
return data
err = MetaError(data.get("error", {}), resp.status_code)
if not err.retryable or attempt == attempts:
raise err
time.sleep(wait_seconds(resp))如何在 Node.js 中呼叫 API 及處理錯誤?
使用相同的輔助函式,適用於 Node.js 18 或以上版本,以 fetch 實作,無需任何依賴套件。遭限流的呼叫會等待 estimated_time_to_regain_access,即 Meta 在 X-Business-Use-Case-Usage 標頭中報告的分鐘數;若沒有該標頭,則等待 60 秒,因為 Meta 會計算限流期間所發出的呼叫。needsNewToken 會標示 code 190 與 102,這些錯誤無法靠重試修復。
const GRAPH = "https://graph.instagram.com/v26.0";
const IG_ID = process.env.IG_ID; // user_id from GET /me
const TOKEN = process.env.TOKEN; // long-lived Instagram User access token, server side only
const RETRY_CODES = new Set([1, 2, 4, 17, 80002]);
const RETRY_SUBCODES = new Set([2207001, 2207003, 2207008, 2207032]);
export class MetaError extends Error {
constructor(error, status) {
super(error.message ?? `HTTP ${status}`);
this.code = error.code;
this.subcode = error.error_subcode;
this.fbtraceId = error.fbtrace_id; // log it: Meta support asks for it
}
get needsNewToken() {
return this.code === 190 || this.code === 102;
}
get retryable() {
if (this.subcode === 2207051) return false; // code 4 with this subcode is suspected spam: stop
return RETRY_CODES.has(this.code) || RETRY_SUBCODES.has(this.subcode);
}
}
export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// estimated_time_to_regain_access from X-Business-Use-Case-Usage, at least 60 s
function waitMs(res) {
try {
const usage = JSON.parse(res.headers.get("x-business-use-case-usage") ?? "{}");
const minutes = Math.max(0, ...Object.values(usage).flat().map((e) => e.estimated_time_to_regain_access ?? 0));
return Math.max(60, minutes * 60) * 1000;
} catch {
return 60_000;
}
}
export async function graph(method, path, params = {}, attempts = 3) {
const url = new URL(`${GRAPH}/${path}`);
for (const [key, value] of Object.entries({ ...params, access_token: TOKEN })) {
url.searchParams.set(key, String(value));
}
for (let attempt = 1; attempt <= attempts; attempt++) {
const res = await fetch(url, { method });
const data = await res.json().catch(() => ({}));
if (res.ok && !data.error) return data;
const err = new MetaError(data.error ?? {}, res.status);
if (!err.retryable || attempt === attempts) throw err;
await sleep(waitMs(res));
}
throw new Error("attempts must be at least 1");
}如何在 Python 中發佈相片與 Reel?
兩者都遵循容器流程。相片容器即時就緒,因此 media_publish 緊接其後執行。Reel 的影片需先處理:函式依 Meta 的建議每分鐘檢查一次 status_code,最長 5 分鐘,遇到 FINISHED 即發佈,遇到 ERROR 或 EXPIRED 則停止。圖片必須為 JPEG,且媒體須位於公開網址。
# Uses graph(), IG_ID and time from the helper above
def publish_photo(image_url: str, caption: str) -> str:
"""A JPEG at a public URL: create the container, then publish it."""
container = graph("POST", f"{IG_ID}/media", image_url=image_url, caption=caption)
return graph("POST", f"{IG_ID}/media_publish", creation_id=container["id"])["id"]
def publish_reel(video_url: str, caption: str) -> str:
"""A Reel: publish once Meta has processed the video, checking once a minute."""
cid = graph("POST", f"{IG_ID}/media", media_type="REELS", video_url=video_url, caption=caption)["id"]
for _ in range(5): # Meta: once a minute, for no more than 5 minutes
time.sleep(60)
status = graph("GET", cid, fields="status_code")["status_code"]
if status == "FINISHED":
return graph("POST", f"{IG_ID}/media_publish", creation_id=cid)["id"]
if status in ("ERROR", "EXPIRED"):
raise RuntimeError(f"Container {cid} ended as {status}")
raise TimeoutError(f"Container {cid} is still processing: check it again later")如何在 Node.js 中發佈相片與 Reel?
與 Python 相同的兩個函式,各自回傳新媒體的 ID。容器若在五次檢查後仍為 IN_PROGRESS,會在建立後 24 小時內保持有效,因此錯誤訊息建議稍後再次檢查,以免超出帳戶每日 400 次的容器上限而另建一個容器。
// Uses graph(), sleep() and IG_ID from the helper above
export async function publishPhoto(imageUrl, caption) {
const { id } = await graph("POST", `${IG_ID}/media`, { image_url: imageUrl, caption });
return (await graph("POST", `${IG_ID}/media_publish`, { creation_id: id })).id;
}
export async function publishReel(videoUrl, caption) {
const { id } = await graph("POST", `${IG_ID}/media`, { media_type: "REELS", video_url: videoUrl, caption });
for (let check = 0; check < 5; check++) {
await sleep(60_000); // Meta: once a minute, for no more than 5 minutes
const { status_code: status } = await graph("GET", id, { fields: "status_code" });
if (status === "FINISHED") return (await graph("POST", `${IG_ID}/media_publish`, { creation_id: id })).id;
if (status === "ERROR" || status === "EXPIRED") throw new Error(`Container ${id} ended as ${status}`);
}
throw new Error(`Container ${id} is still processing: check it again later`);
}如何在 Python 中讀取留言並回覆?
GET /<IG_MEDIA_ID>/comments 會按最新排序回傳頂層留言,每次請求最多 50 則;POST /<IG_COMMENT_ID>/replies 則公開回覆其中一則留言。函式會向你的回呼函式索取每則回覆的文字,並跳過回呼函式未回傳任何內容的留言。隱藏的留言無法回覆,而對回覆的回覆會歸入頂層留言。
# Uses graph() from the helper above
def reply_to_comments(media_id: str, write_reply) -> int:
"""Reply in public to each comment write_reply returns text for."""
page = graph("GET", f"{media_id}/comments", fields="id,text,username,timestamp")
sent = 0
for comment in page.get("data", []):
text = write_reply(comment)
if text:
graph("POST", f"{comment['id']}/replies", message=text)
sent += 1
return sent
# Example: reply to questions about price
reply_to_comments("<IG_MEDIA_ID>", lambda c: "Prices are in our bio link." if "price" in c["text"].lower() else None)如何在 Node.js 中讀取留言並回覆?
在 Node.js 中採用相同的迴圈。兩個呼叫都需要 instagram_business_basic 與 instagram_business_manage_comments 權限,而 username 欄位需要後者。若要改為私下回覆,可使用 POST /<IG_ID>/messages 並帶入 recipient.comment_id,在留言後 7 天內向留言者發送一則私訊;後續訊息須待對方回覆後才能發出。
// Uses graph() from the helper above
// Reply in public to each comment writeReply returns text for
export async function replyToComments(mediaId, writeReply) {
const { data = [] } = await graph("GET", `${mediaId}/comments`, { fields: "id,text,username,timestamp" });
let sent = 0;
for (const comment of data) {
const text = writeReply(comment);
if (text) {
await graph("POST", `${comment.id}/replies`, { message: text });
sent++;
}
}
return sent;
}
// Example: reply to questions about price
await replyToComments("<IG_MEDIA_ID>", (c) => (/price/i.test(c.text) ? "Prices are in our bio link." : null));如何在 Python 中讀取洞察報告?
帳戶洞察報告使用 period=day 與 metric_type=total_value,每個指標隨後回報 total_value.value;貼文的洞察報告則回傳 values[0].value。示例在帳戶層面請求 reach、views 與 accounts_engaged,在貼文或 Reel 層面請求 reach、views、likes、comments、saved 與 shares,這些均列於 Meta 的參考文件中。沒有數據的指標會被略去,而非回傳 0。
# Uses graph() and IG_ID from the helper above
def account_insights() -> dict:
"""Reach, views and accounts engaged over the last 24 hours."""
data = graph("GET", f"{IG_ID}/insights", metric="reach,views,accounts_engaged",
period="day", metric_type="total_value")["data"]
return {m["name"]: m["total_value"]["value"] for m in data}
def post_insights(media_id: str) -> dict:
"""Totals for one post or Reel."""
data = graph("GET", f"{media_id}/insights", metric="reach,views,likes,comments,saved,shares")["data"]
return {m["name"]: m["values"][0]["value"] for m in data}如何在 Node.js 中讀取洞察報告?
在 Node.js 中同樣發出兩個請求,各自回傳以指標名稱為鍵的物件。兩者都不傳送 breakdown:Meta 警告,若請求某指標不支援的 breakdown,請求會以未知錯誤失敗;此外,洞察報告數據可能延遲最多 48 小時,因此應稍後再次讀取近期貼文。
// Uses graph() and IG_ID from the helper above
// Reach, views and accounts engaged over the last 24 hours
export async function accountInsights() {
const { data } = await graph("GET", `${IG_ID}/insights`, {
metric: "reach,views,accounts_engaged",
period: "day",
metric_type: "total_value",
});
return Object.fromEntries(data.map((m) => [m.name, m.total_value?.value]));
}
// Totals for one post or Reel
export async function postInsights(mediaId) {
const { data } = await graph("GET", `${mediaId}/insights`, { metric: "reach,views,likes,comments,saved,shares" });
return Object.fromEntries(data.map((m) => [m.name, m.values?.[0]?.value]));
}如何在 Python 中驗證 Webhook?
使用 Flask,在同一路徑上設兩個路由。GET 回應 Meta 的驗證請求:當 hub.mode 為 subscribe 且 hub.verify_token 吻合時,以純文字回傳 hub.challenge,否則回傳 403。POST 會以應用程式密鑰計算原始內容主體的 HMAC-SHA256,並加上 sha256= 前綴,然後以恆定時間與 X-Hub-Signature-256 比較,並在任何耗時工作開始前回應 200。
import hashlib
import hmac
import json
import os
from queue import Queue
from flask import Flask, abort, request
app = Flask(__name__)
VERIFY_TOKEN = os.environ["VERIFY_TOKEN"]
APP_SECRET = os.environ["APP_SECRET"].encode()
jobs: Queue = Queue() # swap for your own job queue
@app.get("/webhooks/instagram")
def verify():
"""Meta's verification request: send hub.challenge back when the token matches."""
args = request.args
if args.get("hub.mode") == "subscribe" and args.get("hub.verify_token") == VERIFY_TOKEN:
return args.get("hub.challenge", ""), 200, {"Content-Type": "text/plain"}
abort(403)
@app.post("/webhooks/instagram")
def receive():
"""An event: check X-Hub-Signature-256 over the raw bytes, then answer at once."""
raw = request.get_data()
expected = b"sha256=" + hmac.new(APP_SECRET, raw, hashlib.sha256).hexdigest().encode()
if not hmac.compare_digest(expected, request.headers.get("X-Hub-Signature-256", "").encode()):
abort(401)
for entry in json.loads(raw).get("entry", []):
jobs.put(entry) # slow work happens elsewhere; Meta wants a quick 200
return "", 200如何在 Node.js 中驗證 Webhook?
使用內建的 http 模組,不採用任何框架。在任何解析之前,主體先以原始位元組收集,因為經解析再重新序列化的主體,將不再符合 Meta 計算的簽名。Meta 會在最多 36 小時內重試失敗的通知,因此處理程式亦應略過已處理過的事件。
import crypto from "node:crypto";
import http from "node:http";
const { VERIFY_TOKEN, APP_SECRET } = process.env;
const PATH = "/webhooks/instagram";
const jobs = []; // swap for your own job queue
http
.createServer((req, res) => {
const url = new URL(req.url, "http://localhost");
if (url.pathname !== PATH) return res.writeHead(404).end();
if (req.method === "GET") {
// Meta's verification request: send hub.challenge back when the token matches
const ok =
url.searchParams.get("hub.mode") === "subscribe" &&
url.searchParams.get("hub.verify_token") === VERIFY_TOKEN;
return res
.writeHead(ok ? 200 : 403, { "Content-Type": "text/plain" })
.end(ok ? url.searchParams.get("hub.challenge") ?? "" : "");
}
const chunks = [];
req.on("data", (chunk) => chunks.push(chunk));
req.on("end", () => {
const raw = Buffer.concat(chunks); // the exact bytes Meta signed
const expected = Buffer.from("sha256=" + crypto.createHmac("sha256", APP_SECRET).update(raw).digest("hex"));
const given = Buffer.from(req.headers["x-hub-signature-256"] ?? "");
if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) {
return res.writeHead(401).end();
}
res.writeHead(200).end(); // answer first, work after
try {
for (const entry of JSON.parse(raw.toString("utf8")).entry ?? []) jobs.push(entry);
} catch {
// not JSON: nothing to queue
}
});
})
.listen(3000);代碼應重試哪些 Meta 錯誤?
只重試暫時性錯誤,因為其他錯誤在情況改變之前會一再得到相同結果,情況包括檔案、網址、權限或帳戶狀態。Meta 的錯誤參考文件列出了上述輔助函式所區分的每個錯誤代碼,以及對應的處理動作:
如何在 easyCoexistence 的憑證上執行同一套程式碼?
無法使用 easyCoexistence 的權杖來運行:Instagram 權杖永遠不會交出(Meta 的條款),因此 get_social_credentials 及 Partner API 的 GET /api/v1/channels/:id?credentials=1 只會回傳帳戶的 ID 及 API 基礎網址,不含權杖。相同的工作改以 MCP 工具運行,可透過 Claude、ChatGPT 或其他 MCP 客戶端使用;上述輔助函式則可在你自己的 Meta 應用程式所取得的權杖上,無需任何修改即可運行。
{
"platform": "instagram",
"graph_api_base": "https://graph.instagram.com/<VERSION>",
"account_id_on_meta": "<IG_ID>",
"access_token": null,
"token_note": "Meta's terms do not allow handing this account's access token to other apps, so it is not shown. ..."
}如何透過 MCP 連接器完成相同的工作?
透過向助理提出要求,或自行呼叫工具。publish_instagram_post 會建立並發佈容器,並在影片處理期間等待,或以 scheduled_at 排程最多 90 天後的發佈;reply_to_comment 會公開回覆,若 private 設為 true 則改以私訊回覆;get_social_insights 會將指標名稱直接傳遞給 Meta;set_social_webhook_destination 則將留言、提及及私訊轉發至你的端點,並以 X-EC-Signature 簽署。
[
{
"name": "publish_instagram_post",
"arguments": {
"account_id": "<from list_social_accounts>",
"type": "REELS",
"video_url": "https://cdn.example.com/launch.mp4",
"caption": "Launch day.",
"scheduled_at": "2026-11-06T09:00:00-03:00"
}
},
{
"name": "list_social_comments",
"arguments": { "account_id": "<ACCOUNT_ID>", "post_id": "<IG_MEDIA_ID>" }
},
{
"name": "reply_to_comment",
"arguments": { "account_id": "<ACCOUNT_ID>", "comment_id": "<IG_COMMENT_ID>", "text": "Prices are in our bio link." }
},
{
"name": "get_social_insights",
"arguments": {
"account_id": "<ACCOUNT_ID>",
"metrics": ["reach", "views", "accounts_engaged"],
"period": "day",
"params": { "metric_type": "total_value" }
}
},
{
"name": "set_social_webhook_destination",
"arguments": { "account_id": "<ACCOUNT_ID>", "url": "https://hooks.example.com/instagram" }
}
]常見錯誤
- 對已解析的 JSON 計算雜湊。Meta 簽署的是原始位元組,因此框架的 JSON 主體解析器會令 X-Hub-Signature-256 驗證失敗;應保留原始內容主體,之後再解析。
- 逾時後未先檢查便再次呼叫 media_publish。若容器的 status_code 顯示 PUBLISHED,則貼文已經發佈。
- 未看 subcode 便將 code 4 視為限流。若 subcode 為 2207051,表示 Instagram 疑似垃圾訊息,重試會再次執行剛被限制的動作。
- 從瀏覽器或行動裝置代碼傳送應用程式密鑰或權杖。Meta 指出,附帶應用程式密鑰的請求只應置於伺服器端代碼中。
每個連接每月 US$ 9 至 US$ 0.75,連接越多越便宜,前 3 天免費。
常見問題
我需要 SDK 才能呼叫 Instagram API 嗎?
不需要。每次呼叫都是附帶存取權杖的 HTTPS 請求,因此 Python 的 requests 或 Node.js 的 fetch 已足夠,本頁示例亦已展示。
為何在建立 Reel 容器後,media_publish 會立即失敗?
影片仍在處理中,錯誤為 9007,subcode 為 2207027。請每分鐘檢查一次容器的 status_code,待其顯示 FINISHED 時再發佈。
代碼應使用哪個 API 版本?
Meta 仍提供的版本中,v26.0 為最新版本,且每個版本至少維持兩年。呼叫已移除的版本時,會改由下一個仍可用的較舊版本執行。
easyCoexistence 為 Instagram 帳戶的 API 存取收費多少?
每個 Instagram 帳戶即一個連接:每個連接每月 US$ 9 至 US$ 0.75,連接越多越便宜,前 3 天免費。
繼續閱讀
兩分鐘內連接您的第一個頻道。
無需等待平台審核。連接 WhatsApp、Instagram、TikTok 或其他頻道,然後請您的 AI 發佈貼文、回覆訊息或匯報數據,並看着它運作。
- 免費試用 3 天
- 隨時取消
- 只用官方 API
- 24/7 監察
驗證日期