pythontwitterpaginationtwitter4j

How to install twitter4j package (Java) alternative in Python?


I am new to Python. I want to retrive tweets from user timeline.I used the following code.

api = twitter.Api(consumer_key, consumer_secret, access_token, access_secret)
tweets = api.GetUserTimeline(screen_name = user.screen_name,count = 500)

How ever I notice that it retrieves only 200 tweets from first page of Twitter timeline. I want 500 tweets. So the code should iterate through 3 pages to give 500 tweets. Is there any function to do so.


Solution

  • You can only receive 200 tweets per api call. What you can do is save the oldest tweet id and get tweets older than tweet id you saved. This gets you any number of tweets within total number of tweets limit imposed by twitter

    #no of tweets you want to request
    max_tweets = 500
    #make initial request for most recent tweets (200 is the maximum allowed count)
    new_tweets = api.GetUserTimeline(screen_name = screen_name,count=max_tweets)
    
    #save most recent tweets
    alltweets.extend(new_tweets)
    
    
    #save the id of the oldest tweet less one
    oldest = alltweets[-1].id - 1
    #loop for remaining tweets
    while(len(alltweets)<max_tweets):
        alltweets.extend(api.GetUserTimeline(screen_name = screen_name,count=(max_tweets-len(alltweets)),max_id=oldest))
        oldest = alltweets[-1].id - 1
    

    I have not checked if its working but it should work