'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 1:[1]

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.')

Solution 2:[2]

You can use API.exists_friendship(user_a, user_b). It returns true if user_a follows user_b.

Reference: http://docs.tweepy.org/en/v3.5.0/api.html#API.exists_friendship

Solution 3:[3]

I think you could just use the following codes to get all the social media users one user follows:

# Here 1392368760 is just an example user
friends = api.friends_ids(1392368760)
print("This user follow", len(friends), "users")

The friends is a list, which contains all the people's user ids that the user 1392368760 follows.

In your case, you could just replace the 1392368760 with the user you are interested in and check whether you are in the friends list. Moreover, your personal user id could be accessed by the following codes:

api.me().id

Solution 4:[4]

Here's how to accomplish that using Tweepy 4.6.0.

my_screen_name = api.get_user(screen_name='YOUR_SCREEN_NAME')
for follower in my_screen_name.friends():
    Status = api.get_friendship(source_id = my_screen_name.id , source_screen_name = my_screen_name.screen_name, target_id = follower.id, target_screen_name = follower.screen_name)
    if Status [0].followed_by:
        print('{} he is following You'.format(follower.screen_name))
    else:
        print('{} he is not following You'.format(follower.screen_name))
        api.destroy_friendship(screen_name = follower.screen_name)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dzz
Solution 2 Slartibartfast
Solution 3 Bright Chang
Solution 4 Ahmed Elgammudi