7
7
import requests
8
8
from requests_oauthlib import OAuth2Session
9
9
10
+ MEDIA_INIT_ENDPOINT_URL = 'https://api.x.com/2/media/upload/initialize'
10
11
MEDIA_ENDPOINT_URL = 'https://api.x.com/2/media/upload'
11
12
POST_TO_X_URL = 'https://api.x.com/2/tweets'
12
13
@@ -101,18 +102,23 @@ def __init__(self, file_name):
101
102
self .media_id = None
102
103
self .processing_info = None
103
104
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
+
104
111
def upload_init (self ):
105
112
# Initializes Upload
106
113
print ('INIT' )
107
114
108
115
request_data = {
109
- 'command' : 'INIT' ,
110
116
'media_type' : 'video/mp4' ,
111
117
'total_bytes' : self .total_bytes ,
112
118
'media_category' : 'tweet_video'
113
119
}
114
120
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 )
116
122
print (req .status_code )
117
123
print (req .text )
118
124
media_id = req .json ()['data' ]['id' ]
@@ -133,8 +139,6 @@ def upload_append(self):
133
139
files = {'media' : ('chunk' , chunk , 'application/octet-stream' )}
134
140
135
141
data = {
136
- 'command' : 'APPEND' ,
137
- 'media_id' : self .media_id ,
138
142
'segment_index' : segment_id
139
143
}
140
144
@@ -143,7 +147,7 @@ def upload_append(self):
143
147
"User-Agent" : "MediaUploadSampleCode" ,
144
148
}
145
149
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 )
147
151
148
152
if req .status_code < 200 or req .status_code > 299 :
149
153
print (req .status_code )
@@ -162,12 +166,7 @@ def upload_finalize(self):
162
166
# Finalizes uploads and starts video processing
163
167
print ('FINALIZE' )
164
168
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 )
171
170
172
171
print (req .json ())
173
172
0 commit comments