如何使用 tweepy 中的图像 url 更新带有图像的推特状态?

How to update twitter status with image using image url in tweepy?

这是我用过的代码,

#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 ?

您需要使用本地文件通过 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)

为什么不在状态更新中包含 link?

img = "http://animalia-life.com/data_images/bird/bird1.jpg"
api.status(status="%s Nice one" % img)

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