How to Auto-Reply on WhatsApp Using OpenAI API and Node.js

Have you ever wished your WhatsApp could automatically reply to messages just like a chatbot? In this post, we’ll walk you through how to connect your personal WhatsApp account to an auto-responder bot powered by OpenAI API. This solution is built using Node.js and a library called whatsapp-web.js. The final bot reads incoming messages and responds intelligently using OpenAI's ChatGPT.

What You Need

Step 1: Set Up Your Project

Create a new folder for your project and initialize Node.js:

mkdir whatsapp-ai-bot
cd whatsapp-ai-bot
npm init -y

Step 2: Install Required Packages

npm install whatsapp-web.js qrcode-terminal openai dotenv

Step 3: Create Your Bot Script

const { Client } = require('whatsapp-web.js');
const qrcode = require('qrcode-terminal');
const { OpenAI } = require('openai');
require('dotenv').config();
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const client = new Client();

client.on('qr', qr => {
  qrcode.generate(qr, { small: true });
});

client.on('ready', () => {
  console.log('WhatsApp bot is ready!');
});

client.on('message', async message => {
  if (message.fromMe) return;
  try {
    const chatCompletion = await openai.chat.completions.create({
      messages: [{ role: "user", content: message.body }],
      model: "gpt-3.5-turbo"
    });
    const reply = chatCompletion.choices[0].message.content;
    message.reply(reply);
  } catch (err) {
    message.reply("Sorry, something went wrong.");
    console.error(err);
  }
});

client.initialize();

Step 4: Set Up Environment Variables

OPENAI_API_KEY=your_openai_key_here

Step 5: Run Your Bot

node index.js

Scan the QR code with your WhatsApp. Once connected, the bot will auto-reply to any message it receives.

Important Notes

Demo Video

πŸš€ Side Hustle Alert!

Looking to earn money online by doing simple microtasks on your phone or laptop?
ClickWorker pays real cash for jobs like data entry, AI training, and surveys.

πŸ”— Start Earning on ClickWorker

(Affiliate Link – Supports our blog πŸ’š)

Final Thoughts

You now have a working system that lets your WhatsApp auto-reply to messages using AI. You can extend this to filter replies, respond to specific commands, or integrate your own database. Use pm2 or a cloud server to keep it running without interruption.

Would you like this as a downloadable template or app? Leave a comment below!