Skip to content

Instantly share code, notes, and snippets.

@bugb
Created December 26, 2021 19:57
Show Gist options
  • Save bugb/8cde1db29d345ee657ab3bf6219a06e4 to your computer and use it in GitHub Desktop.
Save bugb/8cde1db29d345ee657ab3bf6219a06e4 to your computer and use it in GitHub Desktop.
How to get latest tweet for a user with python and tweepy.

Set tweepy

To install tweepy do:

pip install tweepy

More information at http://tweepy.org.

Get keys and tokens from Twitter

To use tweepy and the Twitter API you need to register your application at https://developer.twitter.com/en/apps and get the consumer API keys, access token and access token secret. I will use the variables consumer_key, consumer_secret, access_token and access_token_secret to store these strings.

Get the last tweet for a user

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
username='some_twitter_username'
tweets_list= api.user_timeline(username, count=1) # Get the last tweet
# By default api.user_timeline() gets the last 20 tweets, but you can specify it
# with the count parameter
tweet= tweet_list[0] # An object of class Status (tweepy.models.Status)
print(tweet.created_at) # Print the datetime object for the tweet
print(tweet.text) # Print the text of the tweet
print(tweet.in_reply_to_screen_name) # Print the username of the user the 
# the tweet is replying to, it is None if the tweet is not a reply

To see a list of attributes of the status object you can do:

dir(tweet) # (tweet is the same variable from above)

tweet.text will give you a 140 character long string, if the text is larger than that it will be truncated to end with an ellipsis character, a space, and a shortened self-permalink. To get the full text you will have to instead use:

tweets_list= api.user_timeline(username, count=1, tweet_mode='extended')
tweet= tweet_list[0]
print(tweet.full_text) # the text attribute is replaced by full_text

Here you can find more informarion about the full text problem:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment