How to write a Python Twitter Unfollow Script in 2022

The Twitter API has changed (from v1 to v2), and Python has gone from 2 to 3, and Google is still serving up loads of outdated results.

I had to clean up a Twitter account I recently took over so I had to look this up, and it was more annoying than strictly had to be. Here you go. (this is just a script dump meant for developers, do not blindly copy without understanding how to modify this code for your needs)

import tweepy
import os
import pprint
from random import randint
from time import sleep


# make sure you create an app with read AND write permissions
# oauth 1.0 app worked for me
# https://stackoverflow.com/questions/8389796/why-this-error-read-only-application-cannot-post for more
SCREEN_NAME = os.environ['screen_name']
CONSUMER_KEY = os.environ['api_key']
CONSUMER_SECRET = os.environ['key_secret']
ACCESS_TOKEN = os.environ['access_token']
ACCESS_TOKEN_SECRET = os.environ['token_secret']

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)

followers = api.get_follower_ids(screen_name=SCREEN_NAME)
friends = api.get_friend_ids(screen_name=SCREEN_NAME)

## manually restricted range so that script doesn't go nuts
## using enumerate so as to track progress
count = 0
for idx, f in enumerate(friends[2000:3000]):
    if f not in followers:
      usr = api.get_user(user_id=f)
      if usr.followers_count < 100:  # arbitrary notability criteria
        print("Unfollowing https://twitter.com/{0} | name:{1} | followers {2} | description {3} , ".format(usr.screen_name,
          usr.name, 
          usr.followers_count,
        usr.description,
          ))
        # https://stackoverflow.com/a/7663441/1106414
        for attempt in range(3): #max retry 3 times
          try:
            api.destroy_friendship(user_id=f)
            count += 1
          except Exception as e:
            print('failed to try ' + e)
          else:
            break
        else:
          # we failed all the attempts
          print('all attempts of {0} failed!'.format(f))
        sleep(randint(1,10))
      print("processed index {0}".format(idx))
      
print("done! unfollowed {0}".format(count)) 

You can run this pretty easily on Replit: https://replit.com/@swyx/tweepy-python-scripting#main.py

image

Tagged in: #python #twitter #api

Reactions: ❤️ 3
Loading comments...
Webmentions
Loading...

Subscribe to the newsletter

Join >10,000 subscribers getting occasional updates on new posts and projects!

I also write an AI newsletter and a DevRel/DevTools newsletter.

Latest Posts

Search and see all content