Search code examples
tweepy

Check if a user is following me using Tweepy


I am using Tweepy and I want to create a script that would unfollow those who don't follow me back. I've created the opposite with ease:

for user in tweepy.Cursor(api.followers).items():
    if not user.following:
        user.follow()

But there seems not to be a property holding whether a user is following me back or not in api.friends.


Solution

  • A year later I've found myself in the need of solving this problem (again). This time I'm a bit more experienced in Python so I could find an approach that works well.

    It only needs an API call for every 100 users, which is the max amount of users that can be queried with the _lookup_friendships method at once. Well, that, + the unfollows, of course.

    for page in tweepy.Cursor(api.friends, count=100).pages():
        user_ids = [user.id for user in page]
        for relationship in api._lookup_friendships(user_ids):
            if not relationship.is_followed_by:
                logger.info('Unfollowing @%s (%d)',
                            relationship.screen_name, relationship.id)
                try:
                    api.destroy_friendship(relationship.id)
                except tweepy.error.TweepError:
                    logger.exception('Error unfollowing.')