I wrote earlier "Access Twitter API with Python", but around March 2014, it became possible to post multiple images, and along with that, around image tweets It seems that the specifications have changed, so I added it.
Until then, the statuses / update API for regular tweets and the [statuses / update_with_media](https: // dev) for tweets with images. .twitter.com/rest/reference/post/statuses/update_with_media), but there is a new media / upload It seems that it has been added and the previous update_with_media has been deprecated.
In the old API, the image and text were posted at the same time, but in the new API, it seems that the image is uploaded first, the media ID is obtained, and the text is tweeted.
The code looks like this. Replace CK, CS, AT, AS
with your own key as appropriate. Python2, 3 works with either.
upload_media.py
#!/usr/bin/env python
# coding: utf-8
import json
from requests_oauthlib import OAuth1Session
CK = 'XXXXXXXXXXXXXXXXXXXXXX' # Consumer Key
CS = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # Consumer Secret
AT = 'XXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # Access Token
AS = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # Accesss Token Secert
url_media = "https://upload.twitter.com/1.1/media/upload.json"
url_text = "https://api.twitter.com/1.1/statuses/update.json"
#Start an OAuth authentication session
twitter = OAuth1Session(CK, CS, AT, AS)
#Image posting
files = {"media" : open('image.jpg', 'rb')}
req_media = twitter.post(url_media, files = files)
#Check the response
if req_media.status_code != 200:
print ("Image update failed: %s", req_media.text)
exit()
#Get Media ID
media_id = json.loads(req_media.text)['media_id']
print ("Media ID: %d" % media_id)
#Post text with Media ID
params = {'status': 'Image posting test', "media_ids": [media_id]}
req_media = twitter.post(url_text, params = params)
#Check the response again
if req_media.status_code != 200:
print ("Text update failed: %s", req_text.text)
exit()
print ("OK")
If you tweet with 4 images, do media / upload 4 times and post the text with all media ids in a list. I haven't tried it.
Recommended Posts