Skip to content

Update media_upload_v2.py #199

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 10 additions & 11 deletions Media Upload/media_upload_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import requests
from requests_oauthlib import OAuth2Session

MEDIA_INIT_ENDPOINT_URL = 'https://api.x.com/2/media/upload/initialize'
MEDIA_ENDPOINT_URL = 'https://api.x.com/2/media/upload'
POST_TO_X_URL = 'https://api.x.com/2/tweets'

Expand Down Expand Up @@ -101,18 +102,23 @@ def __init__(self, file_name):
self.media_id = None
self.processing_info = None

def _create_append_url(self):
return f"https://api.x.com/2/media/upload/{self.media_id}/append"

def _create_finalize_url(self):
return f"https://api.x.com/2/media/upload/{self.media_id}/finalize"

def upload_init(self):
# Initializes Upload
print('INIT')

request_data = {
'command': 'INIT',
'media_type': 'video/mp4',
'total_bytes': self.total_bytes,
'media_category': 'tweet_video'
}

req = requests.post(url=MEDIA_ENDPOINT_URL, params=request_data, headers=headers)
req = requests.post(url=MEDIA_ENDPOINT_URL, json=request_data, headers=headers)
print(req.status_code)
print(req.text)
media_id = req.json()['data']['id']
Expand All @@ -133,8 +139,6 @@ def upload_append(self):
files = {'media': ('chunk', chunk, 'application/octet-stream')}

data = {
'command': 'APPEND',
'media_id': self.media_id,
'segment_index': segment_id
}

Expand All @@ -143,7 +147,7 @@ def upload_append(self):
"User-Agent": "MediaUploadSampleCode",
}

req = requests.post(url=MEDIA_ENDPOINT_URL, data=data, files=files, headers=headers)
req = requests.post(url=self._create_append_url(), data=data, files=files, headers=headers)

if req.status_code < 200 or req.status_code > 299:
print(req.status_code)
Expand All @@ -162,12 +166,7 @@ def upload_finalize(self):
# Finalizes uploads and starts video processing
print('FINALIZE')

request_data = {
'command': 'FINALIZE',
'media_id': self.media_id
}

req = requests.post(url=MEDIA_ENDPOINT_URL, params=request_data, headers=headers)
req = requests.post(url=self._create_finalize_url(), headers=headers)

print(req.json())

Expand Down
Loading