如何使用FaceBook Python SDK上传多个图像?

时间:2014-12-17 10:22:55

标签: python facebook python-2.7 facebook-graph-api

我有三张图片image1.jpg,image2.jpg,image3.jpg。我正在尝试将它们作为一个帖子上传。下面是我的代码:

import facebook
graph = facebook.GraphAPI(oauth_access_token)
profile = graph.get_object("me")
friends = graph.get_connections("me", "friends")
file1 = open("image1","rb")
file2 = open('image2', 'rb')
graph.put_photo(file1, 'Look at this cool photo!')
graph.put_photo(file2, 'Look at this cool photo!')

但是它们会在单独的图片中作为单独的帖子上传。如何在单个帖子中上传多个图片?

3 个答案:

答案 0 :(得分:0)

你尝试过put-wall-post吗? ..或put-object

put-wall-post可能就是你要找的东西:

  

附件 - 为发布到墙上的邮件添加结构化附件的字典。如果您要共享URL,则需要使用附件参数,以便在帖子中显示缩略图预览。它应该是形式的词典:

来源:http://facebook-sdk.readthedocs.io/en/latest/api.html#api-reference

答案 1 :(得分:0)

试试这个。首先,您必须上传所有照片并保留ID(imgs_id)。

然后,制作像args这样的字典,最后调用请求方法。

对不起,如果不是最好的压缩代码......

    imgs_id = []
    for img in img_list:
        photo = open(img, "rb")
        imgs_id.append(api.put_photo(photo, album_id='me/photos',published=False)['id'])
        photo.close()

    args=dict()
    args["message"]="Put your message here"
    for img_id in imgs_id:
        key="attached_media["+str(imgs_id.index(img_id))+"]"
        args[key]="{'media_fbid': '"+img_id+"'}"

    api.request(path='/me/feed', args=None, post_args=args, method='POST')

答案 2 :(得分:0)

如果有人希望在 2021 年使用 Python 中的 Graph API 发布多张图片或视频

import requests

auth_token = "XXXXXXXX"

def postImage(group_id, img):
    url = f"https://graph.facebook.com/{group_id}/photos?access_token=" + auth_token
   
    files = {
            'file': open(img, 'rb'), 
            }
    data = {
        "published" : False
    }
    r = requests.post(url, files=files, data=data).json()
    return r

def multiPostImage(group_id):
    imgs_id = []
    img_list = [img_path_1, img_path_2]
    for img in img_list:
        post_id = postImage(group_id ,img)
        
        imgs_id.append(post_id['id'])

    args=dict()
    args["message"]="Put your message here"
    for img_id in imgs_id:
        key="attached_media["+str(imgs_id.index(img_id))+"]"
        args[key]="{'media_fbid': '"+img_id+"'}"
    url = f"https://graph.facebook.com/{group_id}/feed?access_token=" + auth_token
    requests.post(url, data=args)

multiPostImage("426563960691001")

同样适用于页面,使用 page_id 而不是 group_id

发布视频

def postVideo(group_id, video_path):
    url = f"https://graph-video.facebook.com/{group_id}/videos?access_token=" + auth_token
    files = {
            'file': open(video_path, 'rb'), 
            }
    requests.post(url, files=files)
相关问题