如何修改Python Tweepy脚本优先取关最早关注的未回关用户
解决方法:优先取关最早关注的未回关用户
嘿,这个问题其实很容易搞定!你的脚本现在用api.friends_ids()获取的关注列表,默认是按你关注的时间从晚到早排序(最近关注的排在最前面),所以只需要把这个列表反转,就能让脚本从最早关注的用户开始处理啦。
修改核心点
在获取friends列表后,直接反转它的顺序,有两种简单实现方式:
- 切片反转(一行搞定):
friends = api.friends_ids(api.me().id)[::-1] - 调用列表内置方法:先获取列表再执行
friends.reverse()
修改后的完整代码
import tweepy import time def get_twitter_api(): # personal details consumer_key = "consumer_key" consumer_secret = "consumer_secret" access_token = "access_token" access_token_secret = "access_token_secret" # authentication of consumer key and secret auth = tweepy.OAuthHandler(consumer_key, consumer_secret) # authentication of access token and secret auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True) return api def process(): interval = 60 * 2 api = get_twitter_api() followers = api.followers_ids(api.me().id) print("Followers:", len(followers)) # 反转关注列表,让最早关注的用户排在最前面 friends = api.friends_ids(api.me().id)[::-1] print("You follow:", len(friends)) for friend in friends: if friend not in followers: try: # 可选:打印正在取关的用户名,方便跟踪进度 user = api.get_user(friend) print(f"Unfollowing {user.screen_name} (最早关注的未回关用户)") api.destroy_friendship(friend) time.sleep(interval) except tweepy.TweepyException as e: print(f"Error unfollowing user ID {friend}: {e}") time.sleep(interval) if __name__ == "__main__": process()
额外优化说明
我还给脚本加了两个实用小功能:
- 新增
try-except块处理API异常(比如用户已被删除、权限限制等),避免脚本中途崩溃 - 打印正在取关的用户名,让你能直观跟踪处理进度
内容的提问来源于stack exchange,提问作者TGPZ Media
相关产品推荐
相关产品推荐

