πŸ”Œ Client#

The WhatsApp client has 3 main responsibilities:

  1. Sending messages (text, media, location, contact, etc.)

  2. Listening for incoming messages and events

  3. Creating and managing templates, flows, profile and other business-related resources

Tip

Pywa provides two clients, synchronous and asynchronous, you can choose the one that fits your needs.

from pywa import WhatsApp, types
wa = WhatsApp(...)

@wa.on_message
def on_message(_: WhatsApp, msg: types.Message):
    msg.reply("Hello!")
from pywa_async import WhatsApp, types
wa = WhatsApp(...)

@wa.on_message
async def on_message(_: WhatsApp, msg: types.Message):
    await msg.reply("Hello!")
class pywa.client.WhatsApp#
__init__(phone_id: str | int | None = None, token: str = None, *, session: ~httpx.Client | None = None, server: ~pywa.utils.Flask | ~pywa.utils.FastAPI | None = <object object>, webhook_endpoint: str = '/', verify_token: str | None = None, filter_updates: bool = True, continue_handling: bool = False, skip_duplicate_updates: bool = True, validate_updates: bool = True, business_account_id: str | int | None = None, callback_url: str | None = None, callback_url_scope: ~pywa.utils.CallbackURLScope = CallbackURLScope.APP, webhook_fields: ~typing.Iterable[str] | None = None, app_id: int | None = None, app_secret: str | None = None, webhook_challenge_delay: int = 3, business_private_key: str | None = None, business_private_key_password: str | None = None, flows_request_decryptor: ~typing.Callable[[str, str, str, str, str | None], tuple[dict, bytes, bytes]] | None = <function default_flow_request_decryptor>, flows_response_encryptor: ~typing.Callable[[dict, bytes, bytes], str] | None = <function default_flow_response_encryptor>, api_version: str | int | float | ~typing.Literal[Version.GRAPH_API] = Version.GRAPH_API, handlers_modules: ~typing.Iterable[~types.ModuleType] | None = None) None#
The WhatsApp client.

Example without webhook:

>>> from pywa import WhatsApp
>>> wa = WhatsApp(phone_id="1234567890",token="EAADKQl9oJxx")
>>> wa.send_message("1234567890", "Hello from PyWa!")

Example with webhook (using FastAPI):

>>> import pywa, fastapi
>>> fastapi_app = fastapi.FastAPI()
>>> wa = pywa.WhatsApp(
...     phone_id="1234567890",
...     token="EAADKQl9oJxx",
...     server=fastapi_app,
...     callback_url='https://pywa.ngrok.io',
...     verify_token="XYZ123",
...     app_id=1234567890,
...     app_secret="my_app_secret",
... )
>>> @wa.on_message(filters.text)
... def new_message(_: WhatsApp, msg: Message):
...     msg.reply("Hello from PyWa!")

$ fastapi dev wa.py see uvicorn docs for more options (port, host, reload, etc.)

Parameters:
  • phone_id – The Phone number ID to send messages from (if you manage multiple WhatsApp business accounts (e.g. partner solutions), you can specify the phone ID when sending messages, optional).

  • token – The token to use for WhatsApp Cloud API (In production, you should use permanent token).

  • api_version – The API version of the WhatsApp Cloud API (default to the latest version).

  • session – The session to use for api requests (default: new httpx.Client(), For cases where you want to use a custom session, e.g. for proxy support. Do not use the same session across multiple WhatsApp clients!).

  • server – The Flask or FastAPI app instance to use for the webhook. required when you want to handle incoming updates. pass None to insert the updates with the webhook_update_handler().

  • callback_url – The server URL to register (without endpoint. optional).

  • callback_url_scope – The scope of the callback URL to register (default: APP).

  • verify_token – A challenge string (Required when server is provided. The verify token can be any string. It is used to challenge the webhook endpoint to verify that the endpoint is valid).

  • webhook_challenge_delay – The delay (in seconds, default to 3) to wait for the verify token to be sent to the server (optional, for cases where the server/network is slow or the server is taking a long time to start).

  • webhook_fields – The fields to register for the callback URL (optional, if not provided, all supported fields will be registered. modify this if you want to reduce the number of unused requests to your server). See Availble fields.

  • app_id – The ID of the app in the App Basic Settings (optional, required when registering a callback_url).

  • app_secret –

    The secret of the app in the App Basic Settings (optional, recomended for validating updates, required when registering a callback_url).

  • webhook_endpoint – The endpoint to listen for incoming messages (if you’re using the server for another purpose, you can change this to avoid conflicts).

  • filter_updates – Whether to filter out user updates that are not sent to this phone_id (default: True, does not apply to raw updates or updates that are not user-related).

  • business_account_id – The WhatsApp business account ID (WABA ID) that owns the phone ID (optional, required for some API methods).

  • business_private_key – The global private key to use in the flows_request_decryptor

  • business_private_key_password – The global private key password (if needed) to use in the flows_request_decryptor

  • flows_request_decryptor – The global flows requests decryptor implementation to use to decrypt Flows requests.

  • flows_response_encryptor – The global flows response encryptor implementation to use to encrypt Flows responses.

  • continue_handling – Whether to continue handling updates after a handler or listener has been found (default: False).

  • skip_duplicate_updates – Whether to skip duplicate updates (default: True).

  • validate_updates – Whether to validate updates payloads (default: True, app_secret required).

  • handlers_modules – Modules to load handlers from.

Sending messages#

Method

Description

send_message()

Send a text message

send_image()

Send an image

send_video()

Send a video

send_audio()

Send an audio

send_document()

Send a document

send_location()

Send a location

request_location()

Request location

send_contact()

Send a contact/s

send_sticker()

Send a sticker

send_template()

Send a template

send_catalog()

Send a catalog

send_product()

Send a product

send_products()

Send multiple products

send_reaction()

React to a message

remove_reaction()

Remove a reaction

mark_message_as_read()

Mark a message as read

indicate_typing()

Indicate typing

Handling updates#

Method

Description

on_message()

Handle messages

on_callback_button()

Handle callback button clicks

on_callback_selection()

Handle callback selections

on_message_status()

Handle message status (delivered, read etc.)

on_chat_opened()

Handle when new chat is opened

on_flow_request()

Handle incoming flow requests

on_flow_completion()

Handle flow completions

on_template_status()

Handle template status changes

add_handlers()

Add handlers programmatically

remove_handlers()

Remove handlers programmatically

remove_callbacks()

Remove handlers by callbacks

add_flow_request_handler()

Add a flow request handler programmatically

load_handlers_modules()

Load handlers from modules

Listening#

Method

Description

listen()

Listen to specific user update

stop_listening()

Stop listening

Media#

Method

Description

upload_media()

Upload media to WhatsApp servers

download_media()

Download media

get_media_url()

Get media URL

Templates#

Method

Description

create_template()

Create a template

Flows#

Method

Description

create_flow()

Create a flow

update_flow_metadata()

Update flow metadata (name, categories, endpoint etc.)

update_flow_json()

Update flow JSON

publish_flow()

Publish a flow

delete_flow()

Delete a flow

deprecate_flow()

Deprecate a flow

get_flow()

Get a flow details

get_flows()

List all flows

get_flow_metrics()

Get flow metrics

get_flow_assets()

Get flow assets

migrate_flows()

Migrate flows from one WABA to another

Business profile#

Method

Description

get_business_profile()

Get business profile

get_business_phone_number()

Get business phone number

update_business_profile()

Update business profile details (name, description, picture etc.)

update_conversational_automation()

Update commands and ice breakers

set_business_public_key()

Upload business public key

register_phone_number()

Register new phone number

Managing users#

Method

Description

block_users()

Block users

unblock_users()

Unblock users

get_blocked_users()

Get blocked users

QR Codes#

Method

Description

create_qr_code()

Create a QR code for a phone number

get_qr_code()

Get a QR code

get_qr_codes()

Get all QR codes

update_qr_code()

Update a QR code

delete_qr_code()

Delete a QR code

Commerce#

Method

Description

get_commerce_settings()

Get commerce settings

update_commerce_settings()

Update commerce settings

Server#

Method

Description

webhook_update_handler()

Handle webhook updates manually

webhook_challenge_handler()

Handle webhook challenge manually

get_flow_request_handler()

Get flow request handler to handle manually

Others#

Method

Description

get_app_access_token()

Get app access token

set_app_callback_url()

Set app callback URL

override_waba_callback_url()

Override WABA callback URL

delete_waba_callback_url()

Delete WABA callback URL

override_phone_callback_url()

Override phone callback URL

delete_phone_callback_url()

Delete phone callback URL