Automating Instagram API Using Python: Gain Active Followers

Written by thedevtimeline | Published 2020/01/12
Tech Story Tags: instagram-marketing | api | python | automation | instagram-algorithm | analytics | software-development | coding

TLDR Using Python: Gain Active Followers using Instagram API. The program uses the unofficial Instagram API written by Pasha Lev. It will look for users which you are following and unfollow them as well as follow users. It works pretty well so far but in case of any problems I have to put disclaimer statement here: This post published educational purposes only as to give general information about Instagram API. I am not responsible for any actions and you are taking your own risk. The following_users_list is set to list users_list to avoid automation detection.via the TL;DR App

Hi Devs!
In this lab we are going to automate some actions using Instagram API.

Gain active followers - Algorithm

Maybe some of you do not agree it is a good way to grow your IG page by using follow for follow method but after a lot of researching I found the proper way to use this method.
I have done and used this strategy for a while and my page visits also followers started growing.
The majority of people failing because they randomly targeting the followers and as a result, they are not coming back to your page. So, the key is to find people those have same interests with you.
If you have a programming page go and search for IG pages which have big programming community and once you find one, don't send follow requests to followers of this page. Because some of them are not active even maybe fake accounts. So, in order to gain active followers, go the last post of this page and find people who liked the post.
I think you get the idea. Those people will like your posts as well because they are active followers.
Unofficial Instagram API
In order to query data from Instagram I am going to use the very cool, yet unofficial, Instagram API written by Pasha Lev.
Note: Before you test it make sure you verified your phone number in your IG account.
The program works pretty well so far but in case of any problems I have to put disclaimer statement here:
Disclaimer: This post published educational purposes only as well as to give general information about Instagram API. I am not responsible for any actions and you are taking your own risk.
Let's start by installing and then logging in with API.
pip install InstagramApi
from InstagramAPI import InstagramAPI

api = InstagramAPI("username", "password")
api.login(
Once you run the program you will see "Login success!" in your console.

Get users from liked list

We are going to search for some username (your target page) then get most recent post from this user. Then, get users who liked this post. Unfortunately, I can't find solution how to paginate users so right now it gets about last 500 user.
users_list = []

def get_likes_list(username):
    api.login()
    api.searchUsername(username)
    result = api.LastJson
    username_id = result['user']['pk'] # Get user ID
    user_posts = api.getUserFeed(username_id) # Get user feed
    result = api.LastJson
    media_id = result['items'][0]['id'] # Get most recent post
    api.getMediaLikers(media_id) # Get users who liked
    users = api.LastJson['users']
    for user in users: # Push users to list
        users_list.append({'pk':user['pk'], 'username':user['username']})

Follow Users

Once we get the users list, it is time to follow these users.
IMPORTANT NOTE: set time limit as much as you can to avoid automation detection.
from time import sleep

following_users = []

def follow_users(users_list):
    api.login()
    api.getSelfUsersFollowing() # Get users which you are following
    result = api.LastJson
    for user in result['users']:
        following_users.append(user['pk'])
    for user in users_list:
        if not user['pk'] in following_users: # if new user is not in your following users                   
            print('Following @' + user['username'])
            api.follow(user['pk'])
            # after first test set this really long to avoid from suspension
            sleep(20)
        else:
            print('Already following @' + user['username'])
            sleep(10)

Unfollow Users

This function will look users which you are following then it will check if this user follows you as well. If user not following you then you are unfollowing as well.
follower_users = []

def unfollow_users():
    api.login()
    api.getSelfUserFollowers() # Get your followers
    result = api.LastJson
    for user in result['users']:
        follower_users.append({'pk':user['pk'], 'username':user['username']})

    api.getSelfUsersFollowing() # Get users which you are following
    result = api.LastJson
    for user in result['users']:
        following_users.append({'pk':user['pk'],'username':user['username']})
    for user in following_users:
        if not user['pk'] in follower_users: # if the user not follows you
            print('Unfollowing @' + user['username'])
            api.unfollow(user['pk'])
            # set this really long to avoid from suspension
            sleep(20) 
Full Code with extra functions
Here is the full code of this automation:
import pprint
from time import sleep
from InstagramAPI import InstagramAPI
import pandas as pd


users_list = []
following_users = []
follower_users = []

class InstaBot:

    def __init__(self):
        self.api = InstagramAPI("your_username", "your_password")

    def get_likes_list(self,username):
        api = self.api
        api.login()
        api.searchUsername(username) #Gets most recent post from user
        result = api.LastJson
        username_id = result['user']['pk']
        user_posts = api.getUserFeed(username_id)
        result = api.LastJson
        media_id = result['items'][0]['id']

        api.getMediaLikers(media_id)
        users = api.LastJson['users']
        for user in users:
            users_list.append({'pk':user['pk'], 'username':user['username']})
        bot.follow_users(users_list)


    def follow_users(self,users_list):
        api = self.api
        api.login()
        api.getSelfUsersFollowing()
        result = api.LastJson
        for user in result['users']:
            following_users.append(user['pk'])
        for user in users_list:
            if not user['pk'] in following_users:
                print('Following @' + user['username'])
                api.follow(user['pk'])
                # set this really long to avoid from suspension
                sleep(20)
            else:
                print('Already following @' + user['username'])
                sleep(10)

    def unfollow_users(self):
        api = self.api
        api.login()
        api.getSelfUserFollowers()
        result = api.LastJson
        for user in result['users']:
            follower_users.append({'pk':user['pk'], 'username':user['username']})

        api.getSelfUsersFollowing()
        result = api.LastJson
        for user in result['users']:
            following_users.append({'pk':user['pk'],'username':user['username']})
        for user in following_users:
            if not user['pk'] in follower_users:
                print('Unfollowing @' + user['username'])
                api.unfollow(user['pk'])
                # set this really long to avoid from suspension
                sleep(20) 




bot =  InstaBot()
# To follow users run the function below
# change the username ('instagram') to your target username
bot.get_likes_list('instagram')

# To unfollow users uncomment and run the function below
# bot.unfollow_users()
it will look like this:
some extra functions to play with API:
def get_my_profile_details():
    api.login() 
    api.getSelfUsernameInfo()
    result = api.LastJson
    username = result['user']['username']
    full_name = result['user']['full_name']
    profile_pic_url = result['user']['profile_pic_url']
    followers = result['user']['follower_count']
    following = result['user']['following_count']
    media_count = result['user']['media_count']
    df_profile = pd.DataFrame(
        {'username':username,
        'full name': full_name,
        'profile picture URL':profile_pic_url,
        'followers':followers,
        'following':following,
        'media count': media_count,
        }, index=[0])
    df_profile.to_csv('profile.csv', sep='\t', encoding='utf-8')

def get_my_feed():
    image_urls = []
    api.login()
    api.getSelfUserFeed()
    result = api.LastJson
    # formatted_json_str = pprint.pformat(result)
    # print(formatted_json_str)
    if 'items' in result.keys():
        for item in result['items'][0:5]:
            if 'image_versions2' in item.keys():
                image_url = item['image_versions2']['candidates'][1]['url']
                image_urls.append(image_url)

    df_feed = pd.DataFrame({
                'image URL':image_urls
            })
    df_feed.to_csv('feed.csv', sep='\t', encoding='utf-8')

Mission Accomplished!

I hope you learned something today and if you want to watch video tutorial of this post visit YouTube channel - Reverse Python. Also check web application of Reverse Python

Stay Connected!

Written by thedevtimeline | Sharing real experience
Published by HackerNoon on 2020/01/12