Twython - How to update status with media url

2019-05-14 21:40发布

In my app, I let users to post to twitter. Now i would like to let them update their status with media.

In twython.py i see a method update_status_with_media that reads the image from filesystem and uploads to twitter. My images are not in filesystem but on S3 bucket.

How to make this work with S3 bucket urls?

Passing the url in file_ variable, fails on IO Error, no such file or directory.

Passing StringIO fails on UnicodeDecode Error.

Passing urllib.urlopen(url).read() gives file() argument 1 must be encoded string without NULL bytes, not str.

I also tried using post method and got 403 Forbidden from twitter api, Error creating status.

Just Solved it

Bah, just got it to work, finally! Maybe it will help someone else to save a few hours it cost me.

twitter = Twython(
        app_key=settings.TWITTER_CONSUMER_KEY, app_secret=settings.TWITTER_CONSUMER_SECRET,
        oauth_token=token.token, oauth_token_secret=token.secret
    )
img = requests.get(url=image_obj.url).content
tweet = twitter.post('statuses/update_with_media',
                                 params={'status': msg},
                                 files={'media': (image_obj.url,
                                                  BytesIO(img))})

1条回答
狗以群分
2楼-- · 2019-05-14 22:29

Glad to see you found an answer! There's a similar problem that we handled recently in a repo issue - basically, you can do the following with StringIO and passing it directly to twitter.post like you did:

from StringIO import StringIO
from twython import Twython

t = Twython(...)
img = open('img_url').read()
t.post('/statuses/update_with_media', params = {'status': 'Testing New Status'}, files = {
    'media': StringIO(img)
    # 'media': ('OrThisIfYouWantToNameTheFile.lol', StringIO(img))
})

This isn't a direct answer to your question, so I'm not expecting any vote or anything, but figured it's seemingly useful to some people and somewhat related so I'd drop a note.

查看更多
登录 后发表回答