如何获取Instagram Graph API长期令牌实现自动化发帖、评论与私信
Instagram Graph API长期访问令牌获取与脚本集成方案
一、获取长期访问令牌(有效期60天,可刷新)
前置条件
你已具备:
- 关联Instagram专业账户的Facebook主页
- 完成验证的Facebook开发者应用
- 从API Explorer获取的短期用户访问令牌(需包含权限:
pages_show_list,pages_read_engagement,instagram_basic,instagram_manage_comments,instagram_manage_messages,publish_content,publish_video)
步骤1:换取Facebook主页长期令牌
调用Graph API接口,用短期用户令牌换取主页长期令牌:
GET /{你的FB主页ID}?fields=access_token Authorization: Bearer {你的短期用户访问令牌}
返回的access_token即为主页长期令牌,有效期60天。
步骤2:换取Instagram账户长期令牌
用主页长期令牌调用接口,获取关联IG账户的长期令牌:
GET /{你的IG用户ID}?fields=access_token Authorization: Bearer {你的主页长期访问令牌}
返回的access_token就是可直接在脚本中使用的IG长期访问令牌,有效期60天。
步骤3:令牌刷新(保持长期有效)
当令牌临近过期时,重复步骤1-2即可完成刷新,无需重新走OAuth授权流程。
二、脚本集成示例
通用注意事项
- 公开使用需提交应用审核,确保所需权限通过审核;测试阶段可添加指定测试用户
- 所有API请求需携带
access_token参数或放在Authorization请求头中
1. Express.js 示例
依赖安装
npm install axios
核心代码
const axios = require('axios'); // 配置参数 const IG_USER_ID = '你的IG用户ID'; const LONG_LIVED_TOKEN = '你的IG长期访问令牌'; // 发布优惠帖子(图片示例) async function publishOfferPost(imageUrl, caption) { try { // 上传图片到IG媒体库 const uploadRes = await axios.post( `https://graph.facebook.com/v18.0/${IG_USER_ID}/media`, { image_url: imageUrl, caption: caption, access_token: LONG_LIVED_TOKEN } ); const mediaId = uploadRes.data.id; // 发布媒体内容 await axios.post( `https://graph.facebook.com/v18.0/${IG_USER_ID}/media_publish`, { creation_id: mediaId, access_token: LONG_LIVED_TOKEN } ); console.log('优惠帖子发布成功'); } catch (err) { console.error('发布失败:', err.response.data); } } // 监测并回复特定评论(定时拉取) async function monitorComments() { try { const res = await axios.get( `https://graph.facebook.com/v18.0/${IG_USER_ID}/media?fields=comments{id,message}&access_token=${LONG_LIVED_TOKEN}` ); res.data.data.forEach(media => { if (media.comments?.data) { media.comments.data.forEach(comment => { // 匹配关键词(如“求链接”) if (comment.message.includes('求链接')) { axios.post( `https://graph.facebook.com/v18.0/${comment.id}/replies`, { message: '优惠链接:[你的链接]', access_token: LONG_LIVED_TOKEN } ); } }); } }); } catch (err) { console.error('评论监测失败:', err.response.data); } } // 调用示例 publishOfferPost('https://example.com/offer.jpg', '限时优惠!点击链接直达'); setInterval(monitorComments, 300000); // 每5分钟监测一次
2. Python 示例
依赖安装
pip install requests
核心代码
import requests import time # 配置参数 IG_USER_ID = '你的IG用户ID' LONG_LIVED_TOKEN = '你的IG长期访问令牌' def publish_offer_post(image_url, caption): # 上传图片到IG媒体库 upload_url = f"https://graph.facebook.com/v18.0/{IG_USER_ID}/media" upload_payload = { 'image_url': image_url, 'caption': caption, 'access_token': LONG_LIVED_TOKEN } upload_res = requests.post(upload_url, data=upload_payload).json() media_id = upload_res['id'] # 发布内容 publish_url = f"https://graph.facebook.com/v18.0/{IG_USER_ID}/media_publish" publish_payload = { 'creation_id': media_id, 'access_token': LONG_LIVED_TOKEN } requests.post(publish_url, data=publish_payload) print('优惠帖子发布成功') def monitor_comments(): comments_url = f"https://graph.facebook.com/v18.0/{IG_USER_ID}/media?fields=comments{{id,message}}&access_token={LONG_LIVED_TOKEN}" res = requests.get(comments_url).json() for media in res['data']: if 'comments' in media: for comment in media['comments']['data']: if '求链接' in comment['message']: reply_url = f"https://graph.facebook.com/v18.0/{comment['id']}/replies" reply_payload = { 'message': '优惠链接:[你的链接]', 'access_token': LONG_LIVED_TOKEN } requests.post(reply_url, data=reply_payload) # 调用示例 publish_offer_post('https://example.com/offer.jpg', '限时优惠!点击链接直达') while True: monitor_comments() time.sleep(300) # 每5分钟监测一次
3. PHP 示例
核心代码
<?php $igUserId = '你的IG用户ID'; $longLivedToken = '你的IG长期访问令牌'; // 发布优惠帖子 function publishOfferPost($imageUrl, $caption, $igUserId, $token) { // 上传图片 $uploadUrl = "https://graph.facebook.com/v18.0/{$igUserId}/media"; $uploadData = [ 'image_url' => $imageUrl, 'caption' => $caption, 'access_token' => $token ]; $uploadRes = json_decode(file_get_contents($uploadUrl . '?' . http_build_query($uploadData)), true); $mediaId = $uploadRes['id']; // 发布内容 $publishUrl = "https://graph.facebook.com/v18.0/{$igUserId}/media_publish"; $publishData = [ 'creation_id' => $mediaId, 'access_token' => $token ]; file_get_contents($publishUrl . '?' . http_build_query($publishData)); echo '优惠帖子发布成功'; } // 监测并回复评论 function monitorComments($igUserId, $token) { $commentsUrl = "https://graph.facebook.com/v18.0/{$igUserId}/media?fields=comments{id,message}&access_token={$token}"; $res = json_decode(file_get_contents($commentsUrl), true); foreach ($res['data'] as $media) { if (isset($media['comments'])) { foreach ($media['comments']['data'] as $comment) { if (str_contains($comment['message'], '求链接')) { $replyUrl = "https://graph.facebook.com/v18.0/{$comment['id']}/replies"; $replyData = [ 'message' => '优惠链接:[你的链接]', 'access_token' => $token ]; file_get_contents($replyUrl . '?' . http_build_query($replyData)); } } } } } // 调用示例 publishOfferPost('https://example.com/offer.jpg', '限时优惠!点击链接直达', $igUserId, $longLivedToken); while (true) { monitorComments($igUserId, $longLivedToken); sleep(300); // 每5分钟监测一次 } ?>
三、私信回复集成
实现私信回复需调用/{ig-user-id}/messages接口,Python示例:
def reply_to_message(message_id, reply_text, token): url = f"https://graph.facebook.com/v18.0/{message_id}/replies" payload = { 'message': reply_text, 'access_token': token } requests.post(url, data=payload)
注意:私信功能需instagram_manage_messages权限,且应用需通过审核。
内容的提问来源于stack exchange,提问作者Kamesh Rajput
相关产品推荐
相关产品推荐

