-
Notifications
You must be signed in to change notification settings - Fork 1
/
twitter_stats.py
80 lines (60 loc) · 2.34 KB
/
twitter_stats.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import time
import shelve
import datetime
import settings
from twython import Twython
from contextlib import contextmanager
@contextmanager
def closing(this):
try:
yield this
finally:
this.close()
class TwitterStats():
def __init__(self):
# connect to twitter api
self.twitter = Twython(
app_key=settings.consumer_key,
app_secret=settings.consumer_secret,
oauth_token=settings.oauth_token,
oauth_token_secret=settings.oauth_token_secret
)
def init_storage(self):
storage = shelve.open('twitter_stats', writeback=True)
if not storage:
storage['followers'] = set()
storage['unfollowers'] = []
storage['unfollowers_since_last_check'] = None
storage['last_update'] = None
return storage
def get_followers(self):
follower_ids = self.twitter.getFollowersIDs()['ids']
return set(follower_ids)
def show_screen_name(self, user_id):
user = self.twitter.showUser(user_id=user_id)
screen_name = user['screen_name']
return screen_name
def update_unfollower_stats(self):
with closing(self.init_storage()) as storage:
previous_followers = storage['followers']
current_followers = self.get_followers()
new_unfollower_ids = previous_followers - current_followers
unfollowers_since_last_check = []
for follower_id in new_unfollower_ids:
unfollower = {
'id': follower_id,
'screen_name': self.show_screen_name(follower_id),
'timestamp': datetime.datetime.now().strftime('%b %d %Y %H:%M:%S')
}
storage['unfollowers'].append(unfollower)
unfollowers_since_last_check.append(unfollower)
storage['followers'] = current_followers
storage['unfollowers_since_last_check'] = unfollowers_since_last_check
storage['last_update'] = datetime.datetime.now().strftime('%b %d %Y %H:%M:%S')
def main():
twitter_stats = TwitterStats()
while True:
twitter_stats.update_unfollower_stats()
time.sleep(settings.update_interval)
if __name__ == '__main__':
main()