Randomly Follow Twitter Followers with Tweepy

  • Share this:

Code introduction


This function uses the Tweepy library to connect to the Twitter API and randomly selects a follower to follow. If a screen_name parameter is provided, it will follow the specified user directly. If not, it will randomly select a follower and follow them.


Technology Stack : Tweepy

Code Type : Twitter API Interaction

Code Difficulty : Intermediate


                
                    
import tweepy
import random

def follow_random_user(api_key, api_secret_key, access_token, access_token_secret, screen_name=None):
    # Authenticate to Twitter
    auth = tweepy.OAuthHandler(api_key, api_secret_key)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)

    # If screen_name is not provided, choose a random user to follow
    if not screen_name:
        users = api.get_followers_ids(screen_name='twitter')
        if users:
            screen_name = users[random.randint(0, len(users) - 1)]

    # Follow the user
    try:
        api.create_friendship(screen_name=screen_name)
        return {"status": "Followed user successfully", "screen_name": screen_name}
    except tweepy.TweepError as e:
        return {"status": "Failed to follow user", "error": str(e)}                
              
Tags: