Building an Instagram Bot Using NodeJS, Puppeteer and Firebase
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.
This tutorial requires the following:
- An IDE of choice of your choice e.g Visual Studio Code
- Node.js (minimum Node v7.6.0)
- Firebase real-time database
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
- You’ll be redirected to the dashboard click on Develop from the sidebar then select Database
- 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 the
databaseURL. We will be needing these details later in our development process.
Create a new node project
- Create a project folder and open this folder with your desired I.D.E. Let’s the name project folder
- Create a file
package.jsoin the root folder and add these dependencies
npm install from the terminal to install these dependencies. We’ll be using
shuffle-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
Configuring and setting up the database within our app
Bot folder create a config folder and copy the downloaded database config JSON file to this folder, rename the file to
db_config.json . The content of the file should look similar to the below
Next, we’ll create a
db.js file within our
Bot folder that holds the code for our database interaction. Inside
db.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_historyhold 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.
addFollowingsaves 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.
getFollowingreturns the list of all the users we’re following.
unFollowtakes the username to unfollow as an argument then removes the record from the list of people we are following and add it to the
follow_historyobject i.e people we have followed before.
inHistorytakes a username as an argument and checks if the user exists in the
follow_historyobject. If true, it returns the user object or null if the user doesn’t exist.
Copy the code below to your
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.
settingsproperty in our config file has an object as its value which contains the following properties:
run_every_x_hourshow 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 the
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 a
index.js file within the
Puppeteer exposes a promise based API, we’ll be defining
async methods so we can easily work with the API and keep to our promises 😅
Inside our new file let’s add a class
InstagramBot which contains six methods. These methods will be discussed in detail as we implement them.
index.js file and add the snippet below:
As you can see we created our class and imported our configuration files within the constructor method.
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:
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.
visitInstagram() method to our class like so:
Here we’ll add the key ingredient to give our bot that taste it deserves. We’ll do so by adding the
visitHashTagUrl() method( A core implementation of our bot) to our class. Within this method, we’ll import the
shuffle-array module which we had installed earlier as part of our project dependencies. This library helps us to shuffle through the
hashTags 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:
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 arguments
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.
_doPostLikeAndFollow() method to our class like so:
Next, we’ll implement the
unFollowUsers() 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 as
unFollowUsers() method to our class like so:
The last method we’ll be implementing is the
closeBrowser() method. This method closes the browser after the activity has been completed.
closeBrowser() method to our class and export our
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 an
index.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 running
node 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.
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:
- Get trending hashtags from a source so we don’t have to manually set the hashtags.
- Add ability for our bot to visit the explore page, like posts and follow users.
- 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