A Beginner’s Guide to Bot Creation and Automation

Tanmayee Choudhury
May 8 · 5 min read

Every job has repetitive tasks and processes that can be automated, which can take up a significant amount of your time. In a digital world, automation is the most crucial skill to acquire. In this article, I’ll be guiding you through the basic techniques used in order to create bots for diverse applications. Together we will create simple bots to search in Google and automatically like random posts on Instagram. So, without any further adieu let’s dive in!

Google Search Bot

Firstly, we would be building a simple Search bot that automatically opens up a web browser, loads the Google page and types a term to be searched. Once the next page loads, it takes a screenshot and clicks on Images which then redirects it to images of the term searched. It takes another screenshot of the new page and clicks on the first image it finds. It takes the final screenshot and closes the browser. Interesting isn’t it?

Create a folder named GoogleSearchBot. Open that folder in VSCode and create a file named simple.js. Now, install a new Nodejs project with node init -y and then install the playwright library with npm i playwright. For those of you who are curious to know what this playwright library is and what does it do, playwright is basically a Node.js library to automate Chromium, Firefox and WebKit with a single API. It is built to enable cross-browser web automation that is ever-green, capable, reliable and fast. You can find more about Playwright at https://github.com/microsoft/playwright. Some of the alternatives are Puppeteer or Selenium.

For the async/await feature to operate properly, you need to have a minimum version of 8 for Nodejs. Before getting started with automation and bot creation, you are expected to have some basic knowledge of Chrome DevTools provided by Google Chrome. It would make the tasks a lot easier. When you load a webpage, right click and select Inspect option, the DevTools window appears. The section of the webpage which you want to automate, always has a unique element. You need to look for that unique element. It can be done by opening DevTools and selecting the section of the page you want to automate which would then highlight the respective HTML code under the Elements tab of the Inspect window. You need to find the unique element in that part of the code.

The code for simple.js is as follows:

// may take a while for downloading binaries// minimum node version 8 for async / await featureconst playwright = require(‘playwright’);const browserType = ‘chromium’; // chrome//const browserType = ‘firefox’; // firefox//const browserType = ‘webkit’; // safariasync function main() {// disable headless to see the browser's actionconst browser = await playwright[browserType].launch({ headless: false });const context = await browser.newContext();const page = await context.newPage(); //wait for the browser to create a new page by putting awaitawait page.goto(‘http://google.com'); //opening Google pageawait page.waitForLoadState(‘load’);const searchTerm = ‘Automation Bots’;//the term to be searched in Google searchbarconst input = await page.$(‘[name=”q”]’);//unique element in the search bar section of inspect sourceawait input.type(searchTerm);await page.waitForTimeout(2000);//wait 2000 ms before pressing enter so that the entire term is typedawait input.press(‘Enter’);await page.waitForLoadState(‘load’);await page.screenshot({ path: ‘result1.png’ });//taking screenshot of the page loadedawait page.waitForTimeout(3000);//wait 3s after taking screenshot const imageClicks = await page.$(‘[data-hveid=”CAEQBA”]’); //clicking the images linkawait imageClicks.click();await page.waitForLoadState(‘load’);await page.waitForTimeout(3000);await page.screenshot({ path: ‘result2.png’ });//taking screenshot of the new page loadedawait page.waitForTimeout(3000);const imageOne = await page.$(‘[alt=”Types of Bots in Automation Anywhere | Robotic Process Automation | justSajid”]’); //clicking the first imageawait imageOne.click();await page.waitForLoadState(‘load’);await page.waitForTimeout(3000);await page.screenshot({ path: ‘result3.png’ });await page.waitForTimeout(3000);await browser.close(); //close the browser once everything is done}main();

Let’s run the code by typing node simple.js. Once your code starts running, the Search bot gets activated and starts doing all the tasks provided in the code. The screenshots which it takes are automatically stored in your GoogleSearchBot folder (focus on the left side of the VSCode in the video below, before the bot starts and after the bot completes its task). Let’s have a look at its functionality:

Instagram Like Bot

Now that we gathered a basic knowledge of bot creation, it’s time to advance up a bit. So, we would be designing an Instagram Like Bot that automatically logs in to your Instagram account via your email and password and randomly likes the posts and comments that appear on your feed.

By now, you all must be knowing the starter pack for any Nodejs project: Create a folder named InstaLikeBot → Open VSCode → Open the InstaLikeBot folder → Create a file named instagram.js → Open the terminal window and type npm init -y → Install the playwright library and dotenv package by typing npm install dotenv playwright → Get started with the code.

Here, we would be making use of Environment Variables. So, install the dotenv package to create a virtual environment for your project by typing npm install dotenv. Now, create a file named .env to store the confidential information such as username, email, password, etc. The code for instagram.js looks something like this:

// EMAIL=// PASSWORD=// npm install dotenv playwrightrequire(‘dotenv’).config() //including the dotenv package files to handle all the bootstrap for usconst playwright = require(‘playwright’);const browserType = ‘chromium’; // chrome//passing in the login credentials by Environment Variablesconst email = process.env.EMAIL;const password = process.env.PASSWORD;async function main() {const browser = await playwright[browserType].launch({ headless: false });const context = await browser.newContext();const page = await context.newPage();await page.goto(‘http://instagram.com');// Opening Instagram pageawait page.waitForLoadState(‘load’);// wait until the page is loaded because Instagram is a single page applicationawait page.waitForTimeout(3000);const inputEmail = await page.$(‘[name=”username”]’); //unique element of the input fieldawait inputEmail.type(email, 2000);const inputPassword = await page.$(‘[name=”password”]’);await inputPassword.type(password, 2000);await inputPassword.press(‘Enter’);//in order to submit our login credentialsawait page.waitForTimeout(5000);// closes the modal by clicking on Not Nowconst notNow = await page.$(‘“Not Now”’);await notNow.click();let current = 0;while (true) {// only get unliked imageslet elements = await page.$$(‘[aria-label=”Like”]’);// stop if there are no new itemsif (elements.length — 1 == current) break;for (; current < elements.length; current++) {const element = elements[current];// scrolls into viewawait element.hover();await page.waitForTimeout(2000);// randomly like every third imageif (Math.random() > .3) {await element.click();}}}console.log(‘Finished the script.’);await browser.close();}main();

And we’re done! Now let’s run the project by typing node instagram.js . The bot gets activated and starts working as shown below:

So, that’s all from my side. I hope you will enjoy creating the bots and use your time efficiently and productively. The functionality of the bots are kept pretty simple for easy understanding. You can always add in additional and interesting features to the bots. Moreover, you can now try to create Spotify Listener Bot, Telegram Bot or Twitter Follower Bot. Thanks for reading. Have a good day!

Nerd For Tech

From Confusion to Clarification

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Tanmayee Choudhury

Written by

Btech Undergrad at VIT, Vellore. Budding Web Developer, keen learner, optimist.

Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.