Skip to content

Instantly share code, notes, and snippets.

@vsaraph
Created June 30, 2019 01:38
Show Gist options
  • Save vsaraph/63f8c5f691f59dd55b9bc901df3e0523 to your computer and use it in GitHub Desktop.
Save vsaraph/63f8c5f691f59dd55b9bc901df3e0523 to your computer and use it in GitHub Desktop.
Generate new Twitter OAuth bearer token and use the token to fetch latest tweet from a given account
import requests
import base64
# encode consumer API key and secret key
key = input("key: ")
secret = input("secret: ")
encoded = base64.b64encode((key + ":" + secret).encode()).decode()
# construct payload
endpoint = "https://api.twitter.com/oauth2/token"
payload = "grant_type=client_credentials"
# include encoded keys in header
headers = {"Authorization": "Basic " + encoded,
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"}
# send request
response = requests.post(endpoint, data=payload, headers=headers)
# save bearer token
bearer_token_file = open("bearer.key", "w")
bearer_token_file.write(response.json()["access_token"])
bearer_token_file.close()
import requests
# get bearer token
bearer_token_file = open("bearer.key")
bearer_token = bearer_token_file.readline().strip()
bearer_token_file.close()
# construct payload
endpoint = "https://api.twitter.com/1.1/statuses/user_timeline.json"
screen_name = input("screen name: ")
payload = {"screen_name": screen_name,
"count": 1,
"include_rts": False,
"exclude_replies": True,
"tweet_mode": "extended",
}
# include bearer token in header
headers = {"Authorization": "Bearer " + bearer_token}
# send request and print result tweet content to terminal
response = requests.get(endpoint, params=payload, headers=headers)
print(response.json()[0]['full_text'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment