You need to enable JavaScript to run this app. 如何使用Tweepy和Python实现单次仅取关5个用户
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Tweepy和Python实现单次仅取关5个用户

Tweepy自动取关脚本修改方法

核心修改逻辑是新增取关次数计数器,达到预设阈值后直接终止循环即可实现自动停止。

具体修改点

  • 在遍历关注列表的循环外,定义单次最大取关次数常量,同时初始化计数器统计已完成的取关操作
  • 每次成功执行取关操作后更新计数器
  • 每次进入循环时先判断是否达到次数上限,达到则直接跳出循环结束程序

修改后完整代码

import tweepy
import time

def get_twitter_api():
    # 个人开发者密钥信息
    consumer_key = "xxxx"
    consumer_secret = "xxxx"
    access_token = "xxxx"
    access_token_secret = "xxxx"

    # 消费者密钥认证
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    # 访问令牌认证
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth, wait_on_rate_limit=True)
    return api

def process():
    interval = 61
    MAX_UNFOLLOW = 5 # 单次取关上限,可按需调整数值
    unfollow_count = 0 # 已取关次数计数器
    api = get_twitter_api()

    followers = api.followers_ids(api.me().id)
    print("关注你的用户数:", len(followers))
    friends = api.friends_ids(api.me().id)
    print("你关注的用户数:", len(friends))

    for friend in friends[::-1]:
        # 达到取关上限直接终止循环
        if unfollow_count >= MAX_UNFOLLOW:
            break
        # 仅取关未回关的用户
        if friend not in followers:
            api.destroy_friendship(friend)
            print(f"已完成第{unfollow_count+1}次取关,用户ID:{friend}")
            unfollow_count += 1
            time.sleep(interval)

if __name__ == "__main__":
    process()

修改后脚本会在完成5次取关操作后自动停止运行,你也可以调整MAX_UNFOLLOW的数值自定义单次取关的上限。

内容的提问来源于stack exchange,提问作者TGPZ Media

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 22:06:03