Search code examples
pythontweepyerrno

Tweepy, upload media error API from The art institute of chicago = Invalid argument


Trying to have fun with a twitter bot.

The idea is : according to the art institute of chicago API, posting a Tweet with the informations (Artist, Date, Place...) And the media (picture).

I can't upload a media here, bellow you can see the traceback that I am trying to fix.

I will appreciate ! B

import tweepy
import requests
import random
import time
import io
############################# My logs ######################################
def twitter_api():
    consumer_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    consumer_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    access_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    access_token_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)
    return api

############################# My fonctions #################################

############################# The Loop ######################################

while True:

        get_number()
        r = requests.get(f"https://api.artic.edu/api/v1/artworks/{get_number()}")
        a = r.json()
        get_Titre(),get_Artist(),get_Date(),get_Place(),get_Im()

        requests2 = (f"https://www.artic.edu/iiif/2/{get_Im()}/full/843,/0/default.jpg")

        print("Imge ok:....................", requests2)
        print(type(requests2))
        message = (get_Titre()+ get_Artist()+str(get_Date())+get_Place())
        print("La tête du tweet sera:", message)
        twitter_api().update_status_with_media(message,requests2)
        time.sleep(14400)

Here is the Traceback :

Traceback (most recent call last):
  File "C:\PycharmProjects\TwitterBot\main.py", line 76, in <module>
    twitter_api().update_status_with_media(message,requests2)
  File "C:\PycharmProjects\TwitterBot\venv\lib\site-packages\tweepy\api.py", line 46, in wrapper
    return method(*args, **kwargs)
  File "C:\PycharmProjects\TwitterBot\venv\lib\site-packages\tweepy\api.py", line 1181, in update_status_with_media
    files = {'media[]': stack.enter_context(open(filename, 'rb'))}
OSError: [Errno 22] Invalid argument: 'https://www.artic.edu/iiif/2/904ea189-c852-5f84-c614-a26a851f9b74/full/843,/0/default.jpg'


Solution

  • See documentation for update_status_with_media - second argument has to be filename.

    update_status_with_media(text, filename, file, ...)
    

    But third argument can be file-like object and this means object which has function .read().

    If you would use urllib.request then it gives object which has .read() and it works.

    BTW: you have to use any text as second argument - can be fake filename but function needs it.

    import os
    import urllib.request
    import tweepy
    
    url = "https://www.iheartradio.ca/image/policy:1.15731844:1627581512/rick.jpg?f=default&$p$f=20c1bb3"
    text = "Testing module tweepy"
    
    # --- create file_like_object ---
    
    file_like_object = urllib.request.urlopen(url)
    
    # --- send tweet --- 
    
    consumer_key = os.getenv('TWITTER_CONSUMER_KEY')
    consumer_secret = os.getenv('TWITTER_CONSUMER_SECRET')
    access_token = os.getenv('TWITTER_ACCESS_TOKEN')
    access_token_secret = os.getenv('TWITTER_ACCESS_TOKEN_SECRET')
    
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    
    twitter_api = tweepy.API(auth)
    
    # use any filename as second argument, and file-like object as third argument
    twitter_api.update_status_with_media(text, 'fake_name.jpg', file=file_like_object)
    

    With requests you have to use io.BytesIO to create file-like object

    import os
    import io
    import requests
    import tweepy
    
    url = "https://www.iheartradio.ca/image/policy:1.15731844:1627581512/rick.jpg?f=default&$p$f=20c1bb3"
    text = "Testing module tweepy"
    
    # --- create file_like_object ---
    
    response = requests.get(url)
    file_like_object = io.BytesIO(response.content)
    
    # --- send tweet --- 
    
    consumer_key = os.getenv('TWITTER_CONSUMER_KEY')
    consumer_secret = os.getenv('TWITTER_CONSUMER_SECRET')
    access_token = os.getenv('TWITTER_ACCESS_TOKEN')
    access_token_secret = os.getenv('TWITTER_ACCESS_TOKEN_SECRET')
    
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    
    twitter_api = tweepy.API(auth)
    
    # use any filename as second argument, and file-like object as third argument
    twitter_api.update_status_with_media(text, 'fake_name.jpg', file=file_like_object)
    

    EDIT:

    Eventually you can use stream=True and then response.raw gives file-like object but this is not so popular.

    # --- create file_like_object ---
    
    response = requests.get(url, stream=True)
    file_like_object = response.raw