πŸ”Œ Client#

The WhatsApp client is the heart of the pywa library. It is responsible for managing communication with the WhatsApp Business API.

Its three main responsibilities are:

  1. Sending messages β€” text, media, location, contacts, etc.

  2. Listening β€” handling incoming messages, events, and statuses.

  3. Managing resources β€” templates, flows, profiles, and other business-related settings.

Tip

Pywa provides two types of clients:

  • Synchronous (pywa)

  • Asynchronous (pywa_async)

Choose the one that best fits your application’s 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!")

For optimal type checking, ensure that all your imports come from the same packageβ€”either pywa or pywa_async.

class pywa.client.WhatsApp#
__init__(phone_id=None, token=None, *, session=None, server=None, webhook_endpoint='/', verify_token=None, filter_updates=True, continue_handling=False, skip_duplicate_updates=True, validate_updates=True, waba_id=None, business_portfolio_id=None, callback_url=None, callback_url_scope=CallbackURLScope.APP, webhook_fields=None, app_id=None, app_secret=None, webhook_challenge_delay=3, business_private_key=None, business_private_key_password=None, flows_request_decryptor=<function default_flow_request_decryptor>, flows_response_encryptor=<function default_flow_response_encryptor>, api_version=Version.GRAPH_API, handlers_modules=None, user_identifier_priority=(UserIdentifier.BSUID, UserIdentifier.WA_ID, UserIdentifier.PARENT_BSUID), business_account_id=None)#

The WhatsApp client.

Example without webhook:

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

Example with webhook (using FastAPI):

>>> from pywa import WhatsApp, types, filters
>>> from fastapi import FastAPI
>>> fastapi_app = FastAPI()
>>> wa = 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: types.Message):
...     msg.reply("Hello from PyWa!")

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

Parameters:
  • phone_id (str | int | None) – The Phone Number ID to send messages from. If you manage multiple WhatsApp bots (e.g. Solution Partners or Tech Providers), you may override the phone ID per request when sending messages or calling API methods.

  • token (str) – The system or business access token used for the WhatsApp Cloud API.

  • api_version (str | int | float | Literal[Version.GRAPH_API]) – The Graph API version to use (default: the latest version supported by pywa).

  • session (Client | None) – The session used for API requests (default: a new httpx.Client()). Use a custom session to configure proxies, timeouts, etc. Do not share the same session across multiple WhatsApp clients.

  • server (Flask | FastAPI | None) –

    A Flask or FastAPI app instance used for the webhook. Required to automatically handle incoming updates; pass None to manually insert updates using webhook_update_handler().

  • callback_url (str | None) – The public server URL to register as a webhook, without the endpoint (optional).

  • callback_url_scope (CallbackURLScope) – The scope used when registering the callback URL (default: APP). See Webhook overrides for more information.

  • verify_token (str | None) – A challenge string used to verify the webhook endpoint. Required when server is provided; can be any string and must match the value sent during verification.

  • webhook_challenge_delay (int) – Delay in seconds to wait for the webhook verification challenge (default: 3); useful when the server or network is slow to start.

  • webhook_fields (WebhookFields | Iterable[str] | None) – The webhook fields to register for the callback URL (optional). If not provided, all supported fields are registered; specify this to reduce unnecessary webhook traffic.

  • app_id (int | str | None) – The app ID from the App Basic Settings (optional; required when registering a callback_url with APP scope).

  • app_secret (str | None) –

    The app secret from the App Basic Settings (optional; recommended for validating updates and required when registering a callback_url with APP scope).

  • webhook_endpoint (str) – The endpoint path used to receive incoming webhook requests (default: /); change this to avoid conflicts if the server is used for other purposes.

  • filter_updates (bool) – Whether to filter out updates that do not belong to this phone_id or waba_id (default: True; does not apply to raw updates).

  • waba_id (str | int | None) – The WhatsApp Business Account ID that owns the phone number (optional; required for some API methods).

  • business_portfolio_id (str | int | None) – The Business Portfolio ID that owns the assets. Also known as Business ID or Busines Manager ID (optional; required for some API methods).

  • business_private_key (str | None) – The global private key used by the flows_request_decryptor to decrypt incoming Flows requests.

  • business_private_key_password (str | None) – The password for the global private key, if required by the flows_request_decryptor.

  • flows_request_decryptor (Callable[[str, str, str, str, str | None], tuple[dict, bytes, bytes]] | None) – The global Flows request decryptor implementation used to decrypt incoming Flows requests.

  • flows_response_encryptor (Callable[[dict, bytes, bytes], str] | None) – The global Flows response encryptor implementation used to encrypt outgoing Flows responses.

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

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

  • validate_updates (bool) – Whether to validate incoming update payloads (default: True; requires app_secret).

  • handlers_modules (Iterable[ModuleType] | None) – Python modules from which handlers should be automatically loaded.

  • user_identifier_priority (tuple[UserIdentifier, ...]) – The priority order of user identifiers to use when replying to messages, blocking users, etc (default: bsuid > wa_id > parent_bsuid)

  • business_account_id (None) – Deprecated alias for waba_id (the WhatsApp Business Account ID that owns the phone number).

Sending Messages#

The client allows you to send a wide variety of messages:

Method

Description

send_message()

Send a text message

send_image()

Send an image

send_video()

Send a video

send_audio()

Send an audio file

send_voice()

Send a voice message

send_document()

Send a document

send_location()

Share a location

request_location()

Request location from a user

send_contact()

Send one or multiple contacts

send_sticker()

Send a sticker

send_template()

Send a template message

send_catalog()

Send a product catalog

send_product()

Send a single 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 status to the user

Handling Updates#

Register event handlers to listen for updates:

Method

Description

on_message()

Handle incoming messages

on_callback_button()

Handle callback button clicks

on_callback_selection()

Handle list or menu selections

on_message_status()

Track message delivery, read, and failure statuses

on_flow_request()

Handle incoming flow requests

on_flow_completion()

Handle flow completions

on_phone_number_change()

Handle phone number changes

on_identity_change()

Handle identity changes

on_call_connect()

Handle incoming/outgoing call connections

on_call_terminate()

Handle call terminations

on_call_status()

Handle call status updates

on_call_permission_update()

Handle call permission updates

on_user_marketing_preferences()

Handle user marketing preferences updates

on_template_status_update()

Handle template status updates

on_template_category_update()

Handle template category changes

on_template_quality_update()

Handle template quality changes

on_template_components_update()

Handle template components updates

on_raw_update()

Handle raw updates from WhatsApp

add_handlers()

Dynamically add handlers programmatically

remove_handlers()

Remove handlers programmatically

remove_callbacks()

Remove handlers by callbacks

add_flow_request_handler()

Add flow request handlers programmatically

load_handlers_modules()

Load handlers from external modules

Listening#

You can listen for updates from specific users:

Method

Description

listen()

Listen to a specific user update

stop_listening()

Stop listening

Media#

Manage media with ease:

Method

Description

upload_media()

Upload media to WhatsApp servers

download_media()

Download media

stream_media()

Stream media

get_media_bytes()

Get media as bytes

get_media_url()

Get direct media URL

delete_media()

Delete media from WhatsApp servers

Templates#

Create, update, and manage message templates:

Method

Description

create_template()

Create a new template

upsert_authentication_template()

Bulk create or update authentication templates

get_templates()

Retrieve all templates

get_template()

Get details of a specific template

update_template()

Update an existing template

delete_template()

Delete a template

unpause_template()

Unpause a previously paused template

compare_templates()

Compare two templates

migrate_templates()

Migrate templates between WABAs

Flows#

Programmatically manage flows:

Method

Description

create_flow()

Create a flow

update_flow_metadata()

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

update_flow_json()

Update flow JSON definition

publish_flow()

Publish a flow

delete_flow()

Delete a flow

deprecate_flow()

Deprecate a flow

get_flow()

Get details of a flow

get_flows()

List all flows

get_flow_metrics()

Get flow performance metrics

get_flow_assets()

Get flow assets

migrate_flows()

Migrate flows between WABAs

Business#

Manage business account and profile:

Method

Description

get_business_account()

Get business account details

get_business_profile()

Get business profile

get_business_phone_numbers()

Get all business phone numbers

get_business_phone_number()

Get a specific business phone number

update_business_profile()

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

update_display_name()

Update phone number display name

update_conversational_automation()

Update commands and ice breakers

set_business_public_key()

Upload business public key

get_business_phone_number_settings()

Get phone number settings

update_business_phone_number_settings()

Update phone number settings

Managing Users#

Method

Description

block_users()

Block users

unblock_users()

Unblock users

get_blocked_users()

Retrieve blocked users

QR Codes#

Method

Description

create_qr_code()

Create a QR code

get_qr_code()

Get details of a QR code

get_qr_codes()

List 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

Calls#

Method

Description

get_call_permissions()

Get call permissions

pre_accept_call()

Pre-accept a call

accept_call()

Accept a call

reject_call()

Reject a call

terminate_call()

Terminate a call

Groups#

Method

Description

create_group()

Create a group

get_group()

Get details of a group

get_groups()

List all groups

delete_group()

Delete a group

get_group_join_requests()

Get pending group join requests

approve_group_join_request()

Approve a group join request

reject_group_join_requests()

Reject a group join request

update_group_settings()

Update group details (name, description, picture, etc.)

remove_group_participants()

Remove participants from a group

get_group_invite_link()

Get group invite link

reset_group_invite_link()

Reset group invite link

pin_message()

Pin a message in a group

unpin_message()

Unpin a message in a group

Server#

Integrate with webhook events manually:

Method

Description

run()

Start a webhook server to receive updates

webhook_challenge_handler()

Handle webhook challenge manually

webhook_update_validator()

Validate incoming webhook updates

webhook_update_handler()

Handle webhook updates manually

get_flow_request_handler()

Retrieve flow request handler

Partner tools#

Method

Description

create_phone_number()

Create a phone number on a WhatsApp Business Account.

request_verification_code()

Request a verification code for a phone number.

verify_phone_number()

Verify a phone number with a verification code.

register_phone_number()

Register a new phone number

deregister_phone_number()

Deregister a phone number

get_shared_business_accounts()

Get shared business accounts

get_owned_business_account()

Get owned business account

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

Others#

Method

Description

get_app_access_token()

Retrieve app access token

set_app_callback_url()

Set app callback URL