Get all friends of a given user on twitter with tweepy

user2497792 picture user2497792 · Nov 7, 2014 · Viewed 12.3k times · Source

Using tweepy I am able to return all of my friends using a cursor. Is it possible to specify another user and get all of their friends?

user = api.get_user('myTwitter')
print "Retreiving friends for", user.screen_name
for friend in tweepy.Cursor(api.friends).items():
 print "\n", friend.screen_name

Which prints a list of all my friends, however if I change the first line to another twitter user it still returns my friends. How can I get friends for any given user using tweepy?

#first line is changed to
user = api.get_user('otherUsername') #still returns my friends

Additionally user.screen_name when printed WILL return otherUsername

The question Get All Follower IDs in Twitter by Tweepy does essentially what I am looking for however it returns only a count of ID's. If I remove the len() function I will I can iterate through a list of user IDs, but is it possible to get screen names @twitter,@stackoverflow, @etc.....?

Answer

Luigi picture Luigi · Nov 10, 2014

You can use the ids variable from the answer you referenced in the other answer to get the the id of the followers of a given person, and extend it to get the screen names of all of the followers using Tweepy's api.lookup_users method:

import time
import tweepy

auth = tweepy.OAuthHandler(..., ...)
auth.set_access_token(..., ...)

api = tweepy.API(auth)

ids = []
for page in tweepy.Cursor(api.followers_ids, screen_name="McDonalds").pages():
    ids.extend(page)
    time.sleep(60)

screen_names = [user.screen_name for user in api.lookup_users(user_ids=ids)]