Twitter批量关注报错:已发送关注请求,如何跳过这类用户?
解决Twitter批量关注时跳过已发送请求的问题
方法1:提前获取待处理关注请求并跳过
先获取当前账号已发送的待处理关注请求列表,批量关注时直接跳过这些用户,同时也避免重复关注已成功关注的用户。
修改后的代码:
import tweepy # 请先完成API授权(示例代码) # auth = tweepy.OAuthHandler(你的consumer_key, 你的consumer_secret) # auth.set_access_token(你的access_token, 你的access_token_secret) # api = tweepy.API(auth) target_screen_name = "2Wild2Crazy" # 获取目标用户的关注列表 friends = api.get_friends(screen_name=target_screen_name, count=200) # 获取当前账号已发送的待处理关注请求ID pending_friendships = api.get_outgoing_friendships() pending_ids = [friendship.id for friendship in pending_friendships] # 获取当前账号已成功关注的用户ID following_ids = api.get_friend_ids() # 批量关注逻辑 for friend in friends: print(f'"{friend.screen_name}"') # 检查用户是否已关注或已发送请求 if friend.id not in following_ids and friend.id not in pending_ids: try: api.create_friendship(screen_name=friend.screen_name) print(f"成功关注 {friend.screen_name}") except Exception as e: print(f"关注 {friend.screen_name} 时出错: {str(e)}") else: print(f"跳过 {friend.screen_name} - 已关注或已发送关注请求")
方法2:捕获API异常处理错误
如果不想提前获取待处理请求列表,可以直接在调用关注接口时捕获特定异常,遇到「已发送请求」「已关注」类错误时自动跳过。
修改后的代码:
import tweepy # 请先完成API授权(示例代码) # auth = tweepy.OAuthHandler(你的consumer_key, 你的consumer_secret) # auth.set_access_token(你的access_token, 你的access_token_secret) # api = tweepy.API(auth) target_screen_name = "2Wild2Crazy" friends = api.get_friends(screen_name=target_screen_name, count=200) for friend in friends: print(f'"{friend.screen_name}"') try: api.create_friendship(screen_name=friend.screen_name) print(f"成功关注 {friend.screen_name}") except tweepy.TweepyException as e: error_msg = str(e).lower() # 匹配错误关键词,跳过已处理的用户 if "already requested" in error_msg or "already following" in error_msg: print(f"跳过 {friend.screen_name} - {e}") else: # 其他错误单独打印,方便排查问题 print(f"关注 {friend.screen_name} 时发生未知错误: {e}")
内容的提问来源于stack exchange,提问作者Handra Putratama
相关产品推荐
相关产品推荐

