--> Skip to main content

Featured

Steps to Create a Project on GitHub

Steps to create a project on GitHub:  1.   Start a repo on GitHub 2.   Make a README.md file 3.   Open vs code – new folder – new terminal – git clone http:…. (from the repo). 4.   In terminal – cd theprojectname   à move into the project file 5.   Ls -la is for showing hidden file à not working for me ???? 6.   Make some changes to README file, in terminal git status à shows all the changes on the file 7.   To add all changes update to the folder à git add . (the dot . means all changes to be added) 8.   Add a new file index.html, in terminal à git commit -m “title of commit” -m “description of commit” 9.   Then git push origin master 10.                 ****Initial a repo in local text editor à git init 11.                 After use git add . etc, when pus...

Python Project - Tweepy and Twitter Developer API for Automatically Following The Right Twitter Users

One way to practically grow Twitter account followers is to follow other users who may have the same interest as yours. Do a little keyword search on Twitter, you can find some influential users who usually have a lot of followers. This project is to find some of these big user accounts, using Python code to retrieve their followers' data into a json file. The thesis for doing this is that whoever follows the big user in the niche might have similar interest as your keyword defined.
 
From there we use Python code to randomly follow some of the users saved in the json file. Statistically, there are 10% of the users whom you followed follow back. So after regularly running the code for a while, you should have built a good number of followers who are interested in the same niche. 

Firstly, you need to sign up to a Twitter developer account and create an application for which Twitter will grant you access with API keys and tokens. For the detailed explanation of how to do this, read this guide

This Python project is solely for coding practice purpose, this is not intended to break any Twitter rules or policies. So please consult Twitter User documentation for the regulations about how to follow other users properly. 

Now let jump straightly into the coding.

For interacting with Twitter API v2, we use Tweepy's Client object. A "config.py" file has been created beforehand to save Twitter API's keys and tokens. We import this file so that we can access these credentials in this project.

'''To randomly followed twitter users with specific 
    interests using python Tweepy and Twitter API '''

import tweepy
import config
import json
import random
import time

# part 1: to retrieve (volume) number of followers 
# from a username specified,
# save them into a json file

def get_to_follow_list(target_username, volume, filename):
    # only bearer_token is needed for retrieving tweets and users info
    client = tweepy.Client(bearer_token=config.Bearer_token)

    # choose a username in the niche who has many followers
    user = client.get_user(username=target_username)
    user_id = user.data.id

    # If there are thousands of followers, use tweepy.Paginator to
    # set a bigger limit such as 1000.
    followers = tweepy.Paginator(client.get_users_followers, id=user_id).flatten(limit=volume)
    followers = client.get_users_followers(user_id)

    # retrieve users data from the response (followers), save to a list
    list = [f for f in followers.data]
    # print(list) # output is a list of User objects
    '''[<User id=1326917137693364230 name=Susan Koo username=SusanKoo3>, 
    <User id=1388873538455670791 name=PoeticMetric username=PoeticMetricHQ>,...] ''' 

    # to reconstruct list into a list of dictionaries     
    users_dict = [ {"id":item.id, 'name':item.name, 'username':item.username} for item in list]
    # print(users_dict[:2])
    # output:
    # [{'id': 1326917137693364330, 'name': 'Susan Mu', 'username': 'Susanmu'}, 
    # {'id': 1388873538455670791, # 'name': 'PoeticMetric', 'username': 'PoeticMetricHQ'}]

    # save the new list as json file
    with open(filename, 'w', encoding='utf-8') as file:
        json.dump(users_dict, file, indent=4)

    return users_dict
    
# let's test out this function
username='remote_dev_jobs'
volume = 200
filename = 'to_follow_twitter.json'

dict = get_to_follow_list(username, volume, filename)

This worked out great. A json file has been created with the 200 users' info saved to it.

Next, use the above function with a few small tweaks, you can save all your own 'following' users' id into a json file: the 'username' param should be your own username, 'volume' should be the exact number of your  'following' users, then give a good name as a filename.  For the line of  'followers = client.get_users_followers(user_id)', change the method to 'client.get_users_following(user_id). For 'users_dict' list, I only need to save 'item.id' to the list. 

Once this new json file for your own 'following' users' ids is created, we don't need to repeat this step anymore. This is because in the Part 3 codes, we will keep on update this file to record new 'following' users' ids. In this project, we use this second json file as a filter to ignore those ids that I am following already.

The last step is to do the automatic following to some random users.

We still need a Tweepy Client instance. We need 4 credentials as parameters this time. 

import tweepy
import config
import json
import random
import time

# PART 2: get your own 'following' users' ids
# Use the same method above, 
# except =>
# 1. change usename to yourself
# 2. only scrape id numbers and save them -> item.id
# 3. the volume is your account 'following' number
# 4. save ids to 'my_following_ids.json' file
# This part only needs to be done once


# PART 3: randomly pick some ids to follow using tweepy

def random_follow_twitter_account(database_filename, volume):
    # Access Token must be provided for OAuth 1.0a User Context
    # create a new client with 4 credentials for auth
    client= tweepy.Client(
        consumer_key=config.API_key,
        consumer_secret=config.API_key_secret,
        access_token=config.Access_token,
        access_token_secret=config.Access_token_secret
    )   

    # open file to get users' dictionary list
    with open(database_filename, 'r', encoding='utf-8') as file:
        users = json.load(file)

    # randomly choose (volume) ids
    # check if they are already being followed
    # only follow those not being followed yet

    # get all ids I am following
    with open('my_following_ids.json', 'r+', encoding='utf-8') as filehandle:
        ids = json.load(filehandle)

        for _ in range(volume):   

            #get random user: 
            user = random.choice(users)
            id = user['id'] 

            # check if already 'following' ids
            if not id in ids:
                # do the following
                client.follow_user(id)
                # update ids
                ids.append(id)
                time.sleep(3)
                print(f'Just followed {user["username"]}')
            else:
                print(f'{user["username"]} has been followed already.')

        # change the current file position to 0
        filehandle.seek(0)
        # save the new ids list to the file
        json.dump(ids, filehandle, indent=4)
    
random_follow_twitter_account('to_follow_twitter.json', 2)

This part 3 can be run regularly for a while to accumulate following users, and in turn some of these users will follow you back. You can always run the part 1 to update the first json file and use part 3 to get more followers.

For source code, please check out the github repo

Popular Posts