Last active
January 13, 2023 00:00
-
-
Save nathanKramer/9d7b18bdc458ebe8db586c18ce2a9ac8 to your computer and use it in GitHub Desktop.
Create a twitter list containing your followers or your mutuals, with idempotent `set_list` function
This file contains 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 twitter | |
api = twitter.Api(consumer_key='consumer_key', | |
consumer_secret='consumer_secret', | |
access_token_key='access_token_key', | |
access_token_secret='access_token_secret') | |
u = api.VerifyCredentials() | |
def create_list(name='Untitled', mode='private'): | |
return api.CreateList(name, mode) | |
def in_batches_of(n, items, func): | |
batches = [items[i:i+n] for i in range(0, len(items), n)] | |
for batch in batches: | |
func(batch) | |
def set_list(list_id=None, new_members=set()): | |
old_members = api.GetListMembers(list_id = list_id) | |
old_members = set(map(lambda x: x.id, old_members)) | |
to_add = new_members - old_members | |
to_remove = old_members - new_members | |
if len(to_add) > 0: | |
in_batches_of(100, list(to_add), lambda ids: api.CreateListsMember(list_id=list_id, user_id=ids)) | |
if len(to_remove) > 0: | |
in_batches_of(100, list(to_remove), lambda ids: api.DestroyListsMember(list_id=list_id, user_id=ids)) | |
def create_list_of_my_followers(mode="private"): | |
following_me_list = create_list("Following Me", mode=mode) | |
my_followers = set(api.GetFollowerIDs()) | |
set_list(list_id=following_me_list.id, new_members=my_followers) | |
def create_list_of_my_mutuals(mode="private"): | |
new_twitter_list = create_list("My Mutuals", mode=mode) | |
my_followers = set(api.GetFollowerIDs()) | |
people_i_follow = set(api.GetFriendIDs()) | |
set_list(list_id=new_twitter_list.id, new_members=my_followers.intersection(people_i_follow)) | |
# Other fun stuff | |
def get_intersection_following(handles=[]): # ! Rate Limiting | |
following = [] | |
for u in handles: | |
api.GetFriends(screen_name=u) | |
following.append( | |
set(api.GetFriends(screen_name=u)) | |
) | |
return set.intersection(*following) | |
def get_intersection_followers(handles=[]): # ! Rate Limiting | |
followers = [] | |
for u in handles: | |
api.GetFollowers(screen_name=u) | |
followers.append( | |
set(api.GetFollowers(screen_name=u)) | |
) | |
return set.intersection(*followers) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note, this is using https://github.com/bear/python-twitter