· 7 years ago · Jul 07, 2018, 12:08 AM
1from collections import Counter
2from json import dumps
3from time import sleep
4from twitter import Api # pip install python-twitter
5
6# Twitter access settings
7OAUTH_TOKEN = "YOUR_OAUTH_TOKEN"
8OAUTH_SECRET = "YOUR_OAUTH_SECRET"
9CONSUMER_KEY = "YOUR_CONSUMER_KEY"
10CONSUMER_SECRET = "YOUR_CONSUMER_SECRET"
11
12
13api = Api(consumer_key=CONSUMER_KEY,
14 consumer_secret=CONSUMER_SECRET,
15 access_token_key=OAUTH_TOKEN,
16 access_token_secret=OAUTH_SECRET,
17 sleep_on_rate_limit=True)
18
19users_followed_by_follows = {}
20
21
22def get_following():
23 """
24 Retrieves the people you are following on Twitter.
25
26 Returns a list of twitter.User objects.
27 """
28 follows = api.GetFriends()
29 print("you are following {} people".format(len(following)))
30
31 return following
32
33
34def get_followed_by_people_followed(follows):
35 """
36 Returns a dictionary of follows. Top followed by friends is the suggestions.
37 This can be hampered by Twitter reaching capacity, therefore, there is a kludgy
38 time-sleep in there whenever an error is encountered.
39 """
40 for user in follows:
41 success = False
42 while not success:
43 try:
44 followed = api.GetFriends(user_id=user.id, screen_name=user.screen_name)
45 success = True
46 except:
47 sleep(10)
48 print("User {} is following {} people".format(user.screen_name, len(followed)))
49 for follow in followed:
50 if not follow in follows:
51 if not users_followed_by_follows.get(follow.screen_name):
52 users_followed_by_follows[follow.screen_name] = 1
53 else:
54 users_followed_by_follows[follow.screen_name] += 1
55 with open('users_followed_by_follows.json', 'w') as file:
56 file.write(dumps(users_followed_by_follows))
57 print("The people you follow are following {} unique people".format(len(users_followed_by_follows)))
58
59
60def print_top_suggestions():
61 """
62 Prints the users_followed_by_follows dictionary in descending order of value.
63 """
64 d = Counter(users_followed_by_follows)
65 for k, v in d.most_common():
66 print("{} ({})".format(k, v))
67
68
69following = get_following()
70get_followed_by_people_followed(following)
71print_top_suggestions()