Twitter机器人403错误求助:无法正确关注未关注用户
问题排查与修复方案
核心问题1:条件判断逻辑错误
你代码里的if条件误用了or,这会导致只要用户不是你自己,不管是否已经关注,都会执行关注操作。正确逻辑应该是:既不是你自己,同时你还没关注对方,所以要把or改成and。
错误条件:
if not tweet.user.following or tweet.user.id != user.id:
修正后:
if not tweet.user.following and tweet.user.id != user.id:
核心问题2:tweet.user.following可能不实时
Tweepy返回的User对象中的following属性是API响应的缓存值,不一定能准确反映你当前的真实关注状态。更可靠的方式是主动调用API获取已关注用户列表,再做判断:
def follow_tl_users(): user = api.verify_credentials() # 批量获取当前已关注的用户ID,减少API调用次数 following_ids = set(api.get_friend_ids(user_id=user.id)) for tweet in tweepy.Cursor(api.home_timeline).items(50): target_user_id = tweet.user.id if target_user_id != user.id and target_user_id not in following_ids: try: tweet.user.follow() print(f"followed: {tweet.user.screen_name}") # 更新本地已关注列表,避免重复操作 following_ids.add(target_user_id) except tweepy.TweepyException as e: print(f"Failed to follow {tweet.user.screen_name}: {e}") time.sleep(10)
额外优化建议
- 增加异常捕获,避免单个用户的错误导致整个循环终止
- 批量获取已关注ID,降低API调用频率,符合Twitter的API限制规则
- 关注成功后更新本地已关注列表,避免后续循环重复处理同一用户
内容的提问来源于stack exchange,提问作者kana natasha
相关产品推荐
相关产品推荐

