Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New feature: post video #265

Open
dragonfly90 opened this issue Jan 26, 2016 · 14 comments
Open

New feature: post video #265

dragonfly90 opened this issue Jan 26, 2016 · 14 comments

Comments

@dragonfly90
Copy link
Contributor

Currently, posting video is not supported by python sdk, but actually you can do it by python. Is it a good idea to add the function in sdks?

@martey
Copy link
Member

martey commented Apr 3, 2016

Sorry I didn't reply earlier to this. This would be a fine feature to add, although you might want to look at previous pull requests to add video posting support in order to avoid their problems.

@alochym01
Copy link

is there any documents for upload videos.
i cannot find the examples to do that

@dragonfly90
Copy link
Contributor Author

dragonfly90 commented May 26, 2016

You can try the following, I am planning to testify it and submit a function

"""
Originally created by Mitchell Stewart.
Revised by ncsu student
"""
import facebook
import os
import requests
from requests_toolbelt import MultipartEncoder


#get_api connection
def get_api(cfg):
  graph = facebook.GraphAPI(cfg['access_token'])
  resp = graph.get_object('me/accounts')
  page_access_token = None
  for page in resp['data']:
    if page['id'] == cfg['page_id']:
      page_access_token = page['access_token']
  graph = facebook.GraphAPI(page_access_token)
  return graph

#post video
def put_video(video_url, page_id, access_token,description, title):
    video_file_name=title
    local_video_file=video_url
    path = "{0}/videos".format(page_id)
    fb_url = "https://graph-video.facebook.com/{0}?access_token={1}".format(
             path, access_token)
    print fb_url
    # multipart chunked uploads
    m = MultipartEncoder(
        fields={'description': description,
                'title': title,
                'comment':'postvideo',
                'source': (video_file_name, open(local_video_file, 'rb'))}
    )
    r = requests.post(fb_url, headers={'Content-Type': m.content_type}, data=m) 
    if r.status_code == 200:
        j_res = r.json()
        facebook_video_id = j_res.get('id')
        print ("facebook_video_id = {0}".format(facebook_video_id))
    else:
        print ("Facebook upload error: {0}".format(r.text))

def put_unpublishedvideo(video_url, page_id, access_token,description, title):
    video_file_name=title
    local_video_file=video_url
    path = "{0}/videos".format(page_id)
    fb_url = "https://graph-video.facebook.com/{0}?access_token={1}".format(
             path, access_token)
    print fb_url
    # multipart chunked uploads
    m = MultipartEncoder(
        fields={'description': description,
                'title': title,
                'comment':'postvideo',
                'published':'false',
                'source': (video_file_name, open(local_video_file, 'rb'))}
    )
    r = requests.post(fb_url, headers={'Content-Type': m.content_type}, data=m) 
    if r.status_code == 200:
        j_res = r.json()
        facebook_video_id = j_res.get('id')
        print ("facebook_video_id = {0}".format(facebook_video_id))
    else:
        print ("Facebook upload error: {0}".format(r.text))

@alochym01
Copy link

alochym01 commented May 27, 2016

Hi dragonfly90

My python requests module:
(python)[hadn@host-10-130-10-36 ~]$ pip list|grep request
requests (2.8.1)
requests-toolbelt (0.6.2)

My video format is in mp4
when i run your solution in python console

there is error 408 Request Timeout at the line "r = requests.post(fb_url, headers={'Content-Type': m.content_type}, data=m)"

multipart chunked uploads

m = MultipartEncoder(
    fields={'description': description,
            'title': title,
            'comment':'postvideo',
            'source': (video_file_name, open(local_video_file, 'rb'))}
)

when not using multipart chunked uploads, it works perfectly

"local_video_file = {'file': open(local_video_file, 'rb')}"
"r = requests.post(fb_url, files=local_video_file)"

is there any requirement to make it work with multipart chunked uploads

@dragonfly90

thank you

@mustafa-qamaruddin
Copy link

Is this feature now enabled and merged with master?

@ishandutta2007
Copy link

My file is mp4 but I get Unsupported Video Format.

Facebook upload error: {"error":{"message":"The video file you selected is in a format that we don't support.","type":"OAuthException","code":352,"error_subcode":1363024,"is_transient":false,"error_user_title":"Unsupported Video Format","error_user_msg":"The video you're trying to upload is in a format that isn't supported. Please try again with a video in a supported format.","fbtrace_id":"C8krnf+jgyU"}}

@luiscastillocr
Copy link

luiscastillocr commented Feb 5, 2019

try this:

from facebook import *

class GraphAPIExt(GraphAPI):

    def put_video(self, video=None, video_name=None, album_path="me/videos", **kwargs):
        """
        Upload a video using multipart/form-data.
        video - A file object representing the video to be uploaded.
        album_path - A path representing where the video should be uploaded.
        """

        post_args = {}

        if video and video_name:
            post_args = {
                "source":  (video_name, video)
            }

        post_args.update(kwargs)

        return self.request(
            "{0}/{1}".format(self.version, album_path),
            post_args=post_args,
            method="POST",
        )

read https://developers.facebook.com/docs/graph-api/video-uploads/#nonresumable to know about limitations

@alicmp
Copy link

alicmp commented Apr 23, 2019

When i use the solution @dragonfly90 suggested i get an error:

The video file you selected is in a format that we don't support.

Video is mp4 and its just 2mb.
Any suggestions?

@prashantsengar
Copy link

@alicmp keep the title same as the name of the video file

@tokejepsen
Copy link

Does anyone know how to embed a video that been uploaded, on a post?

I've managed to upload the video without a story/post being created, but now wanna make a custom post with a message and the video embedded:

r = requests.post(url, files={"file": open("C:/Users/admin/Desktop/test.gif", "rb")}, data={"no_story": "true"})

@tokejepsen
Copy link

Does anyone know how to embed a video that been uploaded, on a post?

Ended up using the description field for a message when posting the video:

requests.post(url, files={"file": open("C:/Users/admin/Desktop/test.gif", "rb")}, data={"description": "true"})

@nandandutta
Copy link

nandandutta commented Nov 3, 2020

try this:

from facebook import *

class GraphAPIExt(GraphAPI):

    def put_video(self, video=None, video_name=None, album_path="me/videos", **kwargs):
        """
        Upload a video using multipart/form-data.
        video - A file object representing the video to be uploaded.
        album_path - A path representing where the video should be uploaded.
        """

        post_args = {}

        if video and video_name:
            post_args = {
                "source":  (video_name, video)
            }

        post_args.update(kwargs)

        return self.request(
            "{0}/{1}".format(self.version, album_path),
            post_args=post_args,
            method="POST",
        )

read https://developers.facebook.com/docs/graph-api/video-uploads/#nonresumable to know about limitations
tried but not working graph = GraphAPIExt(token)
NameError: name 'GraphAPIExt' is notreturn requests("{0}/{1}".format(version='2.11', album_path="uploads"),post_args=post_args,method="POST")
IndexError: Replacement index 0 out of range for positional args tuple defined

@cattydev
Copy link

try this:

from facebook import *

class GraphAPIExt(GraphAPI):

    def put_video(self, video=None, video_name=None, album_path="me/videos", **kwargs):
        """
        Upload a video using multipart/form-data.
        video - A file object representing the video to be uploaded.
        album_path - A path representing where the video should be uploaded.
        """

        post_args = {}

        if video and video_name:
            post_args = {
                "source":  (video_name, video)
            }

        post_args.update(kwargs)

        return self.request(
            "{0}/{1}".format(self.version, album_path),
            post_args=post_args,
            method="POST",
        )

read https://developers.facebook.com/docs/graph-api/video-uploads/#nonresumable to know about limitations

thank you it is working

@engineervix
Copy link

this is what worked for me

import requests

# Replace these with your Facebook access token and video file path
access_token = 'YOUR-TOKEN'
video_path = 'video.mp4'  # Path to your video file

# Step 1: Upload video
endpoint = f'https://graph-video.facebook.com/v19.0/me/videos?access_token={access_token}'
files = {'file': open(video_path, 'rb')}
response = requests.post(endpoint, files=files)
video_data = response.json()

if 'id' in video_data:
    video_id = video_data['id']
    print("Video uploaded successfully with ID:", video_id)

    # Step 2: Share the video on your Facebook timeline
    graph_endpoint = f'https://graph.facebook.com/v19.0/me/feed'
    params = {
        'access_token': access_token,
        'message': 'Check out this fancy video!',
        'link': f'https://www.facebook.com/watch/?v={video_id}'
    }
    response = requests.post(graph_endpoint, params=params)

    if response.status_code == 200:
        print("Video shared on your Facebook timeline successfully!")
    else:
        print("Failed to share the video on your Facebook timeline.")

else:
    print("Failed to upload the video.")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests