Created
January 23, 2018 18:44
-
-
Save Roach/cb839d2b017a194b99d4dddc919542c5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment