skip to Main Content

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

Answers


  1. Chosen as BEST ANSWER

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

  2. 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).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search