By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
JishnuKsivan - Unity Game Development, Android Studio App Coding, AdMob Guides, AI Prompts & Source Code Downloads.JishnuKsivan - Unity Game Development, Android Studio App Coding, AdMob Guides, AI Prompts & Source Code Downloads.JishnuKsivan - Unity Game Development, Android Studio App Coding, AdMob Guides, AI Prompts & Source Code Downloads.
  • Home
  • About us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Disclaimer
Search
Categories
  • AdMob Monetization
  • AI Prompts & Tools
  • Android Development
  • Tech Tips & Tricks
  • Unity Game Development
© 2026 JishnuKSivan.com. All Rights Reserved. Unity • Android • AI Tools • Tech Updates
Reading: Build an AI WhatsApp Assistant Using Gemini API – Complete Step-by-Step Guide (2026)
Share
Sign In
Notification Show More
Font ResizerAa
JishnuKsivan - Unity Game Development, Android Studio App Coding, AdMob Guides, AI Prompts & Source Code Downloads.JishnuKsivan - Unity Game Development, Android Studio App Coding, AdMob Guides, AI Prompts & Source Code Downloads.
Font ResizerAa
Search
  • Home
  • About us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Disclaimer
Have an existing account? Sign In
Follow US
  • Contact
  • Blog
  • Complaint
  • Advertise
© 2026 JishnuKSivan.com. All Rights Reserved. Unity • Android • AI Tools • Tech Updates
JishnuKsivan - Unity Game Development, Android Studio App Coding, AdMob Guides, AI Prompts & Source Code Downloads. > Blog > AI Prompts & Tools > Automation ideas > Build an AI WhatsApp Assistant Using Gemini API – Complete Step-by-Step Guide (2026)
AI Prompts & ToolsAutomation ideas

Build an AI WhatsApp Assistant Using Gemini API – Complete Step-by-Step Guide (2026)

jishnuksivan
Last updated: July 1, 2026 1:39 pm
jishnuksivan
Share
Build an AI WhatsApp assistant
Build an AI WhatsApp assistant
SHARE

Artificial Intelligence is transforming how businesses communicate with customers, and messaging platforms are at the center of this shift. Instead of manually answering repetitive questions, businesses can use AI assistants to provide instant responses, summarize conversations, translate messages, and automate customer support.

Contents
What You’ll BuildProject ArchitecturePrerequisitesGet Your Gemini API KeySet Up the WhatsApp Business PlatformCreate the Project FolderInitialize the ProjectInstall Required PackagesCreate the Express ServerCreate Environment VariablesCreate the Webhook RouteVerify the WebhookCreate a Simple Dashboard (Optional)Current ProgressReceive Incoming WhatsApp MessagesUpdate the Webhook RouteExtract the User’s MessageCreate the Gemini ServiceImport the Gemini ServiceGenerate an AI ReplySend a Reply Back to WhatsAppSend the AI ResponseComplete Webhook FlowAdd Conversation ContextLimit Conversation SizeHandle Empty MessagesImprove Prompt QualityLog Incoming RequestsError HandlingTest Your ChatbotExample ConversationFeatures CompletedDeploy Your AI WhatsApp AssistantProtect Your API KeysDeploy the ServerConfigure HTTPSStore Conversations in FirestoreAdd Voice Note SupportSupport Image MessagesCreate Custom AI PersonalitiesRate LimitingPerformance OptimizationUseful Business FeaturesProduction ChecklistFrequently Asked QuestionsCan I use this chatbot for customer support?Can I store conversation history?Can the chatbot understand multiple languages?Can I connect it to other systems?Future ImprovementsFinal Verdict

WhatsApp is one of the world’s most widely used messaging platforms, making it an ideal place to deploy an AI-powered assistant. By combining the WhatsApp Business Platform API with Google’s Gemini API, you can create a chatbot capable of understanding natural language and generating intelligent replies.

In this tutorial, you’ll build an AI WhatsApp Assistant using Node.js, Express, and the Gemini API. The bot will receive incoming WhatsApp messages through webhooks, send them to Gemini for processing, and return AI-generated responses back to the user.

By the end of this guide, you’ll have a working foundation that you can extend with chat history, multilingual support, order tracking, FAQ automation, and human handoff.


What You’ll Build

  • AI-powered WhatsApp chatbot
  • Automatic replies using Gemini API
  • Webhook-based message processing
  • Node.js + Express backend
  • Multi-language support
  • Conversation context (basic)
  • Secure API configuration
  • Production-ready project structure

Project Architecture


WhatsApp User

↓

WhatsApp Business Platform

↓

Webhook (Express.js)

↓

Gemini API

↓

AI Response

↓

WhatsApp User

Whenever a user sends a message, the WhatsApp platform forwards it to your webhook. Your Express server extracts the message, sends it to Gemini, receives the AI-generated reply, and sends that reply back through the WhatsApp Business Platform.


Prerequisites

  • Basic JavaScript knowledge
  • Node.js installed
  • Visual Studio Code
  • A Google account
  • A Gemini API key
  • Access to the WhatsApp Business Platform

Get Your Gemini API Key

Gemini will generate all AI responses for the chatbot.

  1. Open Google AI Studio.
  2. Create a new project if necessary.
  3. Generate an API key.
  4. Copy the key and store it securely.

Avoid hardcoding the key in your source code. Later in this tutorial, you’ll store it in environment variables.


Set Up the WhatsApp Business Platform

Create or configure your WhatsApp Business Platform application and obtain the credentials required for development:

  • Phone Number ID
  • Access Token
  • Webhook Verify Token (you choose this)
  • Business Account ID

These values allow your server to verify webhook requests and send replies through the platform.


Create the Project Folder

Use the following structure:


ai-whatsapp-assistant/

│

├── server.js

├── package.json

├── .env

├── routes/

│      webhook.js

├── services/

│      gemini.js

├── public/

│      index.html

│      style.css

└── README.md

Keeping routing logic and AI integration in separate folders makes the application easier to maintain.


Initialize the Project

Open your terminal and run:


mkdir ai-whatsapp-assistant

cd ai-whatsapp-assistant

npm init -y

Install Required Packages


npm install express axios dotenv cors

These packages are used for:

  • Express – Web server
  • Axios – HTTP requests
  • dotenv – Environment variables
  • CORS – Cross-origin support (if needed)

Create the Express Server

Create server.js.


import express from "express";

import dotenv from "dotenv";

dotenv.config();

const app = express();

app.use(express.json());

app.get("/",(req,res)=>{

res.send("AI WhatsApp Assistant Running");

});

const PORT =
process.env.PORT || 3000;

app.listen(PORT,()=>{

console.log(
`Server running on ${PORT}`
);

});

Start the server:


node server.js

If everything is configured correctly, visiting http://localhost:3000 will display a confirmation message.


Create Environment Variables

Create a file named .env.


PORT=3000

GEMINI_API_KEY=YOUR_API_KEY

WHATSAPP_ACCESS_TOKEN=YOUR_ACCESS_TOKEN

PHONE_NUMBER_ID=YOUR_PHONE_NUMBER_ID

VERIFY_TOKEN=YOUR_VERIFY_TOKEN

Keeping credentials outside your source code makes your project safer and easier to manage across development and production environments.


Create the Webhook Route

Create routes/webhook.js.


import express from "express";

const router =
express.Router();

router.get("/",

(req,res)=>{

res.send(
"Webhook Ready"
);

});

export default router;

Register the route inside server.js.


import webhookRoutes

from "./routes/webhook.js";

app.use(

"/webhook",

webhookRoutes

);

Verify the Webhook

The WhatsApp Business Platform verifies your webhook before sending events. Add a verification endpoint:


router.get("/",(req,res)=>{

const mode =
req.query["hub.mode"];

const token =
req.query["hub.verify_token"];

const challenge =
req.query["hub.challenge"];

if(

mode==="subscribe" &&

token===process.env.VERIFY_TOKEN

){

return res.status(200)

.send(challenge);

}

res.sendStatus(403);

});

When the verification token matches, the platform receives the challenge value and confirms the webhook.


Create a Simple Dashboard (Optional)

Although the bot works through webhooks, you can create a small dashboard to monitor server status.

public/index.html


<!DOCTYPE html>

<html>

<head>

<title>

AI WhatsApp Assistant

</title>

</head>

<body>

<h1>

AI WhatsApp Assistant

</h1>

<p>

Server is running successfully.

</p>

</body>

</html>

Current Progress

At this stage, you have successfully:

  • Created the Node.js project
  • Installed required packages
  • Built the Express server
  • Configured environment variables
  • Created the webhook route
  • Added webhook verification
  • Prepared the project structure for AI integration

Receive Incoming WhatsApp Messages

Now that your Express server and webhook are configured, it’s time to receive incoming WhatsApp messages. Whenever a user sends a message to your WhatsApp Business number, the platform delivers a webhook event to your server.

In this section, you’ll extract the user’s message, send it to the Gemini API, receive an AI-generated response, and send the reply back to WhatsApp automatically.


Update the Webhook Route

Open routes/webhook.js and add a POST endpoint to receive webhook events.


router.post("/", async (req, res) => {

try {

const body = req.body;

console.log(JSON.stringify(body, null, 2));

res.sendStatus(200);

}

catch(error){

console.error(error);

res.sendStatus(500);

}

});

This endpoint receives webhook events whenever a user sends a message.


Extract the User’s Message

The webhook payload contains information about the sender and the message. Extract the text and sender ID.


const message =

body.entry?.[0]

?.changes?.[0]

?.value?.messages?.[0];

if(!message){

return res.sendStatus(200);

}

const userMessage =

message.text.body;

const sender =

message.from;

The sender value uniquely identifies the WhatsApp user who sent the message.


Create the Gemini Service

Create a new file named services/gemini.js.


import axios from "axios";

import dotenv from "dotenv";

dotenv.config();

const API_URL =
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${process.env.GEMINI_API_KEY}`;

export async function askGemini(prompt){

try{

const response =
await axios.post(API_URL,{

contents:[

{

parts:[

{

text:prompt

}

]

}

]

});

return response.data

.candidates[0]

.content.parts[0]

.text;

}

catch(error){

console.error(error);

return "Sorry, I couldn't process your request right now.";

}

}

Import the Gemini Service

Inside routes/webhook.js:


import {

askGemini

}

from "../services/gemini.js";

Generate an AI Reply

After extracting the user’s message, send it to Gemini.


const aiReply =

await askGemini(

userMessage

);

Gemini will analyze the user’s message and return a conversational response.


Send a Reply Back to WhatsApp

Create a helper function that sends a message using the WhatsApp Business Platform API.


import axios from "axios";

async function sendMessage(

to,

message

){

await axios.post(

`https://graph.facebook.com/v23.0/${process.env.PHONE_NUMBER_ID}/messages`,

{

messaging_product:

"whatsapp",

to,

text:{

body:message

}

},

{

headers:{

Authorization:

`Bearer ${process.env.WHATSAPP_ACCESS_TOKEN}`,

"Content-Type":

"application/json"

}

}

);

}

Send the AI Response

After Gemini generates a response:


await sendMessage(

sender,

aiReply

);

The chatbot will automatically send the AI-generated reply back to the user.


Complete Webhook Flow


User sends message

↓

Webhook receives event

↓

Extract message

↓

Gemini API

↓

Generate response

↓

WhatsApp API

↓

Reply sent

Add Conversation Context

Basic conversation memory helps Gemini produce more relevant responses.


const conversations = {};

function getHistory(user){

if(!conversations[user]){

conversations[user]=[];

}

return conversations[user];

}

Store both the user’s message and the AI response.


const history =

getHistory(sender);

history.push({

role:"user",

text:userMessage

});

history.push({

role:"assistant",

text:aiReply

});

For production systems, store conversation history in a database such as Firestore instead of server memory.


Limit Conversation Size

Prevent memory usage from growing indefinitely.


if(history.length>20){

history.splice(

0,

history.length-20

);

}

Keeping only recent messages helps maintain context while reducing memory usage.

Handle Empty Messages


if(

!userMessage ||

userMessage.trim()===""

){

return res.sendStatus(200);

}

Improve Prompt Quality

Instead of forwarding only the user’s message, provide instructions to Gemini.


const prompt =

`You are a helpful WhatsApp assistant.

Answer politely and briefly.

User:

${userMessage}`;

Well-structured prompts often produce more consistent responses.

Log Incoming Requests


console.log(

"User:",

sender

);

console.log(

"Message:",

userMessage

);

console.log(

"AI:",

aiReply

);

Logging helps debug webhook issues during development.

Error Handling


try{

// Process request

}

catch(error){

console.error(error);

await sendMessage(

sender,

"Sorry, an unexpected error occurred."

);

}

Providing a friendly fallback message improves the user experience if something goes wrong.


Test Your Chatbot

After configuring your webhook and server:

  1. Start the Node.js server.
  2. Expose it using your preferred tunneling solution if running locally.
  3. Configure the webhook URL in your WhatsApp Business Platform settings.
  4. Send a message from your test WhatsApp account.
  5. Verify that the bot responds with an AI-generated reply.

Example Conversation

User:


Can you explain what Firebase is?

AI:


Firebase is Google's Backend-as-a-Service platform that provides authentication, databases, cloud storage, hosting, messaging, analytics, and other tools to help developers build and scale web and mobile applications.

Features Completed

  • ✅ Receive WhatsApp messages
  • ✅ Extract incoming text
  • ✅ Connect to Gemini API
  • ✅ Generate AI replies
  • ✅ Send responses back to WhatsApp
  • ✅ Maintain basic conversation context
  • ✅ Logging
  • ✅ Error handling
  • ✅ End-to-end message flow

Deploy Your AI WhatsApp Assistant

Now that your chatbot can receive WhatsApp messages, process them with the Gemini API, and send intelligent replies, the next step is preparing it for real-world usage. This includes deploying the application, protecting sensitive credentials, storing conversations, and improving performance.


Protect Your API Keys

Never hardcode API keys or access tokens inside your JavaScript files or commit them to a public Git repository.

Store all sensitive values inside the .env file.


PORT=3000

GEMINI_API_KEY=YOUR_GEMINI_API_KEY

WHATSAPP_ACCESS_TOKEN=YOUR_ACCESS_TOKEN

PHONE_NUMBER_ID=YOUR_PHONE_NUMBER_ID

VERIFY_TOKEN=YOUR_VERIFY_TOKEN

Also remember to add the following line to your .gitignore file:


.env

This prevents your credentials from being uploaded to version control.


Deploy the Server

Your Express application can be hosted on a VPS or cloud platform. Regardless of the hosting provider, make sure you:

  • Install Node.js
  • Copy the project files
  • Install dependencies with npm install
  • Configure environment variables
  • Start the server with a process manager such as PM2

Example:


npm install

npm install -g pm2

pm2 start server.js

pm2 save

Using a process manager helps restart your application automatically if it crashes or after a server reboot.


Configure HTTPS

The WhatsApp Business Platform requires secure HTTPS endpoints for webhooks. Ensure your server uses a valid SSL/TLS certificate and verify that your webhook URL is publicly accessible over HTTPS before registering it.


Store Conversations in Firestore

Instead of storing conversations in memory, use Firestore so chat history persists across server restarts.

Example document structure:


conversations

|

|--UserPhoneNumber

      |

      |--messages

             |

             |--message1

             |--message2

             |--message3

Example data:


{

user:"919876543210",

role:"user",

message:"Hello",

createdAt:Date.now()

}

Saving conversations also enables analytics, support history, and improved context for future interactions.


Add Voice Note Support

Many users prefer sending voice messages instead of typing. You can extend your assistant to:

  • Download incoming voice notes
  • Convert speech to text using a speech recognition service
  • Send the transcription to Gemini
  • Reply with AI-generated text

This creates a more natural conversational experience for users.


Support Image Messages

If your chosen Gemini model supports image understanding, you can build workflows such as:

  • Identify products from photos
  • Explain screenshots
  • Extract information from receipts
  • Summarize documents from images
  • Answer questions about uploaded pictures

Create Custom AI Personalities

Different businesses require different communication styles. You can customize the system prompt for various use cases.

Example:


const systemPrompt =

`You are a customer support assistant.

Always reply politely.

Keep answers under 100 words.

If you don't know the answer,

recommend contacting human support.`;

A consistent system prompt helps maintain the desired tone across conversations.


Rate Limiting

Protect your application from abuse by limiting the number of requests a user can make within a certain time period.

  • Limit requests per phone number.
  • Reject duplicate requests.
  • Apply cooldown periods for excessive usage.
  • Log suspicious activity for review.

Performance Optimization

  • Cache frequently requested answers.
  • Trim unnecessary conversation history.
  • Reuse HTTP connections where possible.
  • Validate input before sending it to Gemini.
  • Compress responses if your infrastructure supports it.
  • Monitor server memory and CPU usage.

Useful Business Features

You can evolve the assistant beyond simple Q&A by adding:

  • Order status lookup
  • Appointment scheduling
  • Lead qualification
  • Customer feedback collection
  • FAQ automation
  • Product recommendations
  • Multi-language customer support
  • Escalation to a human agent

Production Checklist

TaskStatus
Webhook Verification✅
Environment Variables✅
HTTPS Enabled✅
Conversation Storage✅
Error Handling✅
Logging✅
Rate Limiting✅
Deployment✅
Security Review✅

Frequently Asked Questions

Can I use this chatbot for customer support?

Yes. Many businesses use AI assistants to answer common questions, provide product information, and route complex issues to human agents.


Can I store conversation history?

Yes. Firestore, PostgreSQL, or another database can be used to save messages, enabling persistent chat history and analytics.


Can the chatbot understand multiple languages?

Yes. Gemini supports many languages, allowing the assistant to communicate with users from different regions.


Can I connect it to other systems?

Yes. You can integrate CRM platforms, inventory systems, payment gateways, scheduling tools, or other business applications through your backend.


Future Improvements

  • Voice conversations
  • Image understanding
  • Document summarization
  • AI-powered product recommendations
  • Customer sentiment analysis
  • Multi-agent workflows
  • Admin dashboard with analytics
  • Live agent handoff

Final Verdict

Building an AI WhatsApp Assistant with the Gemini API is a practical way to combine conversational AI with one of the world’s most widely used messaging platforms. Throughout this tutorial, you’ve learned how to create a Node.js server, verify webhooks, process incoming messages, generate intelligent responses with Gemini, and send replies back through the WhatsApp Business Platform.

By securing your credentials, storing conversations, enabling HTTPS, and preparing your application for deployment, you’ve also laid the groundwork for a production-ready solution. From here, you can extend the assistant with voice support, image understanding, CRM integrations, analytics, and other advanced features to meet the needs of real-world users and businesses.

Conclusion: You now have a complete roadmap for building, securing, deploying, and scaling an AI-powered WhatsApp Assistant using Node.js and the Gemini API. This project provides a solid foundation for creating intelligent messaging applications for customer support, automation, and business communication.

You Might Also Like

AI Game Development – Can AI Create Mobile Games?
Build an AI Email Assistant Using Gemini API – Complete Step-by-Step Guide (2026)
Best AI Tools for Business Automation in 2026
Best ChatGPT Prompts for Unity Developers (2026 Guide)
Claude vs ChatGPT for Coding – Which AI Assistant Is Better in 2026?
TAGGED:AI customer support botAI messaging applicationAI WhatsApp AssistantConversational AIExpress.js webhookGemini API tutorialGemini chatbotJavaScript AI projectNode.js chatbotWhatsApp AI integrationWhatsApp automation

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.

By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Share
Previous Article AI email assistant tutorial interface Build an AI Email Assistant Using Gemini API – Complete Step-by-Step Guide (2026)
Leave a Comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Latest Posts

Build your own AI chatbot tutorial
Build a ChatGPT Clone with Firebase and Gemini API – Complete Step-by-Step Guide (2026)
AI Prompts & Tools Unity tutorials
Firestore to MySQL migration guide
How to Migrate Firebase Firestore to MySQL – Complete Step-by-Step Guide (2026)
Firebase Tutorial
n8n vs Make.com 2026 showdown
n8n vs Make.com – Which Automation Tool Is Better in 2026?
Automation ideas AI Prompts & Tools
MCP (Model Context Protocol) Explained – The Future of AI Integrations
MCP (Model Context Protocol) Explained – The Future of AI Integrations
AI Prompts & Tools

We are a tech-focused platform providing tutorials on Unity game development, Android Studio app coding, AdMob monetization, AI prompts, and free source code resources for developers and learners.

You Might also Like

ChatGPT vs GitHub Copilot – Which is Better for Coding?
AI Prompts & ToolsAI tools

ChatGPT vs GitHub Copilot – Which is Better for Coding?

jishnuksivan
jishnuksivan
8 Min Read
Best AI Tools for Developers in 2026
AI tools

Best AI Tools for Developers in 2026

jishnuksivan
jishnuksivan
12 Min Read
JishnuKsivan - Unity Game Development, Android Studio App Coding, AdMob Guides, AI Prompts & Source Code Downloads.
AI Prompts & ToolsUnity tutorials

How to Use ChatGPT for Debugging Unity Errors (2026 Guide)

jishnuksivan
jishnuksivan
9 Min Read
JishnuKsivan - Unity Game Development, Android Studio App Coding, AdMob Guides, AI Prompts & Source Code Downloads.JishnuKsivan - Unity Game Development, Android Studio App Coding, AdMob Guides, AI Prompts & Source Code Downloads.
Follow US
© 2026 JishnuKSivan.com. All Rights Reserved. Unity • Android • AI Tools • Tech Updates
  • Home
  • About us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Disclaimer
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?