{"id":15093458,"url":"https://github.com/green-api/whatsapp-chatbot-python","last_synced_at":"2025-04-05T05:09:58.972Z","repository":{"id":157903981,"uuid":"632255275","full_name":"green-api/whatsapp-chatbot-python","owner":"green-api","description":"This library helps you easily create a Python chatbot with WhatsApp API.","archived":false,"fork":false,"pushed_at":"2025-02-23T17:27:46.000Z","size":283,"stargazers_count":62,"open_issues_count":2,"forks_count":14,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-03-29T04:12:09.512Z","etag":null,"topics":["whatsapp","whatsapp-api","whatsapp-api-python","whatsapp-bot","whatsapp-chat","whatsapp-chatbot","whatsapp-chatbot-python","whatsapp-python"],"latest_commit_sha":null,"homepage":"https://green-api.com/en","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":"LICENSE","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}},"created_at":"2023-04-25T03:15:13.000Z","updated_at":"2025-03-20T00:11:30.000Z","dependencies_parsed_at":null,"dependency_job_id":"5e3cbfc3-d133-4dd8-ade5-51a0639ead74","html_url":"https://github.com/green-api/whatsapp-chatbot-python","commit_stats":{"total_commits":90,"total_committers":9,"mean_commits":10.0,"dds":0.2777777777777778,"last_synced_commit":"51d1a1a00d5e26901423e1163b518130ddf0c8b6"},"previous_names":[],"tags_count":19,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/green-api%2Fwhatsapp-chatbot-python","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/green-api%2Fwhatsapp-chatbot-python/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/green-api%2Fwhatsapp-chatbot-python/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/green-api%2Fwhatsapp-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-chatbot-python/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247289429,"owners_count":20914464,"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":["whatsapp","whatsapp-api","whatsapp-api-python","whatsapp-bot","whatsapp-chat","whatsapp-chatbot","whatsapp-chatbot-python","whatsapp-python"],"created_at":"2024-09-25T11:23:24.500Z","updated_at":"2025-04-05T05:09:58.953Z","avatar_url":"https://github.com/green-api.png","language":"Python","readme":"# whatsapp-chatbot-python\n\n![](https://img.shields.io/badge/license-CC%20BY--ND%204.0-green)\n![](https://img.shields.io/pypi/status/whatsapp-chatbot-python)\n![](https://img.shields.io/pypi/pyversions/whatsapp-chatbot-python)\n![](https://img.shields.io/github/actions/workflow/status/green-api/whatsapp-chatbot-python/python-package.yml)\n![](https://img.shields.io/pypi/dm/whatsapp-chatbot-python)\n\n- [Документация на русском языке](https://github.com/green-api/whatsapp-chatbot-python/blob/master/docs/README.md).\n\nwhatsapp-chatbot-python is a library for integration with WhatsApp messenger using the API\nservice [green-api.com](https://green-api.com/en/). You should get a registration token and an account ID in\nyour [personal cabinet](https://console.green-api.com/) to use the library. There is a free developer account tariff.\n\n## API\n\nThe documentation for the REST API can be found at the [link](https://green-api.com/en/docs/). The library is a wrapper\nfor the REST API, so the documentation at the link above also applies.\n\n## Authorization\n\nTo send a message or perform other Green API methods, the WhatsApp account in the phone app must be authorized. To\nauthorize the account, go to your [cabinet](https://console.green-api.com/) and scan the QR code using the WhatsApp app.\n\n## Installation\n\nInstallation:\n\n```shell\npython -m pip install whatsapp-chatbot-python\n```\n\n## Import\n\n```\nfrom whatsapp_chatbot_python import GreenAPIBot, Notification\n```\n\n## Setup\n\nBefore launching the bot, you should remove Webhook Url (if set) from Personal Cabinet or by setting empty webhookUrl by using [SetSettings method](https://green-api.com/en/docs/api/account/SetSettings/). These settings will be enabled by bot automatically:\n\n\n```json\n{\n  \"incomingWebhook\": \"yes\",\n  \"outgoingMessageWebhook\": \"yes\",\n  \"outgoingAPIMessageWebhook\": \"yes\"\n}\n```\n\n## Examples\n\n### How to initialize an object\n\n```\nbot = GreenAPIBot(\n    \"1101000001\", \"d75b3a66374942c5b3c019c698abc2067e151558acbd412345\"\n)\n```\n\n### How to enable debug mode\n\n```\nbot = GreenAPIBot(\n    \"1101000001\", \"d75b3a66374942c5b3c019c698abc2067e151558acbd412345\",\n    bot_debug_mode=True\n)\n```\n\nYou can also enable API debug mode:\n\n```\nbot = GreenAPIBot(\n    \"1101000001\", \"d75b3a66374942c5b3c019c698abc2067e151558acbd412345\",\n    debug_mode=True, bot_debug_mode=True\n)\n```\n\n### How to set up an instance\n\nTo start receiving incoming notifications, you need to set up an instance. Open the personal cabinet page at\nthe [link](https://console.green-api.com/). Select an instance from the list and click on it. Click **Change**. In the\n**Notifications** category, enable all notifications that you want to receive.\n\n### How to start receiving and answering messages\n\nTo start receiving messages, you must create a handler function with one parameter (`notification`). The `notification`\nparameter is the class where the notification object (`event`) and the functions to answer the message are stored. To\nsend a text message in response to a notification, you need to call the `notification.answer` function and pass there\nthe text of the message. You don't need to pass the `chatId` parameter because it is automatically taken from the\nnotification.\n\nNext, you need to add the handler function to the list of handlers. This can be done with the `bot.router.message`\ndecorator as in the example or with the `bot.router.message.add_handler` function. The decorator must be called with\nbrackets.\n\nTo start the bot, call the `bot.run_forever` function. You can stop the bot with the key combination Ctrl + C.\n\nIn this example, the bot will only answer the `message` message.\n\nLink to example: [base.py](https://github.com/green-api/whatsapp-chatbot-python/blob/master/examples/base.py).\n\n```\n@bot.router.message(text_message=\"message\")\ndef message_handler(notification: Notification) -\u003e None:\n    notification.answer(\"Hello\")\n\n\nbot.run_forever()\n```\n\n### How to receive other notifications and handle the notification body\n\nYou can receive not only incoming messages but also outgoing messages. You can also get the status of the sent message.\n\n- To receive outgoing messages, you need to use the `bot.router.outgoing_message` object;\n- To receive outgoing API messages, you need to use the `bot.router.outgoing_api_message` object;\n- To receive the status of sent messages, you need to use the `bot.router.outgoing_message_status` object.\n\nThe body of the notification is in `notification.event`. In this example, we get the message type from the notification\nbody.\n\nIn this example, the bot receives all incoming messages.\n\nLink to example: [event.py](https://github.com/green-api/whatsapp-chatbot-python/blob/master/examples/event.py).\n\n```\n@bot.router.message()\ndef message_handler(notification: Notification) -\u003e None:\n    print(notification.event)\n\n\nbot.run_forever()\n```\n\n### How to filter incoming messages\n\nMessages can be filtered by chat, sender, message type, and text. To filter chat, sender, and message type, you can use\na string (`str`) or a list of strings (`list[str]`). The message text can be filtered by text, command, and regular\nexpressions. Below is a table with filter names and possible values.\n\n| Filter name    | Description                                                                               | Possible values                                                    |\n|----------------|-------------------------------------------------------------------------------------------|--------------------------------------------------------------------|\n| `from_chat`    | Chats or chats from which you want to receive messages                                    | `\"11001234567@c.us\"` or `[\"11001234567@c.us\", \"11002345678@c.us\"]` |\n| `from_sender`  | The sender or senders from whom you want to receive messages                              | `\"11001234567@c.us\"` or `[\"11001234567@c.us\", \"11002345678@c.us\"]` |\n| `type_message` | The type or types of message to be handled                                                | `\"textMessage\"` or `[\"textMessage\", \"extendedTextMessage\"]`        |\n| `text_message` | Your function will be executed if the text fully matches the text                         | `\"message\"` or `[\"message\", \"MESSAGE\"]`                            |\n| `regexp`       | Your function will be executed if the text matches the regular expression pattern         | `r\"message\"` or `(r\"message\", re.IGNORECASE)`                      |\n| `command`      | Your function will be executed if the prefix and the command match your values completely | `\"help\"` or `(\"help\", \"!/\")`                                       |\n\n#### How to add filters through the decorator\n\n```\n@bot.router.message(command=\"command\")\n```\n\n#### How to add filters with the function\n\n```\nbot.router.message.add_handler(handler, command=\"command\")\n```\n\n#### How to filter messages by chat, sender, or message type\n\nTo filter messages by chat, sender, or message type, you must add a string (`str`) or a list of strings (`list[str]`).\n\n```\nfrom_chat = \"11001234567@c.us\"\n```\n\n```\nfrom_sender = \"11001234567@c.us\"\n```\n\n```\ntype_message = [\"textMessage\", \"extendedTextMessage\"]\n```\n\n#### How to filter messages by message text or regular expressions\n\nYou must add a string (`str`) to filter messages by text or regular expressions.\n\n```\ntext_message = \"Hello. I need help.\"\n```\n\n```\nregexp = r\"Hello. I need help.\"\n```\n\n#### How to filter messages by command\n\nAdd a string (`str`) or a tuple (`tuple`) to filter messages by command. You need to specify either a command name or a\ncommand name and a prefix string. The default prefix is `/`.\n\n```\ncommand = \"help\"\n```\n\n```\ncommand = (\"help\", \"!/\")\n```\n\n#### Example\n\nIn this example, the bot will send a photo in response to the `rates` command.\n\nLink to example: [filters.py](https://github.com/green-api/whatsapp-chatbot-python/blob/master/examples/filters.py).\n\n```\n@bot.router.message(command=\"rates\")\ndef message_handler(notification: Notification) -\u003e None:\n    notification.answer_with_file(file=\"data/rates.png\")\n\n\nbot.run_forever()\n```\n\n### How to handle buttons (deprecated)\n\nThe method is temporarily not working. When the method is called, a 403 error will be returned.\n\nTo be notified when a button is pressed, you must use the `bot.router.buttons` object.\n\nLink to example: [buttons.py](https://github.com/green-api/whatsapp-chatbot-python/blob/master/examples/buttons.py).\n\n```\n@bot.router.buttons()\ndef buttons_handler(notification: Notification) -\u003e None:\n    notification.answer_buttons(\"Choose a color\", [\n        {\n            \"buttonId\": 1,\n            \"buttonText\": \"Red\"\n        },\n        {\n            \"buttonId\": 2,\n            \"buttonText\": \"Green\"\n        },\n        {\n            \"buttonId\": 3,\n            \"buttonText\": \"Blue\"\n        }\n    ])\n\n\nbot.run_forever()\n```\n\n### How to manage user state\n\nAs an example, a bot was created for user registration.\n\nTo manage user states, we need to create states. Import the `BaseStates` class and inherit from it. To manage the state\nwe need to use `notification.state_manager`. The manager has methods for getting, setting, updating and deleting state.\nYou also have the option to save the user's data in his state.\n\n| Manager's method    | Description                                                                           |\n|---------------------|---------------------------------------------------------------------------------------|\n| `get_state`         | Returns a state class with state name and user data                                   |\n| `set_state`         | Sets the state for the user. If the state exists then the data will be deleted        |\n| `update_state`      | If a state exists, it changes it. If not, it creates a new state                      |\n| `delete_state`      | Deletes the user's state. Remember to get the data before deleting                    |\n| `get_state_data`    | If the state exists, it returns the data in the form of a dictionary (dict)           |\n| `set_state_data`    | If the state exists, it changes the data to the new data                              |\n| `update_state_data` | If the state exists, it updates the data. If no data exists, the data will be created |\n| `delete_state_data` | If the state exists, it deletes the data                                              |\n\nThe first argument is the sender ID. It can be found by calling `notification.sender`.\n\nLink to example: [states.py](https://github.com/green-api/whatsapp-chatbot-python/blob/master/examples/states.py).\n\n```python\nfrom whatsapp_chatbot_python import BaseStates, GreenAPIBot, Notification\n\nbot = GreenAPIBot(\n    \"1101000001\", \"d75b3a66374942c5b3c019c698abc2067e151558acbd412345\"\n)\n\n\nclass States(BaseStates):\n    USERNAME = \"username\"\n    PASSWORD = \"password\"\n\n\n@bot.router.message(state=None)\ndef message_handler(notification: Notification) -\u003e None:\n    sender = notification.sender\n\n    notification.state_manager.set_state(sender, States.USERNAME.value)\n\n    notification.answer(\"Hello. Tell me your username.\")\n\n\n@bot.router.message(command=\"cancel\")\ndef cancel_handler(notification: Notification) -\u003e None:\n    sender = notification.sender\n\n    state = notification.state_manager.get_state(sender)\n    if not state:\n        return None\n    else:\n        notification.state_manager.delete_state(sender)\n\n        notification.answer(\"Bye\")\n\n\n@bot.router.message(state=States.USERNAME.value)\ndef username_handler(notification: Notification) -\u003e None:\n    sender = notification.sender\n    username = notification.message_text\n\n    if not 5 \u003c= len(username) \u003c= 20:\n        notification.answer(\"Invalid username.\")\n    else:\n        notification.state_manager.update_state(sender, States.PASSWORD.value)\n        notification.state_manager.set_state_data(\n            sender, {\"username\": username}\n        )\n\n        notification.answer(\"Tell me your password.\")\n\n\n@bot.router.message(state=States.PASSWORD.value)\ndef password_handler(notification: Notification) -\u003e None:\n    sender = notification.sender\n    password = notification.message_text\n\n    if not 8 \u003c= len(password) \u003c= 20:\n        notification.answer(\"Invalid password.\")\n    else:\n        data = notification.state_manager.get_state_data(sender)\n\n        username = data[\"username\"]\n\n        notification.answer(\n            (\n                \"Successful account creation.\\n\\n\"\n                f\"Your username: {username}.\\n\"\n                f\"Your password: {password}.\"\n            )\n        )\n\n        notification.state_manager.delete_state(sender)\n\n\nbot.run_forever()\n```\n\n### FAQ\n\n- How to call API methods?\n\n```\nbot.api.account.getSettings()\n```\n\nOr\n\n```\nnotification.api.account.getSettings()\n```\n\n- How do I disable error raising?\n\n```\nbot = GreenAPIBot(\n    \"1101000001\", \"d75b3a66374942c5b3c019c698abc2067e151558acbd412345\",\n    raise_errors=False\n)\n```\n\n- How do I subscribe only to text messages?\n\nYou need to import the required constants first:\n\n```\nfrom whatsapp_chatbot_python.filters import TEXT_TYPES\n```\n\nThen add this filter: `type_message=TEXT_TYPES`.\n\n- How do I get the message text and sender ID?\n\nThis data is in the notification object (`notification`):\n\n```\n@bot.router.message()\ndef message_handler(notification: Notification) -\u003e None:\n    print(notification.sender)\n    print(notification.message_text)\n```\n\n### Example of a bot\n\nAs an example, a bot was created to support the GREEN API. Command list:\n\n- start (the bot says hello and sends a list of commands)\n- 1 or Report a problem (the bot will send a link to GitHub to create the bug)\n- 2 or Show office address (the bot will send the office address as a map)\n- 3 or Show available rates (the bot will send a picture of the rates)\n- 4 or Call a support operator (the bot will send a text message)\n\nTo send a text message, you have to use the `notification.answer` method.\nTo send a location, you have to use the `sending.sendLocation` method from `notification.api`.\nTo send a message with a file, you have to use the `notification.answer_with_file` method.\n\nIn this example, the bot only responds to commands from the list above.\n\nLink to example: [full.py](https://github.com/green-api/whatsapp-chatbot-python/blob/master/examples/full.py).\n\n```python\nfrom whatsapp_chatbot_python import GreenAPIBot, Notification\n\nbot = GreenAPIBot(\n    \"1101000001\", \"d75b3a66374942c5b3c019c698abc2067e151558acbd412345\"\n)\n\n\n@bot.router.message(command=\"start\")\ndef message_handler(notification: Notification) -\u003e None:\n    sender_data = notification.event[\"senderData\"]\n    sender_name = sender_data[\"senderName\"]\n\n    notification.answer(\n        (\n            f\"Hello, {sender_name}. Here's what I can do:\\n\\n\"\n            \"1. Report a problem\\n\"\n            \"2. Show office address\\n\"\n            \"3. Show available rates\\n\"\n            \"4. Call a support operator\\n\\n\"\n            \"Choose a number and send to me.\"\n        )\n    )\n\n\n@bot.router.message(text_message=[\"1\", \"Report a problem\"])\ndef report_problem_handler(notification: Notification) -\u003e None:\n    notification.answer(\n        \"https://github.com/green-api/issues/issues/new\", link_preview=False\n    )\n\n\n@bot.router.message(text_message=[\"2\", \"Show office address\"])\ndef show_office_address_handler(notification: Notification) -\u003e None:\n    chat = notification.chat\n\n    notification.api.sending.sendLocation(\n        chatId=chat, latitude=55.7522200, longitude=37.6155600\n    )\n\n\n@bot.router.message(text_message=[\"3\", \"Show available rates\"])\ndef show_available_rates_handler(notification: Notification) -\u003e None:\n    notification.answer_with_file(\"data/rates.png\")\n\n\n@bot.router.message(text_message=[\"4\", \"Call a support operator\"])\ndef call_support_operator_handler(notification: Notification) -\u003e None:\n    notification.answer(\"Good. A tech support operator will contact you soon.\")\n\n\nbot.run_forever()\n```\n\n## Service methods documentation\n\n[Service methods documentation](https://green-api.com/en/docs/api/)\n\n## License\n\nLicensed under [\nCreative Commons Attribution-NoDerivatives 4.0 International (CC BY-ND 4.0)\n](https://creativecommons.org/licenses/by-nd/4.0/) terms. Please see file [LICENSE](\nhttps://github.com/green-api/whatsapp-chatbot-python/blob/master/LICENSE\n).\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgreen-api%2Fwhatsapp-chatbot-python","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgreen-api%2Fwhatsapp-chatbot-python","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgreen-api%2Fwhatsapp-chatbot-python/lists"}