Twython returned a 400 (Bad Request) when tweeting an image

时间:2016-02-03 03:00:08

标签: python raspberry-pi raspbian twython

I'm writing a small script in python running in Raspbian to tweet a speedtest result and i'm trying to attach the image, this is the code:

import sys, urllib, cStringIO
from PIL import Image
from twython import Twython

...

file = cStringIO.StringIO(urllib.urlopen(url_img_).read())
imagen = Image.open(file)
print imagen
image_ids = twitter.upload_media(media=imagen)
print image_ids
twitter.update_status(status=MESSAGE_, media_ids=[image_ids['media_id']])

but i getting this error on the twitter.upload_media:

Traceback (most recent call last):
  File "twitter_phy.py", line 29, in <module>
    image_ids = twitter.upload_media(media=imagen)
  File "/usr/local/lib/python2.7/dist-packages/twython/endpoints.py", line 140, in upload_media
    return self.post('https://upload.twitter.com/1.1/media/upload.json', params=params)
  File "/usr/local/lib/python2.7/dist-packages/twython/api.py", line 269, in post
    return self.request(endpoint, 'POST', params=params, version=version)
  File "/usr/local/lib/python2.7/dist-packages/twython/api.py", line 259, in request
    api_call=url)
  File "/usr/local/lib/python2.7/dist-packages/twython/api.py", line 198, in _request
    retry_after=response.headers.get('X-Rate-Limit-Reset'))
twython.exceptions.TwythonError: Twitter API returned a 400 (Bad Request), media parameter is missing.

this is my first approach to python, please help :(

2 个答案:

答案 0 :(得分:1)

woops... so saving the file first made the trick:

## download the image
f = open('speedtest.png','wb')
f.write(urllib.urlopen(url_).read())
f.close()

## read the saved image
imagen =  open('speedtest.png', 'rb')

## upload it
image_ids = twitter.upload_media(media=imagen)

## tweet it!
twitter.update_status(status=MESSAGE_, media_ids=[image_ids['media_id']])
sys.exit()

答案 1 :(得分:1)

Twython需要将媒体参数检测为文件,并通过检查helpers.pyhasattr(v, 'read') and callable(v.read)中执行此操作。