I am trying to make a "simple" script that will unfollow users whom I am following that are not following me back using the Tweepy module for Python 3.5.
import sys, time, tweepy
auth = tweepy.OAuthHandler('Consumer Key', 'Consumer Secret')
auth.set_access_token('Access Token', 'Access Token Secret')
api = tweepy.API(auth)
for page in tweepy.Cursor(api.friends, screen_name='My Twitter Handle').pages():
for friend in page:
relationship = api.show_friendship(source_screen_name='My Twitter Handle', target_screen_name=friend.screen_name)
print(relationship.followed_by)
time.sleep(13)
print('\nDone.')
sys.exit()
Currently, the aim of the above code is to simply print out the users who are not following me back. When the code is executed, Python throws this at me:
AttributeError: 'tuple' object has no attribute 'followed_by'
I know this not to be true, as Twitter's documentation mentions it here.
However, I am no expert, hence why I am asking this question here. Any idea what I am doing wrong?
The @Jzbach's code has an error, the for cicles must to be separated because is improbable that you have the same number of followers and friends.
With this patch the script extract the right subsets
You can change code like below.
Instead of this
use this line of code:
Direct answer to your doubt & alternative approach to your goal (below)
For the newer version of Tweepy (3.5.0), the
show_friendship()
returns a tuple of two elements, each one belonging to each user. For example:Returns the tuple
Then if you want to access the attribute
followed_by
just do the following:And you will get the attribute you are asking for.
Alternative approach to your goal:
If you need that just to check who is following you and who is not, a simple way to discover it is by getting the set difference between the people you follow and the people that follows you. In order to do so, you could apply the code I provide below:
And the variable
not_fback
will be a set with all the users that are not following you back.First of all, if you read the twitter doc carefully, the raw API returns
{target: .., source: ..}, not {followed_by: .., ..}
.Secondly, you are working with Tweepy, which is a wrapper of the raw API. According to the Tweepy doc, it returns a
friendship
object (http://tweepy.readthedocs.org/en/v3.2.0/api.html#API.show_friendship). However, it does not explain how we can use this object. Going to its source, https://github.com/tweepy/tweepy/blob/master/tweepy/models.py#L237, it returns a tuplesource, target
. Bothsource
andtarget
has afollowed_by
attribute. I'm not sure which one you are looking for, but here's how you would access them: