2

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 :(

Alfredo M
  • 568
  • 3
  • 7
  • 26
  • Check out the twitter api - apparently you're missing a parameter... You have set your api key, right? – Wayne Werner Feb 03 '16 at 03:07
  • Also, you may try saving the image to your hard drive first and doing exactly this: http://twython.readthedocs.org/en/latest/usage/advanced_usage.html#updating-status-with-image – Wayne Werner Feb 03 '16 at 03:08
  • @WayneWerner yes, tweeting just text it worked, let me try downloading the image first – Alfredo M Feb 03 '16 at 04:11

2 Answers2

2

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()
Alfredo M
  • 568
  • 3
  • 7
  • 26
1

Twython needs to detect the media parameter as a file, and it does so in helpers.py by checking for hasattr(v, 'read') and callable(v.read).

John Lehmann
  • 7,975
  • 4
  • 58
  • 71