Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all friends of a given user on twitter with tweepy

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.....?

like image 926
user2497792 Avatar asked Nov 07 '14 01:11

user2497792


1 Answers

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)]
like image 74
Luigi Avatar answered Nov 08 '22 05:11

Luigi