这是我用过的代码,
#Twitter credentials
access_token = config.get('twitter_credentials', 'access_token')
access_token_secret = config.get('twitter_credentials', 'access_token_secret')
consumer_key = config.get('twitter_credentials', 'consumer_key')
consumer_secret = config.get('twitter_credentials', 'consumer_secret')
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = API(auth)
img = "http://animalia-life.com/data_images/bird/bird1.jpg"
api.update_with_media(img, status="Nice one")
这是我得到的错误
No such file or directory
我知道我必须使用上面的命令使用本地目录中的文件。有没有办法在使用update_with_media时使用URL?
答案 0 :(得分:19)
您需要使用本地文件通过tweepy上传。我建议先使用像requests
这样的库来下载文件。
import requests
import os
def twitter_api():
access_token = config.get('twitter_credentials', 'access_token')
access_token_secret = config.get('twitter_credentials', 'access_token_secret')
consumer_key = config.get('twitter_credentials', 'consumer_key')
consumer_secret = config.get('twitter_credentials', 'consumer_secret')
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = API(auth)
return api
def tweet_image(url, message):
api = twitter_api()
filename = 'temp.jpg'
request = requests.get(url, stream=True)
if request.status_code == 200:
with open(filename, 'wb') as image:
for chunk in request:
image.write(chunk)
api.update_with_media(filename, status=message)
os.remove(filename)
else:
print("Unable to download image")
url = "http://animalia-life.com/data_images/bird/bird1.jpg"
message = "Nice one"
tweet_image(url, message)
答案 1 :(得分:2)
Twython版本3.4.0
photo = open('/path/to/file/image.jpg', 'rb') response = twitter.upload_media(media=photo) twitter.update_status(status='Checkout this cool image!', media_ids=[response['media_id']])
答案 2 :(得分:0)
为什么不在状态更新中包含该链接?
img = "http://animalia-life.com/data_images/bird/bird1.jpg"
api.status(status="%s Nice one" % img)