Search code examples
pythontwitteriterationtimeline

Twitter timeline iteration to get all of my tweets with a for loop


With this script i'm trying to iterate through my timeline with the twitter api. I'm using time delay in a "for" loop to get all of my tweets in a List of objects like this:

x = [<twitter.status.Status at 0x7fb23b7c5090>, <twitter.status.Status at 0x7fb5fdb7c5090>,<twitter.status.Status at 0x7fbs4b7c5090>,<twitter.status.Status at 0x7f255b7c5090>, ...]

#Setting the connection:
api = twitter.Api(consumer_key= cons_key,
                  consumer_secret = cons_secret,
                  access_token_key = accs_token,
                  access_token_secret = accs_token_secret)

#Getting the latest id and put it on a list called "lis"

x = api.GetUserTimeline(screen_name = "My_Username", count = 1, include_rts = True)
lis=[x[0].id]

#Creating a list to append my twitter status objects.
tweet_info = []

## Iterate through all tweets, say for example 4 times
for i in range(0, 4): 
## tweet extract method with the last list item as the max_id

    user_timeline = api.GetUserTimeline(screen_name="My_Username",
    count=3, include_rts = True, max_id=lis[-1])

    time.sleep(2) ## 2 seconds rest between api calls

    for tweet in range(len(user_timeline)):
    x = user_timeline[tweet]
        tweet_info.append(x)
        lis.append(tweet['id']) #appending the id's in order to my list in order to extract the last one for the next time it iterates.

When i run my code i'm getting this error:

TypeError                                 Traceback (most recent call last)
<ipython-input-103-11f235fc3b3a> in <module>()
      7         x = user_timeline[tweet]
      8         tweet_info.append(x)
----> 9         lis.append(tweet['id'])

TypeError: 'int' object has no attribute '__getitem__'

What am I doing wrong and how can be fixed?


Solution

  • It is because tweet is an integer

    Your code:

    for tweet in range(len(user_timeline)):
        x = user_timeline[tweet]
        tweet_info.append(x)
        lis.append(tweet['id'])
    

    You are internally doing this:

    1["id"]
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: 'int' object has no attribute '__getitem__'
    

    That is :

     for i in range(len(a)):
        print i
        print i["id"]
    
     1
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: 'int' object has no attribute '__getitem__'