Client Reference#
- WhatsApp.send_message(to, text, header=None, footer=None, buttons=None, *, preview_url=False, reply_to_message_id=None, tracker=None, identity_key_hash=None, sender=None)#
Text messages are messages containing text and an optional link preview.
You can have the WhatsApp client attempt to render a preview of the first URL in the body text string, if it contains one. URLs must begin with
http://orhttps://. If multiple URLs are in the body text string, only the first URL will be rendered. If omitted, or if unable to retrieve a link preview, a clickable link will be rendered instead.See Text messages.
See Markdown for formatting text messages.
Example
>>> wa = WhatsApp() >>> wa.send_message( ... to="1234567890", ... text="*Hello from PyWa!* (https://github.com/david-lev/pywa)", ... preview_url=True, ... )
- Parameters:
to (str | int) β The user phone number, WhatsApp ID, BSUID or group ID to send the message to.
text (str) β
The text to send (markdown allowed, max 4096 characters).
header (str | None) β
The header of the message (if
buttonsare provided, optional, up to 60 characters, no markdown allowed).footer (str | None) β
The footer of the message (if
buttonsare provided, optional, up to 60 characters, markdown has no effect).buttons (Iterable[Button] | URLButton | VoiceCallButton | CallPermissionRequestButton | ContactInfoRequestButton | SectionList | FlowButton | None) β The buttons to send with the message (optional).
preview_url (bool) β Whether to show a preview of the URL in the message (if any).
reply_to_message_id (str | None) β The message ID to quote (optional).
tracker (str | CallbackData | None) β The data to track the message with (optional, up to 512 characters, for complex data you can use
CallbackData).identity_key_hash (str | None) β The message would only be delivered if the hash value matches the customerβs current hash (Optional, See Identity Change Check).
sender (str | int | None) β The phone ID to send the message from (optional, overrides the clientβs phone ID).
- Returns:
The sent text message.
- Return type:
- WhatsApp.send_image(to, image, caption=None, footer=None, buttons=None, *, reply_to_message_id=None, mime_type=None, tracker=None, identity_key_hash=None, sender=None)#
Image messages are messages that display a single image and an optional caption.
See Image messages.
Images must be 8-bit, RGB or RGBA.
Example
>>> wa = WhatsApp() >>> wa.send_image( ... to="1234567890", ... image="https://example.com/image.png", ... caption="This is an image!", ... )
- Parameters:
to (str | int) β The user phone number, WhatsApp ID, BSUID or group ID to send the message to.
image (str | int | Media | Path | bytes | BinaryIO | Iterator[bytes]) β The image to send (can be a URL, file path, bytes, bytes generator, file-like object, base64 or a
Mediainstance).caption (str | None) β
The caption of the image (required when buttons are provided, markdown allowed).
footer (str | None) β
The footer of the message (if buttons are provided, optional, markdown has no effect).
buttons (Iterable[Button] | URLButton | FlowButton | None) β The buttons to send with the image (optional).
reply_to_message_id (str | None) β The message ID to quote (optional).
mime_type (str | None) β The mime type of the image (optional, required when sending an image as bytes, or file path that does not have an extension).
tracker (str | CallbackData | None) β The data to track the message with (optional, up to 512 characters, for complex data you can use
CallbackData).identity_key_hash (str | None) β
The message would only be delivered if the hash value matches the customerβs current hash (Optional, See Identity Change Check).
sender (str | int | None) β The phone ID to send the message from (optional, overrides the clientβs phone ID).
- Returns:
The sent image message.
- Return type:
- WhatsApp.send_video(to, video, caption=None, footer=None, buttons=None, *, mime_type=None, reply_to_message_id=None, tracker=None, identity_key_hash=None, sender=None)#
Video messages display a thumbnail preview of a video image with an optional caption. When the WhatsApp user taps the preview, it loads the video and displays it to the user.
Only H.264 video codec and AAC audio codec supported. Single audio stream or no audio stream only.
See Video messages.
Example
>>> wa = WhatsApp() >>> wa.send_video( ... to="1234567890", ... video="https://example.com/video.mp4", ... caption="This is a video", ... )
- Parameters:
to (str | int) β The user phone number, WhatsApp ID, BSUID or group ID to send the message to.
video (str | int | Media | Path | bytes | BinaryIO | Iterator[bytes]) β The video to send (can be a URL, file path, bytes, bytes generator, file-like object, base64 or a
Mediainstance).caption (str | None) β
The caption of the video (required when sending a video with buttons, markdown allowed).
footer (str | None) β
The footer of the message (if buttons are provided, optional, markdown has no effect).
buttons (Iterable[Button] | URLButton | FlowButton | None) β The buttons to send with the video (optional).
reply_to_message_id (str | None) β The message ID to quote (optional).
mime_type (str | None) β The mime type of the video (optional, required when sending a video as bytes or file path that does not have an extension).
tracker (str | CallbackData | None) β The data to track the message with (optional, up to 512 characters, for complex data you can use
CallbackData).identity_key_hash (str | None) β
The message would only be delivered if the hash value matches the customerβs current hash (Optional, See Identity Change Check).
sender (str | int | None) β The phone ID to send the message from (optional, overrides the clientβs phone ID).
- Returns:
The sent video message.
- Return type:
- WhatsApp.send_audio(to, audio, *, is_voice=None, mime_type=None, reply_to_message_id=None, tracker=None, identity_key_hash=None, sender=None)#
Basic audio messages display a download icon and a music icon. When the WhatsApp user taps the play icon, the user must manually download the audio message for the WhatsApp client to load and then play the audio file.
See Audio messages.
Example
>>> wa = WhatsApp() >>> wa.send_audio( ... to='1234567890', ... audio='https://example.com/audio.mp3', ... )
- Parameters:
to (str | int) β The user phone number, WhatsApp ID, BSUID or group ID to send the message to.
audio (str | int | Media | Path | bytes | BinaryIO | Iterator[bytes]) β The audio file to send (can be a URL, file path, bytes, bytes generator, file-like object, base64 or a
Mediainstance).is_voice (bool | None) β Set to True if sending a voice message (use
send_voice()instead for better type support).mime_type (str | None) β The mime type of the audio file (optional, required when sending an audio as bytes or file path that does not have an extension).
reply_to_message_id (str | None) β The message ID to quote (optional).
tracker (str | CallbackData | None) β The data to track the message with (optional, up to 512 characters, for complex data you can use
CallbackData).identity_key_hash (str | None) β
The message would only be delivered if the hash value matches the customerβs current hash (Optional, See Identity Change Check).
sender (str | int | None) β The phone ID to send the message from (optional, overrides the clientβs phone ID).
- Returns:
The sent audio message.
- Return type:
- WhatsApp.send_voice(to, voice, *, mime_type=None, reply_to_message_id=None, tracker=None, identity_key_hash=None, sender=None)#
A voice message (sometimes referred to as a voice note, voice memo, or audio) is a recording of one or more persons speaking, and can include background sounds like music. Voice messages include features like automatic download, profile picture, and voice icon, not available with a basic audio message. If the user has set voice message transcripts to Automatic, a text transcription of the message will also be included.
See Voice messages.
Voice messages require .ogg files encoded with the OPUS codec. If you send a different file type or a file encoded with a different codec, voice message transcription will fail.
The play icon will only appear if the file is 512KB or smaller, otherwise it will be replaced with a download icon (a downward facing arrow).
Your businessβs profile image is used as the profile image, accompanied by a microphone icon.
The text transcription appears if the user has enabled Automatic voice message transcripts. If the user has set this to Manual, the text βTranscribeβ will appear instead, which will display the transcribed text once tapped. If the user has set voice message transcripts to Never, no text will appear.
Example
>>> wa = WhatsApp() >>> wa.send_voice( ... to='1234567890', ... voice='https://example.com/voice.ogg', ... )
- Parameters:
to (str | int) β The user phone number, WhatsApp ID, BSUID or group ID to send the message to.
voice (str | int | Media | Path | bytes | BinaryIO | Iterator[bytes]) β The voice file to send (can be a URL, file path, bytes, bytes generator, file-like object, base64 or a
Mediainstance).mime_type (str | None) β The mime type of the voice file (optional, required when sending an audio as bytes or file path that does not have an extension).
reply_to_message_id (str | None) β The message ID to quote (optional).
tracker (str | CallbackData | None) β The data to track the message with (optional, up to 512 characters, for complex data you can use
CallbackData).identity_key_hash (str | None) β
The message would only be delivered if the hash value matches the customerβs current hash (Optional, See Identity Change Check).
sender (str | int | None) β The phone ID to send the message from (optional, overrides the clientβs phone ID).
- Returns:
The sent voice message.
- Return type:
- WhatsApp.send_document(to, document, filename=<object object>, caption=None, footer=None, buttons=None, *, mime_type=None, reply_to_message_id=None, tracker=None, identity_key_hash=None, sender=None)#
Document messages are messages that display a document icon, linked to a document, that a WhatsApp user can tap to download.
See Document messages.
Example
>>> wa = WhatsApp() >>> wa.send_document( ... to="1234567890", ... document="https://example.com/example_123.pdf", ... filename="example.pdf", ... caption="Example PDF" ... )
- Parameters:
to (str | int) β The user phone number, WhatsApp ID, BSUID or group ID to send the message to.
document (str | int | Media | Path | bytes | BinaryIO | Iterator[bytes]) β The document to send (can be a URL, file path, bytes, bytes generator, file-like object, base64 or a
Mediainstance).filename (str | None) β Document filename, with extension. The WhatsApp client will use an appropriate file type icon based on the extension (Optional, if not provided, if possible, the filename will be extracted from the media. pass
Noneto skip this behavior).caption (str | None) β
The caption of the document (required when sending a document with buttons, markdown allowed).
footer (str | None) β
The footer of the message (if buttons are provided, optional, markdown has no effect).
buttons (Iterable[Button] | URLButton | FlowButton | None) β The buttons to send with the document (optional).
reply_to_message_id (str | None) β The message ID to quote (optional).
mime_type (str | None) β The mime type of the document (optional, required when sending a document as bytes or file path that does not have an extension).
tracker (str | CallbackData | None) β The data to track the message with (optional, up to 512 characters, for complex data you can use
CallbackData).identity_key_hash (str | None) β
The message would only be delivered if the hash value matches the customerβs current hash (Optional, See Identity Change Check).
sender (str | int | None) β The phone ID to send the message from (optional, overrides the clientβs phone ID).
- Returns:
The sent document message.
- Return type:
- WhatsApp.send_location(to, latitude, longitude, name=None, address=None, *, reply_to_message_id=None, tracker=None, identity_key_hash=None, sender=None)#
Location messages allow you to send a locationβs latitude and longitude coordinates to a WhatsApp user.
Read more about Location messages.
Example
>>> wa = WhatsApp() >>> wa.send_location( ... to='1234567890', ... latitude=37.4847483695049, ... longitude=--122.1473373086664, ... name='WhatsApp HQ', ... address='Menlo Park, 1601 Willow Rd, United States', ... )
- Parameters:
to (str | int) β The user phone number, WhatsApp ID, BSUID or group ID to send the message to.
latitude (float) β The latitude of the location.
longitude (float) β The longitude of the location.
name (str | None) β The name of the location (optional).
address (str | None) β The address of the location (optional).
reply_to_message_id (str | None) β The message ID to quote (optional).
tracker (str | CallbackData | None) β The data to track the message with (optional, up to 512 characters, for complex data you can use
CallbackData).identity_key_hash (str | None) β
The message would only be delivered if the hash value matches the customerβs current hash (Optional, See Identity Change Check).
sender (str | int | None) β The phone ID to send the message from (optional, overrides the clientβs phone ID).
- Returns:
The sent location message.
- Return type:
- WhatsApp.request_location(to, text, *, reply_to_message_id=None, tracker=None, identity_key_hash=None, sender=None)#
Location request messages display body text and a send location button. When a WhatsApp user taps the button, a location sharing screen appears which the user can then use to share their location.
Once the user shares their location, a
Messageupdate is triggered, containing the userβs location details.Read more about Location request messages.
Example
>>> wa = WhatsApp() >>> wa.request_location( ... to='1234567890', ... text='Please share your location with us.', ... )
- Parameters:
to (str | int) β The user phone number, WhatsApp ID, BSUID or group ID to send the message to.
text (str) β The text to send with the button.
reply_to_message_id (str | None) β The message ID to quote (optional).
tracker (str | CallbackData | None) β The data to track the message with (optional, up to 512 characters, for complex data you can use
CallbackData).identity_key_hash (str | None) β
The message would only be delivered if the hash value matches the customerβs current hash (Optional, See Identity Change Check).
sender (str | int | None) β The phone ID to send the message from (optional, overrides the clientβs phone ID).
- Returns:
The sent location request message.
- Return type:
- WhatsApp.send_contact(to, contact, *, reply_to_message_id=None, tracker=None, identity_key_hash=None, sender=None)#
Contacts messages allow you to send rich contact information directly to WhatsApp users, such as names, phone numbers, physical addresses, and email addresses. When a WhatsApp user taps the messageβs profile arrow, it displays the contactβs information in a profile view:
Each message can include information for up to 257 contacts, although it is recommended to send fewer for usability and negative feedback reasons.
See Contacts messages.
Example
>>> from pywa.types import Contact >>> wa = WhatsApp() >>> wa.send_contact( ... to='1234567890', ... contact=Contact( ... name=Contact.Name(formatted_name='David Lev', first_name='David'), ... phones=[Contact.Phone(phone='1234567890', wa_id='1234567890', type='MOBILE')], ... emails=[Contact.Email(email='test@test.com', type='WORK')], ... urls=[Contact.Url(url='https://exmaple.com', type='HOME')], ... ) ... )
- Parameters:
to (str | int) β The user phone number, WhatsApp ID, BSUID or group ID to send the message to.
contact (Contact | Iterable[Contact]) β The contact/s to send.
reply_to_message_id (str | None) β The message ID to quote (optional).
tracker (str | CallbackData | None) β The data to track the message with (optional, up to 512 characters, for complex data you can use
CallbackData).identity_key_hash (str | None) β
The message would only be delivered if the hash value matches the customerβs current hash (Optional, See Identity Change Check).
sender (str | int | None) β The phone ID to send the message from (optional, overrides the clientβs phone ID).
- Returns:
The sent contact/s message.
- Return type:
- WhatsApp.send_sticker(to, sticker, *, mime_type=None, reply_to_message_id=None, tracker=None, identity_key_hash=None, sender=None)#
Sticker messages display animated or static sticker images in a WhatsApp message.
A static sticker needs to be 512x512 pixels and cannot exceed 100 KB.
An animated sticker must be 512x512 pixels and cannot exceed 500 KB.
See Sticker messages.
Example
>>> wa = WhatsApp() >>> wa.send_sticker( ... to='1234567890', ... sticker='https://example.com/sticker.webp', ... )
- Parameters:
to (str | int) β The user phone number, WhatsApp ID, BSUID or group ID to send the message to.
sticker (str | int | Media | Path | bytes | BinaryIO | Iterator[bytes]) β The sticker to send (can be a URL, file path, bytes, bytes generator, file-like object, base64 or a
Mediainstance).mime_type (str | None) β The mime type of the sticker (optional, required when sending a sticker as bytes or file path that does not have an extension).
reply_to_message_id (str | None) β The message ID to quote (optional).
tracker (str | CallbackData | None) β The data to track the message with (optional, up to 512 characters, for complex data you can use
CallbackData).identity_key_hash (str | None) β
The message would only be delivered if the hash value matches the customerβs current hash (Optional, See Identity Change Check).
sender (str | int | None) β The phone ID to send the message from (optional, overrides the clientβs phone ID).
- Returns:
The sent sticker message.
- Return type:
- WhatsApp.send_catalog(to, body, footer=None, *, thumbnail_product_sku=None, reply_to_message_id=None, tracker=None, identity_key_hash=None, sender=None)#
Catalog messages are messages that allow you to showcase your product catalog entirely within WhatsApp.
Catalog messages display a product thumbnail header image of your choice, custom body text, a fixed text header, a fixed text sub-header, and a View catalog button.
When a customer taps the View catalog button, your product catalog appears within WhatsApp.
You must have inventory uploaded to Meta in an ecommerce catalog connected to your WhatsApp Business Account.
Read more about Catalog messages.
Example
>>> wa = WhatsApp() >>> wa.send_catalog( ... to='1234567890', ... body='Check out our catalog!', ... footer='Powered by PyWa', ... thumbnail_product_sku='SKU123', ... )
- Parameters:
to (str | int) β The user phone number, WhatsApp ID, BSUID or group ID to send the message to.
body (str) β Text to appear in the message body (up to 1024 characters).
footer (str | None) β Text to appear in the footer of the message (optional, up to 60 characters).
thumbnail_product_sku (str | None) β Item SKU number. Labeled as Content ID in the Commerce Manager. The thumbnail of this item will be used as the messageβs header image. If omitted, the product image of the first item in your catalog will be used.
reply_to_message_id (str | None) β The message ID to quote (optional).
tracker (str | CallbackData | None) β The data to track the message with (optional, up to 512 characters, for complex data you can use
CallbackData).identity_key_hash (str | None) β
The message would only be delivered if the hash value matches the customerβs current hash (Optional, See Identity Change Check).
sender (str | int | None) β The phone ID to send the message from (optional, overrides the clientβs phone ID).
- Returns:
The sent catalog message.
- Return type:
- WhatsApp.send_template(to, name=None, language=None, params=None, *, template=None, use_mm_lite_api=False, message_activity_sharing=None, reply_to_message_id=None, tracker=None, identity_key_hash=None, sender=None)#
Send a template to a WhatsApp user.
To create a template, use
create_template().Read more about Template Messages.
Example:
from pywa.types.templates import * wa = WhatsApp(...) wa.send_template( to='1234567890', name='seasonal_promotion', language=TemplateLanguage.ENGLISH_US, params=[ BodyText.params(season='Summer'), CopyCodeButton.params(coupon_code="25OFF", index=0) ], ) from pywa.types.templates import * t = Template( name='seasonal_promotion', category=TemplateCategory.MARKETING, language=TemplateLanguage.ENGLISH_US, parameter_format=ParamFormat.NAMED, components=[ header := HeaderText(text='Our {{sale_name}} is on!', sale_name='Summer Sale'), body := BodyText( text='Shop now through {{end_date}} and use code {{discount_code}} to get {{discount_amount}} off of all merchandise.', end_date='the end of August', discount_code='25OFF', discount_amount='25%' ), FooterText(text='Use the buttons below to manage your marketing subscriptions'), Buttons( buttons=[ uns_from_promos := QuickReplyButton(text='Unsubscribe from Promos'), uns_from_all := QuickReplyButton(text='Unsubscribe from All'), ] ), ], ) wa.create_template(template=t) wa.send_template( to='1234567890', template=t, # provide the template object to validate parameters against params=[ header.params(sale_name='Summer Sale'), body.params( end_date='the end of August', discount_code='25OFF', discount_amount='25%', ), uns_from_promos.params(callback_data='uns_from_promos'), uns_from_all.params(callback_data='uns_from_all'), ], )
- Parameters:
to (str | int) β The user phone number, WhatsApp ID, BSUID or group ID to send the message to.
name (str | None) β The name of the template to send (optional when
templateis provided).language (TemplateLanguage | None) β The language of the template to send (optional when
templateis provided).template (Template | None) β The template object to validate the parameters against (optional, if not provided,
nameandlanguagemust be provided).params (list[BaseParams | dict] | None) β The parameters to fill in the template.
use_mm_lite_api (bool) β Whether to use Marketing Messages Lite API (optional, default: False).
message_activity_sharing (bool | None) β Whether to share message activities (e.g. message read) for that specific marketing message to Meta to help optimize marketing messages (optional, only if
use_mm_lite_apiis True).reply_to_message_id (str | None) β The ID of the message to reply to (optional).
tracker (str | CallbackData | None) β A callback data to track the message (optional, can be a string or a
CallbackDataobject).identity_key_hash (str | None) β
The message would only be delivered if the hash value matches the customerβs current hash (Optional, See Identity Change Check).
sender (str | int | None) β The phone ID to send the template from (optional, if not provided, the clientβs phone ID will be used).
- Return type:
- WhatsApp.send_product(to, catalog_id, sku, body=None, footer=None, *, reply_to_message_id=None, tracker=None, identity_key_hash=None, sender=None)#
Send a product from a business catalog to a WhatsApp user.
To send multiple products, use
send_products().See Product messages.
Example
>>> wa = WhatsApp() >>> wa.send_product( ... to='1234567890', ... catalog_id='1234567890', ... sku='SKU123', ... body='Check out this product!', ... footer='Powered by PyWa', ... )
- Parameters:
to (str | int) β The user phone number, WhatsApp ID, BSUID or group ID to send the message to.
catalog_id (str) β The ID of the catalog to send the product from. (To get the catalog ID use
get_commerce_settings()or in the Commerce Manager).sku (str) β The product SKU to send.
body (str | None) β Text to appear in the message body (up to 1024 characters).
footer (str | None) β Text to appear in the footer of the message (optional, up to 60 characters).
reply_to_message_id (str | None) β The message ID to quote (optional).
tracker (str | CallbackData | None) β The data to track the message with (optional, up to 512 characters, for complex data you can use
CallbackData).identity_key_hash (str | None) β
The message would only be delivered if the hash value matches the customerβs current hash (Optional, See Identity Change Check).
sender (str | int | None) β The phone ID to send the message from (optional, overrides the clientβs phone ID).
- Returns:
The sent product message.
- Return type:
- WhatsApp.send_products(to, catalog_id, product_sections, title, body, footer=None, *, reply_to_message_id=None, tracker=None, identity_key_hash=None, sender=None)#
Send products from a business catalog to a WhatsApp user.
To send a single product, use
send_product().See Product messages.
Example
>>> from pywa.types import ProductsSection >>> wa = WhatsApp() >>> wa.send_products( ... to='1234567890', ... catalog_id='1234567890', ... title='Tech Products', ... body='Check out our products!', ... product_sections=[ ... ProductsSection( ... title='Smartphones', ... skus=['IPHONE12', 'GALAXYS21'], ... ), ... ProductsSection( ... title='Laptops', ... skus=['MACBOOKPRO', 'SURFACEPRO'], ... ), ... ], ... footer='Powered by PyWa', ... )
- Parameters:
to (str | int) β The user phone number, WhatsApp ID, BSUID or group ID to send the message to.
catalog_id (str) β
The ID of the catalog to send the product from (To get the catalog ID use
get_commerce_settings()or in the Commerce Manager).product_sections (Iterable[ProductsSection]) β The product sections to send (up to 30 products across all sections).
title (str) β The title of the product list (up to 60 characters).
body (str) β Text to appear in the message body (up to 1024 characters).
footer (str | None) β Text to appear in the footer of the message (optional, up to 60 characters).
reply_to_message_id (str | None) β The message ID to quote (optional).
tracker (str | CallbackData | None) β The data to track the message with (optional, up to 512 characters, for complex data you can use
CallbackData).identity_key_hash (str | None) β
The message would only be delivered if the hash value matches the customerβs current hash (Optional, See Identity Change Check).
sender (str | int | None) β The phone ID to send the message from (optional, overrides the clientβs phone ID).
- Returns:
The sent products message.
- Return type:
- WhatsApp.send_reaction(to, emoji, message_id, *, tracker=None, identity_key_hash=None, sender=None)#
Reaction messages are emoji-reactions that you can apply to a previous WhatsApp user message that you have received.
When sending a reaction message, only a
MessageStatusupdate (typeset toSENT) will be triggered;DELIVEREDandREADupdates will not be triggered.You can react to incoming messages by using the
react()method on every update.See Reaction messages.
>>> wa = WhatsApp() >>> @wa.on_message ... def message_handler(_: WhatsApp, msg: Message): ... msg.react('π')
Example
>>> wa = WhatsApp() >>> wa.send_reaction( ... to='1234567890', ... emoji='π', ... message_id='wamid.XXX=' ... )
- Parameters:
to (str | int) β The user phone number, WhatsApp ID, BSUID or group ID to send the message to.
emoji (str) β The emoji to react with.
message_id (str) β The message ID to react to.
tracker (str | CallbackData | None) β The data to track the message with (optional, up to 512 characters, for complex data you can use
CallbackData).identity_key_hash (str | None) β
The message would only be delivered if the hash value matches the customerβs current hash (Optional, See Identity Change Check).
sender (str | int | None) β The phone ID to send the message from (optional, overrides the clientβs phone ID).
- Returns:
The sent reaction message (You canβt use this message id to remove the reaction or perform any other action on it. instead, use the message ID of the message you reacted to).
- Return type:
- WhatsApp.remove_reaction(to, message_id, *, tracker=None, identity_key_hash=None, sender=None)#
Remove reaction from a message.
You can remove reactions from incoming messages by using the
unreact()method on every update.See Reaction messages.
>>> wa = WhatsApp() >>> @wa.on_message ... def message_handler(_: WhatsApp, msg: Message): ... msg.react('π') ... msg.unreact()
Example
>>> wa = WhatsApp() >>> wa.remove_reaction( ... to='1234567890', ... message_id='wamid.XXX=' ... )
- Parameters:
to (str | int) β The user phone number, WhatsApp ID, BSUID or group ID to send the message to.
message_id (str) β The message ID to remove the reaction from.
tracker (str | CallbackData | None) β The data to track the message with (optional, up to 512 characters, for complex data you can use
CallbackData).identity_key_hash (str | None) β
The message would only be delivered if the hash value matches the customerβs current hash (Optional, See Identity Change Check).
sender (str | int | None) β The phone ID to send the message from (optional, overrides the clientβs phone ID).
- Returns:
The sent (un)reaction message (You canβt use this message id to re-react or perform any other action on it. instead, use the message ID of the message you unreacted to).
- Return type:
- WhatsApp.mark_message_as_read(message_id, *, sender=None)#
When you get a
Message, you can use the msg.id value to mark the message as read.You can mark incoming messages as read by using the
mark_as_read()method or indicate typing by using theindicate_typing()method on every update.Itβs good practice to mark an incoming messages as read within 30 days of receipt. Marking a message as read will also mark earlier messages in the thread as read.
Read more about Mark messages as read.
Example
>>> wa = WhatsApp() >>> wa.mark_message_as_read(message_id='wamid.XXX=')
- Parameters:
- Returns:
Whether the message was marked as read.
- Return type:
- WhatsApp.indicate_typing(message_id, *, sender=None)#
When you get a
Message, you can use the msg.id value to mark the message as read and display a typing indicator so the WhatsApp user knows you are preparing a response. This is good practice if it will take you a few seconds to respond.You can indicate typing by using the
indicate_typing()method on every update.The typing indicator will be dismissed once you respond, or after 25 seconds, whichever comes first. To prevent a poor user experience, only display a typing indicator if you are going to respond.
Read more about Typing indicators.
Example
>>> wa = WhatsApp() >>> wa.indicate_typing(message_id='wamid.XXX=')
- Parameters:
- Returns:
Whether the message was marked as read and the typing indicator was displayed.
- Return type:
- WhatsApp.listen(to, *, filters=None, cancelers=None, timeout=None)#
Listen to an update.
- You can use one of the shortcuts to listen to a specific update type:
Example
try: wa.send_message( to="123456", text="Send me a message", buttons=[Button(title="Cancel", callback_data="cancel")] ) update: Message = wa.listen( to=UserUpdateListenerIdentifier(sender="123456", recipient="654321"), filters=filters.message & filters.text, cancelers=filters.callback_button & filters.matches("cancel"), timeout=10 ) print(update) except ListenerTimeout: print("Listener timed out") except ListenerCanceled: print("Listener was canceled") except ListenerStopped: print("Listener was stopped")
- Parameters:
to (BaseListenerIdentifier) β The identifier of the update to listen to.
filters (Filter) β The filters to apply to the update, return the update if the filters pass.
cancelers (Filter) β The filters to cancel the listening, raise
ListenerCanceledif the update matches.timeout (float | None) β The time to wait for the update, raise
ListenerTimeoutif the time passes
- Returns:
The update that passed the filters
- Raises:
ListenerTimeout β If the listener timed out
ListenerCanceled β If the listener was canceled by a filter
ListenerStopped β If the listener was stopped manually
- Return type:
- WhatsApp.stop_listening(to, *, reason=None)#
Stop listening to updates for a specific listener
Raising
ListenerStoppedto the listener
- Parameters:
to (BaseListenerIdentifier) β The identifier of the listener to stop
reason (str | None) β The reason to stop listening
- Raises:
ValueError β If the listener does not exist
- WhatsApp.upload_media(media, mime_type=None, filename=None, dl_session=None, *, ttl=None, download_chunk_size=65536, media_type=None, phone_id=None)#
Upload media to WhatsApp servers.
All media files sent through this endpoint are encrypted and persist for 30 days, unless they are deleted earlier.
You can get media URL with
get_media_url()and download it withdownload_media()or delete it withdelete_media().See Upload media.
Example
>>> wa = WhatsApp() >>> wa.upload_media(media='https://example.com/image.jpg')
>>> wa.upload_media(media=pathlib.Path('image.jpg')) >>> wa.upload_media(media="/path/to/image.jpg")
>>> wa.upload_media( ... media=b'...binary data...', ... mime_type='image/jpeg', ... filename='image.jpg', ... )
>>> with wa.upload_media("https://my-cdn.com/sensitive-image.png") as media: # will be deleted after use ... wa.send_image(to=..., image=media)
- Parameters:
media (str | int | Media | Path | bytes | BinaryIO | Iterator[bytes]) β The media to upload (can be a URL, file path, bytes, bytes generator, file-like object, base64 or a
Mediainstance).mime_type (str | None) β The MIME type of the media.
filename (str | None) β The file name of the media.
ttl (timedelta | int | None) β Override the default 1-hour TTL for No Storage-enabled business phone numbers. This value is in minutes from 1 hour (60) to 30 days (43200).
dl_session (Client | None) β A httpx client to use when downloading the media from a URL (optional, for custom settings like proxies, headers, etc. If not provided, a new client will be created for the download).
download_chunk_size (int) β The size (in bytes) of each chunk to download when downloading media from a URL (default:
64KB). Defines the size of data read into memory at a time.media_type (Literal['image', 'video', 'audio', 'document', 'sticker'] | None) β The type of the media (optional, for default mimetype and filename).
phone_id (str | int | None) β The phone ID to upload the media to (optional, if not provided, the clientβs phone ID will be used).
- Returns:
The uploaded media.
- Return type:
- WhatsApp.download_media(*, url, path=None, filename=None, chunk_size=65536, **httpx_kwargs)#
Download a media file from WhatsApp servers.
Use
get_media_url()to get the media URL from a media ID.Use
download_media()to download media directly from a message.Use
get_media_bytes()to get the media as bytes.Use
stream_media()to stream the media as bytes.See Download media.
Example
>>> wa = WhatsApp() >>> wa.download_media( ... url='https://mmg-fna.whatsapp.net/d/f/Amc.../v2/1234567890', ... path=pathlib.Path('/path/to/save'), ... filename='image.jpg', ... )
- Parameters:
url (str) β The URL of the media file.
path (str | Path | None) β The path where to save the file (if not provided, the current working directory will be used).
filename (str | None) β The name of the file to save (if not provided, it will be extracted from the
Content-Dispositionheader or a SHA256 hash of the URL will be used).chunk_size (int) β The size (in bytes) of each chunk to read when downloading the media (default:
64KB).**httpx_kwargs (Any) β Additional arguments to pass to
httpx.get().
- Returns:
The path of the saved file.
- Return type:
- WhatsApp.stream_media(url, *, chunk_size=65536, **httpx_kwargs)#
Stream media file as bytes from WhatsApp servers.
Use
get_media_url()to get the media URL from a media ID.Use
stream_media()to stream the media directly from a message.Use
download_media()to download the media to a file.Use
get_media_bytes()to get the media as bytes.See Download media.
Example
>>> wa = WhatsApp() >>> with httpx.Client() as client: >>> client.post("https://my-server.com/upload", content=wa.stream_media()) # streaming upload
- WhatsApp.get_media_bytes(url, **httpx_kwargs)#
Get media file as bytes from WhatsApp servers.
Use
get_media_url()to get the media URL from a media ID.Use
get_media_bytes()to get the media directly from a message.Use
download_media()to download the media to a file.Use
stream_media()to stream the media as bytes.See Download media.
Example
>>> wa = WhatsApp() >>> media_bytes = wa.get_media_bytes( ... url='https://mmg-fna.whatsapp.net/d/f/Amc.../v2/1234567890', ... )
- WhatsApp.get_media_url(media_id)#
Get a media URL for a media ID.
Note that clicking this URL (i.e. performing a generic
GET) will not return the media; you must include an access token. Use thedownload_media()method to download the media.The media can be downloaded directly from the message using the
download_media()method.The URL is valid for 5 minutes.
See Retrieve Media URL.
Example
>>> wa = WhatsApp() >>> wa.get_media_url(media_id='wamid.XXX=')
- WhatsApp.delete_media(media_id, *, phone_id=<object object>)#
Delete a media file from WhatsApp servers.
See Delete media.
Example
>>> wa = WhatsApp() >>> wa.delete_media(media_id='wamid.XXX=')
- Parameters:
media_id (str) β The media ID to delete.
phone_id (str | int | None) β The phone ID to delete the media from (optional, If included, the operation will only be processed if the ID matches the ID of the business phone number that the media was uploaded on. pass
Noneto use the clientβs phone ID).
- Returns:
Whether the media was deleted successfully.
- Return type:
- WhatsApp.get_business_account(*, waba_id=None)#
Get the WhatsApp Business Account (WABA) information.
- WhatsApp.update_business_account_settings(*, disable_marketing_messages_on_cloud_api=None, degrees_of_freedom_spec=None, waba_id=None)#
Update the WhatsApp Business Account (WABA) settings.
Example
>>> wa = WhatsApp() >>> wa.update_business_account_settings(disable_marketing_messages_on_cloud_api=True)
- Parameters:
disable_marketing_messages_on_cloud_api (bool | None) β Whether to block Marketing category templates on the Cloud API
/messagesendpoint (in pywa it means that when yousend_template()aMARKETINGtemplate you must setuse_mm_lite_apitoTrue).degrees_of_freedom_spec (DegreesOfFreedomSpec | None) β Configure automatic creative optimizations for message templates. Read more at developers.facebook.com.
waba_id (str | int | None) β The WABA ID to update the settings for (optional, if not provided, the clientβs WABA ID will be used).
- WhatsApp.get_business_profile(*, phone_id=None)#
Get the business profile of the phone number.
Example
>>> wa = WhatsApp() >>> wa.get_business_profile()
- WhatsApp.get_business_phone_numbers(*, waba_id=None, pagination=None)#
Get the phone numbers of the WhatsApp Business account.
Example
>>> wa = WhatsApp() >>> for phone_number in wa.get_business_phone_numbers(): ... print(phone_number)
- Parameters:
waba_id (str | int | None) β The WABA ID to get the phone numbers from (optional, if not provided, the clientβs WABA ID will be used).
pagination (Pagination | None) β Pagination object to paginate through the results (optional).
- Returns:
A Result object containing BusinessPhoneNumber objects.
- Return type:
- WhatsApp.get_business_phone_number(*, phone_id=None)#
Get the phone number details.
Example
>>> wa = WhatsApp() >>> wa.get_business_phone_number()
- WhatsApp.get_business_phone_number_settings(*, include_sip_credentials=None, phone_id=None)#
Get the settings of the WhatsApp Business phone number.
Example
>>> wa = WhatsApp() >>> wa.get_business_phone_number_settings()
- Parameters:
- Returns:
The business phone number settings.
- Return type:
- WhatsApp.update_business_phone_number_settings(*, calling=None, storage_configuration=None, user_identity_change=None, phone_id=None)#
Update the settings of the WhatsApp Business phone number.
Example
>>> from pywa.types.calls import CallingSettingsStatus >>> wa = WhatsApp() >>> s = wa.get_business_phone_number_settings() >>> s.calling.status = CallingSettingsStatus.ENABLED >>> wa.update_business_phone_number_settings(calling=s.calling)
- Parameters:
calling (CallingSettings | None) β The calling settings to update (optional).
storage_configuration (StorageConfiguration | None) β The storage configuration to update (optional).
user_identity_change (UserIdentityChangeSettings | None) β The user identity change settings to update (optional).
phone_id (str | int | None) β The phone ID to update the settings for (optional, if not provided, the clientβs phone ID will be used).
- Returns:
Whether the settings were updated successfully.
- Return type:
- WhatsApp.update_business_profile(*, about=<object object>, address=<object object>, description=<object object>, email=<object object>, profile_picture=<object object>, industry=<object object>, websites=<object object>, phone_id=None, app_id=None)#
Update the business profile of the phone number.
Example
>>> from pywa.types import Industry >>> wa = WhatsApp() >>> wa.update_business_profile( ... about='This is a test business', ... address='Menlo Park, 1601 Willow Rd, United States', ... description='This is a test business', ... email='test@test.com', ... profile_picture='path/to/profile.jpg', ... industry=Industry.NOT_A_BIZ, ... websites=['https://example.com', 'https://google.com'], ... )
- Parameters:
about (str | None) β
The businessβs About text. This text appears in the businessβs profile, beneath its profile image, phone number, and contact buttons. (cannot be empty. must be between 1 and 139 characters. markdown is not supported. Hyperlinks can be included but will not render as clickable links.)
address (str | None) β Address of the business. Character limit 256.
description (str | None) β Description of the business. Character limit 512.
email (str | None) β The contact email address (in valid email format) of the business. Character limit 128.
profile_picture (str | int | Media | Path | bytes | BinaryIO | Iterator[bytes]) β The profile picture to set for the business (can be a media ID, URL, file path, bytes, bytes generator, or file-like object).
industry (Industry | None) β Industry of the business.
websites (Iterable[str] | None) β The URLs associated with the business. For instance, a website, Facebook Page, or Instagram. (You must include the
http://orhttps://portion of the URL. There is a maximum of 2 websites with a maximum of 256 characters each.)phone_id (str | int | None) β The phone ID to update the business profile for (optional, if not provided, the clientβs phone ID will be used).
app_id (str | int | None) β The App ID to upload the profile picture to (optional, if not provided, the clientβs app ID will be used).
- Returns:
Whether the business profile was updated.
- Return type:
- WhatsApp.update_display_name(new_display_name, *, phone_id=None)#
Update the display name of the WhatsApp Business phone number.
The display name is the name that appears in the WhatsApp app for your business.
The display name will undergo verification by WhatsApp, and you will receive a webhook notification when the verification is complete.
Read more about Display Name Verification.
Example
>>> wa = WhatsApp() >>> wa.update_display_name(new_display_name="Pizza Bot")
- Parameters:
- Return type:
- WhatsApp.update_conversational_automation(ice_breakers=None, commands=None, *, phone_id=None)#
Update the conversational automation settings of the WhatsApp Business phone number.
You can receive the current conversational automation settings using
get_business_phone_number()and accessing theconversational_automationattribute.Read more about Conversational Automation.
>>> from pywa.types import Command >>> wa = WhatsApp() >>> wa.update_conversational_automation( ... ice_breakers=['Plan a trip', 'Create a workout plan'], ... commands=[ ... Command( ... command='start', ... description='Start a new conversation', ... ), ... Command( ... command='help', ... description='Get help with the bot', ... ), ... ], ... )
- Parameters:
ice_breakers (Iterable[str] | None) β Ice Breakers are customizable, tappable text strings that appear in a message thread the first time you chat with a user. For example, Plan a trip or Create a workout plan.
commands (Iterable[Command] | None) β Commands are text strings that WhatsApp users can see by typing a forward slash in a message thread with your business.
phone_id (str | int | None) β The phone ID to update the conversational automation settings for (optional, if not provided, the clientβs phone ID will be used).
- Returns:
Whether the conversational automation settings were updated.
- Return type:
- WhatsApp.set_business_public_key(public_key, *, phone_id=None)#
Set the business public key of the phone number (required for end-to-end encryption in flows)
- Parameters:
- Return type:
Example
>>> wa = WhatsApp() >>> wa.set_business_public_key( ... public_key="""-----BEGIN PUBLIC KEY-----...""" ... )
- Returns:
Whether the business public key was set.
- Return type:
- WhatsApp.get_commerce_settings(*, phone_id=None)#
Get the commerce settings of the WhatsApp Business phone number.
Example
>>> wa = WhatsApp() >>> wa.get_commerce_settings()
- WhatsApp.update_commerce_settings(is_catalog_visible=None, is_cart_enabled=None, *, phone_id=None)#
Update the commerce settings of the WhatsApp Business phone number.
Example
>>> wa = WhatsApp() >>> wa.update_commerce_settings( ... is_catalog_visible=True, ... is_cart_enabled=True, ... )
- Parameters:
- Returns:
Whether the commerce settings were updated.
- Raises:
ValueError β If no arguments are provided.
- Return type:
- WhatsApp.create_template(template, *, waba_id=None, app_id=None)#
Create a template for the WhatsApp Business account.
WhatsApp Business Accounts can only create 100 message templates per hour.
Read more about Create and Manage Templates.
Example:
from pywa.types import template as t wa = WhatsApp(..., waba_id='1234567890') created = wa.create_template( template=t.Template( name='seasonal_promotion', category=t.TemplateCategory.MARKETING, language=t.TemplateLanguage.ENGLISH_US, parameter_format=t.ParamFormat.NAMED, components=[ t.HeaderText(text='Our {{sale_name}} is on!', sale_name='Summer Sale'), t.BodyText( text='Shop now through {{end_date}} and use code {{discount_code}} to get {{discount_amount}} off of all merchandise.', end_date='the end of August', discount_code='25OFF', discount_amount='25%' ), t.FooterText(text='Use the buttons below to manage your marketing subscriptions'), t.Buttons( buttons=[ t.QuickReplyButton(text='Unsubscribe from Promos'), t.QuickReplyButton(text='Unsubscribe from All'), ] ), ], ), print('Template created:', created.id, created.status)
- Parameters:
template (Template | LibraryTemplate) β The template to create.
waba_id (str | int | None) β The WhatsApp Business account ID (Overrides the clientβs business account ID, optional).
app_id (str | int | None) β The App ID to upload the template header example media to (optional, if not provided, the clientβs app ID will be used).
- Returns:
The created template.
- Return type:
- WhatsApp.upsert_authentication_template(*, name, languages, otp_button, add_security_recommendation=None, code_expiration_minutes=None, message_send_ttl_seconds=None, waba_id=None)#
Bulk update or create authentication templates in multiple languages that include or exclude the optional security and expiration warnings.
If a template already exists with a matching name and language, the template will be updated with the contents of the request, otherwise, a new template will be created.
You canβt provide the
textorautofill_textproperties for the OTP Buttons. It will be automatically set to a pre-set value localized to the templateβs language. For example, Copy Code for English (US) and Autofill for English (US).Read more at developers.facebook.com.
Read more about Authentication Templates.
Example
>>> from pywa.types.templates import * >>> wa = WhatsApp() >>> templates = wa.upsert_authentication_template( ... name='one_tap_authentication', ... languages=[TemplateLanguage.ENGLISH_US, TemplateLanguage.FRENCH, TemplateLanguage.SPANISH], ... otp_button=OneTapOTPButton(supported_apps=...), ... add_security_recommendation=True, ... code_expiration_minutes=5, ... ) ... for template in templates: ... print(f'Template {template.id} created with status {template.status}')
- Parameters:
name (str) β The name of the template (should be unique, maximum 512 characters).
languages (Iterable[TemplateLanguage]) β A list of languages and locale codes to create or update the template in (See Supported Languages).
otp_button (BaseOTPButton) β A
OneTapOTPButton,ZeroTapOTPButton, orCopyCodeOTPButtonbutton.add_security_recommendation (bool | None) β Boolean value to add information to the template about not sharing authentication codes with anyone.
code_expiration_minutes (int | None) β Integer value to add information to the template on when the code will expire.
message_send_ttl_seconds (int | None) β The time-to-live (TTL) for the template message in seconds. (See Time-to-live (TTL)).
waba_id (str | int | None) β The WhatsApp Business account ID (Overrides the clientβs business account ID, optional).
- Returns:
A
CreatedTemplatesobject containing the created or updated templates.- Return type:
- WhatsApp.update_template(template_id, *, new_category=None, new_components=None, new_message_send_ttl_seconds=None, new_parameter_format=None, app_id=None)#
Update an existing template.
Only templates with an
APPROVED,REJECTED, orPAUSEDstatus can be edited.You cannot edit the category of an approved template.
Approved templates can be edited up to 10 times in a 30 day window, or 1 time in a 24 hour window. Rejected or paused templates can be edited an unlimited number of times.
After editing an approved or paused template, it will automatically be approved unless it fails template review.
Read more at developers.facebook.com.
Example
>>> from pywa.types.templates import * >>> wa = WhatsApp() >>> updated_template = wa.update_template( ... template_id='1234567890', ... new_category=TemplateCategory.MARKETING, ... new_components=[...], ... new_message_send_ttl_seconds=3600 ... )
- Parameters:
template_id (int | str) β The ID of the template to update.
new_category (TemplateCategory | None) β The new category of the template (optional, cannot be changed for approved templates).
new_components (list[TemplateBaseComponent] | None) β The new components of the template (optional, if not provided, the existing components will be used).
new_message_send_ttl_seconds (int | None) β The new message send TTL in seconds (optional, if not provided, the existing TTL will be used).
new_parameter_format (ParamFormat | None) β The new parameter format (optional, if not provided, the existing format will be used).
app_id (str | int | None) β The App ID to upload the template header example media to (optional, if not provided, the clientβs app ID will be used).
- Returns:
Whether the template was updated successfully.
- Return type:
- WhatsApp.get_template(template_id)#
Get the details of a specific template.
Example
>>> wa = WhatsApp() >>> template_details = wa.get_template(template_id='1234567890')
- WhatsApp.get_templates(*, statuses=None, categories=None, languages=None, name=None, content=None, name_or_content=None, quality_scores=None, pagination=None, waba_id=None)#
Get templates of the WhatsApp Business account.
Example
>>> wa = WhatsApp() >>> templates = wa.get_templates( ... statuses=[TemplateStatus.APPROVED], ... categories=[TemplateCategory.MARKETING], ... languages=[TemplateLanguage.ENGLISH_US], ... pagination=Pagination(limit=10) ... ) >>> for template in templates: ... print(f'Template {template.id} - {template.name}: {template}')
- Parameters:
statuses (Iterable[TemplateStatus] | None) β The statuses of the templates to filter by (optional).
categories (Iterable[TemplateCategory] | None) β The categories of the templates to filter by (optional).
languages (Iterable[TemplateLanguage] | None) β The languages of the templates to filter by (optional).
name (str | None) β The name (or part of it) of the template to filter by (optional).
content (str | None) β The content of the template to filter by (optional).
name_or_content (str | None) β The name or content of the template to filter by (optional).
quality_scores (Iterable[QualityScoreType] | None) β The quality scores of the templates to filter by (optional).
pagination (Pagination | None) β Pagination parameters (optional).
waba_id (str | int | None) β The WhatsApp Business account ID (Overrides the clientβs business account ID, optional).
- Returns:
A Result object containing the templates
- Return type:
- WhatsApp.delete_template(template_name, *, template_id=None, waba_id=None)#
Delete a template.
If you delete a template that has been sent in a template message but has yet to be delivered (e.g. because the customerβs phone is turned off), the templateβs status will be set to PENDING_DELETION and we will attempt to deliver the message for 30 days. After this time you will receive a βStructure Unavailableβ error and the customer will not receive the message.
Names of an approved template that has been deleted cannot be used again for 30 days.
Deleting a template by name deletes all templates that match that name (meaning templates with the same name but different languages will also be deleted).
To delete a template by ID, include the templateβs ID along with its name in your request; only the template with the matching template ID will be deleted.
Read more at developers.facebook.com.
Example
>>> wa = WhatsApp() >>> wa.delete_template(template_name='seasonal_promotion') # Deletes all templates with that name >>> wa.delete_template(template_name='seasonal_promotion', template_id='1234567890') # Deletes only the template with that ID
- Parameters:
template_name (str) β The name of the template to delete.
template_id (int | str | None) β The ID of the template to delete (optional, if provided, only the template with the matching ID will be deleted).
waba_id (str | int | None) β The WhatsApp Business account ID (Overrides the clientβs business account ID, optional).
- Returns:
Whether the template was deleted successfully.
- Return type:
- WhatsApp.unpause_template(template_id)#
Unpause a template that has been paused due to pacing.
You must wait 5 minutes after a template has been paused as a result of pacing before calling this method.
Read more at developers.facebook.com.
- WhatsApp.compare_templates(template_id, *template_ids, start, end)#
You can compare two templates by examining how often each one is sent, which one has the lower ratio of blocks to sends, and each templateβs top reason for being blocked.
Only two templates can be compared at a time.
Both templates must be in the same WhatsApp Business Account.
Templates must have been sent at least 1,000 times in the queries specified timeframe.
Timeframes are limited to
7,30,60and90day lookbacks from the time of the request.Read more at developers.facebook.com.
Example
>>> wa = WhatsApp() >>> now = datetime.datetime.now() >>> result = wa.compare_templates( ... '1234567890', '0987654321', ... start=now - datetime.timedelta(days=30), end=now # Compare templates sent in the last 30 days ... )
- Parameters:
- Returns:
A TemplatesCompareResult object containing the comparison results.
- Return type:
- WhatsApp.migrate_templates(source_waba_id, page_number=None, *, destination_waba_id=None)#
Migrate templates from one WhatsApp Business account to another.
Templates can only be migrated between WABAs owned by the same Meta business.
Only templates with a status of
APPROVEDand a quality_score of eitherGREENorUNKNOWNare eligible for migration.Read more at developers.facebook.com.
- Parameters:
source_waba_id (str | int) β The WhatsApp Business account ID to migrate templates from.
page_number (int | None) β Indicates amount of templates to migrate as sets of 500. Zero-indexed. For example, to migrate 1000 templates, send one request with this value set to 0 and another request with this value set to 1, in parallel.
destination_waba_id (str | int | None) β The WhatsApp Business account ID to migrate templates to (optional, overrides the clientβs business account ID).
- Returns:
A MigrateTemplatesResult object containing the migration results.
- Return type:
- WhatsApp.create_flow(name, categories, *, clone_flow_id=None, endpoint_uri=None, flow_json=None, publish=None, waba_id=None)#
Create a flow.
This method requires the WhatsApp Business account ID to be provided when initializing the client.
New Flows are created in
FlowStatus.DRAFTstatus unlessflow_jsonis provided andpublishis True.To update the flow json, use
update_flow().To send a flow, use
send_flow().
- Parameters:
name (str) β The name of the flow (must be unique, can be used later to update and send the flow).
categories (Iterable[FlowCategory | str]) β The categories of the flow.
flow_json (FlowJSON | dict | str | Path | bytes | BinaryIO | None) β The JSON of the flow (optional, if provided, the flow will be created with the provided JSON).
publish (bool | None) β Whether to publish the flow after creating it, only works if
flow_jsonis provided.clone_flow_id (str | None) β The flow ID to clone (optional).
endpoint_uri (str | None) β The URL of the FlowJSON Endpoint. Starting from Flow 3.0 this property should be specified only gere. Do not provide this field if you are cloning a Flow with version below 3.0.
waba_id (str | int | None) β The WhatsApp Business account ID (Overrides the clientβs business account ID).
- Return type:
Example
>>> from pywa.types.flows import * >>> wa = WhatsApp() >>> wa.create_flow( ... name='Feedback', ... categories=[FlowCategory.SURVEY, FlowCategory.OTHER], ... flow_json=FlowJSON(...), ... publish=True, ... )
- Returns:
The created flow.
- Raises:
FlowBlockedByIntegrity β If you canβt create a flow because of integrity issues.
- Return type:
- WhatsApp.update_flow_metadata(flow_id, *, name=None, categories=None, endpoint_uri=None, application_id=None)#
Update the metadata of a flow.
- Parameters:
name (str | None) β The name of the flow (optional).
categories (Iterable[FlowCategory | str] | None) β The new categories of the flow (optional).
endpoint_uri (str | None) β 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 (int | None) β 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.
- Return type:
Example
>>> from pywa.types.flows import FlowCategory >>> wa = WhatsApp() >>> wa.update_flow_metadata( ... flow_id='1234567890', ... name='Feedback', ... categories=[FlowCategory.SURVEY, FlowCategory.OTHER], ... endpoint_uri='https://my-api-server/feedback_flow', ... application_id=1234567890, ... )
- Returns:
Whether the flow was updated.
- Raises:
ValueError β If neither of the arguments is provided.
- Return type:
- WhatsApp.update_flow_json(flow_id, flow_json)#
Update the json of a flow.
- Parameters:
- Return type:
Examples
>>> wa = WhatsApp()
Using a Flow object:
>>> from pywa.types.flows import * >>> wa.update_flow_json( ... flow_id='1234567890', ... flow_json=FlowJSON(version='7.1', screens=[Screen(...)]) ... )
From a json file path:
>>> wa.update_flow_json( ... flow_id='1234567890', ... flow_json="/home/david/feedback_flow.json" ... )
From a json string:
>>> wa.update_flow_json( ... flow_id='1234567890', ... flow_json="""{"version": "2.1", "screens": [...]}""" ... )
- Returns:
A tuple of (success, validation_errors).
- Raises:
FlowUpdatingError β If the flow json is invalid or the flow is already published.
- Return type:
- WhatsApp.publish_flow(flow_id)#
This request updates the status of the Flow to βPUBLISHEDβ.
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
- Parameters:
- Returns:
Whether the flow was published.
- Raises:
FlowPublishingError β If the flow has validation errors or not all publishing checks have been resolved.
- Return type:
- WhatsApp.delete_flow(flow_id)#
While a Flow is in DRAFT status, it can be deleted.
- Parameters:
- Returns:
Whether the flow was deleted.
- Raises:
FlowDeletingError β If the flow is already published.
- Return type:
- WhatsApp.deprecate_flow(flow_id)#
Once a Flow is published, it cannot be modified or deleted, but can be marked as deprecated.
- Parameters:
- Returns:
Whether the flow was deprecated.
- Raises:
FlowDeprecatingError β If the flow is not published or already deprecated.
- Return type:
- WhatsApp.get_flow(flow_id, *, invalidate_preview=True, phone_number_id=None)#
Get the details of a flow.
- Parameters:
- Returns:
The details of the flow.
- Return type:
- WhatsApp.get_flows(*, invalidate_preview=True, phone_number_id=None, pagination=None, waba_id=None)#
Get the flows associated with the WhatsApp Business account.
This method requires the WhatsApp Business account ID to be provided when initializing the client.
Example
>>> wa = WhatsApp() >>> flows = wa.get_flows( ... invalidate_preview=True, ... phone_number_id='1234567890', ... pagination=Pagination(limit=10) ... ) ... for flow in flows: ... print(f'Flow {flow.id} - {flow.name}: {flow}')
- Parameters:
invalidate_preview (bool) β Whether to invalidate the preview (optional, default: True).
waba_id (str | int | None) β The WhatsApp Business account ID (Overrides the clientβs business account ID).
phone_number_id (str | int | None) β To check that the flows can be used with a specific phone number (optional).
pagination (Pagination | None) β The pagination parameters (optional).
- Returns:
Result object containing the flows.
- Return type:
- WhatsApp.get_flow_metrics(flow_id, metric_name, granularity, *, since=None, until=None)#
Get the metrics of a flow.
Read more at developers.facebook.com.
- Parameters:
metric_name (FlowMetricName) β See Available Metrics.
granularity (FlowMetricGranularity) β Time granularity.
since (date | str | None) β Start of the time period. If not specified, the oldest allowed date will be used. Oldest allowed date depends on the specified time granularity: DAY - 90 days, HOUR - 30 days.
until (date | str | None) β End of the time period. If not specified, the current date will be used.
- Return type:
Returns:
- WhatsApp.get_flow_assets(flow_id, *, pagination=None)#
Get assets attached to a specified Flow.
- Parameters:
pagination (Pagination | None) β The pagination parameters (optional).
- Returns:
Result object containing the assets of the flow.
- Return type:
- WhatsApp.migrate_flows(source_waba_id, source_flow_names, *, destination_waba_id=None)#
Migrate flows from one WhatsApp Business Account to another.
- Parameters:
source_waba_id (str | int) β The source WhatsApp Business Account ID.
source_flow_names (Iterable[str]) β The names of the flows to migrate.
destination_waba_id (str | int | None) β The destination WhatsApp Business Account ID (optional, if not provided, the clientβs business account ID will be used).
- Returns:
The response of the migration request.
- Return type:
- WhatsApp.block_users(users, *, phone_id=None)#
Block users from sending messages to the WhatsApp Business account.
Read more at developers.facebook.com.
You can block users with the
block()orblock_sender()shortcuts.
When you block a WhatsApp user, the following happens:
The user cannot contact your business or see that you are online.
Your business cannot message the user. If you do, you will encounter an error.
You can only block users that have messaged your business in the last 24 hours.
64k blocklist limit
Example
>>> wa = WhatsApp() >>> res = wa.block_users(users=['1234567890', '0987654321']) >>> if res.errors: print(res.failed_users)
- Parameters:
- Returns:
A UsersBlockedResult object with the status of the block operation.
- Return type:
- WhatsApp.unblock_users(users, *, phone_id=None)#
Unblock users that were previously blocked from sending messages to the WhatsApp Business account.
Read more at developers.facebook.com.
Example
>>> wa = WhatsApp() >>> res = wa.unblock_users(users=['1234567890', '0987654321']) >>> print(res.removed_users)
- Parameters:
- Returns:
A UsersUnblockedResult object with the status of the unblock operation.
- Return type:
- WhatsApp.get_blocked_users(*, pagination=None, phone_id=None)#
Get blocked users.
Example
>>> wa = WhatsApp() >>> for user in wa.get_blocked_users(): print(user)
- Parameters:
pagination (Pagination | None) β The pagination parameters (optional).
phone_id (str | int | None) β The phone ID to get the list of blocked users from (optional, if not provided, the clientβs phone ID will be used).
- Returns:
A Result object with the list of blocked users. You can iterate over the result to get the users.
- Return type:
Result[BlockedUser]
- WhatsApp.register_phone_number(pin, *, data_localization_region=None, phone_id=None)#
Register a Business Phone Number
Read more at developers.facebook.com
Example
>>> wa = WhatsApp() >>> wa.register_phone_number(password='111111', data_localization_region='US')
- Parameters:
pin (int | str) β If your verified business phone number already has two-step verification enabled, set this value to your numberβs 6-digit two-step verification PIN. If you cannot recall your PIN, you can uptdate it.
data_localization_region (str | None) β If included, enables local storage on the business phone number. Value must be a 2-letter ISO 3166 country code (e.g.
IN) indicating the country where you want data-at-rest to be stored.phone_id (str | int | None) β The phone ID to register (optional, if not provided, the clientβs phone ID will be used).
- Returns:
The success of the registration.
- Return type:
- WhatsApp.deregister_phone_number(*, phone_id=None)#
Deregister a Business Phone Number.
Read more at developers.facebook.com
- WhatsApp.create_phone_number(*, country_calling_code, phone_number, verified_name, waba_id=None)#
Create a phone number on a WhatsApp Business Account.
Read more at developers.facebook.com.
- Parameters:
country_calling_code (str | int) β The phone numberβs country calling code (e.g. β1β).
phone_number (str | int) β The phone number, with or without the country calling code.
verified_name (str) β The phone numberβs display name.
waba_id (str | int | None) β The WhatsApp Business account ID to create the phone number on (optional, if not provided, the clientβs business account ID will be used).
- Returns:
The created phone number.
- Return type:
CreatedBusinessPhoneNumber
- WhatsApp.request_verification_code(*, code_method, language_code, phone_id=None)#
Request a verification code for a phone number.
Read more at developers.facebook.com.
- Parameters:
code_method (Literal['SMS', 'VOICE']) β Chosen method for verification. Supported options are βSMSβ/βVOICEβ
language_code (str) β The languageβs two-character language code. For example: βenβ.
phone_id (str | int | None) β The phone ID to create the verification code for (optional, if not provided, the clientβs phone ID will be used).
- Returns:
The success of the request.
- Return type:
- WhatsApp.verify_phone_number(code, phone_id=None)#
Verify a phone number with the code received by the user.
Read more at developers.facebook.com.
- Parameters:
- Returns:
The success of the request.
- Return type:
- WhatsApp.create_qr_code(prefilled_message, image_type=QRCodeImageType.PNG, *, phone_id=None)#
Create a QR code for a prefilled message.
Read more at developers.facebook.com
- Parameters:
prefilled_message (str) β The prefilled message.
image_type (QRCodeImageType | Literal['PNG', 'SVG']) β The type of the image (PNG or SVG. Default: PNG).
phone_id (str | int | None) β The phone ID to create the QR code for (optional, if not provided, the clientβs phone ID will be used).
- Returns:
The QR code.
- Return type:
- WhatsApp.get_qr_code(code, *, image_type=None, phone_id=None)#
Get a QR code.
- Parameters:
code (str) β The QR code.
image_type (QRCodeImageType | Literal['PNG', 'SVG'] | None) β The type of the image. if not provided, the image URL will not be returned (faster response).
phone_id (str | int | None) β The phone ID to get the QR code for (optional, if not provided, the clientβs phone ID will be used).
- Returns:
The QR code if found, otherwise None.
- Return type:
QRCode | None
- WhatsApp.get_qr_codes(*, image_type=None, phone_id=None, pagination=None)#
Get QR codes associated with the WhatsApp Phone Number.
- Parameters:
image_type (QRCodeImageType | Literal['PNG', 'SVG'] | None) β The type of the image. If not provided, the image URL will not be returned (faster response).
phone_id (str | int | None) β The phone ID to get the QR codes for (optional, if not provided, the clientβs phone ID will be used).
pagination (Pagination | None) β The pagination parameters (optional).
- Returns:
Result object containing the QR codes.
- Return type:
- WhatsApp.update_qr_code(code, prefilled_message, *, phone_id=None)#
Update a QR code.
- WhatsApp.delete_qr_code(code, *, phone_id=None)#
Delete a QR code.
- Parameters:
- Returns:
Whether the QR code was deleted.
- Return type:
- WhatsApp.set_username(username, *, phone_id=None)#
Set a business username.
Read more at developers.facebook.com.
- Parameters:
- Returns:
A UsernameStatus object containing the new username and its status.
- Return type:
UsernameStatus
- WhatsApp.get_current_username(*, phone_id=None)#
Get the status of the business username associated with the business phone number, or information about the username.
Read more at developers.facebook.com.
- WhatsApp.get_reserved_usernames(*, phone_id=None)#
Get a list of usernames that have been reserved for your business portfolio.
Read more at developers.facebook.com.
- WhatsApp.delete_username(*, phone_id=None)#
Delete the business username associated with the business phone number.
Read more at developers.facebook.com.
- WhatsApp.delete_qr_code(code, *, phone_id=None)#
Delete a QR code.
- Parameters:
- Returns:
Whether the QR code was deleted.
- Return type:
- WhatsApp.get_call_permissions(from_user, *, phone_id=None)#
Get the call permissions for the WhatsApp Business account.
Read more at developers.facebook.com.
- Parameters:
- Returns:
The call permissions for the user.
- Return type:
- WhatsApp.pre_accept_call(call_id, sdp, *, phone_id=None)#
Pre-accept a call.
Read more at developers.facebook.com.
In essence, when you pre-accept an inbound call, you are allowing the calling media connection to be established before attempting to send call media through the connection.
When you then call the accept call endpoint, media begins flowing immediately since the connection has already been established
Pre-accepting calls is recommended because it facilitates faster connection times and avoids audio clipping issues.
There is about 30 to 60 seconds after the Call Connect webhook is sent for the business to accept the phone call. If the business does not respond, the call is terminated on the WhatsApp user side with a βNot Answeredβ notification and a Terminate Webhook is delivered back to you.
- Parameters:
call_id (str) β The ID of the call to pre-accept.
sdp (SessionDescription) β Contains the session description protocol (SDP) type and description language.
phone_id (str | int | None) β The phone ID to pre-accept the call from (optional, if not provided, the clientβs phone ID will be used).
- Returns:
Whether the call was pre-accepted.
- Return type:
- WhatsApp.accept_call(call_id, sdp, *, tracker=None, phone_id=None)#
Connect to a call by providing a call agentβs SDP.
Read more at developers.facebook.com.
You have about 30 to 60 seconds after the Call Connect Webhook is sent to accept the phone call. If your business does not respond, the call is terminated on the WhatsApp user side with a βNot Answeredβ notification and a Terminate Webhook is delivered back to you.
- Parameters:
call_id (str) β The ID of the call to accept.
sdp (SessionDescription) β Contains the session description protocol (SDP) type and description language.
tracker (str | CallbackData | None) β The data to track the call with (optional, up to 512 characters, for complex data You can use
CallbackData).phone_id (str | int | None) β The phone ID to accept the call from (optional, if not provided, the clientβs phone ID will be used).
- Returns:
Whether the call was accepted.
- Return type:
- WhatsApp.reject_call(call_id, *, phone_id=None)#
Reject a call.
Read more at developers.facebook.com.
You have about 30 to 60 seconds after the Call Connect webhook is sent to accept the phone call. If the business does not respond the call is terminated on the WhatsApp user side with a βNot Answeredβ notification and a Terminate Webhook is delivered back to you.
- Parameters:
- Returns:
Whether the call was rejected.
- Return type:
- WhatsApp.terminate_call(call_id, *, phone_id=None)#
Terminate an active call.
Read more at developers.facebook.com.
This must be done even if there is an RTCP BYE packet in the media path. Ending the call this way also ensures pricing is more accurate. When the WhatsApp user terminates the call, you do not have to call this endpoint. Once the call is successfully terminated, a Call Terminate Webhook will be sent to you.
- Parameters:
- Returns:
Whether the call was terminated.
- Return type:
- WhatsApp.create_group(*, subject, description=None, join_approval_mode=None, phone_id=None)#
Create a new group.
Read more at developers.facebook.com.
- Parameters:
subject (str) β Group subject, Maximum 128 characters. Whitespace is trimmed.
description (str | None) β Group description. Maximum 2048 characters.
join_approval_mode (GroupJoinApprovalMode | None) β Indicates if WhatsApp users who click the invitation link can join the group with or without being approved first. Default is
AUTO_APPROVE.phone_id (str | int | None) β The phone ID to create the group for (optional, if not provided, the clientβs phone ID will be used).
- Returns:
The response of the group creation request, containing the request ID to track the status of the group creation.
- Return type:
- WhatsApp.get_group(group_id)#
Get details about a group.
Read more at developers.facebook.com.
- Parameters:
group_id (str) β The ID of the group.
- Returns:
The group details.
- Return type:
- WhatsApp.get_groups(*, phone_id=None, pagination=None)#
Get groups associated with the WhatsApp Business account.
Example
>>> wa = WhatsApp() >>> groups = wa.get_groups(pagination=Pagination(limit=10)) ... for group in groups: ... print(f'Group {group.id}: {group}')
- Parameters:
phone_id (str | int | None) β The phone ID to get the groups for (optional, if not provided, the clientβs phone ID will be used).
pagination (Pagination | None) β The pagination parameters (optional).
- Returns:
Result object containing the groups.
- Return type:
- WhatsApp.delete_group(group_id)#
Delete a group.
Read more at developers.facebook.com.
- Parameters:
group_id (str) β The ID of the group to delete.
- Returns:
The response of the group deletion request, containing the request ID to track the status of the group deletion.
- Return type:
- WhatsApp.approve_group_join_requests(group_id, request_ids)#
Approve join requests for a group.
Read more at developers.facebook.com.
- Parameters:
- Returns:
The response of the join request approval, containing the request ID to track the status of the approval.
- Return type:
- WhatsApp.reject_group_join_requests(group_id, request_ids)#
Reject join requests for a group.
Read more at developers.facebook.com.
- Parameters:
- Returns:
The response of the join request rejection, containing the request ID to track the status of the rejection.
- Return type:
- WhatsApp.get_group_invite_link(group_id)#
Get the invite link for a group.
Read more at developers.facebook.com.
- Parameters:
group_id (str) β The ID of the group.
- Returns:
The group invite link.
- Return type:
- WhatsApp.reset_group_invite_link(group_id)#
Reset the invite link for a group.
Read more at developers.facebook.com.
- Parameters:
group_id (str) β The ID of the group.
- Returns:
The new group invite link.
- Return type:
- WhatsApp.remove_group_participants(group_id, participants)#
Remove participants from a group.
Read more at developers.facebook.com.
- Parameters:
- Returns:
The response of the remove participants request, containing the request ID to track the status of the removal.
- Return type:
- WhatsApp.update_group_settings(group_id, *, subject=None, description=None, profile_picture)#
Update group settings.
Read more at developers.facebook.com.
- Parameters:
group_id (str) β The ID of the group.
subject (str | None) β Group subject, Maximum 128 characters.
description (str | None) β Group description. Maximum 2048 characters.
profile_picture (bytes | str | Path | BinaryIO | Iterator[bytes]) β The new group profile picture. Can be a bytes object, a file path, a file-like object, or an iterator that yields bytes.
- Returns:
The response of the update group settings request, containing the request ID to track the status of the update.
- Return type:
- WhatsApp.pin_message(chat_id, message_id, *, expiration_days, sender=None)#
Pin a message in a chat.
Note that currently only group chats support pinning messages.
Read more at developers.facebook.com.
- Parameters:
chat_id (str | int) β The ID of the chat to pin the message in.
message_id (str) β The ID of the message to pin.
expiration_days (timedelta | int) β The number of days until the pinned message expires. Must be between 1 and 30 days.
sender (str | int | None) β The phone ID to pin the message from (optional, if not provided, the clientβs phone ID will be used).
- Returns:
The pinned message.
- Return type:
- WhatsApp.unpin_message(chat_id, message_id, *, sender=None)#
Unpin a message in a chat.
Note that currently only group chats support pinning messages.
Read more at developers.facebook.com.
- Parameters:
- Returns:
The unpinned message.
- Return type:
- WhatsApp.get_app_access_token(app_id, app_secret)#
Get an access token for an app.
Read more at developers.facebook.com.
- Parameters:
app_id (int) β The ID of the app in the App Basic Settings
app_secret (str) β The app secret.
- Returns:
The access token.
- Return type:
- WhatsApp.set_app_callback_url(app_id, app_access_token, callback_url, verify_token, fields)#
Set the callback URL for the webhook.
Read more at developers.facebook.com.
- Parameters:
app_id (int) β
The ID of the app in the App Basic Settings
app_access_token (str) β The app access token from
get_app_access_token().callback_url (str) β The URL to receive the webhook.
verify_token (str) β The token to verify the webhook.
fields (Iterable[str]) β The fields to subscribe to. See Available Fields.
- Returns:
Whether the callback URL was set.
- Return type:
- WhatsApp.override_waba_callback_url(callback_url, verify_token, *, waba_id=None)#
Override the callback URL for the WhatsApp Business account.
Read more at developers.facebook.com.
- Parameters:
- Returns:
Whether the callback URL was overridden.
- Return type:
- WhatsApp.delete_waba_callback_url(*, waba_id=None)#
Delete the callback URL for the WhatsApp Business account.
Read more at developers.facebook.com.
- WhatsApp.override_phone_callback_url(callback_url, verify_token, *, phone_id=None)#
Override the callback URL for the phone.
Read more at developers.facebook.com.
To access to the current webhook configuration use
get_business_phone_number()and access thewebhook_configurationattribute.
- Parameters:
- Returns:
Whether the callback URL was overridden.
- Return type:
Get the WhatsApp Business Accounts (WABAs) in a business portfolio.
- Parameters:
business_portfolio_id (str | int | None) β The business portfolio ID to get the WABAs from (optional, if not provided, the clientβs business portfolio ID will be used).
pagination (Pagination | None) β Pagination object to paginate through the results (optional).
- Returns:
A Result object containing WhatsAppBusinessAccount objects.
- Return type:
- WhatsApp.get_owned_business_accounts(*, business_portfolio_id=None, pagination=None)#
Get the WhatsApp Business Accounts (WABAs) owned by a business portfolio.
- Parameters:
business_portfolio_id (str | int | None) β The business portfolio ID to get the WABAs from (optional, if not provided, the clientβs business portfolio ID will be used).
pagination (Pagination | None) β Pagination object to paginate through the results (optional).
- Returns:
A Result object containing WhatsAppBusinessAccount objects.
- Return type:
- WhatsApp.delete_phone_callback_url(*, phone_id=None)#
Delete the callback URL for the phone.
Read more at developers.facebook.com.
- WhatsApp.run(*, host='127.0.0.1', port=8000, **options)#
Run the server to listen for incoming updates.
- Parameters:
host (str) β The host to listen on (default:
127.0.0.1)port (int) β The port to listen on (default:
8000)**options (Any) β Additional options to pass to
uvicorn.run(e.g.ssl_keyfile,ssl_certfile, etc.). See the uvicorn documentation for more details.
- WhatsApp.webhook_update_handler(update, hmac_header=None)#
Handle the incoming update manually.
Use this function only if you are using a custom server (e.g. Django etc.).
- WhatsApp.webhook_update_validator(update, hmac_header)#
Validate the incoming webhook update signature.
- Parameters:
- Returns:
A tuple of (error_message, status_code) if validation fails, otherwise None.
- Return type:
- WhatsApp.webhook_challenge_handler(vt, ch)#
Handle the verification challenge from the webhook manually.
Use this function only if you are using a custom server (e.g. Django etc.).
- WhatsApp.get_flow_request_handler(endpoint, callback, acknowledge_errors=True, private_key=None, private_key_password=None, request_decryptor=None, response_encryptor=None)#
Get a function that handles the incoming flow requests.
Use this function only if you are using a custom server (e.g. Django etc.), else use the
WhatsApp.on_flow_request()decorator.
- Parameters:
endpoint (str) β The endpoint to listen to (The endpoint uri you set to the flow. e.g
/feedback_flow).callback (Callable[[WhatsApp, FlowRequest], FlowResponse | dict | None | Awaitable[FlowResponse | dict | None]]) β The callback function to call when a flow request is received.
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 (Callable[[str, str, str, str, str | None], tuple[dict, bytes, bytes]] | None) β The function to use to decrypt the requests (Override the global
flows_request_decryptor)response_encryptor (Callable[[dict, bytes, bytes], str] | None) β The function to use to encrypt the responses (Override the global
flows_response_encryptor)
- Returns:
A function that handles the incoming flow request and returns (response, status_code).
- Return type:
- 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])