Created
August 10, 2019 01:16
-
-
Save astrophysik928/a53953ee1c0c8d1c7d07f01367359d11 to your computer and use it in GitHub Desktop.
Tweet With Image In Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import json | |
from requests_oauthlib import OAuth1Session | |
#definition to connect to Twitter | |
CONSUMER_KEY = "***********************************" | |
CONSUMER_SECRET = "***********************************" | |
ACCESS_TOKEN = "***********************************" | |
ACCESS_TOKEN_SECRET = "***********************************" | |
url_text = 'https://api.twitter.com/1.1/statuses/update.json' | |
url_media = 'https://upload.twitter.com/1.1/media/upload.json' | |
twitter = OAuth1Session(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET) | |
#get picture | |
def get_image(): | |
#"image.jpg" is in the same path with do_twitter.py | |
picture_path = "image.jpg" | |
return picture_path | |
#post to twitter | |
def do_twitter(text): | |
#twitter_post_number is global variable | |
global twitter_post_number | |
#get image | |
picture = get_image() | |
files = {"media" : open(picture, 'rb')} | |
req_media = twitter.post(url_media, files = files) | |
#check out response | |
if req_media.status_code != 200: | |
print ("Uploading picture fails: %s", req_media.text) | |
exit() | |
#get Media ID | |
media_id = json.loads(req_media.text)['media_id'] | |
#post text with Media ID | |
params = {'status': text, "media_ids": [media_id]} | |
req_media = twitter.post(url_text, params = params) | |
#confirm response again | |
if req_media.status_code != 200: | |
print ("Uploading text fails: %s", req_text.text) | |
exit() | |
print ("OK") | |
#main process | |
if __name__ == '__main__': | |
tweet_text = "This is test" | |
#upload data to twitter | |
do_twitter(tweet_text) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment