Getting whole user timeline of a Twitter user

Vin23 picture Vin23 · Feb 14, 2017 · Viewed 16.9k times · Source

I want to get the all of a user tweets from one Twitter user and so far this is what I came up with:

import twitter
import json
import sys
import tweepy 
from tweepy.auth import OAuthHandler


CONSUMER_KEY = ''
CONSUMER_SECRET= ''
OAUTH_TOKEN=''
OAUTH_TOKEN_SECRET = ''

auth = twitter.OAuth(OAUTH_TOKEN,OAUTH_TOKEN_SECRET,CONSUMER_KEY,CONSUMER_SECRET)


twitter_api =twitter.Twitter(auth=auth)

print twitter_api

statuses = twitter_api.statuses.user_timeline(screen_name='@realDonaldTrump')
print [status['text'] for status in statuses]

Please ignore the unnecessary imports. One problem is that this only gets a user's recent tweets (or the first 20 tweets). Is it possible to get all of a users tweet? To my knowledge, the GEt_user_timeline (?) only allows a limit of 3200. Is there a way to get at least 3200 tweets? What am I doing wrong?

Answer

asongtoruin picture asongtoruin · Feb 14, 2017

There's a few issues with your code, including some superfluous imports. Particularly, you don't need to import twitter and import tweepy - tweepy can handle everything you need. The particular issue you are running into is one of pagination, which can be handled in tweepy using a Cursor object like so:

import tweepy

# Consumer keys and access tokens, used for OAuth
consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''

# OAuth process, using the keys and tokens
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

# Creation of the actual interface, using authentication
api = tweepy.API(auth)

for status in tweepy.Cursor(api.user_timeline, screen_name='@realDonaldTrump', tweet_mode="extended").items():
    print(status.full_text)