I wanted to post multiple images, but I was a little addicted to it, so I will post it. It is supposed to work with python 3 series
Posting one image has many other articles and can be easily implemented. Reference: Tweet with image in Python Let's use the source code described here.
Use media / upload for multiple posts.
(get media / upload-> media_id) * Number of sheets-> statuses / update
Although it is media_id, let's insert a comma-separated character string in multiple posts. I borrowed the above source code and rewrote it as follows.
media.py
def tweet_with_image(oauth_sess, tweet_text, path_list_images):
url_media = "https://upload.twitter.com/1.1/media/upload.json"
url_text = "https://api.twitter.com/1.1/statuses/update.json"
media_ids = ""
#Loop for the number of images
for path in path_list_images:
files = {"media" : open(path, 'rb')}
req_media = oauth_sess.post(url_media, files = files)
#Check the response
if req_media.status_code != 200:
print ("Image update failed: {}".format(req_media.text))
return -1
media_id = json.loads(req_media.text)['media_id']
media_id_string = json.loads(req_media.text)['media_id_string']
print ("Media ID: {} ".format(media_id))
#Comma the media ID string","Combine with
if media_ids == "":
media_ids += media_id_string
else:
media_ids = media_ids + "," + media_id_string
print ("media_ids: ", media_ids)
params = {'status': tweet_text, "media_ids": [media_ids]}
req_text = oauth_sess.post(url_text, params = params)
#Check the response again
if req_text.status_code != 200:
print ("Text update failed: {}".format(req_text.text))
return -1
print ("tweet uploaded\n")
return 1
Recommended Posts