Twython API - How to see which of my 'friends' are following a specific user?

106 Views Asked by At

as you can see in this picture taken on the Desktop Twitter App (although a similar thing appears in the Mobile App too) example.jpg example2.jpg , when you visit the profile of a user that is followed by users that you are also following, a handy little list pops telling you exactly who the culprits are. I have a need to succinctly extract this information, but I'm struggling on how best to handle it with the limited (~200) API calls we're given per 15 minute intervals.

At present, using the Twython library ( https://twython.readthedocs.io/en/latest/api.html ) I am gathering a list of the userids that I currently follow with "get_friends_ids" and then iterating through them with a loop to check if this user follows my target with the "show_friendship" method. Here's a snippet of the code:

    users = client.get_friends_ids(screen_name=$name)
    users = users['ids']
    target = client.show_user(screen_name=$target)
    target = target['id']
    purged = 0
    worker = 0
    counter3 = 0
    for guy in users:
        counter3 += 1
    stringy = str(counter3)
    print("Found " + stringy + " users to sift through")

    for guy in users:
        worker += 1
        print("Working on user #" + str(worker))
        result = client.show_friendship(source_id=guy, target_id=target)
        result = result['relationship']['source']['following']
        remaining = api.get_lastfunction_header(header='x-rate-limit-remaining')
        API = int(remaining)
        print("We have " + str(API) + "API Calls remaining")
        if API <= 20:
            time.sleep(60)
        if API <= 5:
            time.sleep(900)
        if result == True:
            purged += 1
            client.destroy_friendship(id=guy)
            print("Purging relationship with userid " +str(guy))
        else:
            continue

This works absolutely fine for accounts that are following < 200 users, but when I'm working on accounts that are following thousands of users, it can take 15 minutes to iterate through 200 user chunks. Is there a better way for me to check for all users in my following list that are currently following a specific user? I imagine there's a way that Twitter does in their web app/mobile app that isn't as resource intensive, but I don't know if the Twython library can do it any better than this.

Thanks

1

There are 1 best solutions below

0
oiHamza On

I think there might be an easier solution. Twitter has a GET friendships/show endpoint which allows you to see if someone follows someone else using the input of a 'source user' and 'target user'. It returns true if they do follow them.

Step 1 would be to generate a list of your Twitter followers, and Step 2 would be to use their username/user ID as the 'source' user and whichever other users you want as the 'target' user.

Twython should support this endpoint, and I found it in the docs here.