Open In App

AI Whatsapp Bot using NodeJS, Whatsapp-WebJS And Gemini AI

Last Updated : 27 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

This WhatsApp bot is powered by Gemini AI API, where you can chat with this AI bot and get the desired result from the Gemini AI model. This bot can be used in groups or personal chats and only needs to be authenticated using the mobile WhatsApp app.

Output Preview: Let us have a look at how the final output will look like.

4_11zon

AI Bot , responding by .bot command

Prerequisites

  • Node JS
  • Whatsapp-web.js
  • Gemini API KEY

Approach to create AI Whatsapp Bot

  • If your ever used Whatsapp Web in your browser you can easily understood that we are just going to create one without any frontend.
  • We will create a simple node server, which send receive messages from whatsapp web and reply with Gemini AI.
  • To authenticate, we will use our whatsapp for scanning the QR code.
  • To create AI response we will be using Gemini API, we send prompt to API and it will generate response that we need to send back to user.

Steps To Create The Project

Step 1: Creating Node App with the following command.

npm init -y

Step 2: Installing Required Packages

npm i whatsapp-web.js @google/generative-ai qrcode-terminal

In Non Window System Additional Installation Required

npm i puppeteer

apt-get install gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 ca-certificates fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget

Project Structure:

project-structure

Project Structure

The updated dependencies in package.json file will look like:

"dependencies": {
"@google/generative-ai": "^0.2.1",
"qrcode-terminal": "^0.12.0",
"whatsapp-web.js": "^1.23.0"
}

Step 3: Get the API key from the Gemini AI API

Code Example: Create the bot.js file and add the following code and add your API-key.

Javascript




//For Window User bot.js
 
//Importing All Necessary Packages
const { Client, LocalAuth } = require('whatsapp-web.js');
const qrcode = require('qrcode-terminal');
const { GoogleGenerativeAI } = require('@google/generative-ai');
 
//Creating instances
const genAI = new GoogleGenerativeAI('API-KEY');
const client = new Client({
    authStrategy: new LocalAuth(),
});
 
//Initializing GenAI model
const model = genAI.getGenerativeModel({ model: "gemini-pro" });
 
 
//Function to generate reponse from AI model and reply to user
async function generate(prompt, message) {
 
    const result = await model.generateContent(prompt);
    const response = await result.response;
    const text = response.text();
 
    await message.reply(text); //Reply to user
}
 
 
 
//All event listener to know client status
client.on('qr', (qr) => {
    qrcode.generate(qr, { small: true });
});
 
client.on('authenticated', () => {
    console.log('Client is authenticated!');
});
 
client.on('ready', () => {
    console.log('Client is ready!');
});
 
client.on('disconnected', () => {
    console.log('Client is disconnected!');
});
 
client.on('auth_failure', () => {
    console.log('Client is auth_failure!');
});
 
 
client.on('message', async (message) => {
 
    if (message.body.includes('.bot')) {
 
        var query;
        //Extracting text from message body using regular expression method
        const regxmatch = message.body.match(/.bot(.+)/);
 
        //If no text followed by .bot then we use "Hi" as text
        if (regxmatch) {
            query = regxmatch[1];
        }
        else {
            console.log("No regex match!");
            query = "Hi";
        }
 
        //Call the generate function
        generate(query, message);
    };
 
});
 
client.initialize();


Javascript




//For Non-Window User Bot.js
 
const { Client, LocalAuth } = require('whatsapp-web.js');
const qrcode = require('qrcode-terminal');
const { GoogleGenerativeAI } = require('@google/generative-ai');
 
const genAI = new GoogleGenerativeAI(API_KEY);
const client = new Client({
    authStrategy: new LocalAuth(),
    puppeteer: {
        executablePath: '/usr/bin/google-chrome-stable',
        args: ['--no-sandbox', '--disable-setuid-sandbox'],
    },
});
 
 
const model = genAI.getGenerativeModel({ model: "gemini-pro" });
 
 
 
async function generate(prompt, message) {
 
    const result = await model.generateContent(prompt);
    const response = await result.response;
    const text = response.text();
 
    await message.reply(text);
}
 
client.on('qr', (qr) => {
    qrcode.generate(qr, { small: true });
});
 
client.on('authenticated', () => {
    console.log('Client is authenticated!');
});
 
client.on('ready', () => {
    console.log('Client is ready!');
});
 
client.on('disconnected', () => {
    console.log('Client is disconnected!');
});
 
client.on('auth_failure', () => {
    console.log('Client is auth_failure!');
});
 
 
client.on('message', async (message) => {
 
    if (message.body.includes('.bot')) {
 
        var query;
         
        const regxmatch = message.body.match(/.bot(.+)/);
 
        if (regxmatch) {
            query = regxmatch[1];
        }
        else {
            console.log("No regex match!");
            query = "Hi";
        }
 
        generate(query, message);
    };
 
});
 
client.initialize();


To start the application run the following command.

node bot.js

Authenticate the server

  • After running the server you will find a QR code in terminal, Scan it using whatsapp mobile app.
  • Finally your bot is running on mobile number you used to authenticate.
  • Just message to this whatsapp number, where message should start with “.bot”, See the final result.

Output:

4_11zon

Final Result of AI-Bot



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads