Skip to content

Instantly share code, notes, and snippets.

@EliteMasterEric
Created November 3, 2022 04:59
Show Gist options
  • Select an option

  • Save EliteMasterEric/7bbb2dcec066779360afe892d91b2bc7 to your computer and use it in GitHub Desktop.

Select an option

Save EliteMasterEric/7bbb2dcec066779360afe892d91b2bc7 to your computer and use it in GitHub Desktop.
Get a list of all the users who are not your mutuals, and unfollow them. Updated for Twitter API v2.
import time
import tweepy
import sys
# Debug
#import logging
#logging.basicConfig(level=logging.DEBUG)
# Go here and create a Project: https://developer.twitter.com/en/portal/projects-and-apps
# Then go to the Keys and Tokens tab and copy the values below.
bearer_token = "Bearer Token Here"
consumer_key = "API Key Here"
consumer_secret = "API Key Secret Here"
access_token = "Access Token Here"
access_token_secret = "Access Token Secret Here"
client = tweepy.Client(bearer_token=bearer_token, consumer_key=consumer_key,
consumer_secret=consumer_secret, access_token=access_token, access_token_secret=access_token_secret,
wait_on_rate_limit=True)
# Get the user name from the user input
#try:
# user_name = sys.argv[1]
# user = client.get_user(username=user_name)
#except IndexError:
user = client.get_me()
user_name = user.data.name
user_id = user.data.id
print('Querying user: ' + user_name + ' (' + str(user_id) + ')')
print('Fetching list of followers...')
follower_ids = []
for follower_response in tweepy.Paginator(client.get_users_followers, user_id, max_results=1000):
for follower in follower_response.data:
follower_ids.append(follower.id)
print('Found ' + str(len(follower_ids)) + ' followers.')
print('Fetching list of following...')
following_ids = []
for following_response in tweepy.Paginator(client.get_users_following, user_id, max_results=1000):
for following in following_response.data:
following_ids.append(following.id)
print('Found ' + str(len(following_ids)) + ' following.')
print('Finding mutuals...')
mutual_ids = []
for following_id in following_ids:
if following_id in follower_ids:
mutual_ids.append(following_id)
print('Found ' + str(len(mutual_ids)) + ' mutuals.')
print('Finding non-mutuals...')
non_mutual_ids = []
for following_id in following_ids:
if following_id not in mutual_ids:
non_mutual_ids.append(following_id)
print('Found ' + str(len(non_mutual_ids)) + ' non-mutuals.')
print('Unfollowing non-mutuals...')
for non_mutual_id in non_mutual_ids:
try:
client.unfollow(non_mutual_id)
print(' Unfollowed ' + str(non_mutual_id))
except tweepy.TweepError as e:
print(' Failed to unfollow ' + str(non_mutual_id) + ': ' + str(e))
time.sleep(10)
time.sleep(1)
print('Done! Have a nice day. :)')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment