Posts tagged with python

So,I managed to get an API key with the correct permissions to make posts as a Page. Based off of some online reading, other users should not see the posts I make just yet as my Facebook App has not yet gone live. However, according to those texts, I should still be able to see them as I am the admin, but I check the page, and I cannot see any post that I've made through the Graph API. I'm not sure if I'm done something wrong or not. No errors appears, no crashes occur.

Edit: Using a different source text, the new posts appear for some reason. I'm wondering if this has to do with links in the content. Do links within these kinds of posts have to appear under their own parametre(s)?

I am trying to get a long-lived access token from the Instagram graph API through a python script. No matter what I do, I keep receiving the following error:

{"error":{"message":"Missing client_id parameter.","type":"OAuthException","code":101,"fbtrace_id":"AogeGpzZGW9AwqCYKHlmKM"}} 

My script is the following:

import requests refresh_token_url = 'https://graph.facebook.com/v19.0/oauth/access_token' payload = {     'grant_type': 'fb_exchange_token',      'client_id': '1234567890123456'     'client_secret': '1234abcd1234abcd1234abcd',         'fb_exchange_token':'abcd1234' } r = requests.get(refresh_token_url, data=payload) 

I am for sure passing the client_id parameter. I verified also by printing r.request.body

On the contrary, the request is successful if I send it with the Postman app:

Why do I keep getting that error message? Thank you!

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. 

i am trying to upload a reel (MP4, 16 seconds, and 9 MB) using facebook graph API, but i get the following error:

Failed to upload reel: {'error': {'message': 'The video file you tried to upload is too small. Please try again with a larger file.', 'type': 'OAuthException', 'code': 382, 'error_subcode': 1363022, 'is_transient': False, 'error_user_title': 'Video Too Small', 'error_user_msg': 'The video you tried to upload is too small. The minimum size for a video is 1 KB. Please try again with a larger file.', 'fbtrace_id': 'A0WVVSGWnXEfffdwrjFUENsJVC'}}

The code:

import requests from datetime import datetime import subprocess import os def human_readable_to_timestamp(date_string):     try:         # Convert the human-readable date string to a datetime object         dt_object = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')         # Convert the datetime object to UNIX timestamp         timestamp = int(dt_object.timestamp())         return timestamp     except ValueError:         print("Invalid date format. Please provide the date in the format: YYYY-MM-DD HH:MM:SS")         return None def extract_frame(video_path, time, output_path):     # Use ffmpeg to extract a frame from the video at the specified time     cmd = [         'ffmpeg', '-y',         '-i', video_path,         '-ss', str(time),         '-vframes', '1',         '-q:v', '2',  # Set quality (1-31, 1 being highest)         output_path     ]     subprocess.run(cmd, check=True) def upload_reel_with_thumbnail(video_path, thumbnail_path, access_token, file_size, target_file_size, scheduled_publish_time=None):          # Endpoint for uploading videos     url = 'https://graph.facebook.com/v15.0/me/videos'     if file_size < target_file_size:         # Pad the file with zeros to reach the target file size         with open(video_path, 'ab') as video_file:             video_file.write(b'\0' * (target_file_size - file_size))             file_size = target_file_size  # Update the file size after padding     print (file_size)     # Video data     video_data = {         'access_token': access_token,         #'file_url': video_path,         'description': 'Check out this amazing reel!',         'file_size': file_size,         'published': 'false'         # Additional parameters can be added here as needed     }     # If scheduling time is provided, add it to the request     if scheduled_publish_time:         video_data['scheduled_publish_time'] = human_readable_to_timestamp(scheduled_publish_time)     try:         # Sending POST request to upload the video         files = {'file': video_path}         response = requests.post(url, data=video_data, files=files)         response_json = response.json()         # Check if the upload was successful         if 'id' in response_json:             reel_id = response_json['id']             print("Reel uploaded successfully! Reel ID:", reel_id)             # Upload the thumbnail             upload_thumbnail(reel_id, thumbnail_path, access_token)             # If scheduling time is provided, schedule the reel             if scheduled_publish_time:                 schedule_reel(reel_id, scheduled_publish_time, access_token)         else:             print("Failed to upload reel:", response_json)     except Exception as e:         print("An error occurred:", str(e)) def upload_thumbnail(reel_id, thumbnail_path, access_token):     # Endpoint for uploading thumbnail     url = f'https://graph.facebook.com/v15.0/{reel_id}'          # Thumbnail data     files = {'thumb': open(thumbnail_path, 'rb')}     params = {'access_token': access_token}     try:         # Sending POST request to upload the thumbnail         response = requests.post(url, files=files, params=params)         response_json = response.json()         # Check if the thumbnail upload was successful         if 'success' in response_json and response_json['success']:             print("Thumbnail uploaded successfully!")         else:             print("Failed to upload thumbnail:", response_json)     except Exception as e:         print("An error occurred:", str(e)) def schedule_reel(reel_id, scheduled_publish_time, access_token):     # Endpoint for scheduling the reel     url = f'https://graph.facebook.com/v15.0/{reel_id}'     # Schedule data     data = {         'access_token': access_token,         'published': 'false',         'scheduled_publish_time': scheduled_publish_time     }     try:         # Sending POST request to schedule the reel         response = requests.post(url, data=data)         response_json = response.json()         # Check if scheduling was successful         if 'id' in response_json:             print("Reel scheduled successfully!")         else:             print("Failed to schedule reel:", response_json)     except Exception as e:         print("An error occurred:", str(e)) # Example usage if __name__ == "__main__":     # Path to the video file     video_path = '55.mp4'                  file_size = os.path.getsize(video_path)     target_file_size = 10 * 1024  # 30 KB     print (file_size)     # Path to the thumbnail image     thumbnail_path = 'thumbnails/55.jpg'          extract_frame(video_path, 6, thumbnail_path)     # Facebook Access Token     access_token = 'xxxxx'     # Scheduled publish time (human-readable format)     scheduled_publish_time = '2024-04-10 15:30:00'  # Example: April 10, 2024, 15:30:00 UTC     # Call the function to upload the reel with the extracted thumbnail and schedule it     upload_reel_with_thumbnail(video_path, thumbnail_path, access_token, file_size, target_file_size, scheduled_publish_time)          print ("done") 

Any idea :(?

I'm using Python to create a script that allows me to create a label in the inbox (for a Facebook page), and then associate or tag a user with a specific label.

This is the function I made:

def associate_label_to_user(recipient_id, label_id, access_token): url = f"https://graph.facebook.com/v19.0/{label_id}/label?access_token={access_token}" data = {     "user": recipient_id } response = requests.post(url, json=data) response_json = response.json() # print(response_json) if response.status_code == 200:     success = response_json['success']     if success:         print("[LOGS] Association of label to user successful") else:     print("[LOGS] Error associating label to a user") 

I'm reading their documents here https://developers.facebook.com/docs/messenger-platform/identity/custom-labels/, and I'm not experiencing any other problem.

Whenever I run the script, it works (I see the user being labeled correctly), but I'm getting this error in return:

{'error': {'message': 'Unsupported request - method type: post', 'type': 'GraphMethodException', 'code': 100, 'fbtrace_id': 'ApHRHoVZFM_BUqHpOs3KdKX'}} 

I don't understand what this means, when it works for me anyway.