Skip to content

WhatsApp demo GPT Chatbot Python#

WhatsApp demo chatbot with GPT in Python is a sample chatbot written using the WhatsApp GPT Bot Library for Python, which is designed specifically for writing chatbots using the GREEN-API service.

Using API, the chatbot sends text messages, files, images, music, videos, contacts, geolocation, conducts surveys, requests an avatar, sends links, creates a group with the bot, quotes a message.

Scan the QR code or add a link to start chatting below.

chatbot-QR

Link to bot

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

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

  1. Setting up the environment to launch the chatbot
  2. Authorization in GREEN-API
  3. Launching the chatbot
  4. How to launch the chatbot locally in debug mode
  5. Configuring the chatbot
  6. Usage
  7. Code structure
  8. Message management
  9. Integration with ChatGPT

1. Setting up the environment to launch the chatbot#

To run the chatbot, you need to have the Python interpreter installed. On Linux & MacOS, it is already installed. For Windows, download the latest stable version from the official website, run the installer and follow the recommendations.

Check the Python version, to do this, open the command line (PowerShell - for Windows) and enter the query:

python --version
The response to the entered query should be the Python version in the following format:

Python 3.N.N

You must have Python version 3.8 or higher.

Make a copy of the chatbot using:

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

Or download the archive whatsapp-demo-chatbot-python.

Go to the folder with the chatbot in the command line and install the necessary Python libraries. Make sure you have the package manager pip installed.

The list of necessary libraries is in the requirements.txt file. Run the following command to install them:

python -m pip install -r requirements.txt
The environment and necessary libraries are installed. You can proceed to setting up and running the chatbot on your Whatsapp account.

2. Authorization in GREEN-API#

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

idInstance
apiTokenInstance
Don't forget to enable all notifications in the instance settings so that the chatbot can immediately start receiving messages.

3. Launching the chatbot#

The bot can be launched on the server or locally. For local deployment, you must either enable DEBUG MODE or start a local server to transfer the necessary data.

The .env configuration file is located in the config folder. When receiving data from the server, the configuration file looks like this:

active_profile=GreenAPI
spring_cloud_config_uri=http://localhost:8000

Where active_profile is your profile ID, it takes a string as a value. spring_cloud_config_uri is the address to the server with the port, from where json with the parameters is received.

You can write a small local server to transfer data to your bot.

Server example:

#!/usr/bin/env python3

from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse
import json

class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        parsed_path = urlparse(self.path)
        self.send_response(200)
        self.end_headers()
        self.wfile.write(json.dumps({
            'user_id': 'Ваш ID',
            'api_token_id': 'ВАШ ТОКЕН',
            'link_pdf': 'url ССЫЛКА НА ФАЙЛ',
            'link_jpg': 'url ССЫЛКА НА картинку',
            'link_audio_ru': 'url ССЫЛКА НА аудио файл',
            'link_video_ru': 'url ССЫЛКА НА видео файл',
            'link_audio_en': 'url ССЫЛКА НА аудио файл',
            'link_video_en': 'url ССЫЛКА НА видео файл'
        }).encode())
        return

if __name__ == '__main__':
    server = HTTPServer(('localhost', 8000), RequestHandler)
    print('Starting server at http://localhost:8000')
    server.serve_forever()
Enter the required values ​​in the GET request. First, start the server, and then start your bot in another console.

python bot.py
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-chatbot-python library contains a mechanism for changing the instance settings using the SetSettings method, which is launched when the chatbot is turned on.

All settings for receiving notifications are disabled by default, the chatbot will enable the following settings:

"incomingWebhook": "yes",
"outgoingMessageWebhook": "yes",
"outgoingAPIMessageWebhook": "yes",
which are responsible for receiving notifications about incoming and outgoing messages.

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 whatsapp-chatbot-python library 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 changes and deletion of incoming notifications are completed, the chatbot will begin to respond to messages as usual. In total, this process takes no more than 5 minutes.

To stop the chatbot, hover over the command line and use the keyboard shortcut Ctrl + C

4. How to launch the chatbot locally in debug mode#

To run the bot locally, use the environment variable DEBUG=True. All other necessary variables are presented below (create a .env file and insert your actual values):

DEBUG=True
DEBUG_USER_ID=<Your Instance ID>
DEBUG_API_TOKEN_ID=<Your Api token ID>
DEBUG_LINK_PDF=<Full URL string for .pdf file>
DEBUG_LINK_JPG=<Full URL string for .jpg file>
DEBUG_LINK_AUDIO_RU=<Full URL string for .mp3 file (RU)>
DEBUG_LINK_VIDEO_RU=<Full URL string for .mp4 file (RU)>
DEBUG_LINK_AUDIO_EN=<Full URL string for .mp3 file (EN)>
DEBUG_LINK_VIDEO_EN=<Full URL string for .mp4 file (EN)>
LINK_PREVIEW=True

ACTIVE_PROFILE=<Any name>
SPRING_CLOUD_CONFIG_URI=http://localhost:8000

Example link

DEBUG_LINK_JPG="https://google.com/i/db/2022/11/1817828/image.jpg"

The ACTIVE_PROFILE and SPRING_CLOUD_CONFIG_URI values ​​are used for compatibility.

Then the chatbot will gain access to your account using these details:

bot = GreenAPIBot(id_instance, api_token_instance)
Save the changes to the file.

python bot.py
This request will start the chatbot. The process begins with initializing the chatbot, which involves changing the settings of the associated instance.

5. Configuring the 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 open access. All of them are either written directly in the .env file or transmitted over the network.

'link_pdf': 'url LINK TO FILE',
'link_jpg': 'url LINK TO image',
'link_audio_ru': 'url LINK TO audio file',
'link_video_ru': 'url LINK TO video file',
'link_audio_en': 'url LINK TO audio file',
'link_video_en': 'url LINK TO video file'

For more in-depth customization, go through all the menu items, look in the functions - def main_menu_option_1_handler to main_menu_option_13_handler.

All changes must be saved, after which you can launch the chatbot.

Links must lead to files from cloud storage or open access and are written in .env. Text information is contained in data.yml. On line 159 in bot.py is def main_menu_option_2_handler in the function there is the following code:

    try:
        sender_lang_code = sender_state_data[LANGUAGE_CODE_KEY]
        second_option_answer_text = (
            f'{answers_data["send_file_message"][sender_lang_code]}'
            f'{answers_data["links"][sender_lang_code]["send_file_documentation"]}'
        )
    except KeyError as e:
        logger.exception(e)
        return
    notification.api.sending.sendFileByUrl(
        notification.chat,
        config.link_pdf,
        "corgi.pdf",
        caption=second_option_answer_text,
You can customize the name for your file.

In the same way, enter the link and name for the image on line 221:

    notification.api.sending.sendFileByUrl(
        notification.chat,
        config.link_jpg,
        "corgi.jpg",
        caption=third_option_answer_text,
    )
All changes must be saved, after which you can launch the chatbot. To launch the chatbot, go back to step 3.

6. Usage#

If the previous steps have been completed, then the chatbot should be running on your Whatsapp account. It is important to remember that you must be logged in to your 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 5 languages ​​- English, Kazakh, Russian, Español, עברית. Before greeting the interlocutor, the chatbot will ask you to select the language of communication:

  *1* - English
  *2* - Қазақша
  *3* - Русский
  *4* - Español
  *5* - עברית
Send 1 to 5 to select the language for further communication. After you send 3, the chatbot will send a greeting message in Russian:
GREEN API provides sending 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*. Contact 📱
*7*. Geolocation 🌎
*8*. Poll ✔
*9*. Get a picture of my avatar 👤
*10*. Send a link 🔗
*11*. Create a group with the bot 👥
*12*. Quote a message ©️
*13*. About PYTHON GREEN API chatbot 🦎

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!

7. Code structure#

The functional part of the chatbot is in the bot.py file. Here the GreenAPIBot chatbot class and the Notification incoming notification are imported to process messages:

from whatsapp_chatbot_python import GreenAPIBot, Notification
The chatbot is initialized on line 31:
bot = GreenAPIBot(id_instance, api_token_instance)
Each message sent to the chatbot is processed on line 45:
@bot.router.message(type_message=TEXT_TYPES, state=None)
@debug_profiler(logger=logger)
def initial_handler(notification: Notification) -> None:

The handler receives messages via incoming notifications of the webhook type.

After checking the data about the user who sent the message, the chatbot saves the sender using the internal/utils.py library.

Returning to the bot.py file, after the user sends the first message to the chatbot, the chatbot checks whether the given user is in the list of users. If not, a new user is created.

Then, the chatbot sets the authorization status of the given user to True to indicate that the chat is active and asks the user to select the language of communication:

def initial_handler(notification: Notification) -> None:
    sender_state_data_updater(notification)
    notification.answer(answers_data["select_language"])
notification.answer() is a chatbot library function that checks the user data from the incoming notification and sends a response to that user. data['select_language'] is one of the chatbot's pre-prepared text responses:
  *1* - English
  *2* - Қазақша
  *3* - Русский
  *4* - Español
  *5* - עברית
The user sends from 1 to 5 , thereby choosing the language of communication with the chatbot.

The chatbot receives the incoming notification and sees that the chat with this user is active by checking the authorization status. After that, the chatbot passes the incoming notification to the local function chosen_language_code, sets the language of communication with the user:

    try:
        answer_text = (
            f'{answers_data["welcome_message"][chosen_language_code]}'
            f'*{notification.event["senderData"]["senderName"]}*!'
            f'{answers_data["menu"][chosen_language_code]}'
        )
The chatbot removes unnecessary characters from all received messages so that if the user answers "/1" or makes an extra space, the chatbot can still recognize it, using regxp for this.

After the communication language is set, all incoming notifications go to the options function, which responds to commands 1-13, stop, menu.

For example, if the user sends 1, the following code will be run:

    try:
        sender_lang_code = sender_state_data[LANGUAGE_CODE_KEY]
        first_option_answer_text = (
            f'{answers_data["send_text_message"][sender_lang_code]}'
            f'{answers_data["links"][sender_lang_code]["send_text_documentation"]}'
        )
and sends the following response to the user:
This message is sent via the sendMessage method
To learn how the method works, follow the link
https://green-api.com/en/docs/api/sending/SendMessage/
All chatbot responses are stored in the data.yml file and loaded into bot.py:
YAML_DATA_RELATIVE_PATH = "config/data.yml"

with open(YAML_DATA_RELATIVE_PATH, encoding="utf8") as f:
    answers_data = safe_load(f)
Ответы чатбота хранятся в следующем формате, где data['welcome_message']['ru'] вернет приветственное сообщение на русском языке, а data['welcome_message']['eng'] - на английском языке:
welcome_message:
  en: "Welcome the to the GREEN API chatbot, "
  kz: "GREEN API чат-ботына қош келдіңіз, "
  ru: "Добро пожаловать в GREEN API чат-бот, "
  es: "Bienvenido al chatbot GREEN API, "
  he: "ברוכים הבאים לצ'אטבוט GREEN API, "
Also, every time the user sends a new message, the current_last_interaction_ts field is updated with a new time:
current_last_interaction_ts = current_sender_state_data[LAST_INTERACTION_KEY]
This is done to check when the user contacted last. If more than 5 minutes have passed since the last contact, then the chatbot will reset the authorization and language of communication, and start the chat again:
 MAX_INACTIVITY_TIME_SECONDS = 300

    if now_ts - current_last_interaction_ts > MAX_INACTIVITY_TIME_SECONDS:
        return sender_state_reset(notification)

8. Message management#

As the chatbot indicates in its responses, all messages are sent via API. Documentation on the methods for sending messages can be found on the website in the Sending Methods section.

As for receiving messages, messages are read via HTTP API. Documentation on the methods for receiving messages can be found on the website.

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

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

notification.answer(answers_data["select_language"])
However, other sending methods can be called directly from the whatsapp-api-client-python library. For example, when sending a contact:
notification.api.sending.sendContact(
    chatId=notification.chat,
    contact={
        "phoneContact": notification.chat.split("@")[0],
        "firstName": notification.event["senderData"]["senderName"],
    },

9. Integration with ChatGPT#

The demo chatbot now includes integration with ChatGPT (option 14 in the menu), which allows users to have interactive conversations with OpenAI GPT models directly in WhatsApp chat.

Setup#

To enable ChatGPT functionality, you need to set up an OpenAI API key:

  1. Get an API key from the OpenAI website
  2. Add the key to your environment variables or .env file:
OPENAI_API_KEY=your_openai_api_key

If the OpenAI API key is not configured, the chatbot will display an error message when the user tries to use the ChatGPT feature.

Configuration#

The integration with ChatGPT is configured when the bot is initialized:

gpt_bot = WhatsappGptBot(
    id_instance=config.user_id,
    api_token_instance=config.api_token_id,
    openai_api_key=config.openai_api_key,
    model="gpt-4o",
    system_message="You are a helpful assistant in a WhatsApp chat. Be concise and accurate in your responses.",
    max_history_length=10,
    temperature=0.7
)

You can configure the following parameters: - model: OpenAI model to use (default "gpt-4o") - system_message: System message that determines the behavior of ChatGPT - max_history_length: Number of previous messages to keep in the context - temperature: Controls the "randomness" in responses (from 0.0 to 1.0)

Usage#

Users can access the ChatGPT feature by sending "14" in the main menu. The chatbot will enter a special conversation mode with ChatGPT, where all messages will be forwarded to the GPT model for processing.

To exit a ChatGPT conversation and return to the main menu, users can type one of the following keywords (depending on the selected language): - English: "exit", "menu", "stop", "back"
- Russian: "выход", "меню", "стоқта", "артқа", "menu", "меню"
- Spanish: "salir", "menú", "parar", "atrás", "menu", "exit"
- Hebrew: "יציאה", "תפריט", "עצור", "exit", "menu", "חזור"

Limitations#

  • Using the API may incur costs depending on your OpenAI subscription plan
  • Response times may vary depending on latency OpenAI API and your internet connection speed

License#

Licensed under Creative Commons Attribution-NoDerivatives 4.0 International (CC BY-ND 4.0).

LICENSE.