2016-02-03 68 views
1

我用Python寫一個小腳本在運行Raspbian鳴叫一個SPEEDTEST結果的圖像時,我試圖附加圖像, 這是代碼:Twython返回一個400(壞請求)啁啾

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']]) 

,但我對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. 

這是我的第一種方法蟒蛇,請幫助:(

+0

查看twitter api - 顯然你錯過了一個參數...你已經設置了你的API密鑰,對吧? –

+0

此外,您可以嘗試先將圖像保存到硬盤驅動器,然後執行以下操作:http://twython.readthedocs.org/en/latest/usage/advanced_usage.html#updating-status-with-image –

+0

@WayneWerner yes ,推文只是文本,讓我先嚐試下載圖片 –

回答

1

woops ...所以保存該文件首次提出的伎倆:

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

Twython需要檢測介質參數作爲一個文件,它通過檢查hasattr(v, 'read') and callable(v.read)helpers.py這樣做。