A templates-driven framework for building complete WhatsApp chatbots
Project description
WhatsApp ChatBot Engine
A framework for creating complete 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.
[!NOTE] Core chatbot template engine and WhatsApp client library are decoupled - allowing you to use them independently or together.
Features
- Template-Driven Design: Define conversational flows and business logic in a clean, modular way (Support YAML & JSON templates by default).
- Hooks for Business Logic: Attach Python functions to process messages or actions on your hooks.
- Customizable: implement your own session & template storage source.
- Easy-to-use API for WhatsApp Cloud.
- Supports dynamic messages with placeholders.
- Built-in support for common chatbot input phrases like
back,retry,reportandmenu. Also caches default name underwa_namekey - Support WhatsApp Flow endpoint
- Supports all WhatsApp message types
Installation
pip install pywce
Why pywce
Most WhatsApp chatbot tutorials or libraries acts as client libraries only or give basic chatbot using a lot of if..else.
This project gives you a complete approach for developing chatbots of any scale, giving you access to full package of whatsapp client library and chatbot development framework.
Setup
Summary: Setup in 6 easy steps (with FastAPI)
- Clone repo and install all dependencies,
pip install . - Navigate to the
examplefolder and install its dependencies too,pip install -r requirements.txt - Setup your whatsapp account configs in
.env.exampleand edit the file to.envonly - Run the chatbot,
fastapi dev main.pyand setup tunneling usingngrokor any similar service (if hosted local) and configure your webhook on developer portal - Build on top of available example templates in
example/folder to suit your chatbot needs - Implement your chatbot logic in
example/<project-name>/hooksfolder
After you get the hang of it, you can start your new project afresh
Follow the complete step by step WhatsApp Cloud API guide below.
Important settings needed for this library
- Phone number ID
- Access Token
- Webhook callback verification token of your choice
- App secret
Engine
You can either use .env or add your credentials directly to the WhatsAppConfig class
# config.py
import os
from dotenv import load_dotenv
from pywce import client, Engine, EngineConfig, storage
load_dotenv()
# configure default YAML/JSON templates source
template_storage_manager = storage.YamlJsonStorageManager(
os.getenv("TEMPLATES_DIR"),
os.getenv("TRIGGERS_DIR")
)
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,
storage_manager=template_storage_manager,
start_template_stage=os.getenv("START_STAGE")
)
engine = Engine(config=engine_config)
Example ChatBot
Here's a simple example template to get you started:
[!NOTE] Checkout complete working examples in the example folder
- Define YAML/JSON template (Conversation Flow💬):
# path/to/templates/bot.yaml
"START-MENU":
type: button
template: "path.to.hook.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
prop: age
message: Great, What is your age?
routes:
"re:.*": "ANOTHER-STEP"
- Write your hook (Supercharge⚡):
# path/to/hook.py
from pywce import HookArg, TemplateDynamicBody
def username(arg: HookArg) -> HookArg:
"""
fill message template's dynamic variable: name
to greet user by their whatsapp name 😎
"""
template_value = {"name": arg.user.name}
arg.template_body = TemplateDynamicBody(
render_template_payload=template_value
)
return arg
- Engine client:
Use fastapi or flask or any python library to create endpoint to receive WhatsApp webhooks
# main.py
# ~ fastapi snippet ~
from .config import engine, whatsapp
def bg_wehbook_handler(payload: dict, headers: dict) -> None:
engine.process_webhook(payload, headers)
@app.post("/chatbot/webhook")
async def process_webhook(req: Request, bg_task: BackgroundTasks):
"""
Handle incoming webhook events from WhatsApp
and process them in the background.
"""
payload = await req.json()
bg_task.add_task(bg_wehbook_handler, payload, dict(req.headers))
return Response(content="ACK", status_code=200)
WhatsApp Client Library
[!NOTE] You can use pywce as a standalone whatsapp client library. See Example
PyWCE provides a simple, Pythonic interface to interact with the WhatsApp Cloud API:
- Send messages (text, media, templates, interactive, etc)
- Receive and process webhooks
- Media management (upload and download)
- Out of the box utilities using the
WhatsApp.Utilsclass.
Example usage:
from pywce import client
config = client.WhatsAppConfig(
token="ACCESS-TOKEN",
phone_number_id="PHONE-NUMBER-ID",
hub_verification_token="WEBHOOK-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 for a detailed guide.
Changelog
Visit the changelog list for a full list of changes.
Contributing
We welcome contributions! Please check out the Contributing Guide for details.
License
This project is licensed under the MIT License. See the LICENSE file for details.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pywce-3.0.0.tar.gz.
File metadata
- Download URL: pywce-3.0.0.tar.gz
- Upload date:
- Size: 45.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
66d1da890d1b96703987107680614282149b99a67b32180c5b58b53a0ea3f69d
|
|
| MD5 |
de0fbd1e320e0de0d90ff5680d390e82
|
|
| BLAKE2b-256 |
ef476a2a7d4facc0c99310499332484cf17b8b78ca78b02c02fc330895a7083f
|
File details
Details for the file pywce-3.0.0-py3-none-any.whl.
File metadata
- Download URL: pywce-3.0.0-py3-none-any.whl
- Upload date:
- Size: 49.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.11.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f6c10ce4b9077ddac19e288116b0860329bc3fcfb3194670ada4576298070ad1
|
|
| MD5 |
3ef49c64c730ddc67d12a4b000d61cf1
|
|
| BLAKE2b-256 |
6c2c5d4ce6ac5072eff7cde91d5b7e766432936d7a621435a5d239f4be3b8782
|