如何使用 tweepy 中的图像 url 使用图像更新 twitter 状态? [英] How to update twitter status with image using image url in tweepy?

查看:29
本文介绍了如何使用 tweepy 中的图像 url 使用图像更新 twitter 状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我用过的代码,

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

I know that I have to use a file from the local directory with the above command. Is there a way to use a URL while using update_with_media ?

推荐答案

您需要使用本地文件通过 tweepy 上传.我建议先使用像 requests 这样的库来下载文件.

You need use a local file to upload via tweepy. I would suggest using a library like requests to download the file first.

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)

这篇关于如何使用 tweepy 中的图像 url 使用图像更新 twitter 状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆