Build a WhatsApp ChatGPT-powered AI chatbot for your business

Wassenger
9 min readNov 2, 2023

--

Turn your WhatsApp number into a ChatGPT-powered AI powerful chatbot in minutes with this tutorial, using the Node.js, OpenAI ChatGPT and Wassenger API.

By following this tutorial you will be able to have a fully functional ChatGPT-like AI chatbot running in minutes on your computer or cloud server that behaves like a virtual customer support assistant for a specific business purpose.

You can easily customize and instruct the AI bot to adjust its behaviour, role, purpose and knowledge boundaries. Also, the AI bot will be conversation-aware based on your previous message history with the user on WhatsApp, enabling more context-specific accurate responses.

The chatbot will be able to understand and speak many languages and has been trained to behave like a customer support virtual assistant specialized in certain tasks.

Additionally, you can easily augment domain-specific knowledge about your business in real-time by using function actions that let the AI bot arbitrarily communicate with your code functions or remote APIs to retrieve and feed the AI with custom information. Find an example here.

The code for this tutorial is available on GitHub💻

You can also run the bot program right from your browser without installing any software or code by clicking here 🎉

🤩 🤖 Wassenger is a complete WhatsApp API solution. Sign up for a 7-day free trial and get started in minutes!

Demo conversation on WhatsApp powered by the ChatGPT chatbot using this tutorial

Contents

🤑 💰 Earn 30% comission by referring users to Wassenger. Get your referral link now. Terms apply.

How it works

1. Starts a web service that automatically connects to the Wassenger API and your WhatsApp number

2. Create a tunnel using Ngrok to be able to receive Webhook events on your computer (or you can use a dedicated Webhook URL instead if you run the bot program in your cloud server).

3. Registers the webhook endpoint automatically to receive incoming messages.

4. Processes and replies to messages received using a ChatGPT-powered AI model trained with custom instructions.

5. You can start playing with the AI bot by sending messages to the Wassenger-connected WhatsApp number.

Features

This tutorial provides a complete ChatGPT-powered AI chatbot implementation in Node.js that:

  • Provides a fully featured chatbot in your WhatsApp number connected to Wassenger
  • Replies automatically to any incoming messages from arbitrary users
  • Can understand any text in natural language and reply in 90+ different human languages
  • Allows any user to ask to talk with a human, in which case the chat will be assigned to an agent and exit the bot flow
  • AI bot behaviour can be easily adjusted in the configuration file (open config.js)

Bot behavior

The AI bot will always reply to inbound messages based on the following criteria:

  • The chat belongs to a user (group chats are always ignored)
  • The chat is not assigned to any agent inside Wassenger
  • The chat has not any of the blacklisted labels (see config.js)
  • The chat user number has not been blacklisted (see config.js)
  • The chat or contact has not been archived or blocked
  • If a chat is unassigned from an agent, the bot will take over it again and automatically reply to new incoming messages

Requirements

Project structure

Browse the source files on GitHub

\
|- bot.js -> the bot source code in a single file
|- config.js -> configuration file to customize credentials and bot behavior
|- actions.js -> functions to perform actions through the Wassenger API
|- server.js -> initializes the web server to process webhook events
|- main.js -> initializes the bot server and creates the webhook tunnel (when applicable)
|- store.js -> the bot source code in a single file
|- package.json -> node.js package manifest required to install dependencies
|- node_modules -> where the project dependencies will be installed, managed by npm

Installation

If you have git installed, run the following command from the Terminal:

git clone https://github.com/wassengerhq/whatsapp-chatgpt-bot.git

If you don’t have `git`, download the project source files here and unzip it.

This is what the Wassenger team-optimized cooperative web chat looks like. Sign up for free

🤑 💰 Earn 30% comission by referring users to Wassenger. Get your referral link now. Terms apply.

Configuration

Open your favourite terminal and change the directory to the project folder where `package.json` is located:

cd whatsapp-chatgpt-bot/

From that folder, install dependencies by running:

npm install

With your preferred code editor, open the `config.js` file and follow the steps below.

Set your Wassenger API key

Enter your Wassenger API key

You can sign up here for free and then obtain the API key here:

// Required. Specify the Wassenger API key to be used
// You can obtain it here: https://app.wassenger.com/apikeys
apiKey: env.API_KEY || 'ENTER API KEY HERE',

Set your OpenAI API key

Enter your OpenAI API key

Sign up in OpenAI for free and then obtain the API key here:

// Required. Specify the OpenAI API key to be used
// You can sign up for free here: https://platform.openai.com/signup
// Obtain your API key here: https://platform.openai.com/account/api-keys
openaiKey: env.OPENAI_API_KEY || 'ENTER OPENAI API KEY HERE',

Set your Ngrok token (optional)

If you need to run the program on your local computer, the program needs to create a tunnel using Ngrok to process webhook events for incoming WhatsApp messages.

Sign up on Ngrok for a free account and then obtain your auth token as explained here.

Set the token in `config.js` in line 90th:

// Ngrok tunnel authentication token.
// Required if webhook URL is not provided.
// sign up for free and get one: https://ngrok.com/signup
// Learn how to obtain the auth token: https://ngrok.com/docs/agent/#authtokens
ngrokToken: env.NGROK_TOKEN || 'ENTER NGROK TOKEN HERE',

If you run the program in a cloud server that is publicly accessible from the Internet, you don’t need to use Ngrok. Instead, set your server URL in `config.js` > `webhookUrl` field.

Customization

You can customize the chatbot's behaviour by defining a set of instructions in natural language that the AI will follow.

Read the comments in the code for further instructions.

Also, you can easily adjust the code to match more specific requirements. The possibilities are nearly endless!

To proceed with the customization, open config.js with your preferred code editor and set the bot instructions, welcome and default message based on your preferences:

// Default message when the user sends an unknown message.
const unknownCommandMessage = `I'm sorry, I can only understand text. Can you please describe your query?
If you would like to chat with a human, just reply with *human*.`

// Default welcome message. Change it as you need.
const welcomeMessage = `Hey there 👋 Welcome to this ChatGPT-powered AI chatbot demo using *Wassenger API*! I can also speak many languages 😁`

// AI bot instructions to adjust its behaviour. Change it as you need.
// Use concise and clear instructions.
const botInstructions = `You are a smart virtual customer support assistant that works for Wassenger.
You can identify yourself as Molly, the Wassenger chatbot assistant.
You will be chatting with random customers who may contact you with general queries about the product.
Wassenger is a cloud solution that offers WhatsApp API and multi-user live communication services designed for businesses and developers.
Wassenger also enables customers to automate WhatsApp communication and build chatbots.
You are an expert in customer support. Be polite, be gentle, be helpful and emphatic.
Politely reject any queries that are not related to customer support or Wassenger itself.
Strictly stick to your role as a customer support virtual assistant for Wassenger.
If you can't help with something, ask the user to type *human* in order to talk with customer support.`

// Default help message. Change it as you need.
const defaultMessage = `Don't be shy 😁 try asking anything to the AI chatbot, using natural language!
Example queries:
1️⃣ Explain me what is Wassenger
2️⃣ Can I use Wassenger to send automatic messages?
3️⃣ Can I schedule messages using Wassenger?
4️⃣ Is there a free trial available?
Type *human* to talk with a person. The chat will be assigned to an available member of the team.
Give it a try! 😁`

Open the full configuration file with all available options

Run the bot

You can run the bot program right now in your browser using StackBlitz:

Usage

Run the bot program:

node main

Run the bot program on a custom port:

PORT=80 node main

Run the bot program for a specific Wassenger-connected device:

DEVICE=WHATSAPP_DEVICE_ID node main

Run the bot program in production mode:

NODE_ENV=production node main

Run the bot with an existing webhook server without the Ngrok tunnel:

WEBHOOK_URL=https://bot.company.com:8080/webhook node main

Note: `https://bot.company.com:8080` must point to the bot program itself running in your server and it must be network reachable using HTTPS for a secure connection.

Questions

Can I train the AI to behave in a customized way?

Yes! You can provide customized instructions to the AI to determine the bot's behaviour, identity and more.

To set your customized instructions, enter the text in `config.js` > `botInstructions`.

Can I instruct the AI not to reply about unrelated topics?

Yes! By defining a set of clear and explicit instructions, you can teach the AI to stick to the role and politely not answer to topics that are unrelated to the relevant topic.

For instance, you can add the following in your instructions:

You are a smart virtual customer support assistant who works for Wassenger.
Be polite, be gentle, be helpful and emphatic.
Politely reject any queries that are not related to your customer support role or Wassenger itself.
Strictly stick to your role as customer support virtual assistant for Wassenger.

Can I customize the chatbot response and behaviour?

For sure! The code is available for free and you can adapt it as much as you need.

You just need to have some JavaScript/Node.js knowledge, and you can always ask ChatGPT to help you write the code you need.

How to stop the bot from replying to certain chats?

You should simply assign the specific chats to any agent on the Wassenger web chat or using the API.

Alternatively, you can set blacklisted labels in the `config.js` > `skipChatWithLabels` field, then add one or these labels to the specific chat you want to be ignored by the bot. You can assign labels to chats using the Wassenger web chat or using the API.

Do I have to use Ngrok?

No, you don’t. Ngrok is only used for development/testing purposes when running the program from your local computer. If you run the program in a cloud server, most likely you won’t need Ngrok if your server can be reachable via the Internet using a public domain (e.g. bot.company.com) or a public IP.

In that case, you need to provide your server's full URL ending with `/webhook` like this when running the bot program:

WEBHOOK_URL=https://bot.company.com:8080/webhook node main

Note: `https://bot.company.com:8080` must point to the bot program itself running in your server and it must be network reachable using HTTPS for secure connection.

What happens if the program fails?

Please check the error in the terminal and make sure you are running the program with enough permissions to start it in port 8080 in localhost.

How to avoid specific chats being replied to by the bot?

By default, the bot will ignore messages sent in group chats, blocked and archived chats/contacts.

Besides that, you can blacklist or whitelist specific phone numbers and chat with labels that be handled by the bot.

See `numbersBlacklist`, `numbersWhitelist`, and `skipChatWithLabels` options in `config.js` for more information.

Can I run this bot on my server?

Absolutely! Deploy or transfer the program source code to your server and run the start command from there.

The requirements are the same, no matter where you run the bot.

Also, remember to define the `WEBHOOK_URL` environment variable with your server's Internet-accessible public URL as explained before.

--

--

Wassenger

The complete WhatsApp API + Team Chat + CRM + AI Assistant for smart Businesses and Teams. Automate and work more productively with your clients on WhatsApp!