pywa Documentation

repository·master·Indexed 20 days ago

https://github.com/david-lev/pywa

A fully-typed Python framework for the WhatsApp Cloud API. pywa enables the creation of WhatsApp bots with support for messaging, webhooks, interactive flows, and business resource management. It features a high-level API for sending rich media, managing message templates, and building multi-screen interactive experiences via WhatsApp Flows. The framework includes CLI tools for development and production, integration support for FastAPI, and an asynchronous API via pywa_async.

Tokens
92.9K
Snippets
246
Records
357
Agent score
69%

What's inside pywa

  1. Use common filters in pywa

    master

    The pywa.filters module provides a variety of filters used to intercept and process specific types of incoming updates or messages. These filters allow you to define precise criteria for your handlers, such as filtering by message type, button interaction, call status, or account updates.

    Available filter categories include:

    • Message & Interaction: message, callback_button, callback_selection, message_status, flow_completion.
    • Call Events: call_connect, call_terminate, call_status, call_permission_update.
    • Account & Identity: phone_number_change, identity_change, account_update, user_marketing_preferences.
    • Template Metadata: template_status, template_category, template_quality, template_components.
    • Contextual Filters: private (for private chats), group (for group chats), sent_to_me, sent_to.
    • User/Identity Filters: from_users, without_wa_id, from_countries, waba_id.
    • String/Pattern Matching: matches, contains, startswith, endswith, regex.
  2. Overview of pywa core concepts

    master

    Pywa is built around several key abstractions:

    • WhatsApp: The core client used to send messages, manage business profiles, and register handlers.
    • Handlers: Callbacks that trigger when specific updates (like messages or button clicks) occur.
    • Listeners: A mechanism to wait for a user's next specific reply inline, useful for step-by-step conversational flows.
    • Filters: Composable conditions used to decide if a handler should process an update. They support Python-like logic using & (AND), | (OR), and ~ (NOT).
    • Updates: The data objects representing incoming events (messages, button clicks, delivery statuses, etc.).
    • Flows: A way to build interactive, multi-screen experiences within WhatsApp using Python.
    • Errors: The mechanism for surfacing and handling WhatsApp API errors.
  3. Understand how errors are reported in PyWa

    master

    Errors in pywa are reported in two distinct ways depending on when the failure is detected:

    1. Raised exceptions: These occur immediately when you call a method with invalid parameters (e.g., duplicate callback_data in buttons). You handle these using standard Python try/except blocks.
    2. Returned errors (Message Status Updates): These occur asynchronously when the WhatsApp API reports a failure after a message has been sent (e.g., sending media that is too large or attempting to message outside the 24h window). These do not raise exceptions in your main execution flow; instead, they arrive as pywa.types.MessageStatus updates. You must register a handler using @wa.on_message_status(filters.failed) to catch these.
  4. How Flows and Screens work in PyWa

    master

    A Flow is a collection of related screens that can exchange data with each other and with your server.

    Each Screen is an independent unit with its own data and consists of:

    • id: A unique identifier used for navigation.
    • title: The title rendered at the top of the screen.
    • layout: A Layout object containing the visual elements (children) displayed on the screen.
    • data: The data the screen expects to receive to configure its components dynamically.

    Screens can be static (content is pre-configured when the flow is created) or dynamic (components like TextInput can have dynamic labels, helper text, or pre-filled values based on the data passed to the screen).

    from pywa.types.flows import Screen, Layout
    
    # Example of a static screen definition
    START = Screen(
        id="START",
        title="Home",
        layout=Layout(children=[...])
    )
  5. Configure FlowJSON properties

    master

    The FlowJSON object is the core configuration for a WhatsApp Flow. It requires the following properties:

    • version: The version of the Flow JSON schema.
    • data_api_version: The version of the data API being used (e.g., utils.Version.FLOW_DATA_API).
    • routing_model: A dictionary defining navigation. Keys are screen IDs, and values are lists of screen IDs that can be navigated to from that screen. For example, {"START": ["SIGN_UP"]} means the START screen can navigate to SIGN_UP.
    • screens: A list of Screen objects that make up the flow's UI.
  6. Use .ref for type-safe data and component referencing

    master

    When building screens, you often need to pass values from a ScreenData object or a Form child (like a TextInput) into an Action payload.

    Instead of manually constructing ScreenDataRef or ComponentRef objects using string names, you can use the .ref property on the component or data object itself. This is more type-safe and can be easily implemented using the Python walrus operator (:=) to assign components to variables during layout definition.

    • first_name_initial_value.ref: A shortcut for a ScreenDataRef referencing the first_name_initial_value key.
    • first_name.ref: A shortcut for a ComponentRef referencing the first_name component.
  7. Navigate between screens using FlowActionType.NAVIGATE

    master

    To move a user from one screen to another within a Flow, use an Action with the name set to FlowActionType.NAVIGATE.

    The Action requires a next parameter of type Next, which specifies the target screen type and name. You can also provide a payload dictionary to pass data to the destination screen.

    Key components for navigation:

    • FlowActionType.NAVIGATE: The action type for screen transitions.
    • Next(type=NextType.SCREEN, name="SCREEN_ID"): Defines the target screen.
    • payload: A dictionary of key-value pairs to initialize or pre-fill fields on the next screen.
    from pywa.types.flows import Screen, Layout, Action, Next, FlowActionType, NextType, EmbeddedLink, TextHeading
    
    START = Screen(
        id="START",
        title="Home",
        layout=Layout(
            children=[
                EmbeddedLink(
                    text="Click here to sign up",
                    on_click_action=Action(
                        name=FlowActionType.NAVIGATE,
                        next=Next(
                            type=NextType.SCREEN,
                            name="SIGN_UP",
                        ),
                        payload={
                            "first_name_initial_value": "",
                            "email_initial_value": "",
                        },
                    ),
                ),
            ]
        ),
    )
  8. Use filters to control handler execution

    master

    Filters are conditions used with handlers (like @wa.on_message) to decide whether an incoming update should be processed or ignored. If a filter returns True, the handler's callback is executed; if False, the update is skipped. You can use built-in filters from the pywa.filters module or create custom ones.

    from pywa import WhatsApp, types, filters
    
    wa = WhatsApp(...)
    
    # The handler only runs if the message starts with 'Hello' or 'Hi' (case-insensitive)
    @wa.on_message(filters.startswith("Hello", "Hi", ignore_case=True))
    def handle_hello(wa: WhatsApp, msg: types.Message):
        msg.reply("Hello!")
    
    # The handler only runs if the callback button matches 'click'
    @wa.on_callback_button(filters.matches("click"))
    def handle_click(wa: WhatsApp, clb: types.CallbackButton):
        clb.reply("You clicked me!")
  9. How WhatsApp Flows work in PyWa

    master

    WhatsApp Flows allow you to create structured, interactive experiences (like booking or sign-ups) within a chat. In PyWa, working with Flows follows a four-step lifecycle:

    1. Creating the Flow: Define the flow structure using create_flow.
    2. Sending the Flow: Attach a FlowButton to a message to trigger the flow.
    3. Handling Requests: For dynamic flows, your server responds to screen actions to determine the next screen or data.
    4. Receiving Completion: Listen for the on_flow_completion event to get the user's final payload.

    Flows can be static (predefined components, no server interaction required) or dynamic (server responds to actions to drive the flow).

    from pywa import WhatsApp
    from pywa.types import FlowCategory
    
    # WABA ID is required for flow operations
    wa = WhatsApp(..., waba_id="1234567890123456")
    
    # Create a flow
    created = wa.create_flow(
        name="My New Flow",
        categories=[FlowCategory.CUSTOMER_SUPPORT, FlowCategory.SURVEY]
    )
  10. Use Listeners for conversational flows

    master

    Instead of just reacting to single events, you can use wait_for_reply to chain conversations. This allows you to pause execution and wait for a specific type of user input (like text) before proceeding.

    @wa.on_message(filters.command("start"))
    def start(_: WhatsApp, msg: types.Message):
        # Waits for the next text reply from the user
        name = msg.reply("What's your name?").wait_for_reply(filters=filters.text).text
        msg.reply(f"Nice to meet you, {name}!")