π 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:
Sending messages β text, media, location, contacts, etc.
Listening β handling incoming messages, events, and statuses.
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.WA_ID, UserIdentifier.BSUID, UserIdentifier.PARENT_BSUID), business_account_id=None)#
The WhatsApp client.
Full documentation on pywa.readthedocs.io.
>>> from pywa import WhatsApp, filters, types, utils
>>> wa = WhatsApp( ... phone_id="1234567890", ... token="EAAJB...", ... callback_url=utils.start_ngrok_tunnel(...), ... verify_token="xyzxyz", ... app_id=1234567890, ... app_secret="41678a4f...", ... )
>>> @wa.on_message(filters.text) ... def new_message(_: WhatsApp, msg: types.Message): ... msg.reply("Hello from PyWa!")
$ pywa dev
- 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 should leave it as
Noneand specify the phone ID in the method calls instead.token (str) β The system or business access token used for the WhatsApp Cloud API. If not provided, the client can still be used to handle incoming updates.
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 httpx client used for API requests (default: a new httpx.Client()). Use a custom client to configure proxies, timeouts, etc. Do not use the same session for another client or make other API calls while it is being used by the WhatsApp client, as this may cause unexpected behavior.
server (Flask | FastAPI | None) β A Flask or FastAPI app instance used for the webhook. Designed for cases where you want to use the same server for other routes or purposes; if you just want a simple webhook server, itβs easier to leave this as
Noneand let pywa create and manage the server for you.callback_url (str | None) β The public server URL to register, without the endpoint. If you using static domain (e.g.
utils.start_ngrok_tunnel(domain=...)), you can comment this out after the first successful registration to avoid unnecessary re-registrations on every restart.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; can be any string and must match the value sent during verification. Required when handling updates.
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_urlwithAPPscope and when creating templates that contain media).app_secret (str | None) β
The app secret from the App Basic Settings (optional; recommended for validating updates and required when registering a
callback_urlwithAPPscope).webhook_endpoint (str) β The endpoint path used to receive incoming webhook requests (default:
/); change this to avoid conflicts if theserveris used for other purposes.filter_updates (bool) β Whether to filter out updates that do not belong to this
phone_id,waba_idorbusiness_portfolio_id(default:True; does not apply to raw updates).waba_id (str | int | None) β The WhatsApp Business Account ID that owns the
phone_id(optional; required for some API methods).business_portfolio_id (str | int | None) β The Business Portfolio ID that owns the
waba_id. 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_decryptorto decrypt incoming flow 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 flow requests.
flows_response_encryptor (Callable[[dict, bytes, bytes], str] | None) β The global Flows response encryptor implementation used to encrypt outgoing flow 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. Important when using custom server that block the incoming request until the response is sent, as WhatsApp may retry sending the same update if it does not receive a timely response (default:
True).validate_updates (bool) β Whether to validate incoming webhhoks payloads (default:
True; requiresapp_secret).handlers_modules (Iterable[ModuleType] | None) β Python modules from which handlers should be automatically loaded. A convenient way to organize handlers in separate files without having to import and register them manually (default:
None).user_identifier_priority (tuple[UserIdentifier, ...]) β The priority order of user identifiers to use when replying to messages, blocking users, etc (default:
wa_id>bsuid>parent_bsuid). Will be changed tobsuid>wa_id>parent_bsuidwhen the API supports BSUID-based endpoints.business_account_id (None) β Deprecated alias for
waba_id(the WhatsApp Business Account ID that owns thephone_id).
Sending Messages#
The client allows you to send a wide variety of messages:
Method |
Description |
|---|---|
Send a text message |
|
Send an image |
|
Send a video |
|
Send an audio file |
|
Send a voice message |
|
Send a document |
|
Share a location |
|
Request location from a user |
|
Send one or multiple contacts |
|
Send a sticker |
|
Send a template message |
|
Send a product catalog |
|
Send a single product |
|
Send multiple products |
|
Send a carousel message |
|
React to a message |
|
Remove a reaction |
|
Mark a message as read |
|
Indicate typing status to the user |
Handling Updates#
Register event handlers to listen for updates:
Method |
Description |
|---|---|
Handle incoming messages |
|
Handle callback button clicks |
|
Handle list or menu selections |
|
Track message delivery, read, and failure statuses |
|
Handle incoming flow requests |
|
Handle flow completions |
|
Handle phone number changes |
|
Handle identity changes |
|
Handle incoming/outgoing call connections |
|
Handle call terminations |
|
Handle call status updates |
|
Handle call permission updates |
|
Handle user marketing preferences updates |
|
Handle template status updates |
|
Handle template category changes |
|
Handle template quality changes |
|
Handle template components updates |
|
Handle edited messages |
|
Handle deleted messages |
|
Handle outgoing messages |
|
Handle outgoing edited messages |
|
Handle outgoing deleted messages |
|
Handle business account updates |
|
Handle raw updates from WhatsApp |
|
Dynamically add handlers programmatically |
|
Remove handlers programmatically |
|
Remove handlers by callbacks |
|
Add flow request handlers programmatically |
|
Load handlers from external modules |
Listening#
You can listen for updates from specific users:
Method |
Description |
|---|---|
Listen to a specific user update |
|
Stop listening |
Media#
Manage media with ease:
Method |
Description |
|---|---|
Upload media to WhatsApp servers |
|
Download media |
|
Stream media |
|
Get media as bytes |
|
Get direct media URL |
|
Delete media from WhatsApp servers |
Templates#
Create, update, and manage message templates:
Method |
Description |
|---|---|
Create a new template |
|
Bulk create or update authentication templates |
|
Retrieve all templates |
|
Get details of a specific template |
|
Update an existing template |
|
Delete a template |
|
Unpause a previously paused template |
|
Compare two templates |
|
Migrate templates between WABAs |
Flows#
Programmatically manage flows:
Method |
Description |
|---|---|
Create a flow |
|
Update flow metadata (name, categories, endpoint, etc.) |
|
Update flow JSON definition |
|
Publish a flow |
|
Delete a flow |
|
Deprecate a flow |
|
Get details of a flow |
|
List all flows |
|
Get flow performance metrics |
|
Get flow assets |
|
Migrate flows between WABAs |
Business#
Manage business account and profile:
Method |
Description |
|---|---|
Get business account details |
|
Update business account settings |
|
Get business profile |
|
Get all business phone numbers |
|
Get a specific business phone number |
|
Update profile details (name, description, picture, etc.) |
|
Update phone number display name |
|
Update commands and ice breakers |
|
Upload business public key |
|
Get phone number settings |
|
Update phone number settings |
|
Set a username for the business account |
|
Get the current username of the business account |
|
Get a list of reserved usernames for the business account |
|
Delete the current username of the business account |
Managing Users#
Method |
Description |
|---|---|
Block users |
|
Unblock users |
|
Retrieve blocked users |
QR Codes#
Method |
Description |
|---|---|
Create a QR code |
|
Get details of a QR code |
|
List all QR codes |
|
Update a QR code |
|
Delete a QR code |
Commerce#
Method |
Description |
|---|---|
Get commerce settings |
|
Update commerce settings |
Calls#
Method |
Description |
|---|---|
Get call permissions |
|
Pre-accept a call |
|
Accept a call |
|
Reject a call |
|
Terminate a call |
Groups#
Method |
Description |
|---|---|
Create a group |
|
Get details of a group |
|
List all groups |
|
Delete a group |
|
|
Get pending group join requests |
|
Approve a group join request |
Reject a group join request |
|
Update group details (name, description, picture, etc.) |
|
Remove participants from a group |
|
Get group invite link |
|
Reset group invite link |
|
Pin a message in a group |
|
Unpin a message in a group |
Server#
Integrate with webhook events manually:
Method |
Description |
|---|---|
Start a webhook server to receive updates |
|
Handle webhook challenge manually |
|
Validate incoming webhook updates |
|
Handle webhook updates manually |
|
Retrieve flow request handler |
Partner tools#
Method |
Description |
|---|---|
Create a phone number on a WhatsApp Business Account. |
|
Request a verification code for a phone number. |
|
Verify a phone number with a verification code. |
|
Register a new phone number |
|
Deregister a phone number |
|
Get shared business accounts |
|
Get owned business account |
|
Override WABA callback URL |
|
Delete WABA callback URL |
|
Override phone callback URL |
|
Delete phone callback URL |
Others#
Method |
Description |
|---|---|
Retrieve app access token |
|
Set app callback URL |
- Client Reference
WhatsApp.send_message()WhatsApp.send_image()WhatsApp.send_video()WhatsApp.send_audio()WhatsApp.send_voice()WhatsApp.send_document()WhatsApp.send_location()WhatsApp.request_location()WhatsApp.send_contact()WhatsApp.send_sticker()WhatsApp.send_catalog()WhatsApp.send_template()WhatsApp.send_product()WhatsApp.send_products()WhatsApp.send_carousel()WhatsApp.send_reaction()WhatsApp.remove_reaction()WhatsApp.mark_message_as_read()WhatsApp.indicate_typing()WhatsApp.listen()WhatsApp.stop_listening()WhatsApp.upload_media()WhatsApp.download_media()WhatsApp.stream_media()WhatsApp.get_media_bytes()WhatsApp.get_media_url()WhatsApp.delete_media()WhatsApp.get_business_account()WhatsApp.update_business_account_settings()WhatsApp.get_business_profile()WhatsApp.get_business_phone_numbers()WhatsApp.get_business_phone_number()WhatsApp.get_business_phone_number_settings()WhatsApp.update_business_phone_number_settings()WhatsApp.update_business_profile()WhatsApp.update_display_name()WhatsApp.update_conversational_automation()WhatsApp.set_business_public_key()WhatsApp.get_commerce_settings()WhatsApp.update_commerce_settings()WhatsApp.create_template()WhatsApp.upsert_authentication_template()WhatsApp.update_template()WhatsApp.get_template()WhatsApp.get_templates()WhatsApp.delete_template()WhatsApp.unpause_template()WhatsApp.compare_templates()WhatsApp.migrate_templates()WhatsApp.create_flow()WhatsApp.update_flow_metadata()WhatsApp.update_flow_json()WhatsApp.publish_flow()WhatsApp.delete_flow()WhatsApp.deprecate_flow()WhatsApp.get_flow()WhatsApp.get_flows()WhatsApp.get_flow_metrics()WhatsApp.get_flow_assets()WhatsApp.migrate_flows()WhatsApp.block_users()WhatsApp.unblock_users()WhatsApp.get_blocked_users()WhatsApp.register_phone_number()WhatsApp.deregister_phone_number()WhatsApp.create_phone_number()WhatsApp.request_verification_code()WhatsApp.verify_phone_number()WhatsApp.create_qr_code()WhatsApp.get_qr_code()WhatsApp.get_qr_codes()WhatsApp.update_qr_code()WhatsApp.delete_qr_code()WhatsApp.set_username()WhatsApp.get_current_username()WhatsApp.get_reserved_usernames()WhatsApp.delete_username()WhatsApp.delete_qr_code()WhatsApp.get_call_permissions()WhatsApp.pre_accept_call()WhatsApp.accept_call()WhatsApp.reject_call()WhatsApp.terminate_call()WhatsApp.create_group()WhatsApp.get_group()WhatsApp.get_groups()WhatsApp.delete_group()WhatsApp.approve_group_join_requests()WhatsApp.reject_group_join_requests()WhatsApp.get_group_invite_link()WhatsApp.reset_group_invite_link()WhatsApp.remove_group_participants()WhatsApp.update_group_settings()WhatsApp.pin_message()WhatsApp.unpin_message()WhatsApp.get_app_access_token()WhatsApp.set_app_callback_url()WhatsApp.override_waba_callback_url()WhatsApp.delete_waba_callback_url()WhatsApp.override_phone_callback_url()WhatsApp.get_shared_business_accounts()WhatsApp.get_owned_business_accounts()WhatsApp.delete_phone_callback_url()WhatsApp.run()WhatsApp.webhook_update_handler()WhatsApp.webhook_update_validator()WhatsApp.webhook_challenge_handler()WhatsApp.get_flow_request_handler()WhatsApp.load_handlers_modules()
- API Reference