{"id":21942912,"url":"https://github.com/green-api/whatsapp-demo-chatbot-python","last_synced_at":"2025-06-21T05:02:50.764Z","repository":{"id":208379579,"uuid":"709252369","full_name":"green-api/whatsapp-demo-chatbot-python","owner":"green-api","description":"A python chatbot application built for WhatsApp","archived":false,"fork":false,"pushed_at":"2025-04-02T06:30:58.000Z","size":4344,"stargazers_count":4,"open_issues_count":0,"forks_count":1,"subscribers_count":4,"default_branch":"main","last_synced_at":"2025-04-22T18:55:39.076Z","etag":null,"topics":["green-api","whatsapp-api","whatsapp-bot","whatsapp-chatbot","whatsapp-chatbot-python"],"latest_commit_sha":null,"homepage":"https://green-api.com/en/docs/chatbots/python/chatbot-demo/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/green-api.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2023-10-24T10:43:49.000Z","updated_at":"2025-04-02T06:31:02.000Z","dependencies_parsed_at":"2023-11-21T07:56:03.930Z","dependency_job_id":"98854b15-d079-4879-8df5-b8ef5ccb6d98","html_url":"https://github.com/green-api/whatsapp-demo-chatbot-python","commit_stats":null,"previous_names":["green-api/whatsapp-demo-chatbot-python"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/green-api/whatsapp-demo-chatbot-python","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/green-api%2Fwhatsapp-demo-chatbot-python","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/green-api%2Fwhatsapp-demo-chatbot-python/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/green-api%2Fwhatsapp-demo-chatbot-python/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/green-api%2Fwhatsapp-demo-chatbot-python/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/green-api","download_url":"https://codeload.github.com/green-api/whatsapp-demo-chatbot-python/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/green-api%2Fwhatsapp-demo-chatbot-python/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":261065252,"owners_count":23104762,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["green-api","whatsapp-api","whatsapp-bot","whatsapp-chatbot","whatsapp-chatbot-python"],"created_at":"2024-11-29T03:27:13.929Z","updated_at":"2025-06-21T05:02:45.751Z","avatar_url":"https://github.com/green-api.png","language":"Python","readme":"# whatsapp-demo-chatbot-python  \n\n![](https://img.shields.io/badge/license-CC%20BY--ND%204.0-green)  \n\n- [Документация на русском языке](https://github.com/green-api/whatsapp-demo-chatbot-python/blob/main/README_RU.md).  \n\nDemo version of Whatsapp chatbot based on API service [GREEN-API](https://green-api.com/en).\nUsing API, the chatbot sends text messages, files, images, music, videos, contacts, geolocation, surveys, requests an avatar, sends links, creates a group with the bot, and quotes a message.  \n\n## Table of contents\n* [Installation](#installation)\n* [Authorization in GREEN-API](#authorization-in-green-api)\n* [Launching the chatbot](#launching-the-chatbot)\n* [Launch the chatbot in debug mode](#launch-the-chatbot-in-debug-mode)\n* [Setup](#setup)\n* [Usage](#usage)\n* [Code structure](#code-structure)\n* [Message handling](#message-handling)\n\n## Installation  \n\nTo run the chatbot, you need to have the Python interpreter installed. It is already installed on Linux and MacOS. For Windows, download the latest stable version from the [official website](https://www.python.org/), run the installer and follow the recommendations.  \n\nCheck the Python version by entering the command line (PowerShell - for Windows) and entering the query:  ``` python --version ```  \nThe response to the entered query should be the Python version in the following format: ``` Python 3.N.N ```. You must have installed Python version 3.8 or higher.  \n\nMake a copy of the bot chat with ``` git clone https://github.com/green-api/whatsapp-demo-chatbot-python.git ``` or download the archive [whatsapp-demo-chatbot-python](https ://github.com/green-api/whatsapp-demo-chatbot-python).  \n\nThe 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 and ready for running chatbot. You can set up and launch the chatbot on the Whatsapp account.\n\n## Authorization in GREEN-API  \n\nTo set up the chatbot on your Whatsapp account you must sign up to [console](https://console.green-api.com/) and register. For new users, [instructions](https://green-api.com/en/docs/before-start/) are provided for setting up an account and obtaining the parameters necessary for the chatbot to work, namely:  \n```bash\nidInstance\napiTokenInstance\n```  \n\n## Launching the chatbot  \n\nThe bot can be launched on the server or locally. To start chatbot local deployment, you must enable DEBUG MODE or start a local server to transfer the necessary data.\n\nThe configuration file *.env* is located in the *config* directory. When receiving data from the server, the configuration file looks like this:\n\n```\nactive_profile=GreenAPI\nspring_cloud_config_uri=http://localhost:8000\n```\n\nWhere active_profile is your profile ID, it takes a string as a value.\nspring_cloud_config_uri is the address to the server with the port from where JSON with parameters is received.\n\nYou can write a small local server to transfer data to your bot.\n\nServer example:\n\n```python3\n#!/usr/bin/env python3\n\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nfrom urllib.parse import urlparse\nimport json\n\nclass RequestHandler(BaseHTTPRequestHandler):\n    def do_GET(self):\n        parsed_path = urlparse(self.path)\n        self.send_response(200)\n        self.end_headers()\n        self.wfile.write(json.dumps({\n            'user_id': 'Your ID',\n            'api_token_id': 'Your TOKEN',\n            'link_pdf': 'url LINK TO FILE',\n            'link_jpg': 'url LINK TO IMAGE',\n            'link_audio_ru': 'url LINK TO audio file',\n            'link_video_ru': 'url LINK TO video file',\n            'link_audio_en': 'url LINK TO audio file',\n            'link_video_en': 'url LINK TO video file'\n        }).encode())\n        return\n\nif __name__ == '__main__':\n    server = HTTPServer(('localhost', 8000), RequestHandler)\n    print('Starting server at http://localhost:8000')\n    server.serve_forever()\n```\n\nEnter the required values ​​in the GET request. First, start the server and then start your bot in another console.\n\n```\npython bot.py\n```\nThis request will start the chatbot. The process begins with the initialization of the chatbot, which includes changing the settings of the associated instance.\n\nThe [whatsapp-chatbot-python](https://github.com/green-api/whatsapp-chatbot-python) library contains a mechanism for changing the instance settings using the [SetSettings](https://green-api.com/en/docs/api/account/SetSettings/) method, which is launched when the chatbot is running.\n\nAll settings for receiving notifications are disabled by default, the chatbot turn on the following settings:\n```\n\"incomingWebhook\": \"yes\",\n\"outgoingMessageWebhook\": \"yes\",\n\"outgoingAPIMessageWebhook\": \"yes\",\n```\nwhich are responsible for receiving notifications about incoming and outgoing messages.  \n\nThe settings changing process takes several minutes, the instance will be unavailable during which times. Messages sent to the chatbot during this time will not be processed.  \n\nThen there will be deletion of the old notifications, another process invoked by the parent library [whatsapp-chatbot-python](https://github.com/green-api/whatsapp-chatbot-python), which is essential to make sure chatbot will not process the messages from the already opened chats.\n\nAfter the initialization is completed, chatbot is ready to answer the messages. The whole process of initialization will take up to 5 minutes.\n\nTo stop the chatbot hover the cmd / bash from the current directory and click `Ctrl + C`  \n\n### Launch the chatbot in debug mode  \n\nTo 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):\n\n```\nDEBUG=True\nDEBUG_USER_ID=\u003cYour Instance ID\u003e\nDEBUG_API_TOKEN_ID=\u003cYour Api token ID\u003e\nDEBUG_LINK_PDF=\u003cFull URL string for .pdf file\u003e\nDEBUG_LINK_JPG=\u003cFull URL string for .jpg file\u003e\nDEBUG_LINK_AUDIO_RU=\u003cFull URL string for .mp3 file (RU)\u003e\nDEBUG_LINK_VIDEO_RU=\u003cFull URL string for .mp4 file (RU)\u003e\nDEBUG_LINK_AUDIO_EN=\u003cFull URL string for .mp3 file (EN)\u003e\nDEBUG_LINK_VIDEO_EN=\u003cFull URL string for .mp4 file (EN)\u003e\nLINK_PREVIEW=True\n\nACTIVE_PROFILE=\u003cAny name\u003e\nSPRING_CLOUD_CONFIG_URI=http://localhost:8000\n```\n\nLink example\n```\nDEBUG_LINK_JPG=\"https://google.com/i/db/2022/11/1817828/image.jpg\"\n```\n\nThe ACTIVE_PROFILE and SPRING_CLOUD_CONFIG_URI values ​​are used for compatibility.\n\nThen the chatbot will access your account using these details:\n```python\nbot = GreenAPIBot(id_instance, api_token_instance)\n```\nSave the changes to the file.\n\n```\npython bot.py\n```\nThis request will start the chatbot. The process begins with the initialization of the chatbot, which includes changing the settings of the associated instance.\n\n## Setup  \n\nBy default, the chatbot uses links to download files from the network, but users can add their links to files, one for a file of any extension pdf / docx / ... and one for an image.\n\nLinks must lead to files from cloud storage or open access. You can write them directly in the *.env* file or transmit them over the network.\n\n```\n'link_pdf': 'url LINK TO FILE',\n'link_jpg': 'url LINK TO image',\n'link_audio_ru': 'url LINK TO audio file',\n'link_video_ru': 'url LINK TO video file',\n'link_audio_en': 'url LINK TO audio file',\n'link_video_en': 'url LINK TO video file'\n```\n\nFor more in-depth customization, go through all the menu items, see the functions - def main_menu_option_1_handler to main_menu_option_13_handler.\n\nAll changes must be saved, after which you can launch the chatbot.\n\nLinks 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:\n```python\ntry:\nsender_lang_code = sender_state_data[LANGUAGE_CODE_KEY]\nsecond_option_answer_text = (\nf'{answers_data[\"send_file_message\"][sender_lang_code]}'\nf'{answers_data[\"links\"][sender_lang_code][\"send_file_documentation\"]}'\n)\nexcept KeyError as e:\nlogger.exception(e)\nreturn\nnotification.api.sending.sendFileByUrl(\nnotification.chat,\nconfig.link_pdf,\n\"corgi.pdf\",\ncaption=second_option_answer_text,\n```\nYou can choose the name for your file.\n\nLikewise enter the link and name for the image on line 221:\n```python\nnotification.api.sending.sendFileByUrl(\nnotification.chat,\nconfig.link_jpg,\n\"corgi.jpg\",\ncaption=third_option_answer_text,\n)\n```\nAll changes must be saved, after which you can launch the chatbot. Return to [step 3](#launching-the-chatbot) to launch the chatbot.  \n\n## Usage  \nAfter completing the previous steps, you can run the chatbot with your Whatsapp account. It is important to remember that you must be logged in to your [console](https://console.green-api.com/).\n\nNow you can send messages to the chatbot!\n\nThe chatbot will respond to any message sent to the account.\nThis chatbot version supports 5 languages ​​- English, Kazakh, Russian, Español, עברית.\nBefore greeting a user, the chatbot will ask to select the language of communication:\n```\n*1* - English\n*2* - Kazakh\n*3* - Russian\n*4* - Español\n*5* - עברית\n```\nSend from 1 to 5 to select the language for communication. After you send 1, the chatbot will send a greeting message in English:\n```\nGREEN API provides the following kinds of message services.\n\nSelect a number from the list to check how the sending method works!\n\n*1*. Text message 📩\n*2*. File 📋\n*3*. Image 🖼\\\n*4*. Audio 🎵\n*5*. Video 📽\n*6*. Contact 📱\n*7*. Location 🌎\n*8*. Poll ✔\n*9*. Get image of my avatar👤\n*10*. Send link 🔗\n*11*. Create a group with the bot 👥\n*12*. Quote message ©️\n*13*. About PYTHON GREEN API chatbot 🦎\n\nTo return to the beginning, write *stop* or *0*\n```\n\nBy selecting a number from the list and sending it, the chatbot will respond to which API sent this type of message and share a link to information about the API.\n\nFor example, by sending 1, the user will receive in response:\n```\nThis message was sent via the sendMessage method\n\nTo find out how the method works, follow the link\nhttps://green-api.com/docs/api/sending/SendMessage/\n```\nIf you send something other than numbers 1-13, the chatbot will briefly respond:\n```\nSorry, I didn't quite understand you, write a menu to see the possible options\n```\nThe 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:\n```\nThank you for using the GREEN-API chatbot, user!\n```\n\n## Code structure  \nThe functional part of the chatbot is in the `bot.py` file.\nHere the `GreenAPIBot` chatbot class and the `Notification` incoming notification are imported to handle messages:\n```python\nfrom whatsapp_chatbot_python import GreenAPIBot, Notification\n```\nThe chatbot is initialized on line 31:\n```python\nbot = GreenAPIBot(id_instance, api_token_instance)\n```\nEach message sent to the chatbot is processed on line 45:\n```python\n@bot.router.message(type_message=TEXT_TYPES, state=None)\n@debug_profiler(logger=logger)\ndef initial_handler(notification: Notification) -\u003e None:\n```\n\nThe handler receives messages via incoming notifications of type [webhook](https://green-api.com/en/docs/api/receiving/notifications-format/incoming-message/Webhook-IncomingMessageReceived/).\nThe chatbot checks the details from the sender and then saves the sender using the **internal/utils.py** library.\n\nReturning to the `bot.py` file, after the user sends the first message to the chatbot, the chatbot checks if the user is already in the list of users. If not, a new user is created.\n\nThen, the chatbot sets the user's authorization status to `True` to indicate that the chat is active and asks the user to select a language for communication:\n```python\ndef initial_handler(notification: Notification) -\u003e None:\nsender_state_data_updater(notification)\nnotification.answer(answers_data[\"select_language\"])\n```\n```notification.answer()``` is a chatbot library function that checks the user data from the incoming notification and sends a response to the user. ```data['select_language']``` is one of the chatbot's pre-prepared text responses:\n```\n*1* - English\n*2* - Қазақша\n*3* - Русский\n*4* - Español\n*5* - עברית\n```\nThe user sends from 1 to 5 to select the language of communication with the chatbot.\n\nThe chatbot receives an 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`, and sets the language of communication with the user:\n```python\ntry:\nanswer_text = (\nf'{answers_data[\"welcome_message\"][chosen_language_code]}'\nf'*{notification.event[\"senderData\"][\"senderName\"]}*!'\nf'{answers_data[\"menu\"][chosen_language_code]}'\n)\n```\nThe 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, for this purpose, regxp is used.\n\nAfter the communication language is set, all incoming notifications go to the `options` function, which responds to commands 1-13, stop, menu.\n\nFor example, if the user sends 1, the following code will be run:\n```python\ntry:\nsender_lang_code = sender_state_data[LANGUAGE_CODE_KEY]\nfirst_option_answer_text = (\nf'{answers_data[\"send_text_message\"][sender_lang_code]}'\nf'{answers_data[\"links\"][sender_lang_code][\"send_text_documentation\"]}'\n)\n```\nand send the following response to the user:\n\n```\nThis message is sent via the sendMessage method.\nHow to the method works, follow the link\nhttps://green-api.com/en/docs/api/sending/SendMessage/\n```\nAll chatbot responses are stored in the `data.yml` file and loaded into `bot.py`:\n```python\nYAML_DATA_RELATIVE_PATH = \"config/data.yml\"\n\nwith open(YAML_DATA_RELATIVE_PATH, encoding=\"utf8\") as f:\nanswers_data = safe_load(f)\n```\nThe chatbot responses are stored in the following format, where `data['welcome_message']['ru']` will return a welcome message in Russian, and `data['welcome_message']['eng']` - in English:\n```yml\nwelcome_message:\nen: \"Welcome the to the GREEN API chatbot, \"\nkz: \"GREEN API chat-bot, \"\nru: \"Welcome to the GREEN API chat-bot, \"\nes: \"Bienvenido al chatbot GREEN API, \"\nhe: \"GREEN API for Chatbots,\"\n```\nAlso, every time a user sends a new message, the ```current_last_interaction_ts``` field is updated with a new time:\n```python\ncurrent_last_interaction_ts = current_sender_state_data[LAST_INTERACTION_KEY]\n```\nThis is done to check when the user connected last time. If more than 5 minutes have passed since the last contact, then the chatbot will reset authorization and language of communication, and start the chat again:\n```python\nMAX_INACTIVITY_TIME_SECONDS = 300\n\nif now_ts - current_last_interaction_ts \u003e MAX_INACTIVITY_TIME_SECONDS:\nreturn sender_state_reset(notification)\n```\n\n## Message handling  \nThe chatbot indicates in its responses, all messages are sent via API. Documentation on sending methods can be found at [Sending methods](https://green-api.com/en/docs/api/sending/).\n\nAs for receiving messages, messages are read via HTTP API. Documentation on receiving methods can be found at [site](https://green-api.com/en/docs/api/receiving/technology-http-api/).\n\nThe chatbot uses the [whatsapp-chatbot-python](https://github.com/green-api/whatsapp-chatbot-python) library, which already integrates sending and receiving methods, so messages are read automatically, and sending regular text messages is simplified.\n\nFor example, the chatbot automatically sends a message to the contact from whom it received a message:\n```python\nnotification.answer(answers_data[\"select_language\"])\n```\nHowever, other sending methods can be called directly from the [whatsapp-api-client-python](https://github.com/green-api/whatsapp-api-client-python) library. For example, when sending a contact:\n```python\nnotification.api.sending.sendContact(\nchatId=notification.chat,\ncontact={\n\"phoneContact\": notification.chat.split(\"@\")[0],\n\"firstName\": notification.event[\"senderData\"][\"senderName\"],\n},\n```  \n\n## ChatGPT Integration\n\nThe chatbot now includes integration with ChatGPT (option 14 in the main menu), which allows users to have interactive conversations with OpenAI's GPT models directly within the WhatsApp chat.\n\n### Setup\n\nTo enable the ChatGPT functionality, you need to set up your OpenAI API key:\n\n1. Obtain an API key from [OpenAI](https://platform.openai.com/api-keys)\n2. Add the key to your environment variables or `.env` file:\n\n```\nOPENAI_API_KEY=your_openai_api_key_here\n```\n\nIf the OpenAI API key is not configured, the chatbot will display an error message when a user tries to use the ChatGPT feature.\n\n### Configuration\n\nThe ChatGPT integration is configured in the bot initialization:\n\n```python\ngpt_bot = WhatsappGptBot(\n    id_instance=config.user_id,\n    api_token_instance=config.api_token_id,\n    openai_api_key=config.openai_api_key,\n    model=\"gpt-4o\",\n    system_message=\"You are a helpful assistant in a WhatsApp chat. Be concise and accurate in your responses.\",\n    max_history_length=10,\n    temperature=0.7\n)\n```\n\nYou can customize the following parameters:\n- `model`: The OpenAI model to use (default is \"gpt-4o\")\n- `system_message`: The system prompt that guides ChatGPT's behavior\n- `max_history_length`: Number of previous messages to maintain in context\n- `temperature`: Controls randomness in responses (0.0-1.0)\n\n### Usage\n\nUsers can access the ChatGPT feature by sending \"14\" when in the main menu. The chatbot will enter a special ChatGPT conversation mode where all messages are forwarded to the GPT model for processing.\n\nTo exit the ChatGPT conversation and return to the main menu, users can type one of the following keywords (depending on their selected language):\n- English: \"exit\", \"menu\", \"stop\", \"back\"\n- Russian: \"выход\", \"меню\", \"стоп\", \"назад\"\n- Kazakh: \"шығу\", \"мәзір\", \"тоқта\", \"артқа\", \"menu\", \"меню\"\n- Spanish: \"salir\", \"menú\", \"parar\", \"atrás\", \"menu\", \"exit\"\n- Hebrew: \"יציאה\", \"תפריט\", \"עצור\", \"exit\", \"menu\", \"חזור\"\n\n### Limitations\n\n- API usage may incur costs depending on your OpenAI subscription plan\n- Response times may vary based on OpenAI API latency and your internet connection\n\n## License\n\nLicensed under [Creative Commons Attribution-NoDerivatives 4.0 International (CC BY-ND 4.0)](https://creativecommons.org/licenses/by-nd/4.0/).\n\nPlease see file [LICENSE](https://github.com/green-api/whatsapp-demo-chatbot-python/blob/main/LICENCE).\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgreen-api%2Fwhatsapp-demo-chatbot-python","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgreen-api%2Fwhatsapp-demo-chatbot-python","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgreen-api%2Fwhatsapp-demo-chatbot-python/lists"}