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

18,759

Solution 1

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)

Solution 2

Twython Release 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']])
Share:
18,759

Related videos on Youtube

kane.zorfy
Author by

kane.zorfy

Updated on June 04, 2022

Comments

  • kane.zorfy
    kane.zorfy almost 2 years

    This is the code I've used,

    #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")
    

    This is the error I'm getting

    No such file or directory
    

    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 ?

  • kane.zorfy
    kane.zorfy almost 9 years
    Tried it too. Twitter just shows it as a plain text
  • kane.zorfy
    kane.zorfy almost 9 years
    Works fine. Is there any way to remove the temporary downloaded file once the operation is done.
  • Brobin
    Brobin almost 9 years
    Yep! just use os.remove(filename). I'll edit my post to reflect this.
  • AtAFork
    AtAFork over 7 years
    Note: URLs will count against your tweet character limit