Skip to content

Instantly share code, notes, and snippets.

Last active October 30, 2017 07:42
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cclauss/8391840 to your computer and use it in GitHub Desktop.
Save cclauss/8391840 to your computer and use it in GitHub Desktop.
Given a Twitter application access_token and a Twitter screen_name... print out that user's most recent Tweets using the Twitter v1.1 REST API.
import json, requests, sys #, pprint
Use (works on Pythonista) to get your Twitter access_token.
> You will need to create a new application on
> Enter below the Twitter access_token you get from running
twitter_access_token = 'Replace this text with the access_token you get from running'
tweet_fmt = 'On {created_at}, {user[name]} ({user[screen_name]}) wrote:\n> {text}'
def recent_tweets(screen_name, tweet_count = 3):
headers = { 'Authorization' : 'Bearer ' + twitter_access_token }
payload = { 'count' : str(tweet_count), # keep low to avoid taxing Twitter API
'screen_name' : screen_name }
timelineURL = ''
response = requests.get(timelineURL, params=payload, headers=headers)
tweets_as_json = response.json()
if not isinstance(tweets_as_json, list): # we should get a list of tweet_dicts
return response.text # exit with an error message from API
with open('tweets.json', 'w') as out_file: # write the tweets to a file to allow
json.dump(tweets_as_json, out_file) # experimentation without calling API
for tweet_dict in tweets_as_json:
#pprint.pprint(tweet_dict) # uncomment to see available fields
def main(argv):
screen_name = argv[1] if len(argv) > 1 else 'pycoders'
tweet_count = argv[2] if len(argv) > 2 else 3
return recent_tweets(screen_name, tweet_count)
if __name__ == '__main__':
print('-' * 40)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment