Skip to main content

A templates-driven framework for building WhatsApp chatbots

Project description

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.

[!NOTE] Template engine and WhatsApp client library are decoupled - allowing you to use them independently or together.

Features

  • Template-Driven Design: Use templates (YAML by default) for conversational flows.
  • Hooks for Business Logic: Attach Python functions to process messages or actions.
  • Focus on your conversation flow and business logic.
  • Easy-to-use API for WhatsApp Cloud.
  • Model based templates
  • Supports dynamic messages with placeholders.
  • Built-in support for WhatsApp Webhooks.
  • Starter templates

Installation

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.

WhatsApp Cloud API Complete Setup Guide

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

import os
from dotenv import load_dotenv
from pywce import client, Engine, EngineConfig, storage

load_dotenv()

# configure default YAML templates manager
yaml_storage = storage.YamlStorageManager(
    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=yaml_storage,
    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:

[!NOTE] Checkout complete working examples in the example folder

  1. Define YAML template (Conversation Flow💬):
# path/to/templates
"START-MENU":
  type: button
  template: "dotted.path.to.python.func"
  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"
  1. Write your hook (Supercharge⚡):
# dotted/path/to/python/func.py
from pywce import hook, HookArg, TemplateDynamicBody

@hook
def username(arg: HookArg) -> HookArg:
    # set render payload data to match the required templates dynamic var
    
    # greet user by their whatsapp name 😎
    arg.template_body = TemplateDynamicBody(
        render_template_payload={"name": arg.user.name}
    )

    return arg
  1. Engine client:

Use fastapi or flask or any python library to create endpoint to receive whatsapp webhooks

# ~ fastapi snippet ~

async def webhook_event(payload: dict, headers: dict) -> None:
    """
    Process webhook event in the background using pywce engine.
    """
    await engine_instance.process_webhook(payload, 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 project or the example projects successfully, your webhook url will be available on localhost:port/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.

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)
  • Receive and process webhooks
  • Media management (upload and download)
  • Out of the box utilities using the WhatsApp.Utils class.

Example usage:

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 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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pywce-2.0.0.tar.gz (43.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pywce-2.0.0-py3-none-any.whl (51.4 kB view details)

Uploaded Python 3

File details

Details for the file pywce-2.0.0.tar.gz.

File metadata

  • Download URL: pywce-2.0.0.tar.gz
  • Upload date:
  • Size: 43.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.11.9

File hashes

Hashes for pywce-2.0.0.tar.gz
Algorithm Hash digest
SHA256 4b5cae1c6f355800f6f9aea6c5cc7b114a62fa3b8fa0bcf9722e8616fae76b2e
MD5 99acb76cd460cb5e2e72b24f65ea3f93
BLAKE2b-256 98261743d6f1d0276091b7d6485b33837f14e873c93eeb2bb31c3011f514b8f0

See more details on using hashes here.

File details

Details for the file pywce-2.0.0-py3-none-any.whl.

File metadata

  • Download URL: pywce-2.0.0-py3-none-any.whl
  • Upload date:
  • Size: 51.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.11.9

File hashes

Hashes for pywce-2.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 85f4fdc901848ff610c75fc801fd77521f7b447626794ae15863f07c9610b1d2
MD5 be434c875d4cf207df4fb7c708308027
BLAKE2b-256 2a9d9629948422450e3b928571caa17a3a3dcc8145c80159d2493afb8e8d6661

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page