如何用Python发布含文字多图的Facebook主页帖子?解决重复报错
如何用Python发布含文字和多图的Facebook主页帖子?
我尝试用Python在Facebook主页发布带文字和多张图片的帖子,编写了如下代码:
import requests import tempfile import os import json params = { 'access_token': 'MY_ACCESS_TOKEN', 'format': 'json' } image_urls = ['https://example.com/images/tw8qxmjwrb.jpg', 'https://example.com/images/g41oikacph.jpg'] temp_images = [] for url in image_urls: response = requests.get(url) if response.status_code == 200: with tempfile.NamedTemporaryFile(delete=False) as file: file.write(response.content) temp_image_path = file.name temp_images.append(temp_image_path) uploaded_images = [] for temp_image in temp_images: with open(temp_image, 'rb') as file: files = {'source': file} response = requests.post('https://graph.facebook.com/v11.0/PAGE_ID/photos', params=params, files=files) if response.status_code == 200: uploaded_images.append(response.json().get('id')) else: print('Failed to upload image:', response.json()) for temp_image in temp_images: os.remove(temp_image) args = { "message": "HELLO WORLD.", "attached_media[0]": json.dumps({"media_fbid": uploaded_images[0]}), "attached_media[1]": json.dumps({"media_fbid": uploaded_images[1]}), "published": True } response = requests.post('https://graph.facebook.com/v11.0/PAGE_ID/feed', params=params, data=args) print(response.status_code, response.json())
运行代码后出现报错:
{'error': {'message': 'Invalid parameter', 'type': 'OAuthException', 'code': 100, 'error_subcode': 1366051, 'is_transient': False, 'error_user_title': 'Already Posted', 'error_user_msg': 'These photos were already posted.'}}
解决方案
问题根源是上传图片时,默认会直接将图片单独发布到主页,后续通过feed接口关联这些图片时,系统判定图片已发布,因此抛出重复发布的错误。
解决方法是在上传单张图片前,给请求参数添加published: False,让图片仅上传至Facebook服务器但不单独发布,之后再通过feed接口将文字与多张图片合并发布。
在上传图片的循环前添加如下代码:
params['published'] = False
修改后的上传图片段代码如下:
uploaded_images = [] # 添加参数,设置图片仅上传不发布 params['published'] = False for temp_image in temp_images: with open(temp_image, 'rb') as file: files = {'source': file} response = requests.post('https://graph.facebook.com/v11.0/PAGE_ID/photos', params=params, files=files) if response.status_code == 200: uploaded_images.append(response.json().get('id')) else: print('Failed to upload image:', response.json())
修改后即可成功发布包含文字和多张图片的Facebook主页帖子。
内容的提问来源于stack exchange,提问作者Bassem v3
相关产品推荐
相关产品推荐

