Python: Check if Twitter user A following user B
<p>I have been trying to use either Tweepy or Twython with the Twitter API to search for a specific hashtag, extract usernames of users tweeting with the hashtage, and then see how many of those users follow one another. My ultimate goal is to then visualize the connections with NetworkX.</p>

<p>So far, I have been able to search for the hashtag and get a list of users tweeting with it. However, I can't figure out how to see who is following whom on that list. I finally got a friendship lookup to work, but then realized that that parameter only searches friends of the authenticated user (me).</p>

<p>Here is the latest version of the code:</p>

<pre><code>from twython import Twython
import tweepy

# fill these in from Twitter API Dev
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
ACCESS_KEY = ''
ACCESS_SECRET = ''

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth, wait_on_rate_limit=True)

twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET)

# Search for hashtag, limit number of users
try:
    search_results = twitter.search(q='energy', count=5)
except TwythonError as e:
    print e

test5 = []
for tweet in search_results['statuses']:
    if tweet['user']['screen_name'] not in test5:
        test5.append((tweet['user']['screen_name']).encode('utf-8'))
print test5

# Lookup friendships
relationships = api.lookup_friendships(screen_names=test5[0:5])
for relationship in relationships:
    if relationship.is_following:
        print("User is following", relationship.screen_name)
</code></pre>

<p>Thanks!</p>

<p>With Tweepy, you can check if <code>user_a</code> follows <code>user_b</code> using the <a href="http://tweepy.readthedocs.io/en/v3.5.0/api.html#API.exists_friendship" rel="nofollow">API.exists_friendship</a> method.  The code would look something like:</p>

<pre><code>auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth, wait_on_rate_limit=True)
is_following = api.exists_friendship(user_a, user_b)
</code></pre>

<p>You can specify users by id or screenname.</p>

<p>Alternatively, you can fetch the entire list of followers using the <a href="http://tweepy.readthedocs.io/en/v3.5.0/api.html#API.followers_ids" rel="nofollow">API.followers_ids</a> method:</p>

<pre><code>auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth, wait_on_rate_limit=True)
user_b_followers = api.followers_ids(user_b)
is_following = user_a in user_b_followers
</code></pre>

<p>This approach would make more sense for large networks of users.</p>

<p>Keep in mind that, for either approach, you will only be able to see friendships that are visible to the authenticated user.  This is a restriction put in place by Twitter for privacy reasons.</p>

python twitter tweepy twython