From 9e536a0f16e91ea0441038e1f9db4c6fcca6e458 Mon Sep 17 00:00:00 2001 From: David Lev Date: Thu, 2 Jan 2025 23:39:24 +0200 Subject: [PATCH] [flows] adding `FlowRequest.token_no_longer_valid` shortcut --- docs/source/content/flows/flow_types.rst | 2 +- pywa/types/flows.py | 27 +++++++++++++++++++++--- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/docs/source/content/flows/flow_types.rst b/docs/source/content/flows/flow_types.rst index 08547ea..8538168 100644 --- a/docs/source/content/flows/flow_types.rst +++ b/docs/source/content/flows/flow_types.rst @@ -4,7 +4,7 @@ Flow Types .. currentmodule:: pywa.types.flows .. autoclass:: FlowRequest() - :members: has_error, is_health_check, respond, decrypt_media + :members: respond, decrypt_media, has_error, token_no_longer_valid .. autoclass:: FlowRequestActionType() diff --git a/pywa/types/flows.py b/pywa/types/flows.py index 7a1ebe6..3c92584 100644 --- a/pywa/types/flows.py +++ b/pywa/types/flows.py @@ -291,6 +291,27 @@ def respond( close_flow=close_flow, ) + def token_no_longer_valid(self, error_message: str): + """ + Raise a :class:`FlowTokenNoLongerValid` exception with the provided error message. + + Example: + + >>> wa = WhatsApp(...) + >>> @wa.on_flow_request("/my-flow-endpoint") + ... def my_flow_endpoint(_: WhatsApp, req: FlowRequest) -> FlowResponse: + ... if req.flow_token == "v1.0": # you see the token is no longer valid + ... req.token_no_longer_valid("Open the flow again to continue.") + ... ... + + Args: + error_message: The error message to display to the user. + + Raises: + FlowTokenNoLongerValid: Well, always. + """ + raise FlowTokenNoLongerValid(error_message) + @classmethod def from_dict(cls, data: dict, raw_encrypted: dict): return cls( @@ -440,7 +461,7 @@ class FlowResponseError(Exception): """ Base class for all flow response errors - + - Read more at `developers.facebook.com `_. - Subclass this exception to return or raise from the flow endpoint callback (@wa.on_flow_request). - Override the ``status_code`` attribute to set the status code of the response. - Override the ``body`` attribute to set the body of the response (optional). @@ -484,8 +505,8 @@ class FlowTokenNoLongerValid(FlowResponseError): >>> 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 + ... def my_flow_endpoint(_: WhatsApp, req: FlowRequest) -> FlowResponse: + ... if req.flow_token == "v1.0": # 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.') ... ...