Twitter media/upload image by its web url

1.2k views Asked by At

I followed the steps in media/upload. I wrote this function in python

def upload_media(self,access_token,image_url): client = self.get_client(access_token) message = {'media' : image_url} encoded_status = urllib.urlencode(message) url = "https://upload.twitter.com/1.1/media/upload.json?"+ encoded_status resp, content = client.request(url,'post') return content

And I got this :

{"request":"\/1.1\/media\/upload.json","error":"media type unrecognized."}

1

There are 1 answers

1
esdalmaijer On

As far as I can tell, the error is in trying to upload a URL. The Twitter API requires you to upload a base64-encoded image.

See: https://dev.twitter.com/rest/reference/post/media/upload

So instead of the image's URL, it should be the file content:

with open('example.jpg', 'rb') as f:
    data = f.read()
message = {'media':data}

Optionally (I still haven't figured out whether this is required or not, as different people give different answers), you could encode the image in base-64 encoding:

with open('example.jpg', 'rb') as f:
    data = f.read()
data = data.encode('base64')
message = {'media':data}