Reputation: 3
I am trying to update a user's Twitter profile picture using an image that is in memory. Here is what I have right now:
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
tweets = api.user_timeline(screen_name = QUERY, count = 5, include_rts = False,
tweet_mode = 'extended'
response = requests.get(tweets[0].user.profile_image_url)
img = Image.open(BytesIO(response.content))
flipped_img = img.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
api.update_profile_image(flipped_img)
when I run this I run into the following error
File "c:\Users\x\Python\twitter_bot.py", line 32, in <module>
api.update_profile_image(flipped_img)
File "C:\Users\x\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\tweepy\api.py", line 46, in wrapper
return method(*args, **kwargs)
File "C:\Users\x\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\tweepy\api.py", line 2912, in update_profile_image
files = {'image': open(filename, 'rb')}
TypeError: expected str, bytes or os.PathLike object, not Image
I have tried to search online for ways to convert in memory Image to os.PathLike object but found no solution. Thanks in advance for the help!
Upvotes: 0
Views: 872
Reputation: 168957
It looks like the Tweepy API doesn't like images that are in memory, so use a temporary file:
img = Image.open(BytesIO(response.content))
flipped_img = img.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
with tempfile.NamedTemporaryFile(suffix=".png") as tf:
img.save(tf, format="png")
api.update_profile_image(tf.name)
The with
block ensures the temporary file is deleted afterwards.
Upvotes: 1