swyxio / swyxdotio

This is the repo for swyx's blog - Blog content is created in github issues, then posted on swyx.io as blog pages! Comment/watch to follow along my blog within GitHub
https://swyx.io
MIT License
325 stars 43 forks source link

How to write a Python Twitter Unfollow Script in 2022 #442

Closed swyxio closed 1 year ago

swyxio commented 1 year ago

category: snippet tags: python, twitter, api cover_image: https://user-images.githubusercontent.com/6764957/185775655-22b5f13d-f207-4d5f-bf71-15bc40a00a0b.png

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