Building a WhatsApp AI Chatbot with Node.js, OpenAI, and WhatsApp-Web.js

Efe Fortune Samuel
4 min readDec 21, 2023

--

Introduction: In this tutorial, I will guide you through the process of building a WhatsApp chatbot powered by artificial intelligence (AI) using Node.js, OpenAI’s GPT-3.5 Turbo, and WhatsApp-Web.js. With this chatbot, you can receive WhatsApp messages from users and provide them with automatic responses generated by the AI. This project will help you understand how to set up a WhatsApp chatbot and integrate it with a powerful language model to deliver meaningful and engaging responses.

Requirements:

Before we get started, make sure you have the following prerequisites installed on your system:

  1. Node.js: You can download and install Node.js from the official website (https://nodejs.org/).
  2. A WhatsApp account: You’ll need a WhatsApp account to use WhatsApp-Web.js. Make sure you have WhatsApp installed on your mobile device and that it’s connected to the internet.
  3. OpenAI API Key: Obtain an API key from OpenAI (https://beta.openai.com/signup/) to access their GPT-3.5 Turbo API.
  4. Code Editor: You can use any code editor of your choice. We recommend Visual Studio Code.

Getting Started:

Step 1, Set Up the Project: Create a new directory for your project and open a terminal inside it. Initialize a Node.js project by running the following command:

npm init -y

Step 2, Install Dependencies: Install the necessary Node.js packages for WhatsApp-Web.js and OpenAI. Run the following command:

npm install whatsapp-web.js openai qrcode-terminal

Step 3, WhatsApp-Web.js Configuration: Create a JavaScript file, e.g., whatsapp-bot.js, and set up the basic WhatsApp-Web.js configuration. Import the required modules and create a WhatsApp Client instance:

const qrcode = require("qrcode-terminal");
const { Client } = require("whatsapp-web.js");
const client = new Client();

Step 4, WhatsApp QR Code Authentication: Configure your WhatsApp client to display a QR code for authentication:

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

Step 5, WhatsApp Client Ready: Implement a listener for when the WhatsApp client is ready:

client.on("ready", () => {
console.log("Client is ready!");
});

Step 6, OpenAI Integration: Create a function to interact with OpenAI’s GPT-3.5 Turbo to generate responses with specified prompts. Designing a prompt is essentially how you “program” a GPT model, usually by providing instructions or some examples of how to successfully complete a task. In this case, we are creating a sarcastic bot and we provide some sample prompt and replies:


const generateResponse = async (message) => {
const response = await openai?.chat?.completions?.create({
model: "gpt-3.5-turbo",
messages: [
{
role: "system",
content:
"You are Efe 2.0, a chatbot that reluctantly answers questions with sarcastic responses.",
},
{
role: "user",
content: "How many pounds are in a kilogram?",
},
{
role: "assistant",
content:
"This again? There are 2.2 pounds in a kilogram. Please make a note of this.",
},
{
role: "user",
content: "What does HTML stand for?",
},
{
role: "assistant",
content:
"Was Google too busy? Hypertext Markup Language. The T is for try to ask better questions in the future.",
},
{
role: "user",
content: "When did the first airplane fly?",
},
{
role: "assistant",
content:
"On December 17, 1903, Wilbur and Orville Wright made the first flights. I wish they'd come and take me away.",
},
{
role: "user",
content: message,
},
],
temperature: 0.5,
max_tokens: 256,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
});
return response.choices[0].message.content;
};

Step 7, Handle Incoming Messages: Set up an event listener to handle incoming WhatsApp messages. We’ll use OpenAI to generate responses to these messages:

client.on("message", async (message) => {
if (message.from !== "status@broadcast") {
const response = await generateResponse(message.body);
await message.reply(response);
}
});

Step 8, Initialize the WhatsApp Client: Initialize the WhatsApp client to start listening for messages and provide QR code authentication:

client.initialize();

Step 9, Starting the bot: You can start the bot by running the following command:

node whatsapp-bot.js //or whatever you named your file

Step 10, Connecting a whatsapp account: After running the command, you should see a qr code on the code editor terminal. Proceed to navigate to the following path on a WhatsApp account (This account would be the bot)

Settings -> Linked devices -> Link a device.

Once there, scan the qr code.

Conclusion:

Congratulations! You’ve successfully created a WhatsApp chatbot that uses OpenAI’s GPT-3.5 Turbo to generate responses. Users can send messages to your phone number, and it will reply with AI-generated text. This tutorial provides the foundation for building a more sophisticated chatbot, including customizing responses, handling different user scenarios, and improving the overall user experience. Feel free to enhance this project further and explore more possibilities with Node.js, OpenAI, and WhatsApp-Web.js. Happy bot building!

NB: To avoid sending to important chats, dont use a personal whatsapp account for the bot.

--

--