made a collection of twitter api solutions
[twitter-api-cdsw-solutions] / solution-followers-2-cursor.py
1 # For each of your followers, find out how many followers they have.
2
3 import encoding_fix
4 import tweepy
5 from twitter_authentication import CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET
6 import time
7
8 auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
9 auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
10
11 api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
12
13 user = api.get_user("makoshark")
14
15 # I found the list of functions in Tweepy here:
16 #   https://tweepy.readthedocs.org/en/v3.2.0/api.html
17
18 # I found the idea of how to the user the Cursor here:
19 #   https://tweepy.readthedocs.org/en/v3.2.0/cursor_tutorial.html
20
21 follower_ids = []
22 for page in tweepy.Cursor(api.followers_ids, screen_name="makoshark").pages():
23     for follower in page:
24         follower_ids.append(follower)
25
26
27 # the answer is using the api.lookup_users() code. unfortunately, this
28 # seems to only work with 100 users at a time. the following code makes that
29 # work
30 counter = 0
31 tmp_ids = []
32 users = []
33 for follower in follower_ids:
34     tmp_ids.append(follower)
35     counter = counter + 1
36
37     # if we've hit 100, we grab data and then reset things and keep going
38     if counter == 100:
39         tmp_users = api.lookup_users(user_ids=tmp_ids)
40         users = users + tmp_users
41
42         counter = 0
43         tmp_ids = []
44
45 # run once more when we're done
46 tmp_users = api.lookup_users(user_ids=tmp_ids)
47 users = users + tmp_users
48
49 # run through and print out the list of followers
50 for user in users:
51     print("%s : %s" % (user.screen_name, user.followers_count))
52
53           

Benjamin Mako Hill || Want to submit a patch?