Tweepy:检查用户是否在关注我



我有以下代码,其中我试图取消关注任何不关注我的人。我目前只是看看用户名是否在关注者列表中,如果不是,取消关注他们。

followers = []
for follower in tweepy.Cursor(api.followers).items():
followers.append(follower.screen_name)
for friend in tweepy.Cursor(api.friends).items():
if friend.screen_name in followers:
continue
else:
api.destroy_friendship(friend.screen_name)

有点乏味,所以我想把它缩短一些。我想我应该使用api.show_friendshipsapi.lookup_friendships,但我不完全确定如何做到这一点。

我该如何解决这个问题?

你可以使用lookup_friendships来确认谁在跟踪你

screen_names = ["user1", "user2", "user3"]
api = tweepy.API(auth, wait_on_rate_limit=True)
ret = api.lookup_friendships(screen_names = screen_names)
for rel in ret:
# name:user1 isFollowedBy? False
print(f'name:{rel.screen_name} isFollowedBy? {rel.is_followed_by} ')

输出是Relationship对象的列表,您可以在其中看到谁是追随者(参见上面的示例)以及您在追随谁

我使用了以下代码:

my_screen_name = api.me().screen_name
status = api.show_friendship(source_screen_name = friend.screen_name, target_screen_name = my_screen_name)
if status[0].following:
print(f'{friend.screen_name} follows {my_screen_name}.')
else:
api.destroy_friendship(friend.screen_name)

最新更新