Flow Types#
- class pywa.types.flows.FlowRequest#
Represents a flow data exchange request. This request is sent to the flow endpoint when a user interacts with a flow and perform an
Actionthat trigger a data exchange.Read more at developers.facebook.com.
- Variables:
version (str) β The version of the data exchange.
flow_token (str | None) β The flow token used to create the flow.
Noneif action isFlowRequestActionType.PING.action (pywa.types.flows.FlowRequestActionType) β The action that triggered the request.
screen (str | None) β The screen that triggered the request.
Noneif action isFlowRequestActionType.PING.data (dict[str, Any] | None) β The data sent from the screen.
Noneif action isFlowRequestActionType.PINGand optional if action isFlowRequestActionType.BACKorFlowRequestActionType.INIT.raw_encrypted (dict[str, str]) β The raw-encrypted data of the request.
- respond(screen: str | None = None, data: dict[str, str | int | float | bool | dict | DataSource | Iterable[str | int | float | bool | dict | DataSource]] = None, error_message: str | None = None, close_flow: bool = False, flow_token: str | None = None, version: str | None = None) FlowResponse#
Create a response for this request.
A shortcut for initializing a
FlowResponsewith the same version as this request.
Example
>>> wa = WhatsApp(business_private_key="...", ...) >>> @wa.on_flow_request("/my-flow-endpoint") ... def my_flow_endpoint(_: WhatsApp, req: FlowRequest) -> FlowResponse: ... return req.respond( ... screen="SCREEN_ID", ... data={"key": "value"}, ... )
- Parameters:
screen β The screen to display (if
close_flowisFalse).data β The data to send to the screen or to add to flow completion message (default to empty dict).
error_message β This will redirect the user to
screenand will trigger a snackbar error with the error_message present (ifclose_flowisFalse).close_flow β Whether to close the flow or just navigate to the screen.
flow_token β The flow token to close the flow (if
close_flowisTrue).version β The version of the data exchange (Default to the request version).
- property has_error: bool#
Check if the request has an error. When True, if flow endpoint register with
acknowledge_errors=True, pywa will acknowledge the error and ignore the response from the callback. The callback still be called.
- property is_health_check: bool#
Check if the request is a health check. When True, if flow endpoint register with
handle_health_check=True, pywa will not call the callback and will return a health check response.
- decrypt_media(key: str, index: int = 0, dl_session: Client | None = None) tuple[str, str, bytes]#
Decrypt the encrypted media file from the flow request.
Example
>>> from pywa import WhatsApp, types >>> wa = WhatsApp(...) >>> @wa.on_flow_request("/my-flow-endpoint") ... def my_flow_endpoint(_: WhatsApp, req: types.FlowRequest): ... media_id, filename, decrypted_data = req.decrypt_media(key="driver_license", index=0) ... with open(filename, "wb") as file: ... file.write(decrypted_data) ... return req.respond(...)
- Parameters:
key β The key of the media in the data (e.g.
"driver_license").index β The index of the media in the data (default to
0).dl_session β The HTTPX client session to download the media (optional, new session will be created if not provided).
- class pywa.types.flows.FlowRequestActionType#
The type the action that triggered the
FlowRequest.- Variables:
INIT β if the request is triggered when opening the flow (The
FlowButtonwas sent with flow_action_type set toFlowActionType.DATA_EXCHANGE)BACK β if the request is triggered when pressing back (The screen has
refresh_on_backset toTrue)DATA_EXCHANGE β if the request is triggered when submitting the screen (And the
Actionname isFlowActionType.DATA_EXCHANGE)PING β if the request is triggered by a health check (Ignore this requests by leaving
handle_health_checktoTrue)NAVIGATE β if the
FlowButtonsent withFlowActionType.NAVIGATEand the screen is not in the routing model (the request will contain an error)
- class pywa.types.flows.FlowResponse#
Represents a flow data exchange response. This response is sent to the flow endpoint to determine the next screen to display or to close the flow. You should return this response from your flow endpoint callback.
Read more at developers.facebook.com.
Use the
FlowRequest.respond()method to create a response for a request with the same version.
Example
>>> from pywa import WhatsApp >>> from pywa.types import FlowResponse
>>> wa = WhatsApp(business_private_key="...", ...) >>> @wa.on_flow_request("/my-flow-endpoint") ... def my_flow_endpoint(_: WhatsApp, req: FlowRequest) -> FlowResponse: ... return req.respond( ... screen="SCREEN_ID", ... data={"key": "value"}, ... )
- Variables:
version (str) β The version of the data exchange (You can use the same version as the request (
request.version)).screen (str | None) β The screen to display (if the flow is not closed).
data (dict[str, str | int | float | bool | dict | pywa.types.flows.DataSource | Iterable[str | int | float | bool | dict | pywa.types.flows.DataSource]]) β The data to send to the screen or to add to flow completion message (default to empty dict).
error_message (str | None) β This will redirect the user to
screenand will trigger a snackbar error with the error_message present (if the flow is not closed).flow_token (str | None) β The flow token to close the flow (if
close_flowisTrue).close_flow (bool) β Whether to close the flow or just navigate to the screen.
- class pywa.types.flows.FlowCategory#
The category of the flow
- Variables:
SIGN_UP β Sign up
SIGN_IN β Sign in
APPOINTMENT_BOOKING β Appointment booking
LEAD_GENERATION β Lead generation
CONTACT_US β Contact us
CUSTOMER_SUPPORT β Customer support
SURVEY β Survey
OTHER β Other
- class pywa.types.flows.FlowDetails#
Represents the details of a flow.
Read more at developers.facebook.com.
- Variables:
id (str) β The unique ID of the Flow.
name (str) β The user-defined name of the Flow which is not visible to users.
status (FlowStatus) β The status of the flow.
updated_at (datetime.datetime | None) β The last time the flow was updated (name, categories, endpoint_uri, json, etc.).
json_version (str | None) β The version specified by the developer in the Flow JSON asset uploaded.
data_api_version (str | None) β The version of the Data API specified by the developer in the Flow JSON asset uploaded. Only for Flows with an Endpoint.
categories (tuple[FlowCategory, ...]) β The categories of the flow.
validation_errors (tuple[FlowValidationError, ...] | None) β The validation errors of the flow (All errors must be fixed before the Flow can be published).
endpoint_uri (str | None) β The URL of the WA Flow Endpoint specified by the developer via API or in the Builder UI (Was
data_channel_uribefore v19.0).preview (FlowPreview | None) β The URL to the web preview page to visualize the flow and its expiry time.
whatsapp_business_account (WhatsAppBusinessAccount | None) β The WhatsApp Business Account which owns the Flow.
application (FacebookApplication | None) β The Facebook developer application used to create the Flow initially.
health_status (dict | None) β A summary of the Flows health status.
- publish() bool#
- Update the status of this flow to
FlowStatus.PUBLISHED. A shortcut for
pywa.client.WhatsApp.publish_flow().
This action is not reversible.
The Flow and its assets become immutable once published.
To update the Flow after that, you must create a new Flow. You specify the existing Flow ID as the clone_flow_id parameter while creating to copy the existing flow.
You can publish your Flow once you have ensured that:
All validation errors and publishing checks have been resolved.
The Flow meets the design principles of WhatsApp Flows
The Flow complies with WhatsApp Terms of Service, the WhatsApp Business Messaging Policy and, if applicable, the WhatsApp Commerce Policy
- Returns:
Whether the flow was published.
- Raises:
FlowPublishingError β If this flow has validation errors or not all publishing checks have been resolved.
- Update the status of this flow to
- delete() bool#
- When the flow is in
FlowStatus.DRAFTstatus, you can delete it. A shortcut for
pywa.client.WhatsApp.delete_flow().
- Returns:
Whether the flow was deleted.
- Raises:
FlowDeletingError β If this flow is already published.
- When the flow is in
- deprecate() bool#
- When the flow is in
FlowStatus.PUBLISHEDstatus, you can only deprecate it. A shortcut for
pywa.client.WhatsApp.deprecate_flow().
- Returns:
Whether the flow was deprecated.
- Raises:
FlowDeprecatingError β If this flow is not published or already deprecated.
- When the flow is in
- get_assets() tuple[FlowAsset, ...]#
- Get all assets attached to this flow.
A shortcut for
pywa.client.WhatsApp.get_flow_assets().
- Returns:
The assets of the flow.
- update_metadata(name: str | None = None, categories: Iterable[FlowCategory | str] | None = None, endpoint_uri: str | None = None, application_id: int | None = None) bool#
- Update the metadata of this flow.
A shortcut for
pywa.client.WhatsApp.update_flow_metadata().
- Parameters:
name β The name of the flow (optional).
categories β The new categories of the flow (optional).
endpoint_uri β The URL of the FlowJSON Endpoint. Starting from FlowJSON 3.0 this property should be specified only gere. Do not provide this field if you are cloning a FlowJSON with version below 3.0.
application_id β The ID of the Meta application which will be connected to the Flow. All the flows with endpoints need to have an Application connected to them.
Example
>>> from pywa.types.flows import FlowCategory >>> wa = WhatsApp(business_account_id='1234567890', ...) >>> my_flows = wa.get_flows() >>> my_flows[0].update_metadata( ... name='Feedback', ... categories=[FlowCategory.SURVEY, FlowCategory.OTHER], ... endpoint_uri='https://my-api-server/feedback_flow' ... )
- Returns:
Whether the flow was updated.
- Raises:
ValueError β If neither
name,categoriesorendpoint_uriis provided.
- update_json(flow_json: FlowJSON | dict | str | Path | bytes | BinaryIO) bool#
- Update the json of this flow.
A shortcut for
pywa.client.WhatsApp.update_flow_json().
- Parameters:
flow_json β The new json of the flow. Can be a
FlowJSONobject,dict, jsonstr, json file path or json bytes.- Returns:
Whether the flow was updated.
- Raises:
FlowUpdatingError β If the flow json is invalid or this flow is already published.
- class pywa.types.flows.FlowStatus#
The status of the flow
- Variables:
DRAFT β This is the initial status. The Flow is still under development. The Flow can only be sent with βmodeβ: βdraftβ for testing.
PUBLISHED β The Flow has been marked as published by the developer so now it can be sent to customers. This Flow cannot be deleted or updated afterwards.
DEPRECATED β The developer has marked the Flow as deprecated (since it cannot be deleted after publishing). This prevents sending and opening the Flow, to allow the developer to retire their endpoint. Deprecated Flows cannot be deleted or deprecated.
BLOCKED β Monitoring detected that the endpoint is unhealthy and set the status to Blocked. The Flow cannot be sent or opened in this state; the developer needs to fix the endpoint to get it back to Published state (more details in Flows Health and Monitoring).
THROTTLED β
Monitoring detected that the endpoint is unhealthy and set the status to Throttled. Flows with throttled status can be opened, however only 10 messages of the Flow could be sent per hour. The developer needs to fix the endpoint to get it back to the PUBLISHED state (more details in Flows Health and Monitoring on developers.facebook.com).
- class pywa.types.flows.FlowPreview#
Represents the preview of a flow.
- Variables:
url (str) β The URL to the preview.
expires_at (datetime.datetime) β The expiration date of the preview.
- class pywa.types.flows.FlowValidationError#
Represents a validation error of a
FlowJSON.- Variables:
error (str) β The error code.
error_type (str) β The type of the error.
message (str) β The error message.
line_start (int) β The start line of the error.
line_end (int) β The end line of the error.
column_start (int) β The start column of the error.
column_end (int) β The end column of the error.
- class pywa.types.flows.FlowAsset#
Represents an asset in a flow.
Read more at developers.facebook.com.
- class pywa.types.flows.FlowMetricName#
The name of the metric
See Available Metrics.
- Variables:
ENDPOINT_REQUEST_COUNT β Flow endpoint request count.
ENDPOINT_REQUEST_ERROR β Flow endpoint errors.
ENDPOINT_REQUEST_ERROR_RATE β Flow endpoint request error rate.
ENDPOINT_REQUEST_LATENCY_SECONDS_CEIL β Flow endpoint latency in seconds.
ENDPOINT_AVAILABILITY β Flow endpoint request error rate.
- class pywa.types.flows.FlowMetricGranularity#
The granularity of the metric
- Variables:
DAY β Daily granularity.
HOUR β Hourly granularity.
LIFETIME β Lifetime granularity.
- class pywa.types.flows.FlowResponseError#
Bases:
ExceptionBase class for all flow response errors
Subclass this exception to return or raise from the flow endpoint callback (@wa.on_flow_request).
Override the
status_codeattribute to set the status code of the response.Override the
bodyattribute to set the body of the response (optional).
- class pywa.types.flows.FlowTokenNoLongerValid#
Bases:
FlowResponseErrorThis exception need to be returned or raised from the flow endpoint callback when the Flow token is no longer valid.
Example
>>> from pywa.types.flows import FlowTokenNoLongerValid >>> wa = WhatsApp(...) >>> @wa.on_flow_request("/my-flow-endpoint") ... def my_flow_endpoint(wa: WhatsApp, req: FlowRequest) -> FlowResponse: ... if req.flow_token == "123": # you see the token is no longer valid ... # wa.send_message(..., buttons=FlowButton(...)) # resend the flow? ... raise FlowTokenNoLongerValid(error_message='Open the flow again to continue.') ... ...
The layout will be closed and the
FlowButtonwill be disabled for the user.You can send a new message to the user generating a new Flow token.
This action may be used to prevent users from initiating the same Flow again.
You are able to set an error message to display to the user. e.g. βThe order has already been placedβ
- class pywa.types.flows.FlowRequestSignatureAuthenticationFailed#
Bases:
FlowResponseErrorThis exception need to be returned or raised from the flow endpoint callback when the request signature authentication fails.
A generic error will be shown on the client.
- pywa.utils.FlowRequestDecryptor#
Type hint for the function that decrypts the request from WhatsApp Flow.
All parameters need to be positional.
See
default_flow_request_decryptor()source code for an example.
- Parameters:
- Returns:
tuple[dict, bytes, bytes] - decrypted_data (dict): decrypted data from the request - aes_key (bytes): AES key you should use to encrypt the response - iv (bytes): initial vector you should use to encrypt the response
- pywa.utils.FlowResponseEncryptor#
Type hint for the function that encrypts the response to WhatsApp Flow.
All parameters need to be positional.
See
default_flow_response_encryptor()source code for an example.
- pywa.utils.default_flow_request_decryptor(encrypted_flow_data_b64: str, encrypted_aes_key_b64: str, initial_vector_b64: str, private_key: str, password: str = None) tuple[dict, bytes, bytes]#
The default global decryption function for decrypting data exchange requests from WhatsApp Flow.
This implementation follows the
FlowRequestDecryptortype hint.This implementation requires
cryptographyto be installed. To install it, runpip3 install 'pywa[cryptography]'orpip3 install cryptography.This implementation was taken from the official documentation at developers.facebook.com.
Example
Set the default global decryptor (This is indeed the default):
>>> from pywa.utils import default_flow_request_decryptor >>> from pywa import WhatsApp >>> wa = WhatsApp(flows_request_decryptor=default_flow_request_decryptor, ...)
Set the decryptor for a specific flow:
>>> from pywa import WhatsApp >>> from pywa.types.flows import FlowRequest, FlowResponse >>> from pywa.utils import default_flow_request_decryptor >>> wa = WhatsApp(...) >>> @wa.on_flow_request("/sign-up-flow", request_decryptor=default_flow_request_decryptor) ... def on_sign_up_request(_: WhatsApp, flow: FlowRequest) -> FlowResponse | None: ...
- pywa.utils.default_flow_response_encryptor(response: dict, aes_key: bytes, iv: bytes) str#
The default global encryption function for encrypting data exchange responses to WhatsApp Flow.
This implementation follows the
FlowResponseEncryptortype hint.This implementation requires
cryptographyto be installed. To install it, runpip3 install 'pywa[cryptography]'orpip3 install cryptography.This implementation was taken from the official documentation at developers.facebook.com.
Example
Set the default global encryptor (This is indeed the default):
>>> from pywa.utils import default_flow_response_encryptor >>> from pywa import WhatsApp >>> wa = WhatsApp(flows_response_encryptor=default_flow_response_encryptor, ...)
Set the encryptor for a specific flow:
>>> from pywa import WhatsApp >>> from pywa.types.flows import FlowRequest, FlowResponse >>> from pywa.utils import default_flow_response_encryptor >>> wa = WhatsApp(...) >>> @wa.on_flow_request("/sign-up-flow", response_encryptor=default_flow_response_encryptor) ... def on_sign_up_request(_: WhatsApp, flow: FlowRequest) -> FlowResponse | None: ...
- pywa.utils.flow_request_media_decryptor(encrypted_media: dict[str, str | dict[str, str]], dl_session: Client | None = None) tuple[str, str, bytes]#
Decrypt the encrypted media file from the flow request.
Read more at developers.facebook.com.
Use the .decrypt_media() s
This implementation requires
cryptographyto be installed. To install it, runpip3 install 'pywa[cryptography]'orpip3 install cryptography.
Example
>>> from pywa import WhatsApp, types >>> wa = WhatsApp(...) >>> @wa.on_flow_request("/media-upload") ... def on_media_upload_request(_: WhatsApp, req: types.FlowRequest) -> types.FlowResponse | None: ... media_id, filename, decrypted_data = req.decrypt_media(key="driver_license", index=0) ... with open(filename, "wb") as file: ... file.write(decrypted_data) ... return req.respond(...)
- Parameters:
encrypted_media (dict) β encrypted media data from the flow request (see example above).
dl_session (httpx.Client) β download session. Optional.
- Returns:
tuple[str, str, bytes] - media_id (str): media ID - filename (str): media filename - decrypted_data (bytes): decrypted media file
- Raises:
HTTPStatusError β If the request to the CDN URL fails.
ValueError β If any of the hash verifications fail.
- class pywa.handlers.FlowRequestCallbackWrapper(wa: WhatsApp, endpoint: str, callback: _FlowRequestHandlerT, acknowledge_errors: bool = True, handle_health_check: bool = True, private_key: str | None = None, private_key_password: str | None = None, request_decryptor: utils.FlowRequestDecryptor | None = None, response_encryptor: utils.FlowResponseEncryptor | None = None)#
This is a wrapper class for the flow request callback. It allows you to add more handlers to the same endpoint and split the logic into multiple functions.
THIS CLASS IS NOT MEANT TO BE INSTANTIATED DIRECTLY!
- on(*, action: FlowRequestActionType, screen: Screen | str | None = None, filters: Filter = None) Callable[[_FlowRequestHandlerT], _FlowRequestHandlerT]#
Decorator to help you add more handlers to the same endpoint and split the logic into multiple functions.
Example
>>> wa = WhatsApp(...) >>> @wa.on_flow_request("/feedback_flow") >>> def feedback_flow_handler(_: WhatsApp, req: FlowRequest): ... if req.has_error: print(req.data) >>> @feedback_flow_handler.on(action=FlowRequestActionType.INIT) >>> def on_init(_: WhatsApp, req: FlowRequest): ... ... >>> @feedback_flow_handler.on(action=FlowRequestActionType.DATA_EXCHANGE, screen="SURVEY") >>> def on_survey_data_exchange(_: WhatsApp, req: FlowRequest): ... ... >>> @feedback_flow_handler.on(..., data_filter=filters.new(lambda _, data: data.get("rating") == 5)) >>> def on_rating_5(_: WhatsApp, req: FlowRequest): ... ...
- Parameters:
action β The action type to listen to.
screen β The screen ID to listen to (if screen is not provided, the handler will be called for all screens for this action!).
filters β A filter function to apply to the incoming request.
- Returns:
The function itself.
- on_errors(clb=typing.Callable[[ForwardRef('WhatsApp'), pywa.types.flows.FlowRequest], typing.Union[pywa.types.flows.FlowResponse, pywa.types.flows.FlowResponseError, dict, NoneType, typing.Awaitable[pywa.types.flows.FlowResponse | pywa.types.flows.FlowResponseError | dict | None]]]) Callable[[_FlowRequestHandlerT], _FlowRequestHandlerT]#
Decorator to add an error handler to the current endpoint.
Shortcut for
set_errors_handler().
Example
>>> wa = WhatsApp(...) >>> @wa.on_flow_request("/feedback_flow") >>> def feedback_flow_handler(_: WhatsApp, req: FlowRequest): ... ... >>> @feedback_flow_handler.on_errors >>> def on_error(_: WhatsApp, req: FlowRequest): ... logging.error("An error occurred: %s", req.data)
- Returns:
The function itself.
- add_handler(*, callback: _FlowRequestHandlerT, action: FlowRequestActionType, screen: Screen | str | None = None, filters: Filter = None) FlowRequestCallbackWrapper#
Add a handler to the current endpoint.
You can add multiple handlers to the same endpoint and split the logic into multiple functions.
Example
>>> wa = WhatsApp(...) >>> def feedback_flow_handler(_: WhatsApp, req: FlowRequest): ... ... >>> on_init = lambda _, req: ... >>> on_survey_data_exchange = lambda _, req: ... >>> wa.add_flow_request_handler( ... FlowRequestHandler(callback=feedback_flow_handler, endpoint="/feedback_flow") ... ).add_handler(callback=on_init, action=FlowRequestActionType.INIT) ... .add_handler(callback=on_survey_data_exchange, action=FlowRequestActionType.DATA_EXCHANGE, screen="SURVEY")
- Parameters:
callback β The callback function to handle this particular request.
action β The action type to listen to.
screen β The screen ID to listen to (if screen is not provided, the handler will be called for all screens for this action!).
filters β A filter function to apply to the incoming request.
- Returns:
The current instance.
- set_errors_handler(callback: _FlowRequestHandlerT) FlowRequestCallbackWrapper#
Add an error handler to the current endpoint.
Example
>>> wa = WhatsApp(...) >>> def feedback_flow_handler(_: WhatsApp, req: FlowRequest): ... ... >>> def on_error(_: WhatsApp, req: FlowRequest): ... logging.error("An error occurred: %s", req.data) >>> wa.add_flow_request_handler( ... FlowRequestHandler(callback=feedback_flow_handler, endpoint="/feedback_flow") ... ).set_errors_handler(callback=on_error) ...
- Parameters:
callback β The callback function to handle errors.
- Returns:
The current instance.
- Raises:
ValueError β If an error handler is already set for this endpoint.