| import json | |
| from twitter import * | |
| # Twitter app credentials | |
| token = "..." | |
| token_secret = "..." | |
| consumer_key = "..." | |
| consumer_secret = "..." | |
| # Twitter client | |
| t = Twitter(auth=OAuth(token, token_secret, consumer_key, consumer_secret)) | |
| def save_list(data): | |
| formatted = {"ids": data} | |
| with open('/home/gifs/twitterdiff/twitter-followers.json', 'w') as f: | |
| json.dump(formatted, f, ensure_ascii=False) | |
| def diff(first, second): | |
| missing_followers = set(first) - set(second) | |
| new_followers = set(second) - set(first) | |
| ids = {'new': list(new_followers), 'missing': list(missing_followers)} | |
| return ids | |
| def screen_names(user_ids): | |
| # Fetch the screennames | |
| users = t.users.lookup(user_id=','.join(map(str, user_ids))) | |
| screen_names = ["@{}".format(user['screen_name']) for user in users] | |
| # Join the list of screennames as "@bill, @jenny and @joe unfollowed you" | |
| sn_list = ", ".join(screen_names[:-2] + [" and ".join(screen_names[-2:])]) | |
| return sn_list | |
| # Load previous list from JSON file | |
| previous_follower_ids = json.load(open('/home/gifs/twitterdiff/twitter-followers.json'))['ids'] | |
| # Fetch updated follower list from the API | |
| current_follower_ids = t.followers.ids()['ids'] | |
| # # Compare previous followers with current followers | |
| results = diff(previous_follower_ids, current_follower_ids) | |
| if results['missing']: | |
| try: | |
| unfollows = screen_names(results['missing']) | |
| t.direct_messages.new( | |
| user="@roach", | |
| text="{} unfollowed you.".format(unfollows)) | |
| except: | |
| print "API Error" | |
| save_list(current_follower_ids) |