Pregunta

I would like to post image on Twitter by using PTT (Python Twitter Tools). Currently, my code is quite like that:

def _TweetMedia(self, t, m):
    try:
        param = {'media[]', m}
        self.API.statuses.update_with_media(status = t, **param)
    except Exception as e:
        print("Failed to tweet media, reason: %s" % e)
        return False

    return True

But it fails with

Failed to tweet media, reason: Twitter sent status 403 for URL: 1.1/statuses/update_with_media.json 
using parameters: (oauth_consumer_key=y&oauth_nonce=13911566611016743303&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1399668386&oauth_token=x&oauth_version=1.0&oauth_signature=z)
details: {"errors":[{"code":189,"message":"Error creating status."}]}

I really don't know why. My image is read from a URL, then encoded in base64.

def DownloadImg(self, uri):
    try:
        source = b64encode(urllib2.urlopen(uri).read())
        filename  = uri.split('/')[-1]
        return (filename, source)
    except Exception as e:
        print("Failed to download %s: %s." % (uri.split()[-1], e))
        return (None, None)
        pass
¿Fue útil?

Solución

I was wondering about how this works too. I don't have the answer yet, I maybe more of a noob than you but maybe I have a lead. In the docs for this API call it explains the format for the image data it expects:

Blockquote Unlike POST statuses/update, this method expects raw multipart data. Your POST request's Content-Type should be set to multipart/form-data with the media[] parameter .

Blockquote

it describes the image format as:

Blockquote This data must be either the raw image bytes or encoded as base64

looks like you got the base64 encoding right as far as I can tell, but what about the multipart requirement? I honestly don't know what this means, but perhaps that's something to look into

another gotcha is that the image size is restricted:

Blockquote Note: Request the GET help/configuration endpoint to get the current max_media_per_upload and photo_size_limit values

It looks like you're just uploading a single image but to get the image size limit you make a one time call to the GET help/configuration endpoint and you should get a size restriction that should be valid until Twitter hopefully makes it more liberal as time goes on. judging from the example response given in the API docs for that endpoint it looks like the image size restrictions are:

Blockquote

photo_size_limit": 3145728,

"photo_sizes": { "large": { "w": 1024, "resize": "fit", "h": 2048 }, "medium": { "w": 600, "resize": "fit", "h": 1200 }, "small": { "w": 340, "resize": "fit", "h": 480 }, "thumb": { "w": 150, "resize": "crop", "h": 150 } },

I'm going to get back to this when I have time. Let me know if you figure it out and I'll do the same.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top