Skip to content

Instantly share code, notes, and snippets.

@perpetual-hydrofoil
Last active January 19, 2023 01:35
Show Gist options
  • Save perpetual-hydrofoil/1243373 to your computer and use it in GitHub Desktop.
Save perpetual-hydrofoil/1243373 to your computer and use it in GitHub Desktop.
Twitter Unfollow Example (python)
#! /usr/bin/env python
# how to unfollow everyone who isn't following you
# By Jamieson Becker (Public Domain/no copyright, do what you will)
# Easy instructions, even if you don't know Python
#
# 1. Install pip (apt-get install python-pip) and then
# pip install tweepy, which is the python twitter client
#
# 2. create a new app in your account at dev.twitter.com
# and then plug in your consumer and app keys below.
# Trim all whitespace at beginning/end of your keys.
#
# 3. the twitter app needs to have permissions changed to
# read-write, as apps are read-only by default.
#
# 4. Execute this script: python unfollow.py
import time
import tweepy
import sys
auth = tweepy.auth.OAuthHandler(
consumer_key='foo',
consumer_secret='bar')
auth.set_access_token(
'foobaz',
'foobar')
api=tweepy.API(auth_handler=auth)
print "Loading followers.."
follower_objects = [follower for follower in tweepy.Cursor(api.followers).items()]
print "Found %s followers, finding friends.." % len(followers)
friend_objects = [friend for friend in tweepy.Cursor(api.friends).items()]
# create dictionaries based on id's for easy lookup
friends = dict([(friend.id, friend) for friend in friend_objects])
followers = dict([(follower.id, follower) for follower in follower_objects])
# find all your "non_friends" - people who don't follow you even though you follow them.
non_friends = [friend for friend in friend_objects if friend.id not in followers]
# double check, since this could be a rather traumatic operation.
print "Unfollowing %s non-following users.." % len(non_friends)
print "This will take approximately %s minutes." % (len(non_friends)/60.0)
answer = raw_input("Are you sure? [Y/n]").lower()
if answer and answer[0] != "y":
sys.exit(1)
# start the removal process. In the event of a failure (thanks, twitter!),
# retry once after five seconds. An error on same record again is
# probably more serious issue, so abort with error
for nf in non_friends:
print "Unfollowing " + str(nf.id).rjust(10)
try:
nf.unfollow()
except:
print " .. failed, sleeping for 5 seconds and then trying again."
time.sleep(5)
nf.unfollow()
print " .. completed, sleeping for 1 second."
time.sleep(1)
@nicolewiggins
Copy link

I'm getting this error

and the prog.
api=tweepy.API(auth_handler=auth)

print ("Loading followers..")
follower_objects = [follower for follower in tweepy.Cursor(api.followers).items()]

print ("Found %s followers, finding friends..") % len(followers)
friend_objects = [friend for friend in tweepy.Cursor(api.friends).items()]

create dictionaries based on id's for easy lookup

friends = dict([(friend.id, friend) for friend in friend_objects])
followers = dict([(follower.id, follower) for follower in follower_objects])

find all your "non_friends" - people who don't follow you even though you follow them.

non_friends = [friend for friend in friend_objects if friend.id not in followers]

double check, since this could be a rather traumatic operation.

print ("Unfollowing %s non-following users..") % len(non_friends)
print ("This will take approximately %s minutes.") % (len(non_friends)/60.0)
answer = raw_input("Are you sure? [Y/n]").lower()
if answer and answer[0] != "y":
sys.exit(1)

start the removal process. In the event of a failure (thanks, twitter!),

retry once after five seconds. An error on same record again is

probably more serious issue, so abort with error

for nf in non_friends:
print ("Unfollowing ") + str(nf.id).rjust(10)
try:
nf.unfollow()
except:
print (" .. failed, sleeping for 5 seconds and then trying again.")
time.sleep(5)
nf.unfollow()
print (" .. completed, sleeping for 1 second.")
time.sleep(1)

Loading followers..
Traceback (most recent call last):
File "D:\Projects\M Tools\tweepy\tweet by tweep.py", line 18, in
follower_objects = [follower for follower in tweepy.Cursor(api.followers).items()]
File "D:\Projects\M Tools\tweepy\tweet by tweep.py", line 18, in
follower_objects = [follower for follower in tweepy.Cursor(api.followers).items()]
File "C:\Python34\lib\site-packages\tweepy-3.1.0-py3.4.egg\tweepy\cursor.py", line 49, in next
return self.next()
File "C:\Python34\lib\site-packages\tweepy-3.1.0-py3.4.egg\tweepy\cursor.py", line 197, in next
self.current_page = self.page_iterator.next()
File "C:\Python34\lib\site-packages\tweepy-3.1.0-py3.4.egg\tweepy\cursor.py", line 75, in next
**self.kargs)
File "C:\Python34\lib\site-packages\tweepy-3.1.0-py3.4.egg\tweepy\binder.py", line 235, in _call
return method.execute()
File "C:\Python34\lib\site-packages\tweepy-3.1.0-py3.4.egg\tweepy\binder.py", line 219, in execute
raise TweepError(error_msg, resp)
tweepy.error.TweepError: Twitter error response: status code = 429

@cairey
Copy link

cairey commented Feb 6, 2016

@nicolewiggins You need to enter your access token.

@Simoneth
Copy link

Simoneth commented Apr 3, 2016

Thanks for this tool, is it possible to unfollow oldest users added first? (like Crowdfire)

@Simoneth
Copy link

Simoneth commented Apr 3, 2016

I'm getting these warnings, my website has SSL certificate

Loading followers..
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:315: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#snimissingwarning.
  SNIMissingWarning
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:120: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
Traceback (most recent call last):
  File "unfollow.py", line 34, in <module>
    follower_objects = [follower for follower in tweepy.Cursor(api.followers).items()]
  File "/usr/local/lib/python2.7/dist-packages/tweepy/cursor.py", line 197, in next
    self.current_page = self.page_iterator.next()
  File "/usr/local/lib/python2.7/dist-packages/tweepy/cursor.py", line 75, in next
    **self.kargs)
  File "/usr/local/lib/python2.7/dist-packages/tweepy/binder.py", line 245, in _call
    return method.execute()
  File "/usr/local/lib/python2.7/dist-packages/tweepy/binder.py", line 227, in execute
    raise RateLimitError(error_msg, resp)
tweepy.error.RateLimitError: [{u'message': u'Rate limit exceeded', u'code': 88}]

@alinakhay
Copy link

looks like it unfollows everyone for some reason

@bryanmaina
Copy link

@drhouse7 this might help you :

api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) 

@samayo
Copy link

samayo commented Jun 30, 2017

You are trying to echo followers on line 36, but it is not defined prior to that. Also, has anyone had any successes in making this thing work, it's not working

@TechVows
Copy link

TechVows commented May 9, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment