Handler Decorators#

WhatsApp.on_message(filters: Filter = None, priority: int = 0) Callable[[_MessageCallback], _MessageCallback] | _MessageCallback#

Decorator to register a function as a callback for incoming Message.

Example

>>> from pywa import WhatsApp, types, filters
>>> wa = WhatsApp(...)
>>> @wa.on_message(filters.matches("Hello", "Hi", ignore_case=True))
... def hello_handler(_: WhatsApp, msg: types.Message):
...     msg.react("πŸ‘‹")
...     msg.reply_text(text="Hello from PyWa!", quote=True)
Parameters:
  • filters – Filters to apply to the incoming messages.

  • priority – The priority of the handler (default: 0).

WhatsApp.on_callback_button(filters: Filter = None, factory: type[CallbackData] | None = None, priority: int = 0) Callable[[_CallbackButtonCallback], _CallbackButtonCallback] | _CallbackButtonCallback#

Decorator to register a function as a callback for incoming CallbackButton (when a user clicks on a Button or QuickReplyButton).

Example

>>> from pywa import WhatsApp, types, filters
>>> wa = WhatsApp(...)
>>> @wa.on_callback_button(filters.matches("help"))
... def help_handler(_: WhatsApp, btn: types.CallbackButton):
...     btn.reply_text(text="What can I help you with?")
Parameters:
  • filters – Filters to apply to the incoming callback button presses.

  • factory – The CallbackData subclass to use to construct the callback data.

  • priority – The priority of the handler (default: 0).

WhatsApp.on_callback_selection(filters: Filter = None, factory: type[CallbackData] | None = None, priority: int = 0) Callable[[_CallbackSelectionCallback], _CallbackSelectionCallback] | _CallbackSelectionCallback#

Decorator to register a function as a callback for incoming CallbackSelection (when a user selects an SectionRow from a SectionList.).

Example

>>> from pywa import WhatsApp, types, filters
>>> wa = WhatsApp(...)
>>> @wa.on_callback_selection(filters.startswith("id:"))
... def id_handler(_: WhatsApp, sel: types.CallbackSelection):
...     sel.reply_text(text=f"Your ID is {sel.data.split(':', 1)[1]}")
Parameters:
  • filters – Filters to apply to the incoming callback selections.

  • factory – The CallbackData subclass to use to construct the callback data.

  • priority – The priority of the handler (default: 0).

WhatsApp.on_flow_completion(filters: Filter = None, priority: int = 0) Callable[[_FlowCompletionCallback], _FlowCompletionCallback] | _FlowCompletionCallback#

Decorator to register a function as a callback for FlowCompletion updates (FlowButton is completed).

Example

>>> from pywa import WhatsApp, types
>>> wa = WhatsApp(...)
>>> @wa.on_flow_completion
... def flow_handler(client: WhatsApp, flow: types.FlowCompletion):
...     print(f"Flow {flow.token} just got completed!. Flow data: {flow.response}")
Parameters:
  • filters – Filters to apply to the incoming flow completion.

  • priority – The priority of the handler (default: 0).

WhatsApp.on_flow_request(endpoint: str = None, *, acknowledge_errors: 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) Callable[[_FlowRequestHandlerT], FlowRequestCallbackWrapper | FlowRequestHandler]#

Decorator to register a function to handle and respond to incoming FlowRequest (when a user interacts with a flow. e.g. trigger DataExchangeAction or navigates to a screen in a flow).

Example

>>> from pywa import WhatsApp, types
>>> wa = WhatsApp(business_private_key='...', ...)
>>> @wa.on_flow_request('/feedback_flow')
... def feedback_flow_handler(_: WhatsApp, req: FlowRequest) -> FlowResponse:
...     ...
>>> @feedback_flow_handler.on(types.FlowRequestActionType.DATA_EXCHANGE, screen="SURVEY")
... def survey_data_handler(_: WhatsApp, req: FlowRequest):
...     ...
Parameters:
  • endpoint – The endpoint to listen to (The endpoint uri you set to the flow. e.g /feedback_flow).

  • acknowledge_errors – Whether to acknowledge errors (The return value of the callback will be ignored, and pywa will acknowledge the error automatically).

  • private_key – The private key to use to decrypt the requests (Override the global business_private_key).

  • private_key_password – The password to use to decrypt the private key (Override the global business_private_key_password).

  • request_decryptor – The function to use to decrypt the requests (Override the global flows_request_decryptor)

  • response_encryptor – The function to use to encrypt the responses (Override the global flows_response_encryptor)

WhatsApp.on_message_status(filters: Filter = None, factory: type[CallbackData] | None = None, priority: int = 0) Callable[[_MessageStatusCallback], _MessageStatusCallback] | _MessageStatusCallback#

Decorator to register a function as a callback for incoming MessageStatus (when a message status changes, e.g. sent, delivered, read, failed).

DO NOT USE THIS HANDLER WITHOUT FILTERS TO SEND MESSAGES, IT WILL CAUSE AN INFINITE LOOP!

Example

>>> from pywa import WhatsApp, types, filters
>>> wa = WhatsApp(...)
>>> @wa.on_message_status(filters.failed)
... def delivered_handler(client: WhatsApp, status: types.MessageStatus):
...     print(f"Message {status.id} failed to send to {status.from_user.wa_id}: {status.error.message})
Parameters:
  • filters – Filters to apply to the incoming message status changes.

  • factory – The CallbackData subclass to use to construct the tracker data.

  • priority – The priority of the handler (default: 0).

WhatsApp.on_chat_opened(filters: Filter = None, priority: int = 0) Callable[[_ChatOpenedCallback], _ChatOpenedCallback] | _ChatOpenedCallback#

Decorator to register a function as a callback for incoming ChatOpened (when a user opens a chat with the business).

Example

>>> from pywa import WhatsApp, types
>>> wa = WhatsApp(...)
>>> @wa.on_chat_opened
... def chat_opened_handler(client: WhatsApp, chat_opened: types.ChatOpened):
...     print(f"The user {chat_opened.from_user.wa_id} just opened a chat with us!")
Parameters:
  • filters – Filters to apply to the incoming chat opened events.

  • priority – The priority of the handler (default: 0).

WhatsApp.on_phone_number_change(filters: Filter = None, priority: int = 0) Callable[[_PhoneNumberChangeCallback], _PhoneNumberChangeCallback] | _PhoneNumberChangeCallback#

Decorator to register a function as a callback for incoming PhoneNumberChange (when a user changes their phone number).

Example

>>> from pywa import WhatsApp, types
>>> wa = WhatsApp(...)
>>> @wa.on_phone_number_change
... def phone_number_change_handler(client: WhatsApp, phone_number_change: types.PhoneNumberChange):
...     print(f"The user {phone_number_change.from_user.wa_id} just changed their phone number to {phone_number_change.new_phone_number}!")
Parameters:
  • filters – Filters to apply to the incoming phone number change events.

  • priority – The priority of the handler (default: 0).

WhatsApp.on_identity_change(filters: Filter = None, priority: int = 0) Callable[[_IdentityChangeCallback], _IdentityChangeCallback] | _IdentityChangeCallback#

Decorator to register a function as a callback for incoming IdentityChange (when a user changes their identity).

Example

>>> from pywa import WhatsApp, types
>>> wa = WhatsApp(...)
>>> @wa.on_identity_change
... def identity_change_handler(client: WhatsApp, identity_change: types.IdentityChange):
...     print(f"The user {identity_change.from_user.wa_id} just changed their identity!: {identity_change.body}")
Parameters:
  • filters – Filters to apply to the incoming identity change events.

  • priority – The priority of the handler (default: 0).

WhatsApp.on_call_connect(filters: Filter = None, priority: int = 0) Callable[[_CallConnectCallback], _CallConnectCallback] | _CallConnectCallback#

Decorator to register a function as a callback for CallConnect updates (incoming/outgoing call).

Example

>>> from pywa import WhatsApp, types
>>> wa = WhatsApp(...)
>>> @wa.on_call_connect
... def incoming_call_handler(client: WhatsApp, call: types.CallConnect):
...     print(f"You getting an incoming call from {call.from_user.name}")
...     call.accept()
Parameters:
  • filters – Filters to apply to the incoming call connect.

  • priority – The priority of the handler (default: 0).

WhatsApp.on_call_terminate(filters: Filter = None, priority: int = 0) Callable[[_CallTerminateCallback], _CallTerminateCallback] | _CallTerminateCallback#

Decorator to register a function as a callback for CallTerminate updates (when a call is ended).

Example

>>> from pywa import WhatsApp, types
>>> wa = WhatsApp(...)
>>> @wa.on_call_terminate
... def on_hangup(client: WhatsApp, call: types.CallTerminate):
...     print(f"The call {call.from_user.name} is terminated")
Parameters:
  • filters – Filters to apply to the incoming call terminate.

  • priority – The priority of the handler (default: 0).

WhatsApp.on_call_status(filters: Filter = None, factory: type[CallbackData] | None = None, priority: int = 0) Callable[[_CallStatusCallback], _CallStatusCallback] | _CallStatusCallback#

Decorator to register a function as a callback for CallStatus updates (when a call status changes, e.g. ringing, accepted, rejected, etc.).

Example

>>> from pywa import WhatsApp, types
>>> wa = WhatsApp(...)
>>> @wa.on_call_status
... def on_status(client: WhatsApp, call: types.CallStatus):
...     print(f"The call with {call.from_user.name} is {call.status}")
Parameters:
  • filters – Filters to apply to the incoming call status.

  • factory – The constructor to use to construct the callback data.

  • priority – The priority of the handler (default: 0).

WhatsApp.on_call_permission_update(filters: Filter = None, priority: int = 0) Callable[[_CallPermissionUpdateCallback], _CallPermissionUpdateCallback] | _CallPermissionUpdateCallback#

Decorator to register a function as a callback for CallPermissionUpdate updates (when the user accepts or rejects the CallPermissionRequestButton).

Example

>>> from pywa import WhatsApp, types
>>> wa = WhatsApp(...)
>>> @wa.on_call_permission_update
... def call_permission_handler(client: WhatsApp, update: types.CallPermissionUpdate):
...     if update: # Use boolean context to check if the call permission is granted
...         update.reply("We will now be able to call you!")
...         update.call(...)
Parameters:
  • filters – Filters to apply to the incoming call permission updates.

  • priority – The priority of the handler (default: 0).

WhatsApp.on_user_marketing_preferences(filters: Filter = None, priority: int = 0) Callable[[_UserMarketingPreferencesCallback], _UserMarketingPreferencesCallback] | _UserMarketingPreferencesCallback#

Decorator to register a function as a callback for UserMarketingPreferences updates (User wants to stop or resume receiving marketing Template β€˜s).

Example

>>> from pywa import WhatsApp, types
>>> wa = WhatsApp(...)
>>> @wa.on_user_marketing_preferences
... def user_marketing_preferences_handler(client: WhatsApp, prefs: types.UserMarketingPreferences):
...     if not prefs: # use boolean context to check if the user wants to stop receiving marketing messages
...         print(f"The user {prefs.from_user.wa_id} wants to stop receiving marketing messages.")
Parameters:
  • filters – Filters to apply to the incoming user marketing preferences updates.

  • priority – The priority of the handler (default: 0).

WhatsApp.on_template_status_update(filters: Filter = None, priority: int = 0) Callable[[_TemplateStatusUpdateCallback], _TemplateStatusUpdateCallback] | _TemplateStatusUpdateCallback#

Decorator to register a function as a callback for TemplateStatusUpdate updates (Template status changed, e.g. approved, rejected, etc.).

Example

>>> from pywa import WhatsApp, types, filters
>>> wa = WhatsApp(...)
>>> @wa.on_template_status_update
... def approved_handler(client: WhatsApp, update: types.TemplateStatusUpdate):
...     print(f"Template {update.template_name} just got {update.new_status}!")
Parameters:
  • filters – Filters to apply to the incoming template status changes.

  • priority – The priority of the handler (default: 0).

WhatsApp.on_template_category_update(filters: Filter = None, priority: int = 0) Callable[[_TemplateCategoryUpdateCallback], _TemplateCategoryUpdateCallback] | _TemplateCategoryUpdateCallback#

Decorator to register a function as a callback for templatesCategoryUpdate updates (Template category changed, e.g. from UTILITY to MARKETING).

Example

>>> from pywa import WhatsApp, types, filters
>>> wa = WhatsApp(...)
>>> @wa.on_template_category_update
... def category_update_handler(client: WhatsApp, update: types.TemplateCategoryUpdate):
...     print(f"Template {update.template_name} category changed from {update.previous_category} to {update.new_category}!")
Parameters:
  • filters – Filters to apply to the incoming template category changes.

  • priority – The priority of the handler (default: 0).

WhatsApp.on_template_quality_update(filters: Filter = None, priority: int = 0) Callable[[_TemplateQualityUpdateCallback], _TemplateQualityUpdateCallback] | _TemplateQualityUpdateCallback#

Decorator to register a function as a callback for TemplateQualityUpdate updates (Template quality changed).

Example

>>> from pywa import WhatsApp, types, filters
>>> wa = WhatsApp(...)
>>> @wa.on_template_quality_update
... def quality_update_handler(client: WhatsApp, update: types.TemplateQualityUpdate):
...     print(f"Template {update.template_name} quality changed to {update.new_quality_score}!")
Parameters:
  • filters – Filters to apply to the incoming template quality changes.

  • priority – The priority of the handler (default: 0).

WhatsApp.on_template_components_update(filters: Filter = None, priority: int = 0) Callable[[_TemplateComponentsUpdateCallback], _TemplateComponentsUpdateCallback] | _TemplateComponentsUpdateCallback#

Decorator to register a function as a callback for pywa.types.templates.TemplateComponentsUpdate updates (Template components changed).

Example

>>> from pywa import WhatsApp, types, filters
>>> wa = WhatsApp(...)
>>> @wa.on_template_components_update
... def components_update_handler(client: WhatsApp, update: types.TemplateComponentsUpdate):
...     print(f"Template {update.template_name} components updated!")
Parameters:
  • filters – Filters to apply to the incoming template components changes.

  • priority – The priority of the handler (default: 0).

WhatsApp.on_raw_update(filters: Filter = None, priority: int = 0) Callable[[_RawUpdateCallback], _RawUpdateCallback] | _RawUpdateCallback#

Decorator to register a function as a callback for raw updates (dict).

  • This callback is called for EVERY update received from WhatsApp, even if it’s not sent to the client phone number.

  • Shortcut for add_handlers() with a RawUpdateHandler.

Example

>>> wa = WhatsApp(...)
>>> @wa.on_raw_update
... def raw_update_handler(_: WhatsApp, update: dict):
...     print(update)
Parameters:
  • filters – Filters to apply to the incoming updates.

  • priority – The priority of the handler (default: 0).

WhatsApp.remove_callbacks(*callbacks: Callable[[WhatsApp, Any], Any]) None#

Remove callbacks programmatically (not flow callbacks).

Example

>>> from pywa.handlers import MessageHandler, CallbackButtonHandler
>>> from pywa import filters as fil
>>> wa = WhatsApp(...)
>>> @wa.on_message(fil.text)
... def message_handler(_: WhatsApp, msg: Message): print(msg)
>>> wa.remove_callbacks(message_handler)
Parameters:

callbacks – The callbacks to remove.

WhatsApp.load_handlers_modules(*modules: ModuleType) None#

Load handlers from modules.

Example

my_handlers.py#
1from pywa import WhatsApp, types, filters as fil
2
3@WhatsApp.on_message(fil.text)
4def on_text_message(wa: WhatsApp, msg: types.Message):
5    ...
6
7@WhatsApp.on_callback_button
8def on_callback_button(wa: WhatsApp, msg: types.CallbackButton):
9    ...
main.py#
1from pywa import WhatsApp
2from . import my_handlers
3
4wa = WhatsApp(..., handlers_modules=[my_handlers])