Callback Selection#
- class pywa.types.CallbackSelection#
Represents a callback selection (Incoming update when user clicks on
SectionRow
inSectionList
).CallbackSelection
is a generic class, so when providing afactory
parameter in callback handlers, you can specify the type of the factory to get autocomplete in thedata
attribute.Here is an example:
>>> from pywa.types import CallbackData >>> from dataclasses import dataclass >>> @dataclass(frozen=True, slots=True) >>> class UserData(CallbackData): # Subclass CallbackData ... id: int ... name: str ... admin: bool
>>> from pywa import WhatsApp >>> from pywa.types import SectionList, Section, SectionRow, CallbackSelection >>> wa = WhatsApp(...) >>> wa.send_message( ... to='972987654321', ... text='Click the button to get the user', ... buttons=SectionList( ... button_title='Get user', sections=[ ... Section(title='Users', rows=[ ... SectionRow(title='Get user', callback_data=UserData(id=123, name='david', admin=True)) ... ]) # Here ^^^ we use the UserData class as the callback data ... ] ... ) ... )
>>> @wa.on_callback_selection(factory=UserData) # Use the factory parameter to convert the callback data ... def on_user_data(_: WhatsApp, sel: CallbackSelection[UserData]): # For autocomplete ... if sel.data.admin: print(sel.data.id) # Access the data object as an attribute
You can even use multiple factories, and not only
CallbackData
subclasses!>>> from enum import Enum >>> class State(str, Enum): ... START = 's' ... END = 'e'
>>> wa.send_message( ... to='972987654321', ... text='Click the button to get the user and state', ... buttons=SectionList( ... button_title='Get user', sections=[ ... Section(title='Users', rows=[ ... SectionRow(title='Get user', callback_data=(UserData(id=123, name='david', admin=True), State.START)) ... ]) # Here ^^^ we send a tuple of UserData and State ... ] ... ) ... )
>>> @wa.on_callback_selection(factory=(UserData, State)) # Use the factory parameter to convert the callback data ... def on_user_data(_: WhatsApp, sel: CallbackSelection[tuple[UserData, State]]): # For autocomplete ... user, state = sel.data # Unpack the tuple ... if user.admin: print(user.id, state)
- Variables:
id (str) – The ID of the message.
metadata (pywa.types.others.Metadata) – The metadata of the message (to which phone number it was sent).
type (pywa.types.others.MessageType) – The message type (always
MessageType.INTERACTIVE
).from_user (pywa.types.others.User) – The user who sent the message.
timestamp (datetime.datetime) – The timestamp when the message was sent.
reply_to_message (pywa.types.others.ReplyToMessage) – The message to which this callback selection is a reply to.
data (pywa.types.callback.CallbackDataT) – The data of the selection (the
callback_data
parameter you provided inSectionRow
).title (str) – The title of the selection.
description (str | None) – The description of the selection (optional).