Search code examples
pythonpython-3.xtweepy

How to get a person's friends and followers on Twitter using the tweepy library?


The getting_friends_follwers() function below works if I remove the value 100 from (cursor2.items (100)). My goal is to get these names (followers and friends) and save them in a "amigos.txt" file.

The problem: The name screen_name has a gigantic amount of friends and followers and, thus, the connection is closed by Twitter. I thought about trying to capture the names 100 out of 100 (hence the value 100 in the call to cursor2) but the following error occurs:

builtins.TypeError: '<' not supported between instances of 'User' and 'User'

How to fix it?

Meu = []
def getting_friends_follwers():
    # Get list of followers and following for group of users tweepy
    f = open("amigos.txt","w")
    cursor = tweepy.Cursor(api.friends, screen_name="Carlos")
    cursor2 = tweepy.Cursor(api.followers, screen_name="Carlos")
##    for user in cursor.items():
##        print('friend: ' + user.screen_name)

    for user in sorted(cursor2.items(100)):###funciona se eu tirar este valor!!!
         f.write(str(user.screen_name)+ "\n")


         print('follower: ' + user.screen_name)

f.close()
getting_friends_follwers()

Solution

  • You are getting that error because you are passing the items to the "sorted" function, which is trying to sort those "User" objects but it is not able to do that as there's no instructions about how to "sort" tweepy user objects.

    If you remove "sorted" then the program would work fine.

    Also, you close the file before calling the function. I would suggest you to use the "with open" syntax to assure the file gets closed properly.

    You could write your code like this:

    def getting_friends_follwers(file):
        # Get list of followers and following for group of users tweepy
        cursor = tweepy.Cursor(api.friends, screen_name="Carlos")
        cursor2 = tweepy.Cursor(api.followers, screen_name="Carlos")
    ##    for user in cursor.items():
    ##        print('friend: ' + user.screen_name)
    
        for user in cursor2.items(100):###funciona se eu tirar este valor!!!
             file.write(str(user.screen_name)+ "\n")
             print('follower: ' + user.screen_name)
    
    with open("amigos.txt", "w") as file:
        getting_friends_follwers(file)