Sam Perry
Sam Perry

Reputation: 2614

How To Add An Image To A Tweet With TwitterAPI?

I'm struggling to find documentation on how to add an image to a Tweet through Python's TwitterAPI. Any ideas?

Here's what I have so far:

consumer_key = ' '
consumer_secret = ' '
access_token_key = ' '
access_token_secret = ' '

from TwitterAPI import TwitterAPI

api = TwitterAPI(consumer_key, consumer_secret, access_token_key, access_token_secret)
file = open('image.jpg', 'rb')
data = file.read()
r = api.request('statuses/update_with_media', {'status':'Your tweet'}, {'media[]':data})
print(r.status_code)

Output:

Traceback (most recent call last):
File "tweet_media.py", line 48, in <module>
r = api.request('statuses/update_with_media', {'status':'Your tweet'}, {'media[]':data})
TypeError: request() takes at most 3 arguments (4 given)

Upvotes: 5

Views: 6704

Answers (2)

Jonas
Jonas

Reputation: 4048

This example will upload a tweet with an embedded image. You will need to use TwitterAPI 2.1.8.7 or higher.

from TwitterAPI import TwitterAPI

CONSUMER_KEY = ''
CONSUMER_SECRET = ''
ACCESS_TOKEN_KEY = ''
ACCESS_TOKEN_SECRET = ''

api = TwitterAPI(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET)
file = open('Your_image.png', 'rb')
data = file.read()
r = api.request('statuses/update_with_media', {'status':'Your tweet'}, {'media[]':data})
print(r.status_code)

Upvotes: 9

poke
poke

Reputation: 387517

Two options:

  1. Put a link into the tweet text.
  2. Upload the file to Twitter itself using the update_with_media API endpoint.

Upvotes: 0

Related Questions