Building an Instagram Bot Using NodeJS, Puppeteer and Firebase

Introduction

Recently I created a business account on Instagram. I then realized getting new followers comes with a price of time and data. You have to like, comment and most importantly follow others so as to get follow backs. These activities also let Instagram bring up your account as suggestions to other users on its platform. So I decided to try out my Merlin powers by automating the task. After several bouts of googling and researching how to accomplish this task. I discovered most of the solutions found were either too complex to implement or outdated. I decided to gather the knowledge and create one so as to save curious cats like me the hassle.

In this tutorial, we will create a bot that helps automate regular Instagram activities such as; liking posts, follow users and unfollow users. These activities get us more followers as well as boost interaction on the content of our account.

Prerequisites

This tutorial requires the following:

Please ensure you have Node and NPM installed before starting the tutorial.

We’ll discuss on setting up Firebase real-time database as we proceed.

What is Puppeteer?

Puppeteer is a NodeJs Library which provides a high-level API to control headless Chrome or Chromium over the DevTools Protocol. By default, this library runs headless which means it runs without showing the browser open but can be configured to run non-headless Chrome or Chromium.

With the help of puppeteer, our bot will be able to browse Instagram and perform operations as a regular user would. The library uses selectors to interact with a web page i.e click, input e.t.c. we’ll learn more about how Puppeteer works as we proceed.

What is Firebase?

Firebase is a mobile and web development platform that offers different services such as analytics, authentication, real-time database, storage and more. In the course of this tutorial we’ll be using Firebase real-time database to store users we are following and archive users we have unfollowed. For the sake of this tutorial, we won’t be looking elaborately on how to use Firebase to learn more visit the Docs.

Setting up our database on Firebase

  • Visit firebase.google.com and sign in with your Google account
  • Click Add Project and enter a project name e.g ig-bot-demo, create the project then click on continue
Firebase welcome page
  • You’ll be redirected to the dashboard click on Develop from the sidebar then select Database
Firebase dashboard
  • Now choose Real-time Database, select test mode then click the enable button.
  • You’ll be redirected to your database dashboard, now we need to get our database credentials so we can integrate with it from our bot. To get these credentials, click on project overview from the side menu and select project settings.
  • Navigate to service accounts and generate a new private key for our NodeJs App and download the JSON file which contains our DB credentials, also note thedatabaseURL. We will be needing these details later in our development process.
DB credential page

Getting Started

Create a new node project

  • Create a project folder and open this folder with your desired I.D.E. Let’s the name project folderig-bot
  • Create a file package.jsoin the root folder and add these dependencies

now runnpm install from the terminal to install these dependencies. We’ll be usingshuffle-array to shuffle through our predefined hashtag so our bot doesn’t visit the hashtag URL in the same pattern. Now let’s create a folder that will house all our code. Let’s name it Bot

Configuring and setting up the database within our app

Within theBot folder create a config folder and copy the downloaded database config JSON file to this folder, rename the file todb_config.json . The content of the file should look similar to the below

Next, we’ll create a db.js file within ourBot folder that holds the code for our database interaction. Insidedb.js, we will establish a connection between two objects (coming from MySQL background objects are similar to tables) in our database.

  • followingobjects hold the list of users we have followed.
  • follow_history hold the list of users we have unfollowed so we don’t follow them again.

We’ll add four functions to this file that help with these tasks.

  1. addFollowing saves a username we started following along with the time. We are saving the time because we will be unfollowing users based on how long we have followed them. Note that we are setting usernames as key in our object instead of using ID since we are sure Instagram usernames are unique.
  2. getFollowing returns the list of all the users we’re following.
  3. unFollow takes the username to unfollow as an argument then removes the record from the list of people we are following and add it to thefollow_history object i.e people we have followed before.
  4. inHistorytakes a username as an argument and checks if the user exists in thefollow_history object. If true, it returns the user object or null if the user doesn’t exist.

Copy the code below to your db.js file

Now that we are done setting up our database, let’s proceed to implement puppeteer.

Setting configuration for puppeteer library

Before we begin implementing our bot we need to first create a puppeter.json file inside our config folder. This file holds some important data i.e authentication details, hashtags, selectors and the bot settings. Puppeteer uses selectors to navigate around the website, we need to save the needed selectors in our config so we don’t have to go through our code when Instagram update their classes.

The settingsproperty in our config file has an object as its value which contains the following properties:

  • run_every_x_hours how often we want our bot to run
  • like_ratiothe ratio at which we want our bot to like a post
  • unfollow_after_daysnumbers of days before unfollowing a user
  • headlesswhether to run puppeteer in headless mode or not. For easy debugging, we won’t run puppeteer in headless mode.

Paste the following JSON data in thepuppeteer.json file.

Implementing our bot with puppeteer

For the sake of clarity, this section will be broken into a series of steps. Before proceeding with these steps create aindex.js file within theBot folder.

Puppeteer exposes a promise based API, we’ll be definingasync methods so we can easily work with the API and keep to our promises 😅

Step 1:

Inside our new file let’s add a classInstagramBot which contains six methods. These methods will be discussed in detail as we implement them.

Open theindex.js file and add the snippet below:

As you can see we created our class and imported our configuration files within the constructor method.

Step 2:

The next thing we’ll be doing is to add a initPupperer() method to our class which imports the puppeteer library, starts the browser and creates a new page as well as sets the browser width and height.

As Instagram is a responsive website, we need to set the browser’s viewport to the same size as a desktop layout. This is because the selectors in our config file match that of a desktop view.

We will add the initPuppeter()method to our class like so:

Step 3:

In this step we’ll add a visitInstagram() method which of course visits Instagram’s website and waits for 2.5 seconds before performing the next action, this delay is needed because if the actions are too fast our bot will be easily detected by Instagram which may result in our account being blocked or suspended.

After loading Instagram, the next set of instructions navigates to the login page, inputs our login details(username and password) and then, closes the turn on notification modal after a successful login.

Add the visitInstagram() method to our class like so:

Step 4:

Here we’ll add the key ingredient to give our bot that taste it deserves. We’ll do so by adding thevisitHashTagUrl() method( A core implementation of our bot) to our class. Within this method, we’ll import theshuffle-array module which we had installed earlier as part of our project dependencies. This library helps us to shuffle through thehashTags array so we don’t revisit our hashtags in the same order each time we run our bot. The goto function as seen in line 10 enables our bot to visit each hashtag URL. Actions such as liking posts and following users will be performed by the_doLikeAndFollow() method which we’ll discuss in step 5.

We will add the visitHashTagUrl() method to our class like so:

Step 5:

Let us add_doPostLikeAndFollow() method which we invoke in the previous step. As the name implies the method likes a post and follows the user who created the post. This method takes two argumentsparentClass andpage.

Here’s a summary of what happened within this method:

  • Our bot Iterates through the first 3 row of the has-tag page which contains 3 post item. See the screenshot attached below.
  • Loops through each post item within these rows. We will be interacting with 9 posts in total.
  • Check’s if we have already liked the post, if not our bot proceeds to click the like button.
  • Get’s the username of the post creator, then checks our follow_historyobject from our database to confirm if we have ever followed the user.

Each line has been properly commented to explain each code block.

Instagram’s hashtag page with 3 post item on a row.

Add the _doPostLikeAndFollow() method to our class like so:

Step 6:

Next, we’ll implement theunFollowUsers() method. What this does as the name implies is to unfollow users we have followed for a certain period of time. The duration is specified in our config file asunfollow_after_days.

Add the unFollowUsers() method to our class like so:

Step 7:

The last method we’ll be implementing is thecloseBrowser() method. This method closes the browser after the activity has been completed.

Add thecloseBrowser() method to our class and export our InstagramBot lass:

We are almost done. The next thing we’ll do is to create an entry point to our bot where we will invoke each method we have created. The last line of code simply runs our bot at an interval, as defined in our config file. Running the bot too often might call attention to our account. So we need to set a reasonable amount of time.

To do this we’ll create anindex.js file inside our root folder ig-bot and add the following line code like so:

Now that we are done implementing our bot, its time to test. We’ll do this by runningnode index.js from the terminal inside our root folder.

Our bot can be hosted on a remote server. If there are enough reactions, we’ll discuss that and more in the second part of this article.

Conclusion

In this article, we’ve successfully built our own Instagram bot, which does basic Instagram activities. You can always clone the project repository.

Here are some things we can do to add more functionalities to our bot.

Additional Features we can add:

  1. Get trending hashtags from a source so we don’t have to manually set the hashtags.
  2. Add ability for our bot to visit the explore page, like posts and follow users.
  3. While navigating each post we can temporarily store at latest 3 users, browse their pictures like and follow then this will increase our chances of getting more followers.

Yay!! 🎊 you made it to the end.

Thanks for your time reading. Hopefully, this has been elaborate enough.

If you like this tutorial please give a clap

If you like this tutorial please give a clap

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Balogun Wahab

Balogun Wahab

A human who writes code and likes to makes amazing things happen.