Python中如何实现批量操作Twitter好友的工具?

代码地址: https://github.com/xiaomoinfo/fastTwitter

使用步骤 1

application manager 上创建一个 app, 你将会得到我们所需要的相关信息

使用步骤 2

打开 'cfg.json'文件, 修改成你自己账号的配置

使用步骤 3

  • 功能 1: 批量关注

打开文件 'follow.py',右键,选择 run 命令。

  • 功能 2: 批量取关

打开文件 'unfollow.py', 右键,选择run 命令。 这是个危险的操作,所以会在config目录生成一个名为unfollow.txt的备份文件,以便随时加回来。

修改你要关注的人

如果你想添加或修改想要 follow 的人, 你可修改 follow.txt这个文件

祝你好运

如果在使用过程中有任何问题请随时联系

相关链接

license

MIT License

Copyright © 2018 Peng Hu

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:


Python中如何实现批量操作Twitter好友的工具?

3 回复

要批量操作Twitter好友,需要先通过Twitter API获取授权,然后使用tweepy库实现自动化操作。下面是一个完整的示例,包含获取好友列表、批量关注和取消关注的核心功能:

import tweepy
import time

class TwitterBatchManager:
    def __init__(self, api_key, api_secret, access_token, access_secret):
        """初始化Twitter API客户端"""
        auth = tweepy.OAuthHandler(api_key, api_secret)
        auth.set_access_token(access_token, access_secret)
        self.api = tweepy.API(auth, wait_on_rate_limit=True)
        
    def get_friends_list(self, username=None, count=200):
        """获取关注列表"""
        try:
            if username:
                user = self.api.get_user(screen_name=username)
                friends = self.api.get_friends(user_id=user.id, count=count)
            else:
                friends = self.api.get_friends(count=count)
            
            return [{'id': f.id, 'screen_name': f.screen_name, 'name': f.name} 
                   for f in friends]
        except tweepy.TweepyException as e:
            print(f"获取好友列表失败: {e}")
            return []
    
    def batch_follow(self, user_ids):
        """批量关注用户"""
        success_count = 0
        for user_id in user_ids:
            try:
                self.api.create_friendship(user_id=user_id)
                success_count += 1
                print(f"已关注用户ID: {user_id}")
                time.sleep(1)  # 避免速率限制
            except tweepy.TweepyException as e:
                print(f"关注用户 {user_id} 失败: {e}")
        return success_count
    
    def batch_unfollow(self, user_ids):
        """批量取消关注"""
        success_count = 0
        for user_id in user_ids:
            try:
                self.api.destroy_friendship(user_id=user_id)
                success_count += 1
                print(f"已取消关注用户ID: {user_id}")
                time.sleep(1)
            except tweepy.TweepyException as e:
                print(f"取消关注 {user_id} 失败: {e}")
        return success_count
    
    def find_inactive_users(self, days_inactive=30, max_users=100):
        """查找不活跃用户(简化示例)"""
        friends = self.get_friends_list(count=max_users)
        inactive_users = []
        
        for friend in friends:
            try:
                tweets = self.api.user_timeline(user_id=friend['id'], count=1)
                if tweets:
                    last_tweet_time = tweets[0].created_at
                    days_since_last = (time.time() - last_tweet_time.timestamp()) / 86400
                    if days_since_last > days_inactive:
                        inactive_users.append(friend['id'])
            except:
                continue
        
        return inactive_users

# 使用示例
if __name__ == "__main__":
    # 填入你的API密钥
    manager = TwitterBatchManager(
        api_key="YOUR_API_KEY",
        api_secret="YOUR_API_SECRET",
        access_token="YOUR_ACCESS_TOKEN",
        access_secret="YOUR_ACCESS_SECRET"
    )
    
    # 获取我的关注列表
    friends = manager.get_friends_list()
    print(f"当前关注了 {len(friends)} 个用户")
    
    # 批量取消关注不活跃用户
    inactive_users = manager.find_inactive_users(days_inactive=60)
    if inactive_users:
        unfollowed = manager.batch_unfollow(inactive_users[:10])  # 每次最多处理10个
        print(f"成功取消关注 {unfollowed} 个不活跃用户")

关键点说明:

  1. 需要先在Twitter开发者平台申请API访问权限
  2. tweepy库封装了Twitter API v1.1和v2版本
  3. 必须遵守Twitter的速率限制(15次/15分钟关注操作)
  4. 批量操作时要添加适当延迟避免触发限制

注意遵守Twitter的使用政策,避免滥用批量操作功能。建议先小规模测试,确认功能正常后再扩大操作范围。

总结:用tweepy库配合Twitter API实现,注意遵守平台规则。


单机了,心塞塞

回到顶部