I'm desperately trying to post a post with an image and an image URL via the Facebook Graph API. No matter what I do, I always get error messages.
Does anyone here have any sample code or ideas on how to implement this with Python? I would be very grateful for constructive answers!
import requests
from io import BytesIO
def post_facebook_photo(message, image_url):
access_token = 'DEIN_ACCESS_TOKEN'
feed_url = "https://graph.facebook.com/v20.0/me/feed"
try:
image_response = requests.get(image_url)
image_response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"Fehler beim Herunterladen des Bildes: {e}")
return
image_file = BytesIO(image_response.content)
photo_upload_url = "https://graph.facebook.com/v20.0/me/photos"
photo_data = {'access_token': access_token}
photo_files = {'file': ('image.jpg', image_file, 'image/jpeg')}
photo_response = requests.post(photo_upload_url, data=photo_data, files=photo_files)
photo_response_data = photo_response.json()
if 'id' in photo_response_data:
photo_id = photo_response_data['id']
post_data = {
'message': message,
'attached_media': [{'media_fbid': photo_id}],
'access_token': access_token
}
post_response = requests.post(feed_url, json=post_data)
return post_response.json()
else:
return photo_response_data
response = post_facebook_photo("Hier ist ein neues Bild!", "IMAGE-URL")
print(response)