Creating Scheduled Posts with an Image using Facebook Graph API
I'm using a Python script to try and create a post on a Facebook page. I've been able to create the post and schedule it for the future. It all goes wrong when I try to add an image.
First question, is this a limit of the Facebook API?
Here is my Python code (I've redacted the access token and page ID). I've included the error I'm getting beneath.
For background, I've added the page_access_token
element because I was originally getting an error Error: (#200) Unpublished posts must be posted to a page as the page itself.
. This error appeared after I added the temporary=True
during the image upload - I found this as a potential solution to a bug in the scheduled posts.
Any suggestions appreciated.
import facebook import datetime # Your Facebook access token access_token = 'xxx_Redacted_xxx' # ID of your Facebook page page_id = '426572384077950' # Initialize Facebook Graph API with your access token user_graph = facebook.GraphAPI(access_token) page_info = user_graph.get_object(f'/{page_id}?fields=access_token') page_access_token = page_info.get("access_token") print(page_info) print("Page: ", page_access_token) graph = facebook.GraphAPI(page_access_token) def schedule_post(page_id, message, days_from_now, scheduled_time=None, image_path=None): try: # Default scheduled time: 17:00 if not provided if scheduled_time is None: scheduled_time = datetime.time(17, 0) # Default to 17:00 # Calculate scheduled datetime scheduled_datetime = datetime.datetime.now() + datetime.timedelta(days=days_from_now) scheduled_datetime = scheduled_datetime.replace(hour=scheduled_time.hour, minute=scheduled_time.minute, second=0, microsecond=0) # Default image path: None (no image) attached_media = [] if image_path: # Upload the image (check for errors) try: image = open(image_path, 'rb') image_id = graph.put_photo(image, album_path=f'{page_id}/photos', published=False, temporary=True)['id'] print(image_id) except facebook.GraphAPIError as e: print(f"Error uploading image: {e}") # Handle image upload error (optional: log the error or continue without image) # If upload successful, append to attached_media attached_media.append({'media_fbid': image_id}) # Format scheduled time as required by Facebook API scheduled_time_str = scheduled_datetime.strftime('%Y-%m-%dT%H:%M:%S') # Debugging: Print attached_media before scheduling the post print("Attached Media:", attached_media) # Construct parameters for the put_object method parameters = { 'message': message, 'published': False, 'scheduled_publish_time': scheduled_time_str } # Add attached_media to parameters if it's not None if attached_media is not None: parameters['attached_media'] = attached_media print("parameters:", parameters) # Schedule the post graph.put_object(page_id, "feed", **parameters) print(f"Post scheduled for {scheduled_time_str}: {message}") return True except facebook.GraphAPIError as e: print(f"Error: {e}") return False # Example usage if __name__ == "__main__": # Message for the post message = "This is a scheduled post for 3 days from now at 17:00!" # Number of days from now days_from_now = 3 # Scheduled time (optional) scheduled_time = datetime.time(10, 30) # Change this to the desired time or None for default (17:00) # Image path (set to None for no image) image_path = 'img/Academic.jpg' # Change this to the path of your image or None for no image # image_path = None # Schedule the post success = schedule_post(page_id, message, days_from_now, scheduled_time, image_path) if not success: print("Failed to schedule the post.")
Output:
{'access_token': 'xxx_Redacted_xxx', 'id': '426572384077950'} Page: xxx_Redacted_xxx 860430092794306 Attached Media: [{'media_fbid': '860430092794306'}] parameters: {'message': 'This is a scheduled post for 3 days from now at 17:00!', 'published': False, 'scheduled_publish_time': '2024-04-20T10:30:00', 'attached_media': [{'media_fbid': '860430092794306'}]} Error: (#100) param attached_media must be an array. Failed to schedule the post.