Learn how you can become a Python programmer in just 12 weeks.

    We respect your privacy. Unsubscribe at anytime.

    Python Twitter Bot to Unfollow Friends that do not Follow Back – 3 Easy Steps

    What will we cover in this tutorial?

    • How to unfollow friends in Twitter Python that do not follow back.
    • The process to get the access tokens to use the Twitter API
    • How to connect to the twitter API
    • The actual implementation of the code.

    This is updated to Tweepy version 4.4

    Step 1: Setup up environment

    In order to get a connection to twitter you need to have access tokens and consumer keys. If you don’t already have that, or you do not know what it is, then I recommend you follow this tutorial.

    You also need the tweepy library. You can install it by typing the following command in the command line or see here for more details.

    pip install tweepy
    

    Then you are ready to connect to the Twitter API.’

    Step 2: Connecting to Twitter API

    The first thing your code should do is to connect to the Twitter API and return the tweepy api to your program.

    import tweepy
     
    def get_twitter_api():
        # personal details
        consumer_key = "__USE YOUR KEY HERE__"
        consumer_secret = "__USE YOUR KEY HERE__"
        access_token = "__USE YOUR KEY HERE__"
        access_token_secret = "__USE YOUR KEY HERE__"
     
        # authentication of consumer key and secret
        auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
     
        # authentication of access token and secret
        auth.set_access_token(access_token, access_token_secret)
        api = tweepy.API(auth, wait_on_rate_limit=True)
        return api
    

    This code will authenticate and return the tweepy api.

    Step 3: List friends and followers to unfollow non-following friends

    Confused by the headline? Me, too. But here is where the magic happens. 

    The code simply explained.

    • Retrieves all the users that follow you (followers)
    • Retrieves those you follow (friends)
    • Loops through friends and check if they follow you
      • If not, unfollow them with a call to destroy_friendship
    def process():
        api = get_twitter_api()
     
        followers = api.get_followers_ids(user_id="PythonWithRune")
        print("Followers", len(followers))
        friends = api.get_friends_ids(user_id="PythonWithRune")
        print("You follow:", len(friends))
     
        for friend in friends:
            if friend not in followers:
                api.destroy_friendship(friend)
    

    Full code example here

    You can see the full code here to unfollow friends that do not follow back in Twitter using Python

    import tweepy
     
     
    def get_twitter_api():
        # personal details
        consumer_key = "__USE YOUR KEY HERE__"
        consumer_secret = "__USE YOUR KEY HERE__"
        access_token = "__USE YOUR KEY HERE__"
        access_token_secret = "__USE YOUR KEY HERE__"
     
        # authentication of consumer key and secret
        auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
     
        # authentication of access token and secret
        auth.set_access_token(access_token, access_token_secret)
        api = tweepy.API(auth, wait_on_rate_limit=True)
        return api
     
     
    def process():
        api = get_twitter_api()
     
        followers = api.get_followers_ids(user_id="PythonWithRune")
        print("Followers", len(followers))
        friends = api.get_friends_ids(user_id="PythonWithRune")
        print("You follow:", len(friends))
     
        for friend in friends:
            if friend not in followers:
                api.destroy_friendship(friend) 
     
    if __name__ == "__main__":
        process()
    

    Next step

    • Deploy it to an cron job so it runs every hour.
    • You can use PythonAnywhere (not sponsored by them)

    Python Circle

    Do you know what the 5 key success factors every programmer must have?

    How is it possible that some people become programmer so fast?

    While others struggle for years and still fail.

    Not only do they learn python 10 times faster they solve complex problems with ease.

    What separates them from the rest?

    I identified these 5 success factors that every programmer must have to succeed:

    1. Collaboration: sharing your work with others and receiving help with any questions or challenges you may have.
    2. Networking: the ability to connect with the right people and leverage their knowledge, experience, and resources.
    3. Support: receive feedback on your work and ask questions without feeling intimidated or judged.
    4. Accountability: stay motivated and accountable to your learning goals by surrounding yourself with others who are also committed to learning Python.
    5. Feedback from the instructor: receiving feedback and support from an instructor with years of experience in the field.

    I know how important these success factors are for growth and progress in mastering Python.

    That is why I want to make them available to anyone struggling to learn or who just wants to improve faster.

    With the Python Circle community, you can take advantage of 5 key success factors every programmer must have.

    Python Circle
    Python Circle

    Be part of something bigger and join the Python Circle community.

    4 thoughts on “Python Twitter Bot to Unfollow Friends that do not Follow Back – 3 Easy Steps”

      • Sure.

        You can do it with a simple counter:


        counter = 0
        for friend in friends:
        if friend not in followers:
        counter += 1
        api.destroy_friendship(friend)
        if counter >= 10:
        break

        Reply
    1. When running the destroy_friendship api, I am getting the error:

      destroy_friendship() takes 1 positional argument but 2 were given

      My code is this:

      # Create Lists
      followers_list = list()
      friends_list = list()
      unfollow_list = list()

      # Get account followers
      followers = Follower.objects.filter(twitter_user_account=own_account_id)
      for follower in followers:
      followers_list.append(follower.follower_screen_name)

      # Get account friends
      friends = Friend.objects.filter(twitter_user_account=own_account_id)
      for friend in friends:
      friends_list.append(friend.friend_screen_name)

      # Create unfollow list of users – List of accounts to unfollow
      for item in friends_list:
      if item not in followers_list:
      unfollow_list.append(item)

      # Unfollow users in unfollow list
      for i in unfollow_list:
      print(i)
      api.destroy_friendship(i)
      print(‘Removed ‘ + i + ‘ from following!’)
      time.sleep(2)

      Can you help please?

      Reply
      • First check the version of Tweepy.
        The tutorial is for Tweepy version 4.4.
        You can get the version by typing in a terminal where you installation is: pip freeze
        Then find tweepy with the version.

        Reply

    Leave a Comment