This is part three of my series on using Python to connect to the Twitter API.
Imagine for a moment that you had a specific vision for your Twitter account. A vision of balance, and harmony. What if you only followed people who also followed you? Whether or not you want to curate your Twitter experience in this transactional way is entirely up to you. It’s your account!
We can do that with Python. As always, replace the placeholders with your own account credentials. See Part One of this series if you’re not sure how to do that.
Let’s take a look at the code required to do this:
import tweepy consumerKey = "<>" consumerSecret = "<>" accessToken = "<>" accessTokenSecret = "<>" auth = tweepy.OAuthHandler(consumerKey, consumerSecret) auth.set_access_token(accessToken, accessTokenSecret) #Call the api api = tweepy.API(auth,wait_on_rate_limit=True) #define two empty lists followers =  following =  #Get the list of friends for status in tweepy.Cursor(api.get_friends,count=200).items(): #Add the results to the list following.append(status.screen_name) #get the list of followers for status in tweepy.Cursor(api.get_followers,count=200).items(): #Add the results to the list followers.append(status.screen_name) #compare the lists and take action for person in following: if person not in followers: api.destroy_friendship(screen_name=person) print("Unfollowed " + person)
As always, we start by importing Tweepy, and declaring our credentials variables. We used the credentials to connect to Twitter with OAuth.
Next we define two lists, as we’ll be collecting two lists of people and comparing those lists.
Using the Cursor, we get a list of all of the friends of a twitter account. As we have not specified a target account, the list returned will be that of the authenticated user.
We take the same action again, but we store a list of all the followers of the authenticated account. In the parlance of the Twitter API, a friend is someone an account follows. A follower is someone following the account.
Now we have two lists: friends and followers. What we want to do next is look at all of the people we’re following. For each person we follow, we check to see if that person is following us back by looking at the list of followers. In other words, the account is following “John”. We check the list of followers. If “John” isn’t a follower, then we’re following him but he must not be following us. Rude!
That’s what the final loop does. For each person in the list of accounts that we follow, we check the other list to see if they’re in there. If they’re not following us, we call the destroy_friendship() method and feed it the person variable as an attribute.
Finally, we write to the console what we’ve done so that we can sanity check the operation.