# WhatsApp ChatBot Engine
A framework for creating WhatsApp chatbots of any scale using a template-driven approach -
allowing you to define conversation flows and business logic in a clean and modular way.
It decouples the engine from the WhatsApp client library, allowing developers to use them independently or together.
## Features
- **Template-Driven Design**: Use YAML templates for conversational flows.
- **Hooks for Business Logic**: Attach Python functions to process messages or actions.
- Easy-to-use API for WhatsApp Cloud.
- Supports dynamic messages with placeholders.
- Built-in support for WhatsApp Webhooks.
- Starter templates
- Live Support / Human interaction portal template
## Installation
```bash
pip install pywce
```
## Why pywce
Most WhatsApp chatbot tutorials or libraries just scraps the surface, only sending a few message or handling simple logic or are client libraries only.
This library gives you a full-blown framework for chatbots of any scale allowing you access to full package of whatsapp client library and chatbot development framework.
## Setup
### WhatsApp
Follow the complete step by step WhatsApp Cloud API guide below.
[](https://www.youtube.com/watch?v=Y8kihPdCI_U)
Important settings needed for this framework
1. Phone number ID (be it test number or live number) -
2. Access Token (Temporary or permanent)
3. Webhook callback verification token of your choice
Create a `.env `with the below settings in your project or test folder (be it `example` or `portal` folders)
```
ACCESS_TOKEN = <your-whatsapp-access-token>
PHONE_NUMBER_ID = <your-number-phone-id>
WEBHOOK_HUB_TOKEN = <your-webhook-verification-token>
# path to your templates & triggers folders
TEMPLATES_DIR = portal/chatbot/templates
TRIGGERS_DIR = portal/chatbot/triggers
# your templates initial or start stage
START_STAGE = START-MENU
```
### Engine
You can either use `.env` or add your credentials directly to the WhatsAppConfig class
```python
import os
from dotenv import load_dotenv
from pywce import client, Engine, EngineConfig
load_dotenv()
whatsapp_config = client.WhatsAppConfig(
token=os.getenv("ACCESS_TOKEN"),
phone_number_id=os.getenv("PHONE_NUMBER_ID"),
hub_verification_token=os.getenv("WEBHOOK_HUB_TOKEN")
)
whatsapp = client.WhatsApp(whatsapp_config=whatsapp_config)
engine_config = EngineConfig(
whatsapp=whatsapp,
templates_dir=os.getenv("TEMPLATES_DIR"),
trigger_dir=os.getenv("TRIGGERS_DIR"),
start_template_stage=os.getenv("START_STAGE")
)
engine_instance = Engine(config=engine_config)
```
## Example ChatBot
Here's a simple example template to get you started:
_Checkout complete example of [e-hailing chatbot](https://github.com/DonnC/pywce/blob/master/example/engine_chatbot/main.py)_
1. Define YAML template (Conversation Flow💬):
```yaml
# path/to/templates
"START-MENU":
type: button
template: "example.hooks.name_template.username"
message:
title: Welcome
body: "Hi {{ name }}, I'm your assistant, click below to start!"
footer: pywce
buttons:
- Start
routes:
"start": "NEXT-STEP"
"NEXT-STEP":
type: text
message: Great, lets get you started quickly. What is your age?
routes:
"re://d{1,}": "NEXT-STEP-FURTHER"
```
2. Write your hook (Supercharge⚡):
```python
# example/hooks/name_template.py
from pywce import hook, HookArg, TemplateDynamicBody
@hook
def username(arg: HookArg) -> HookArg:
# set render payload data to match the required template dynamic var
# greet user by their whatsapp name 😎
arg.template_body = TemplateDynamicBody(
render_template_payload={"name": arg.user.name}
)
return arg
```
3. Engine client:
Use `fastapi` or `flask` or any python library to create endpoint to receive whatsapp webhooks
```python
# ~ fastapi snippet ~
async def webhook_event(payload: Dict, headers: Dict) -> None:
"""
Process webhook event in the background using pywce engine.
"""
print("Received webhook event, processing..")
await engine_instance.ep_process_webhook(webhook_data=payload, webhook_headers=headers)
@app.post("/chatbot/webhook")
async def process_webhook(request: Request, background_tasks: BackgroundTasks):
"""
Handle incoming webhook events from WhatsApp
and process them in the background.
"""
payload = await request.json()
headers = dict(request.headers)
# handle event in the background
background_tasks.add_task(webhook_event, payload, headers)
# Immediately respond to WhatsApp with acknowledgment
return Response(content="ACK", status_code=200)
```
### Run ChatBot
If you run your or the example projects successfully, your webhook url will be available on `your-backend-url/chatbot/webhook`.
_You can use `ngrok` or any service to tunnel your local service_
You can then configure the endpoint in Webhook section on Meta developer portal.
## Live Support
Engine comes with default live support / human interaction portal out-of-the-box powered by [Reflex](https://reflex.dev/)
Check out [Live Support Portal](https://github.com/DonnC/pywce/tree/feat/live-support/portal)
## WhatsApp Client Library
_You can use pywce as a standalone whatsapp client library. See [Example](https://github.com/DonnC/pywce/blob/master/example/standalone_chatbot/main.py)_
PyWCE provides a simple, Pythonic interface to interact with the WhatsApp Cloud API:
- **Send messages** (text, media, templates, interactive)
- **Receive and process webhooks**
- **Media management** (upload and download)
- **Out of the box utilities** using the `WhatsApp.Utils` class.
Example usage:
```python
from pywce import client
config = client.WhatsAppConfig(
token="your_access_token",
phone_number_id="your_phone_number_id",
hub_verification_token="your_webhook_hub_verification_token"
)
whatsapp = client.WhatsApp(whatsapp_config=config)
# Sending a text message
response = whatsapp.send_message(
recipient_id="recipient_number",
message="Hello from PyWCE!"
)
# verify if request was successful, using utils
is_sent = whatsapp.util.was_request_successful(
recipient_id="recipient_number",
response_data=response
)
if is_sent:
message_id = whatsapp.util.get_response_message_id(response)
print("Request successful with msg id: ", message_id)
```
## Documentation
Visit the [official documentation](https://docs.page/donnc/wce) for a detailed guide.
## Changelog
Visit the [changelog list](https://github.com/DonnC/pywce/blob/master/CHANGELOG.md) for a full list of changes.
## Contributing
We welcome contributions! Please check out the [Contributing Guide](https://github.com/DonnC/pywce/blob/master/CONTRIBUTING.md) for details.
## License
This project is licensed under the MIT License. See the [LICENSE](https://github.com/DonnC/pywce/blob/master/LICENCE) file for details.
Raw data
{
"_id": null,
"home_page": "https://github.com/DonnC/pywce",
"name": "pywce",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.9",
"maintainer_email": null,
"keywords": "whatsapp, chatbot, yaml, automation, template, hooks",
"author": "Donald Chinhuru",
"author_email": "donychinhuru@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/be/e1/109ea40161055193a5cecffa81f58efa3f1b8622d92fd2f55c3f74e722c3/pywce-1.0.4.tar.gz",
"platform": null,
"description": "# WhatsApp ChatBot Engine\n\nA framework for creating WhatsApp chatbots of any scale using a template-driven approach - \nallowing you to define conversation flows and business logic in a clean and modular way. \n\nIt decouples the engine from the WhatsApp client library, allowing developers to use them independently or together. \n\n## Features\n\n- **Template-Driven Design**: Use YAML templates for conversational flows.\n- **Hooks for Business Logic**: Attach Python functions to process messages or actions.\n- Easy-to-use API for WhatsApp Cloud.\n- Supports dynamic messages with placeholders.\n- Built-in support for WhatsApp Webhooks.\n- Starter templates\n- Live Support / Human interaction portal template\n\n## Installation\n```bash\npip install pywce\n```\n\n## Why pywce\nMost WhatsApp chatbot tutorials or libraries just scraps the surface, only sending a few message or handling simple logic or are client libraries only.\n\nThis library gives you a full-blown framework for chatbots of any scale allowing you access to full package of whatsapp client library and chatbot development framework.\n\n## Setup\n### WhatsApp\nFollow the complete step by step WhatsApp Cloud API guide below. \n\n[](https://www.youtube.com/watch?v=Y8kihPdCI_U)\n\nImportant settings needed for this framework\n1. Phone number ID (be it test number or live number) - \n2. Access Token (Temporary or permanent)\n3. Webhook callback verification token of your choice\n\nCreate a `.env `with the below settings in your project or test folder (be it `example` or `portal` folders)\n\n```\nACCESS_TOKEN = <your-whatsapp-access-token>\nPHONE_NUMBER_ID = <your-number-phone-id>\nWEBHOOK_HUB_TOKEN = <your-webhook-verification-token>\n\n# path to your templates & triggers folders\nTEMPLATES_DIR = portal/chatbot/templates\nTRIGGERS_DIR = portal/chatbot/triggers\n\n# your templates initial or start stage\nSTART_STAGE = START-MENU\n```\n\n### Engine\nYou can either use `.env` or add your credentials directly to the WhatsAppConfig class\n```python\nimport os\nfrom dotenv import load_dotenv\nfrom pywce import client, Engine, EngineConfig\n\nload_dotenv()\n\nwhatsapp_config = client.WhatsAppConfig(\n token=os.getenv(\"ACCESS_TOKEN\"),\n phone_number_id=os.getenv(\"PHONE_NUMBER_ID\"),\n hub_verification_token=os.getenv(\"WEBHOOK_HUB_TOKEN\")\n)\n\nwhatsapp = client.WhatsApp(whatsapp_config=whatsapp_config)\n\nengine_config = EngineConfig(\n whatsapp=whatsapp,\n templates_dir=os.getenv(\"TEMPLATES_DIR\"),\n trigger_dir=os.getenv(\"TRIGGERS_DIR\"),\n start_template_stage=os.getenv(\"START_STAGE\")\n)\n\nengine_instance = Engine(config=engine_config)\n```\n\n## Example ChatBot\nHere's a simple example template to get you started:\n\n_Checkout complete example of [e-hailing chatbot](https://github.com/DonnC/pywce/blob/master/example/engine_chatbot/main.py)_\n\n1. Define YAML template (Conversation Flow\ud83d\udcac):\n\n```yaml\n# path/to/templates\n\"START-MENU\":\n type: button\n template: \"example.hooks.name_template.username\"\n message:\n title: Welcome\n body: \"Hi {{ name }}, I'm your assistant, click below to start!\"\n footer: pywce\n buttons:\n - Start\n routes:\n \"start\": \"NEXT-STEP\"\n\n\"NEXT-STEP\":\n type: text\n message: Great, lets get you started quickly. What is your age?\n routes:\n \"re://d{1,}\": \"NEXT-STEP-FURTHER\"\n```\n\n2. Write your hook (Supercharge\u26a1):\n```python\n# example/hooks/name_template.py\nfrom pywce import hook, HookArg, TemplateDynamicBody\n\n@hook\ndef username(arg: HookArg) -> HookArg:\n # set render payload data to match the required template dynamic var\n \n # greet user by their whatsapp name \ud83d\ude0e\n arg.template_body = TemplateDynamicBody(\n render_template_payload={\"name\": arg.user.name}\n )\n\n return arg\n```\n\n3. Engine client:\n\nUse `fastapi` or `flask` or any python library to create endpoint to receive whatsapp webhooks\n\n```python\n# ~ fastapi snippet ~\n\nasync def webhook_event(payload: Dict, headers: Dict) -> None:\n \"\"\"\n Process webhook event in the background using pywce engine.\n \"\"\"\n print(\"Received webhook event, processing..\")\n await engine_instance.ep_process_webhook(webhook_data=payload, webhook_headers=headers)\n\n\n@app.post(\"/chatbot/webhook\")\nasync def process_webhook(request: Request, background_tasks: BackgroundTasks):\n \"\"\"\n Handle incoming webhook events from WhatsApp \n and process them in the background.\n \"\"\"\n payload = await request.json()\n headers = dict(request.headers)\n\n # handle event in the background\n background_tasks.add_task(webhook_event, payload, headers)\n\n # Immediately respond to WhatsApp with acknowledgment\n return Response(content=\"ACK\", status_code=200)\n```\n\n### Run ChatBot\nIf you run your or the example projects successfully, your webhook url will be available on `your-backend-url/chatbot/webhook`.\n\n_You can use `ngrok` or any service to tunnel your local service_\n\nYou can then configure the endpoint in Webhook section on Meta developer portal.\n\n## Live Support \nEngine comes with default live support / human interaction portal out-of-the-box powered by [Reflex](https://reflex.dev/)\n\nCheck out [Live Support Portal](https://github.com/DonnC/pywce/tree/feat/live-support/portal)\n\n## WhatsApp Client Library\n_You can use pywce as a standalone whatsapp client library. See [Example](https://github.com/DonnC/pywce/blob/master/example/standalone_chatbot/main.py)_\n\nPyWCE provides a simple, Pythonic interface to interact with the WhatsApp Cloud API:\n\n- **Send messages** (text, media, templates, interactive)\n- **Receive and process webhooks**\n- **Media management** (upload and download)\n- **Out of the box utilities** using the `WhatsApp.Utils` class.\n\nExample usage:\n\n```python\nfrom pywce import client\n\nconfig = client.WhatsAppConfig(\n token=\"your_access_token\",\n phone_number_id=\"your_phone_number_id\",\n hub_verification_token=\"your_webhook_hub_verification_token\"\n)\n\nwhatsapp = client.WhatsApp(whatsapp_config=config)\n\n# Sending a text message\nresponse = whatsapp.send_message(\n recipient_id=\"recipient_number\",\n message=\"Hello from PyWCE!\"\n)\n\n# verify if request was successful, using utils\nis_sent = whatsapp.util.was_request_successful(\n recipient_id=\"recipient_number\",\n response_data=response\n)\n\nif is_sent:\n message_id = whatsapp.util.get_response_message_id(response)\n print(\"Request successful with msg id: \", message_id)\n```\n\n\n## Documentation\n\nVisit the [official documentation](https://docs.page/donnc/wce) for a detailed guide.\n\n## Changelog\n\nVisit the [changelog list](https://github.com/DonnC/pywce/blob/master/CHANGELOG.md) for a full list of changes.\n\n## Contributing\n\nWe welcome contributions! Please check out the [Contributing Guide](https://github.com/DonnC/pywce/blob/master/CONTRIBUTING.md) for details.\n\n## License\n\nThis project is licensed under the MIT License. See the [LICENSE](https://github.com/DonnC/pywce/blob/master/LICENCE) file for details.\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "A template-driven framework for building WhatsApp chatbots",
"version": "1.0.4",
"project_urls": {
"Bug Tracker": "https://github.com/DonnC/pywce/issues",
"Documentation": "https://docs.page/donnc/wce",
"Homepage": "https://github.com/DonnC/pywce",
"Source Code": "https://github.com/DonnC/pywce"
},
"split_keywords": [
"whatsapp",
" chatbot",
" yaml",
" automation",
" template",
" hooks"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "4f1a53846f717af5db5102a62a14b39c44e18252a4d0b8b877b563d3282be4db",
"md5": "f7de2bd992ef9416c0dd294f2c0f9211",
"sha256": "e1a22ce3543b366f9b4dc6bc1130b9014e82358574183ecb1be0266882bb5dcb"
},
"downloads": -1,
"filename": "pywce-1.0.4-py3-none-any.whl",
"has_sig": false,
"md5_digest": "f7de2bd992ef9416c0dd294f2c0f9211",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.9",
"size": 39414,
"upload_time": "2025-02-11T19:51:13",
"upload_time_iso_8601": "2025-02-11T19:51:13.116437Z",
"url": "https://files.pythonhosted.org/packages/4f/1a/53846f717af5db5102a62a14b39c44e18252a4d0b8b877b563d3282be4db/pywce-1.0.4-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "bee1109ea40161055193a5cecffa81f58efa3f1b8622d92fd2f55c3f74e722c3",
"md5": "ef0ee4ca01396c3b86a509321c9d0c07",
"sha256": "93ea1c3950759432f767b8abf858d414f628f893289c79733845593e03409c0b"
},
"downloads": -1,
"filename": "pywce-1.0.4.tar.gz",
"has_sig": false,
"md5_digest": "ef0ee4ca01396c3b86a509321c9d0c07",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.9",
"size": 35389,
"upload_time": "2025-02-11T19:51:14",
"upload_time_iso_8601": "2025-02-11T19:51:14.311147Z",
"url": "https://files.pythonhosted.org/packages/be/e1/109ea40161055193a5cecffa81f58efa3f1b8622d92fd2f55c3f74e722c3/pywce-1.0.4.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-02-11 19:51:14",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "DonnC",
"github_project": "pywce",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"requirements": [
{
"name": "httpx",
"specs": [
[
"~=",
"0.28.1"
]
]
},
{
"name": "cachetools",
"specs": [
[
"~=",
"5.5.0"
]
]
},
{
"name": "ruamel.yaml",
"specs": [
[
"~=",
"0.18.10"
]
]
},
{
"name": "requests-toolbelt",
"specs": [
[
"~=",
"1.0.0"
]
]
},
{
"name": "Jinja2",
"specs": [
[
"~=",
"3.1.5"
]
]
},
{
"name": "colorlog",
"specs": [
[
"~=",
"6.9.0"
]
]
},
{
"name": "python-json-logger",
"specs": [
[
"~=",
"3.2.1"
]
]
}
],
"lcname": "pywce"
}