77import requests
88from requests_oauthlib import OAuth2Session
99
10+ MEDIA_INIT_ENDPOINT_URL = 'https://api.x.com/2/media/upload/initialize'
1011MEDIA_ENDPOINT_URL = 'https://api.x.com/2/media/upload'
1112POST_TO_X_URL = 'https://api.x.com/2/tweets'
1213
@@ -101,18 +102,23 @@ def __init__(self, file_name):
101102 self .media_id = None
102103 self .processing_info = None
103104
105+ def _create_append_url (self ):
106+ return f"https://api.x.com/2/media/upload/{ self .media_id } /append"
107+
108+ def _create_finalize_url (self ):
109+ return f"https://api.x.com/2/media/upload/{ self .media_id } /finalize"
110+
104111 def upload_init (self ):
105112 # Initializes Upload
106113 print ('INIT' )
107114
108115 request_data = {
109- 'command' : 'INIT' ,
110116 'media_type' : 'video/mp4' ,
111117 'total_bytes' : self .total_bytes ,
112118 'media_category' : 'tweet_video'
113119 }
114120
115- req = requests .post (url = MEDIA_ENDPOINT_URL , params = request_data , headers = headers )
121+ req = requests .post (url = MEDIA_ENDPOINT_URL , json = request_data , headers = headers )
116122 print (req .status_code )
117123 print (req .text )
118124 media_id = req .json ()['data' ]['id' ]
@@ -133,8 +139,6 @@ def upload_append(self):
133139 files = {'media' : ('chunk' , chunk , 'application/octet-stream' )}
134140
135141 data = {
136- 'command' : 'APPEND' ,
137- 'media_id' : self .media_id ,
138142 'segment_index' : segment_id
139143 }
140144
@@ -143,7 +147,7 @@ def upload_append(self):
143147 "User-Agent" : "MediaUploadSampleCode" ,
144148 }
145149
146- req = requests .post (url = MEDIA_ENDPOINT_URL , data = data , files = files , headers = headers )
150+ req = requests .post (url = self . _create_append_url () , data = data , files = files , headers = headers )
147151
148152 if req .status_code < 200 or req .status_code > 299 :
149153 print (req .status_code )
@@ -162,12 +166,7 @@ def upload_finalize(self):
162166 # Finalizes uploads and starts video processing
163167 print ('FINALIZE' )
164168
165- request_data = {
166- 'command' : 'FINALIZE' ,
167- 'media_id' : self .media_id
168- }
169-
170- req = requests .post (url = MEDIA_ENDPOINT_URL , params = request_data , headers = headers )
169+ req = requests .post (url = self ._create_finalize_url (), headers = headers )
171170
172171 print (req .json ())
173172
0 commit comments