Skip to content

JS demo chatbot v2.0#

GREEN-API JS demo GPT chatbot#

JS demo GPT chatbot is an example of a chatbot written using the Whatsapp JS chatbot library, which is designed specifically for writing chatbots using the GREEN-API service.

The chatbot clearly demonstrates the use of the API for sending text messages, files, images, locations and contacts.

Scan the following QR to start or follow the link to start a chat with the bot to see how it works:

chatbot-QR

Link to the chat

To launch the chatbot on your own Whatsapp account, follow the instructions:

Contents#

  1. Installing the environment for launching the chatbot
  2. Launching the chatbot
  3. Configuring chatbot
  4. Usage
  5. Code structure
  6. Message management
  7. GPT integration

1. Installing the environment for launching the chatbot#

To run the chatbot, you need to install the js environment. If necessary, download and install the latest version of Node.js from the official website.

After completion, you need to check whether the environment was deployed correctly. To do this, open the command line (for example, cmd or bash) and enter the query:

node -v

Download and unzip the zip archive of the project or clone it using the version control command:

How to install Git version control system?

Download and install Git version control system suitable for your operating system from official website.

git clone https://github.com/green-api/whatsapp-demo-chatbot-js-v2  

# Install dependencies
cd whatsapp-demo-chatbot-js-v2
npm install

Open the project in any IDE.

The environment for running the chatbot is ready, now you need to configure and run the chatbot on your Whatsapp account.

2. Launching the chatbot#

In order to set up a chatbot on your Whatsapp account, you need to go to your console and register. For new users, instructions are provided for setting up an account and obtaining the parameters necessary for the chatbot to work, namely:

Environment Configuration Create a .env file in the project root:

INSTANCE_ID=your_instance_id
INSTANCE_TOKEN=your_api_token

Core Files

bot.ts - Main bot implementation
strings.yml - Multi-language message strings
.env - Environment configuration

Next, you can run the program by clicking start in the IDE interface or entering the following query in the command line:

npm run start 
This request will start the chatbot. The process begins with the initialization of the chatbot, which includes changing the settings of the associated instance.

The whatsapp-api-client-js-v2 library contains a mechanism for changing the instance settings using the SetSettings method, which is launched when the chatbot is turned on.

Instance Settings The bot automatically configures these settings::

{
    "webhookUrl": "",
    "webhookUrlToken": "",
    "outgoingWebhook": "no",
    "stateWebhook": "no",
    "incomingWebhook": "yes",
    "outgoingAPIMessageWebhook": "no",
    "outgoingMessageWebhook": "no",
    "pollMessageWebhook": "yes",
    "markIncomingMessagesReaded": "yes"
}
which are responsible for receiving notifications about incoming and outgoing messages, poll updates, and also include marking incoming messages as read.

The process of changing the settings takes several minutes, during which time the instance will be unavailable. Messages sent to the chatbot during this time will not be processed.

After the settings are applied, notifications about previously received incoming messages will be deleted. This process is also prescribed in the library whatsapp-api-client-js-v2 and is automatically launched after changing the settings.

This is necessary so that the chatbot does not start processing messages from old chats.

After the settings are changed and incoming notifications are deleted, the chatbot will start responding to messages as usual. In total, this process takes no more than 5 minutes.

To stop the chatbot, use the keyboard shortcut Ctrl + C in the command line.

3. Configuring chatbot#

By default, the chatbot uses links to download files from the network, but users can add their own links to files, one for a file of any extension pdf / docx / ... and one for an image.

Links must lead to files from cloud storage or public access. The scene endpointsScene contains the following code for sending a file:

    endpointsScene.hears(['2'], (ctx) => {
    if (checkSession(ctx)) {
        ctx.telegram.restAPI.file.sendFileByUrl(
            ctx.update.message.chat.id.toString(),
            undefined,
            "https://storage.yandexcloud.net/sw-prod-03-test/ChatBot/corgi.pdf",
            "image.pdf",
            strings.send_file_message[ctx.session.lang] + strings.links[ctx.session.lang].send_file_documentation)
    }
})
Add a reference to a file of any extension as the first parameter of the answerWithUrlFile method and specify the file name in the second parameter. The file name must contain the extension, for example "somefile.pdf". This line after modification will be in the following format:
    endpointsScene.hears(['2'], (ctx) => {
    if (checkSession(ctx)) {
        ctx.telegram.restAPI.file.sendFileByUrl(
            ctx.update.message.chat.id.toString(),
            undefined,
            "https://...somefile.pdf",
            "somefile.pdf",
            strings.send_file_message[ctx.session.lang] + strings.links[ctx.session.lang].send_file_documentation)
    }
})

All changes must be saved, after which you can launch the chatbot. To launch the chatbot, go back to step 2.

4. Usage#

If the previous steps have been completed, then the chatbot should be running on your Whatsapp account. It is important to remember that the user must be authorized in the personal account.

Now you can send messages to the chatbot!

The chatbot will respond to any message sent to the account. Since the chatbot supports several languages, before greeting the interlocutor, the chatbot will ask you to select the language of communication:

1 - English
2 - Қазақша
3 - Русский
...
Answer with 1, 2 or 3 to select the language for further communication. After you send 3, the chatbot will send a greeting message in Russian:
Welcome to the GREEN-API chatbot, user! GREEN-API provides sending of the following types of data. Select a number from the list to check how the sending method works

1. Text message 📩
2. File 📋
3. Picture 🖼
4. Audio 🎵
5. Video 📽
6. ...

To return to the beginning, write stop or 0
By selecting a number from the list and sending it, the chatbot will respond with which API this type of message was sent and share a link to information about the API.

For example, by sending 1, the user will receive in response:

This message was sent via the sendMessage method.

To find out how the method works, follow the link
https://green-api.com/en/docs/api/sending/SendMessage/
If you send something other than numbers 1-13, the chatbot will briefly respond:
Sorry, I didn't quite understand you 😔, write a menu to see the possible options
The user can also call the menu by sending a message containing "menu". And by sending "stop", the user will end the conversation with the chatbot and receive a message:
Thank you for using the GREEN-API chatbot, user!

5. Code structure#

The main file of the chatbot is bot.js, it contains the main function and starts the program execution. In this class, the bot object is initialized, the first scene is set up and the bot is launched.

async function main() {
    const strings = getStringsData()  //Getting data from the strings.yml file, which stores the bot's replies

    const bot = new WhatsAppBot({       //Initiate the bot object
        idInstance: "{{INSTANCE_ID}}",
        apiTokenInstance: "{{TOKEN}}",
    })

    let settings = await bot.telegram.restAPI.settings.setSettings({    //Setting up settings so that the bot receives all the necessary webhooks
        incomingWebhook: "yes",
        outgoingMessageWebhook: "yes",
        outgoingAPIMessageWebhook: "yes",
        pollMessageWebhook: "yes",
        markIncomingMessagesReaded: "yes"
    })
    console.log(settings);

    await clearWebhookQueue(bot) //Clearing the webhook queue of old notifications so that the bot does not process them

    //
    //...Description of scenes
    //

    const stage = new Stage([mainMenuScene, endpointsScene, startScene, createGroup]) //Registering scenes in bot state

    bot.use(session())
    bot.use(stage.middleware())
    bot.on('message', (ctx) => ctx.scene.enter('startScene'))   /Start the first scene
    launchBotWithErrorHandler(bot)                              //Launch the bot
}

This bot uses scenes to organize the code. This means that the chatbot logic is divided into fragments (scenes), a scene corresponds to a certain state of the dialogue and is responsible for processing the response.

For each chat, only one scene can be active at a time.

For example, the first scene startScene is responsible for the greeting message. Regardless of the text of the message, the bot asks which language is convenient for the user and includes the next scene, which is responsible for processing the response.

There are 4 scenes in the bot:

  • Scene startScene - responds to any incoming message, sends a list of available languages. Starts the scene MainMenu.
  • Scene mainMenuScene - processes the user's choice and sends the main menu text in the selected language. Starts the scene Endpoints
  • Scene endpointsScene - executes the method selected by the user and sends a description of the method in the selected language.
  • Scene createGroup - creates a group if the user said that he added the bot to his contacts. If not, it returns to the "endpoints" scene.

The checkSession method is used to reset the start scene if the bot has not been texted for more than 2 minutes. It checks how long ago the user touched the session and if it was more than 5 minutes ago, it refreshes the session and starts the conversation over.

The ymlReader file contains a function that returns data from the strings.xml file. This file is used to store the bot's lines.

6. Message management#

As the chatbot indicates in its responses, all messages are sent via API. Documentation on sending methods.

As for receiving messages, messages are read via HTTP API. Documentation on receiving methods.

The chatbot uses the whatsapp-chatbot-js library, where methods for sending and receiving messages are already integrated, so messages are read automatically, and sending regular text messages is simplified.

For example, a chatbot automatically sends a message to the contact from whom it received a message:

    ctx.reply("text")
However, other sending methods can be called directly from the whatsapp-api-client-js library. For example, when receiving an avatar:
    ctx.telegram.restAPI.instance.getAvatar(
        ctx.update.message.from.id.toString(),
        undefined);

7. GPT integration#

This demo bot shows how to integrate a library as a message handler in a state-based architecture. The integration is done through a special GPT state that manages a conversation with a GPT model.

Implementing a GPT state#

const gptBot = new WhatsappGptBot({
    idInstance: process.env.INSTANCE_ID!,
    apiTokenInstance: process.env.INSTANCE_TOKEN!,
    openaiApiKey: process.env.OPENAI_API_KEY!,
    model: "gpt-4o",
    maxHistoryLength: 15,
    systemMessage: "You are a helpful WhatsApp assistant created by GREEN-API. Answer concisely but informatively.",
    temperature: 0.7,
});

interface CustomSessionData {
    lang?: string;
    gptSession?: GPTSessionData;
}

const gptState: State<CustomSessionData> = {
    name: "gpt_state",
    async onEnter(message, data) {
        const lang = data?.lang || "en";
        await bot.sendText(message.chatId, strings.chat_gpt_intro[lang]);

        // Initializing GPT session with system message
        data.gptSession = {
            messages: [{role: "system", content: gptBot.systemMessage}],
            lastActivity: Date.now(),
        };
    },
    async onMessage(message, data) {
        const lang = data?.lang || "en";
        const exitCommands = [
            "menu", "меню", "exit", "выход", "stop", "стоп", "back", "назад",
            "menú", "salir", "parar", "atrás", "תפריט", "יציאה", "עצור", "חזור",
            "мәзір", "шығу", "тоқта", "артқа",
        ];

        // Processing exit commands
        if (exitCommands.includes(message.text?.toLowerCase() || "")) {
            return {state: "main", data};
        }

        try {
            // Processing a message via GPT
            const {response, updatedData} = await gptBot.processMessage(
                    message,
                    data.gptSession
            );

            await bot.sendText(message.chatId, response);
            data.gptSession = updatedData;
            return undefined;
        } catch (error) {
            console.error("Error in GPT processing:", error);
            await bot.sendText(message.chatId, strings.chat_gpt_error[lang]);
            return undefined;
        }
    }
};

Key Features:#

  1. State-Based Integration
  2. GPT functionality is encapsulated in a separate state
  3. Seamless integration with existing bot states
  4. Clean transition between normal and GPT modes

  5. Session Management

  6. GPT conversation history is stored in the state data
  7. Persisted between messages within a single session
  8. Cleanly cleared when exiting a state

  9. Multilingual Support

  10. Exit commands in multiple languages
  11. Language-aware error messages

Usage#

  1. Select option 14 from the main menu to enter GPT mode
  2. Conversate naturally with the GPT model
  3. Use any of the exit commands to return to the main menu
  4. Conversation history is persisted within a session