Posts tagged with facebook-graph-api

I Am trying to upload Reels from a business Instagram account for that i already have access token and long lived token.The problem is that whenever i try to publish a reel it gives me "The video file you selected is in a format that we don't support." error code:352 and error_subcode:2207026.I have also converted that video but its saying the same.But I am able to upload a video of "640x480" but not any other resolution like 720x1280 etc. The url of video is aws

I have tried converting video using ffmpeg but it gives me aspect ratio error on 720x1280 whether its 9:16 or 16:9 when i try to upload video of like 1080x1920 it gives me streams error i have also added validation in my uploadReel function and funtion return true but still i am getting video format not supported error

import { Request, Response } from 'express'; import axios from 'axios'; import asyncHandler from '../../../middlewares/asyncHandler'; import ffmpeg from 'fluent-ffmpeg'; import ffmpegInstaller from '@ffmpeg-installer/ffmpeg'; ffmpeg.setFfmpegPath(ffmpegInstaller.path); export const uploadReel = asyncHandler(async (req: Request, res: Response) => {   const { longLivedToken, videoUrl }: any = req.body;   if (!longLivedToken || !videoUrl) {     return res.status(400).json({ error: 'Invalid data' });   }   console.log('Checking video format for:', videoUrl);   // Check if the video has supported codecs (H.264 for video and AAC for audio)   ffmpeg(videoUrl).ffprobe((err, metadata) => {     if (err) {       console.error('Error reading video metadata:', err.message);       return res.status(400).json({ error: 'Unable to check video metadata or invalid file.' });     }     console.log('Video metadata:', JSON.stringify(metadata, null, 2));     const hasValidCodec = metadata.streams.some(       (stream: any) => stream.codec_name === 'h264' && stream.codec_type === 'video'     ) && metadata.streams.some(       (stream: any) => stream.codec_name === 'aac' && stream.codec_type === 'audio'     );     if (!hasValidCodec) {       console.error('Unsupported file format. Expected H.264 video codec and AAC audio codec.');       return res.status(400).json({         error: 'Unsupported file format. Ensure the video is in MP4 format with H.264 video codec and AAC audio codec.',       });     }     console.log('Video format is supported. Proceeding with upload.');     // If format is supported, proceed to upload the video     axios.post(       `https://graph.instagram.com/v20.0/me/media`,       {         media_type: 'REELS',         video_url: videoUrl, // Publicly accessible URL of the video file         access_token: longLivedToken,       },       {         headers: { 'Content-Type': 'application/json' },       }     )       .then((response) => {         console.log('Reel successfully uploaded:', response.data);         return res.status(200).json({ mediaId: response.data.id });       })       .catch((error) => {         console.error('Error uploading reel:', error.response ? error.response.data : error.message);         return res.status(500).json({ error: 'Failed to upload reel' });       });   }); }); export const publishReel = asyncHandler(async (req: Request, res: Response) => {   const { mediaId, longLivedToken }: any = req.body;   if (!mediaId || !longLivedToken) {     return res.status(400).json({ error: 'Invalid data' });   }   try {     const response = await axios.post(       `https://graph.instagram.com/v20.0/me/media_publish`,       {         creation_id: mediaId,         access_token: longLivedToken,       },       {         headers: { 'Content-Type': 'application/json' }       }     );     return res.status(200).json({ postId: response.data.id }); // Return post ID   } catch (error) {     console.error('Error publishing image:', error.response ? error.response.data : error.message)}      }); 

enter image description here`

I implemented successfully the code to make a request to the Facebook GraphRequest by using the the following code:

GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {   ... } 

In some documentation I found the code below to retrieve values:

Bundle parameters = new Bundle(); parameters.putString("fields","name,email"); request.setParameters(parameters); request.executeAsync(); 

I want to use System.out.println() to print out name and email of the person who logged in successfully with Facebook to my Android app. How can I invoke request to print out those values? Thank you.

UPDATE 1:

I suspect I might be experiencing the same problem reported at Facebook Integration Android: onCompleted(GraphJSONObjectCallback) block not executing: onCompleted(GraphJSONObjectCallback) block not executing

See more context of my code:

private void handleFacebookAccessToken(LoginResult loginResult) {   GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {     @Override     public void onCompleted(@Nullable JSONObject jsonObject, @Nullable GraphResponse graphResponse) {       //Access the response here and retrieve the information you want and print it out       String rawResponse = graphResponse.getRawResponse();       System.out.println("rawResponse: "+rawResponse);     });     Bundle parameters = new Bundle();     parameters.putString("fields","name,email");     request.setParameters(parameters);     request.executeAsync(); } 

I was expecting the following line to print out the response to the request, but I do not see anything printed out:

System.out.println("rawResponse: "+rawResponse); 

I've tried getting
graph.facebook.com/v20.0/1*************3_7*************1/comments, where
1*************3 is a valid user id, and
7*************1 is a valid (and public) post id.

Unfortunately, the Graph API Explorer shows an OAuthException:

{   "error": {     "message": "Unsupported get request. Object with ID '1*************3_7*************1' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api",     "type": "GraphMethodException",     "code": 100,     "error_subcode": 33,     "fbtrace_id": "A*********************Z"   } } 

How could I get all the comments of a user's public Facebook post?

I'd prefer a Graph API (or other official Meta tool) solution.

But I'm open to other approaches too.

I'm working on a Python script that uploads videos directly to a Facebook Page as Reels using the Facebook Graph API. My videos are hosted on a CDN, and I would like to upload them directly to Facebook without downloading them to my local server.

I am currently using Facebook's video_reels endpoint to upload videos as reels. For local files, the process works perfectly by uploading the video in binary form. However, I want to avoid downloading the video locally when it's hosted on a CDN and instead directly upload it from the CDN URL.

Here’s a simplified version of my current code:

import requests # Facebook API parameters page_access_token = 'your_page_access_token' page_id = 'your_page_id' api_version = 'v20.0' video_url = 'https://cdn.example.com/video.mp4'  # CDN URL of the video video_description = "My awesome reel" video_title = "Reel Title" thumbnail_path = 'thumb.jpg' # Step 1: Initialize the upload session for reels def initialize_upload_reel():     url = f"https://graph.facebook.com/{api_version}/{page_id}/video_reels"     payload = {         'upload_phase': 'start',         'access_token': page_access_token     }          response = requests.post(url, data=payload)     if response.status_code == 200:         data = response.json()         video_id = data['video_id']         print(f"Upload session started. Video ID: {video_id}")         return video_id     else:         raise Exception(f"Error initializing reel upload: {response.text}") # Step 2: Upload the reel video file def process_upload_reel(video_id, file_size):     url = f"https://rupload.facebook.com/video-upload/v20.0/{video_id}"     headers = {         'Authorization': f'OAuth {page_access_token}',         'Content-Type': 'application/octet-stream',         'offset': '0',         'file_size': str(file_size)     }     with open(video_url, 'rb') as file_data:         response = requests.post(url, headers=headers, data=file_data)          if response.status_code == 200:         print("Reel Uploaded")     else:         raise Exception(f"Error uploading reel video: {response.text}") def publish_reel(video_id, description, publish_time=None, published=True):     url = f"https://graph.facebook.com/{api_version}/{page_id}/video_reels"     thumb_file = {'thumb': open(thumbnail_url, 'rb')}          payload = {         'access_token': page_access_token,         'video_id': video_id,         'upload_phase': 'finish',         'title': title_entry.get(),  # Ensure title is passed         'description': description_entry.get()  # Ensure description is passed     }     if publish_time:         payload['video_state'] = 'SCHEDULED'         payload['scheduled_publish_time'] = publish_time     else:         payload['video_state'] = 'PUBLISHED' if published else 'DRAFT'     response = requests.post(url, data=payload, files=thumb_file)     thumb_file['thumb'].close()     if response.status_code == 200:         check_video_status(video_id)              else:         raise Exception(f"Error publishing reel: {response.text}") 

The Problem: When I attempt to upload using the CDN URL, I receive the following error message:

{   "error": {     "message": "There was a problem uploading your video file. Please try again with another file.",     "type": "OAuthException",     "code": 6000,     "error_subcode": 1363130,     "error_user_title": "Video Upload Is Missing",     "error_user_msg": "The video was not uploaded.",     "fbtrace_id": "Ai3SicB2QxOVA-ZpIQu7cjT"   } } 

It seems like Facebook's Reels API doesn't support uploading videos directly from a CDN URL using the file_url parameter, or I may be missing something in the implementation.

Question: Is it possible to upload videos directly from a CDN URL to Facebook Reels via the Graph API without downloading the video locally first?

If yes, how should I structure my API request to achieve this?

If no, what is the recommended approach for handling CDN-hosted videos in this scenario (such as avoiding downloading the video to the server)? Any help or guidance would be greatly appreciated!

I'm tring to get tagged user in post. Currently I'm fetching user post using Business Discovery and some of the post data is possible to fetch. But for tagged user no information is post.

Is there way or endpoint that I'm just overlooking? or just simply not possible with Business Discovery?

Also if it not possible with Business Discovery I would like to know if there is any other way to do it.