I have three images image1.jpg ,image2.jpg, image3.jpg. I am trying to upload them as a single post. Below is my code:
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!')
But they get uploaded as separate posts in separate images. How do I upload multiple images in single post?
If someone looking to post Multiple Images or a Video in 2021 using Graph API in Python
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")
same way it work for page, use page_id instead of group_id
Posting a Video
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)
First, you have to upload all photos and keep the id's (imgs_id).
Then, make a dict like args, and finally call request method.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With