Search code examples
pythontwitter

Twitter API - get tweets with specific id


I have a list of tweet ids for which I would like to download their text content. Is there any easy solution to do this, preferably through a Python script? I had a look at other libraries like Tweepy and things don't appear to work so simple, and downloading them manually is out of the question since my list is very long.


Solution

  • You can access specific tweets by their id with the statuses/show/:id API route. Most Python Twitter libraries follow the exact same patterns, or offer 'friendly' names for the methods.

    For example, Twython offers several show_* methods, including Twython.show_status() that lets you load specific tweets:

    CONSUMER_KEY = "<consumer key>"
    CONSUMER_SECRET = "<consumer secret>"
    OAUTH_TOKEN = "<application key>"
    OAUTH_TOKEN_SECRET = "<application secret"
    twitter = Twython(
        CONSUMER_KEY, CONSUMER_SECRET,
        OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    
    tweet = twitter.show_status(id=id_of_tweet)
    print(tweet['text'])
    

    and the returned dictionary follows the Tweet object definition given by the API.

    The tweepy library uses tweepy.get_status():

    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    api = tweepy.API(auth)
    
    tweet = api.get_status(id_of_tweet)
    print(tweet.text)
    

    where it returns a slightly richer object, but the attributes on it again reflect the published API.