Handler Decorators#
- WhatsApp.on_message(filters=None, priority=0)#
Decorator to register a function as a callback for incoming
Message.Shortcut for
add_handlers()with aMessageHandler.
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 (Filter) – Filters to apply to the incoming messages.
priority (int) – The priority of the handler (default:
0).
- Return type:
Callable[[_MessageCallback], _MessageCallback] | _MessageCallback
- WhatsApp.on_callback_button(filters=None, factory=None, priority=0)#
Decorator to register a function as a callback for incoming
CallbackButton(when a user clicks on aButtonorQuickReplyButton).Shortcut for
add_handlers()with aCallbackButtonHandler.
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 (Filter) – Filters to apply to the incoming callback button presses.
factory (type[CallbackData] | None) – The
CallbackDatasubclass to use to construct the callback data.priority (int) – The priority of the handler (default:
0).
- Return type:
Callable[[_CallbackButtonCallback], _CallbackButtonCallback] | _CallbackButtonCallback
- WhatsApp.on_callback_selection(filters=None, factory=None, priority=0)#
Decorator to register a function as a callback for incoming
CallbackSelection(when a user selects anSectionRowfrom aSectionList.).Shortcut for
add_handlers()with aCallbackSelectionHandler.
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 (Filter) – Filters to apply to the incoming callback selections.
factory (type[CallbackData] | None) – The
CallbackDatasubclass to use to construct the callback data.priority (int) – The priority of the handler (default:
0).
- Return type:
Callable[[_CallbackSelectionCallback], _CallbackSelectionCallback] | _CallbackSelectionCallback
- WhatsApp.on_flow_completion(filters=None, priority=0)#
Decorator to register a function as a callback for
FlowCompletionupdates (FlowButtonis completed).Shortcut for
add_handlers()with aFlowCompletionHandler.
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 (Filter) – Filters to apply to the incoming flow completion.
priority (int) – The priority of the handler (default:
0).
- Return type:
Callable[[_FlowCompletionCallback], _FlowCompletionCallback] | _FlowCompletionCallback
- WhatsApp.on_flow_request(endpoint=None, *, acknowledge_errors=True, private_key=None, private_key_password=None, request_decryptor=None, response_encryptor=None)#
Decorator to register a function to handle and respond to incoming
FlowRequest(when a user interacts with a flow. e.g. triggerDataExchangeActionor navigates to a screen in a flow).Shortcut for
add_handlers()with aFlowRequestHandler.
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 (str) – The endpoint to listen to (The endpoint uri you set to the flow. e.g
/feedback_flow).acknowledge_errors (bool) – Whether to acknowledge errors (The return value of the callback will be ignored, and pywa will acknowledge the error automatically).
private_key (str | None) – The private key to use to decrypt the requests (Override the global
business_private_key).private_key_password (str | None) – The password to use to decrypt the private key (Override the global
business_private_key_password).request_decryptor (utils.FlowRequestDecryptor | None) – The function to use to decrypt the requests (Override the global
flows_request_decryptor)response_encryptor (utils.FlowResponseEncryptor | None) – The function to use to encrypt the responses (Override the global
flows_response_encryptor)
- Return type:
Callable[[_FlowRequestHandlerT], FlowRequestCallbackWrapper | FlowRequestHandler]
- WhatsApp.on_message_status(filters=None, factory=None, priority=0)#
Decorator to register a function as a callback for incoming
MessageStatus(when a message status changes, e.g.sent,delivered,read,failed).Shortcut for
add_handlers()with aMessageStatusHandler.
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 (Filter) – Filters to apply to the incoming message status changes.
factory (type[CallbackData] | None) – The
CallbackDatasubclass to use to construct thetrackerdata.priority (int) – The priority of the handler (default:
0).
- Return type:
Callable[[_MessageStatusCallback], _MessageStatusCallback] | _MessageStatusCallback
- WhatsApp.on_phone_number_change(filters=None, priority=0)#
Decorator to register a function as a callback for incoming
PhoneNumberChange(when a user changes their phone number).Shortcut for
add_handlers()with aPhoneNumberChangeHandler.
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 (Filter) – Filters to apply to the incoming phone number change events.
priority (int) – The priority of the handler (default:
0).
- Return type:
Callable[[_PhoneNumberChangeCallback], _PhoneNumberChangeCallback] | _PhoneNumberChangeCallback
- WhatsApp.on_identity_change(filters=None, priority=0)#
Decorator to register a function as a callback for incoming
IdentityChange(when a user changes their identity).Shortcut for
add_handlers()with aIdentityChangeHandler.
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 (Filter) – Filters to apply to the incoming identity change events.
priority (int) – The priority of the handler (default:
0).
- Return type:
Callable[[_IdentityChangeCallback], _IdentityChangeCallback] | _IdentityChangeCallback
- WhatsApp.on_call_connect(filters=None, priority=0)#
Decorator to register a function as a callback for
CallConnectupdates (incoming/outgoing call).Shortcut for
add_handlers()with aCallConnectHandler.
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 (Filter) – Filters to apply to the incoming call connect.
priority (int) – The priority of the handler (default:
0).
- Return type:
Callable[[_CallConnectCallback], _CallConnectCallback] | _CallConnectCallback
- WhatsApp.on_call_terminate(filters=None, priority=0)#
Decorator to register a function as a callback for
CallTerminateupdates (when a call is ended).Shortcut for
add_handlers()with aCallTerminateHandler.
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 (Filter) – Filters to apply to the incoming call terminate.
priority (int) – The priority of the handler (default:
0).
- Return type:
Callable[[_CallTerminateCallback], _CallTerminateCallback] | _CallTerminateCallback
- WhatsApp.on_call_status(filters=None, factory=None, priority=0)#
Decorator to register a function as a callback for
CallStatusupdates (when a call status changes, e.g.ringing,accepted,rejected, etc.).Shortcut for
add_handlers()with aCallStatusHandler.
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 (Filter) – Filters to apply to the incoming call status.
factory (type[CallbackData] | None) – The constructor to use to construct the callback data.
priority (int) – The priority of the handler (default:
0).
- Return type:
Callable[[_CallStatusCallback], _CallStatusCallback] | _CallStatusCallback
- WhatsApp.on_call_permission_update(filters=None, priority=0)#
Decorator to register a function as a callback for
CallPermissionUpdateupdates (when the user accepts or rejects theCallPermissionRequestButton).Shortcut for
add_handlers()with aCallPermissionUpdateHandler.
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 (Filter) – Filters to apply to the incoming call permission updates.
priority (int) – The priority of the handler (default:
0).
- Return type:
Callable[[_CallPermissionUpdateCallback], _CallPermissionUpdateCallback] | _CallPermissionUpdateCallback
- WhatsApp.on_user_marketing_preferences(filters=None, priority=0)#
Decorator to register a function as a callback for
UserMarketingPreferencesupdates (User wants to stop or resume receiving marketingTemplate‘s).Shortcut for
add_handlers()with aUserMarketingPreferencesHandler.
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 (Filter) – Filters to apply to the incoming user marketing preferences updates.
priority (int) – The priority of the handler (default:
0).
- Return type:
Callable[[_UserMarketingPreferencesCallback], _UserMarketingPreferencesCallback] | _UserMarketingPreferencesCallback
- WhatsApp.on_template_status_update(filters=None, priority=0)#
Decorator to register a function as a callback for
TemplateStatusUpdateupdates (Template status changed, e.g.approved,rejected, etc.).Shortcut for
add_handlers()with aTemplateStatusUpdateHandler.
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 (Filter) – Filters to apply to the incoming template status changes.
priority (int) – The priority of the handler (default:
0).
- Return type:
Callable[[_TemplateStatusUpdateCallback], _TemplateStatusUpdateCallback] | _TemplateStatusUpdateCallback
- WhatsApp.on_template_category_update(filters=None, priority=0)#
Decorator to register a function as a callback for
templatesCategoryUpdateupdates (Template category changed, e.g. fromUTILITYtoMARKETING).Shortcut for
add_handlers()with aTemplateCategoryUpdateHandler.
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 (Filter) – Filters to apply to the incoming template category changes.
priority (int) – The priority of the handler (default:
0).
- Return type:
Callable[[_TemplateCategoryUpdateCallback], _TemplateCategoryUpdateCallback] | _TemplateCategoryUpdateCallback
- WhatsApp.on_template_quality_update(filters=None, priority=0)#
Decorator to register a function as a callback for
TemplateQualityUpdateupdates (Template quality changed).Shortcut for
add_handlers()with aTemplateQualityUpdateHandler.
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 (Filter) – Filters to apply to the incoming template quality changes.
priority (int) – The priority of the handler (default:
0).
- Return type:
Callable[[_TemplateQualityUpdateCallback], _TemplateQualityUpdateCallback] | _TemplateQualityUpdateCallback
- WhatsApp.on_template_components_update(filters=None, priority=0)#
Decorator to register a function as a callback for
TemplateComponentsUpdateupdates (Template components changed).Shortcut for
add_handlers()with aTemplateComponentsUpdateHandler.
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 (Filter) – Filters to apply to the incoming template components changes.
priority (int) – The priority of the handler (default:
0).
- Return type:
Callable[[_TemplateComponentsUpdateCallback], _TemplateComponentsUpdateCallback] | _TemplateComponentsUpdateCallback
- WhatsApp.on_raw_update(filters=None, priority=0)#
Decorator to register a function as a callback for raw updates (
RawUpdate).This callback is called for EVERY update received from WhatsApp, even if it is already handled by another handler or listener.
Shortcut for
add_handlers()with aRawUpdateHandler.
Example
>>> wa = WhatsApp(...) >>> @wa.on_raw_update ... def raw_update_handler(_: WhatsApp, update: RawUpdate): ... print(update)
- Parameters:
filters (Filter) – Filters to apply to the incoming updates.
priority (int) – The priority of the handler (default:
0).
- Return type:
Callable[[_RawUpdateCallback], _RawUpdateCallback] | _RawUpdateCallback
- WhatsApp.remove_callbacks(*callbacks)#
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)
- WhatsApp.load_handlers_modules(*modules)#
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])