Created
March 5, 2016 21:49
-
-
Save jcipriano/e506b81a6062307c5189 to your computer and use it in GitHub Desktop.
Upload video file with Python TwitterAPI package.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
from TwitterAPI import TwitterAPI | |
consumer_key = '' | |
consumer_secret = '' | |
access_token = '' | |
access_token_secret = '' | |
twitter = TwitterAPI(consumer_key, consumer_secret, access_token, access_token_secret) | |
VIDEO_FILENAME = 'path/to/video/file' | |
bytes_sent = 0 | |
total_bytes = os.path.getsize(VIDEO_FILENAME) | |
file = open(VIDEO_FILENAME, 'rb') | |
def check_status(r): | |
if r.status_code < 200 or r.status_code > 299: | |
print(r.status_code) | |
print(r.text) | |
sys.exit(0) | |
# initialize media upload and get a media reference ID in the response | |
r = twitter.request('media/upload', {'command':'INIT', 'media_type':'video/mp4', 'total_bytes':total_bytes}) | |
check_status(r) | |
media_id = r.json()['media_id'] | |
segment_id = 0 | |
# start chucked upload | |
while bytes_sent < total_bytes: | |
chunk = file.read(4*1024*1024) | |
# upload chunk of byets (5mb max) | |
r = twitter.request('media/upload', {'command':'APPEND', 'media_id':media_id, 'segment_index':segment_id}, {'media':chunk}) | |
check_status(r) | |
segment_id = segment_id + 1 | |
bytes_sent = file.tell() | |
print('[' + str(total_bytes) + ']', str(bytes_sent)) | |
# finalize the upload | |
r = twitter.request('media/upload', {'command':'FINALIZE', 'media_id':media_id}) | |
check_status(r) | |
# post Tweet with media ID from previous request | |
r = twitter.request('statuses/update', {'status':'Video uploaded from python script.', 'media_ids':media_id}) | |
check_status(r) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/shyal/dev/monolith/scripts/twitter/upload.py", line 36, in
r = twitter.request('media/upload', {'command':'APPEND', 'media_id':media_id, 'segment_index':segment_id}, {'media':chunk})
File "/usr/local/lib/python3.9/site-packages/TwitterAPI/TwitterAPI.py", line 193, in request
raise TwitterConnectionError(e)
TwitterAPI.TwitterError.TwitterConnectionError: ('Connection aborted.', timeout('The write operation timed out'))