Skip to content

API Reference

This page provides an auto-generated API reference for the key components of the WhatsPlay library.

Client

The Client is the main entry point for interacting with WhatsApp.

Method Returns Notes
start() / stop() None start() runs the main loop until stop() is called.
wait_until_logged_in(timeout=60) bool
refresh(timeout=180) bool Reloads WhatsApp Web to release renderer memory; emits on_refresh.
open(chat_name, timeout=10000, open_via_url=False, is_group=None) bool True only when the open chat is verifiably the requested one.
close() None Closes the current chat.
search_conversations(query, close=True) List[Dict]
collect_messages(own_push_names=None, dispose=False) List[Message] Includes FileMessage and VoiceMessage items.
send_message(chat_query, message, open_via_url=False, is_group=None) bool True only after WhatsApp shows the new message with a delivery status.
send_file(chat_name, path, open_via_url=False, is_group=None) bool Same confirmation as send_message.
react_to_last_message(emoji) bool
download_all_files(carpeta=None, detect_codecs=True) List[Dict] Each dict: path, type, and codec (when detected).
download_file_by_index(index, carpeta=None) Optional[Dict] Dict with path and type.
new_group(group_name, members) bool
add_members_to_group(group_name, members) bool
del_members_from_group(group_name, members) bool
page_lock (property) ReentrantLock async with client.page_lock: to run several operations atomically.
running (property) bool

WhatsPlay does not define custom exceptions: failures are reported as False, [], or None, plus an on_error event and a log record.

whatsplay.client.Client

Bases: BaseWhatsAppClient

High-level WhatsApp Web client with full automation capabilities.

This client provides a complete interface for WhatsApp Web automation including authentication, chat management, message sending, and event handling.

Attributes:

Name Type Description
locale

Locale for the browser (default: "en-US")

poll_freq

Frequency of state polling in seconds

current_state Optional[State]

Current WhatsApp Web state

unread_messages_sleep

Sleep time between unread message checks

wa_elements Optional[WhatsAppElements]

WhatsApp Web elements helper

chat_manager Optional[ChatManager]

Chat operations manager

state_manager Optional[StateManager]

State transition manager

Example

client = Client(auth=LocalProfileAuth("./session")) @client.event("on_logged_in") ... async def on_ready(): ... print("Client is ready!") await client.start()

Source code in src/whatsplay/client.py
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
class Client(BaseWhatsAppClient):
    """
    High-level WhatsApp Web client with full automation capabilities.

    This client provides a complete interface for WhatsApp Web automation
    including authentication, chat management, message sending, and event handling.

    Attributes:
        locale: Locale for the browser (default: "en-US")
        poll_freq: Frequency of state polling in seconds
        current_state: Current WhatsApp Web state
        unread_messages_sleep: Sleep time between unread message checks
        wa_elements: WhatsApp Web elements helper
        chat_manager: Chat operations manager
        state_manager: State transition manager

    Example:
        >>> client = Client(auth=LocalProfileAuth("./session"))
        >>> @client.event("on_logged_in")
        ... async def on_ready():
        ...     print("Client is ready!")
        >>> await client.start()
    """

    def __init__(
        self,
        user_data_dir: Optional[str] = None,
        headless: bool = False,
        locale: str = "en-US",
        auth: Optional[Any] = None,
    ) -> None:
        """
        Initialize the WhatsApp Web client.

        Args:
            user_data_dir: Directory for browser profile data
            headless: Run browser in headless mode
            locale: Browser locale setting
            auth: Authentication provider instance
        """
        super().__init__(
            user_data_dir=user_data_dir, headless=headless, auth=auth, locale=locale
        )
        self._cached_chats: set = set()
        self.poll_freq = DEFAULT_POLL_FREQUENCY
        self.wa_elements: Optional[WhatsAppElements] = None
        self.qr_task: Optional[asyncio.Task] = None
        self.current_state: Optional[State] = None
        self.unread_messages_sleep = DEFAULT_UNREAD_MESSAGES_SLEEP
        self._shutdown_event = asyncio.Event()
        # Serializes every page operation; see page_lock.py.
        self._page_lock = ReentrantLock()
        self._consecutive_errors = 0
        self.last_qr_shown: Optional[bytes] = None
        self.chat_manager: Optional[ChatManager] = None
        self.state_manager: Optional[StateManager] = None
        self._setup_signal_handlers()

    def _setup_signal_handlers(self) -> None:
        """
        Configure signal handlers for clean shutdown.

        Sets up handlers for SIGINT and SIGTERM to ensure proper cleanup
        when the process is terminated.
        """
        if sys.platform != "win32":
            for sig in (signal.SIGINT, signal.SIGTERM):
                try:
                    asyncio.get_event_loop().add_signal_handler(
                        sig, lambda s=sig: asyncio.create_task(self._handle_signal(s))
                    )
                except (NotImplementedError, RuntimeError):
                    signal.signal(
                        sig, lambda s, f: asyncio.create_task(self._handle_signal(s))
                    )
        else:
            for sig in (signal.SIGINT, signal.SIGTERM):
                signal.signal(
                    sig, lambda s, f: asyncio.create_task(self._handle_signal(s))
                )

    async def _handle_signal(self, signum: int) -> None:
        """
        Handle system signals for graceful shutdown.

        Args:
            signum: Signal number received
        """
        signame = (
            signal.Signals(signum).name if hasattr(signal, "Signals") else str(signum)
        )
        logger.info(f"\nReceived signal {signame}. Shutting down gracefully...")
        self._shutdown_event.set()
        await self.stop()
        sys.exit(0)

    @property
    def running(self) -> bool:
        """Check if the client is currently running."""
        return getattr(self, "_is_running", False)

    async def stop(self) -> None:
        """
        Stop the client and clean up resources.

        This method ensures all resources are properly released including
        browser instances, pages, and the Playwright instance.
        """
        if not getattr(self, "_is_running", False):
            return

        self._is_running = False

        try:
            # Close page
            if hasattr(self, "_page") and self._page:
                try:
                    await self._page.close()
                except Exception as e:
                    await self.emit("on_error", f"Error closing page: {e}")
                finally:
                    self._page = None

            # Call parent stop
            await super().stop()

            # Close browser
            if hasattr(self, "_browser") and self._browser:
                try:
                    await self._browser.close()
                except Exception as e:
                    await self.emit("on_error", f"Error closing browser: {e}")
                finally:
                    self._browser = None

            # Stop playwright
            if hasattr(self, "playwright") and self.playwright:
                try:
                    await self.playwright.stop()
                except Exception as e:
                    await self.emit("on_error", f"Error stopping Playwright: {e}")
                finally:
                    self.playwright = None

        except Exception as e:
            await self.emit("on_error", f"Error during cleanup: {e}")
        finally:
            await self.emit("on_stop")
            self._shutdown_event.set()

    @property
    def page_lock(self) -> ReentrantLock:
        """Lock held by every page operation. Hold it across several calls that
        must not be interleaved with the background scan, e.g.::

            async with client.page_lock:
                if await client.open(chat):
                    messages = await client.collect_messages()
        """
        return self._page_lock

    def _bind_components(self) -> None:
        """(Re)create the page-bound helpers for the current self._page."""
        self.wa_elements = WhatsAppElements(self._page)
        self.chat_manager = ChatManager(self)
        self.state_manager = StateManager(self)

    async def reconnect(self) -> None:
        """Reconnect and rebind every helper to the new page.

        The base reconnect opens a new page; helpers created for the old one
        would otherwise keep driving a closed page.
        """
        await super().reconnect()
        self._bind_components()

    async def start(self) -> None:
        """
        Start the WhatsApp Web client.

        Initializes all components and begins the main event loop.
        This method will run until the client is stopped.

        Raises:
            Exception: If initialization or main loop fails
        """
        try:
            await super().start()
            self._bind_components()
            self._is_running = True
            await self._main_loop()

        except asyncio.CancelledError:
            await self.emit("on_info", "Operation cancelled")
            raise
        except Exception as e:
            await self.emit("on_error", f"Error in main loop: {e}")
            raise
        finally:
            await self.stop()

    async def _main_loop(self) -> None:
        """
        Initialize and start the main event loop.

        Sets up initial state and begins monitoring WhatsApp Web.
        """
        if not self._page:
            await self.emit("on_error", "Could not initialize page")
            return

        await self.emit("on_start")

        await self._run_main_loop()

    async def _run_main_loop(self) -> None:
        """
        Execute the main event loop.

        Continuously monitors WhatsApp Web state and handles state transitions
        until the client is stopped or encounters unrecoverable errors.
        """
        state: Optional[State] = None

        while self._is_running and not self._shutdown_event.is_set():
            try:
                curr_state = await self.state_manager._get_state()
                self.current_state = curr_state

                if curr_state is None:
                    await asyncio.sleep(self.poll_freq)
                    continue

                if curr_state != state:
                    await self.state_manager._handle_state_change(curr_state, state)
                    state = curr_state
                    self._consecutive_errors = (
                        0  # Reset error counter on successful state change
                    )
                else:
                    await self.state_manager._handle_same_state(curr_state)

                await self.emit("on_tick")
                await asyncio.sleep(self.poll_freq)

            except asyncio.CancelledError:
                await self.emit("on_info", "Main loop cancelled")
                raise

            except Exception as e:
                self._consecutive_errors += 1
                await self.emit("on_error", f"Error in loop iteration: {e}")
                await asyncio.sleep(1)

                if self._consecutive_errors > MAX_CONSECUTIVE_ERRORS:
                    await self.emit(
                        "on_warning",
                        "Too many consecutive errors, attempting to reconnect...",
                    )
                    try:
                        await self.reconnect()
                        self._consecutive_errors = 0
                    except Exception as reconnect_error:
                        await self.emit(
                            "on_error", f"Reconnection error: {reconnect_error}"
                        )
                        break

    async def wait_until_logged_in(self, timeout: int = DEFAULT_LOGIN_TIMEOUT) -> bool:
        """
        Wait until the client is logged in.

        Args:
            timeout: Maximum time to wait in seconds

        Returns:
            True if logged in within timeout, False otherwise
        """
        start = time.time()
        while time.time() - start < timeout:
            if self.current_state == State.LOGGED_IN:
                return True
            await asyncio.sleep(self.poll_freq)

        await self.emit("on_error", "Login timeout expired")
        return False

    async def refresh(self, timeout: int = 180) -> bool:
        """
        Reload WhatsApp Web to release accumulated renderer memory.

        WhatsApp Web accumulates detached DOM nodes and JS heap over hours of
        use. Left running, the renderer reaches V8's heap ceiling and crashes
        with SIGTRAP ("Target crashed"). A page reload destroys the JS context
        and frees all of it; cookies persist, so the session survives and no QR
        is needed.

        Intended to be called periodically by the consumer (the schedule is an
        operational policy, not a library concern).

        Args:
            timeout: Maximum seconds to wait for the client to log back in.

        Returns:
            True when the client is logged in again after the reload.
        """
        if not self._page:
            return False
        # Force a fresh state read: current_state is stale right after a
        # reload, and wait_until_logged_in would return immediately on it.
        self.current_state = None
        # No other page operation may run while the page is being replaced.
        async with self._page_lock:
            try:
                await self._page.reload(wait_until="domcontentloaded", timeout=60000)
            except Exception as e:
                await self.emit("on_error", f"refresh: reload failed: {e}")
                return False
            # A tick may have read the old DOM during the reload; read again.
            self.current_state = None
            if getattr(self, "wa_elements", None):
                self.wa_elements._search_active = False
        await self.emit("on_refresh")
        return await self.wait_until_logged_in(timeout=timeout)

    # -------------------------------------------------------------------------
    # Delegated methods to ChatManager
    # -------------------------------------------------------------------------

    async def close(self) -> None:
        """Close the currently open chat."""
        async with self._page_lock:
            return await self.chat_manager.close()

    async def open(
        self,
        chat_name: str,
        timeout: int = 10000,
        open_via_url: bool = False,
        is_group: Optional[bool] = None,
    ) -> bool:
        """
        Open a chat by name.

        Args:
            chat_name: Name of the chat to open
            timeout: Maximum wait time in milliseconds
            open_via_url: Force opening via URL (for phone numbers)
            is_group: If set, the chat must be a group (True) or a contact (False)

        Returns:
            True if chat was opened successfully
        """
        async with self._page_lock:
            return await self.chat_manager.open(
                chat_name, timeout, open_via_url=open_via_url, is_group=is_group
            )

    async def search_conversations(
        self, query: str, close: bool = True
    ) -> List[Dict[str, Any]]:
        """
        Search for conversations.

        Args:
            query: Search term
            close: Close search after completion

        Returns:
            List of matching conversations
        """
        async with self._page_lock:
            return await self.chat_manager.search_conversations(query, close)

    async def collect_messages(
        self,
        own_push_names: Optional[Union[str, list]] = None,
        dispose: bool = False,
    ) -> List[Union[Message, FileMessage]]:
        """
        Collect all visible messages in the current chat.

        Args:
            own_push_names: Account push names identifying own bubbles
                (e.g. ["Marcos Bustos"]). Forwarded to ChatManager so own
                continuation bubbles without tail markers are still
                flagged outgoing. Compared accent/case-insensitively.
            dispose: When True, release each message's container handle
                before returning. Pass True for data-only consumers that
                read text/sender/timestamp but never call react()/download();
                this prevents DOM handles from accumulating in the renderer
                across poll cycles.

        Returns:
            List of Message and FileMessage objects
        """
        async with self._page_lock:
            return await self.chat_manager.collect_messages(
                own_push_names=own_push_names, dispose=dispose
            )

    async def download_all_files(
        self, carpeta: Optional[str] = None, detect_codecs: bool = True
    ) -> List[Dict[str, Any]]:
        """
        Download all files from the current chat.

        Args:
            carpeta: Optional custom download directory
            detect_codecs: If True, detect codec info for each file

        Returns:
            List of dicts with path, type, and codec info
        """
        async with self._page_lock:
            return await self.chat_manager.download_all_files(carpeta, detect_codecs)

    async def download_file_by_index(
        self, index: int, carpeta: Optional[str] = None
    ) -> Optional[Dict[str, Any]]:
        """
        Download a specific file by index.

        Args:
            index: Zero-based file index
            carpeta: Optional custom download directory

        Returns:
            Dict with path and codec info, or None if failed
        """
        async with self._page_lock:
            return await self.chat_manager.download_file_by_index(index, carpeta)

    async def send_message(
        self,
        chat_query: str,
        message: str,
        open_via_url: bool = False,
        is_group: Optional[bool] = None,
    ) -> bool:
        """
        Send a text message.

        Args:
            chat_query: Chat name or identifier
            message: Message text to send
            open_via_url: Open chat via URL before sending
            is_group: If set, the chat must be a group (True) or a contact (False)

        Returns:
            True if message was sent successfully
        """
        async with self._page_lock:
            return await self.chat_manager.send_message(
                chat_query, message, open_via_url=open_via_url, is_group=is_group
            )

    async def send_file(
        self,
        chat_name: str,
        path: str,
        open_via_url: bool = False,
        is_group: Optional[bool] = None,
    ) -> bool:
        """
        Send a file attachment.

        Args:
            chat_name: Name of the chat
            path: Absolute path to the file
            open_via_url: Open chat via URL before sending (required for phone numbers)
            is_group: If set, the chat must be a group (True) or a contact (False)

        Returns:
            True if file was sent successfully
        """
        async with self._page_lock:
            return await self.chat_manager.send_file(
                chat_name, path, open_via_url=open_via_url, is_group=is_group
            )

    async def react_to_last_message(self, emoji: str) -> bool:
        """
        React to the last visible message in the current chat.

        Args:
            emoji: The emoji to react with (e.g., "👍", "❤️")

        Returns:
            True if reaction was successful
        """
        async with self._page_lock:
            return await self.chat_manager.react_to_last_message(emoji)

    async def new_group(self, group_name: str, members: List[str]) -> bool:
        """
        Create a new group.

        Args:
            group_name: Name for the new group
            members: List of member names

        Returns:
            True if group was created successfully
        """
        async with self._page_lock:
            return await self.wa_elements.new_group(group_name, members)

    async def add_members_to_group(self, group_name: str, members: List[str]) -> bool:
        """
        Add members to an existing group.

        Args:
            group_name: Name of the group
            members: List of member names to add

        Returns:
            True if members were added successfully
        """
        async with self._page_lock:
            return await self.wa_elements.add_members_to_group(group_name, members)

    async def del_members_from_group(self, group_name: str, members: List[str]) -> bool:
        """
        Elimina varios miembros de un grupo procesando la lista completa.
        """
        if not await self.wait_until_logged_in():
            return False

        results = []
        async with self._page_lock:
            for member in members:
                # pasamos el nombre individual, no la lista
                success = await self.wa_elements.del_member_group(group_name, member)
                results.append(success)

        return all(results)  # devuelve True solo si todos fueron eliminados

page_lock property

Lock held by every page operation. Hold it across several calls that must not be interleaved with the background scan, e.g.::

async with client.page_lock:
    if await client.open(chat):
        messages = await client.collect_messages()

running property

Check if the client is currently running.

__init__(user_data_dir=None, headless=False, locale='en-US', auth=None)

Initialize the WhatsApp Web client.

Parameters:

Name Type Description Default
user_data_dir Optional[str]

Directory for browser profile data

None
headless bool

Run browser in headless mode

False
locale str

Browser locale setting

'en-US'
auth Optional[Any]

Authentication provider instance

None
Source code in src/whatsplay/client.py
def __init__(
    self,
    user_data_dir: Optional[str] = None,
    headless: bool = False,
    locale: str = "en-US",
    auth: Optional[Any] = None,
) -> None:
    """
    Initialize the WhatsApp Web client.

    Args:
        user_data_dir: Directory for browser profile data
        headless: Run browser in headless mode
        locale: Browser locale setting
        auth: Authentication provider instance
    """
    super().__init__(
        user_data_dir=user_data_dir, headless=headless, auth=auth, locale=locale
    )
    self._cached_chats: set = set()
    self.poll_freq = DEFAULT_POLL_FREQUENCY
    self.wa_elements: Optional[WhatsAppElements] = None
    self.qr_task: Optional[asyncio.Task] = None
    self.current_state: Optional[State] = None
    self.unread_messages_sleep = DEFAULT_UNREAD_MESSAGES_SLEEP
    self._shutdown_event = asyncio.Event()
    # Serializes every page operation; see page_lock.py.
    self._page_lock = ReentrantLock()
    self._consecutive_errors = 0
    self.last_qr_shown: Optional[bytes] = None
    self.chat_manager: Optional[ChatManager] = None
    self.state_manager: Optional[StateManager] = None
    self._setup_signal_handlers()

add_members_to_group(group_name, members) async

Add members to an existing group.

Parameters:

Name Type Description Default
group_name str

Name of the group

required
members List[str]

List of member names to add

required

Returns:

Type Description
bool

True if members were added successfully

Source code in src/whatsplay/client.py
async def add_members_to_group(self, group_name: str, members: List[str]) -> bool:
    """
    Add members to an existing group.

    Args:
        group_name: Name of the group
        members: List of member names to add

    Returns:
        True if members were added successfully
    """
    async with self._page_lock:
        return await self.wa_elements.add_members_to_group(group_name, members)

close() async

Close the currently open chat.

Source code in src/whatsplay/client.py
async def close(self) -> None:
    """Close the currently open chat."""
    async with self._page_lock:
        return await self.chat_manager.close()

collect_messages(own_push_names=None, dispose=False) async

Collect all visible messages in the current chat.

Parameters:

Name Type Description Default
own_push_names Optional[Union[str, list]]

Account push names identifying own bubbles (e.g. ["Marcos Bustos"]). Forwarded to ChatManager so own continuation bubbles without tail markers are still flagged outgoing. Compared accent/case-insensitively.

None
dispose bool

When True, release each message's container handle before returning. Pass True for data-only consumers that read text/sender/timestamp but never call react()/download(); this prevents DOM handles from accumulating in the renderer across poll cycles.

False

Returns:

Type Description
List[Union[Message, FileMessage]]

List of Message and FileMessage objects

Source code in src/whatsplay/client.py
async def collect_messages(
    self,
    own_push_names: Optional[Union[str, list]] = None,
    dispose: bool = False,
) -> List[Union[Message, FileMessage]]:
    """
    Collect all visible messages in the current chat.

    Args:
        own_push_names: Account push names identifying own bubbles
            (e.g. ["Marcos Bustos"]). Forwarded to ChatManager so own
            continuation bubbles without tail markers are still
            flagged outgoing. Compared accent/case-insensitively.
        dispose: When True, release each message's container handle
            before returning. Pass True for data-only consumers that
            read text/sender/timestamp but never call react()/download();
            this prevents DOM handles from accumulating in the renderer
            across poll cycles.

    Returns:
        List of Message and FileMessage objects
    """
    async with self._page_lock:
        return await self.chat_manager.collect_messages(
            own_push_names=own_push_names, dispose=dispose
        )

del_members_from_group(group_name, members) async

Elimina varios miembros de un grupo procesando la lista completa.

Source code in src/whatsplay/client.py
async def del_members_from_group(self, group_name: str, members: List[str]) -> bool:
    """
    Elimina varios miembros de un grupo procesando la lista completa.
    """
    if not await self.wait_until_logged_in():
        return False

    results = []
    async with self._page_lock:
        for member in members:
            # pasamos el nombre individual, no la lista
            success = await self.wa_elements.del_member_group(group_name, member)
            results.append(success)

    return all(results)  # devuelve True solo si todos fueron eliminados

download_all_files(carpeta=None, detect_codecs=True) async

Download all files from the current chat.

Parameters:

Name Type Description Default
carpeta Optional[str]

Optional custom download directory

None
detect_codecs bool

If True, detect codec info for each file

True

Returns:

Type Description
List[Dict[str, Any]]

List of dicts with path, type, and codec info

Source code in src/whatsplay/client.py
async def download_all_files(
    self, carpeta: Optional[str] = None, detect_codecs: bool = True
) -> List[Dict[str, Any]]:
    """
    Download all files from the current chat.

    Args:
        carpeta: Optional custom download directory
        detect_codecs: If True, detect codec info for each file

    Returns:
        List of dicts with path, type, and codec info
    """
    async with self._page_lock:
        return await self.chat_manager.download_all_files(carpeta, detect_codecs)

download_file_by_index(index, carpeta=None) async

Download a specific file by index.

Parameters:

Name Type Description Default
index int

Zero-based file index

required
carpeta Optional[str]

Optional custom download directory

None

Returns:

Type Description
Optional[Dict[str, Any]]

Dict with path and codec info, or None if failed

Source code in src/whatsplay/client.py
async def download_file_by_index(
    self, index: int, carpeta: Optional[str] = None
) -> Optional[Dict[str, Any]]:
    """
    Download a specific file by index.

    Args:
        index: Zero-based file index
        carpeta: Optional custom download directory

    Returns:
        Dict with path and codec info, or None if failed
    """
    async with self._page_lock:
        return await self.chat_manager.download_file_by_index(index, carpeta)

new_group(group_name, members) async

Create a new group.

Parameters:

Name Type Description Default
group_name str

Name for the new group

required
members List[str]

List of member names

required

Returns:

Type Description
bool

True if group was created successfully

Source code in src/whatsplay/client.py
async def new_group(self, group_name: str, members: List[str]) -> bool:
    """
    Create a new group.

    Args:
        group_name: Name for the new group
        members: List of member names

    Returns:
        True if group was created successfully
    """
    async with self._page_lock:
        return await self.wa_elements.new_group(group_name, members)

open(chat_name, timeout=10000, open_via_url=False, is_group=None) async

Open a chat by name.

Parameters:

Name Type Description Default
chat_name str

Name of the chat to open

required
timeout int

Maximum wait time in milliseconds

10000
open_via_url bool

Force opening via URL (for phone numbers)

False
is_group Optional[bool]

If set, the chat must be a group (True) or a contact (False)

None

Returns:

Type Description
bool

True if chat was opened successfully

Source code in src/whatsplay/client.py
async def open(
    self,
    chat_name: str,
    timeout: int = 10000,
    open_via_url: bool = False,
    is_group: Optional[bool] = None,
) -> bool:
    """
    Open a chat by name.

    Args:
        chat_name: Name of the chat to open
        timeout: Maximum wait time in milliseconds
        open_via_url: Force opening via URL (for phone numbers)
        is_group: If set, the chat must be a group (True) or a contact (False)

    Returns:
        True if chat was opened successfully
    """
    async with self._page_lock:
        return await self.chat_manager.open(
            chat_name, timeout, open_via_url=open_via_url, is_group=is_group
        )

react_to_last_message(emoji) async

React to the last visible message in the current chat.

Parameters:

Name Type Description Default
emoji str

The emoji to react with (e.g., "👍", "❤️")

required

Returns:

Type Description
bool

True if reaction was successful

Source code in src/whatsplay/client.py
async def react_to_last_message(self, emoji: str) -> bool:
    """
    React to the last visible message in the current chat.

    Args:
        emoji: The emoji to react with (e.g., "👍", "❤️")

    Returns:
        True if reaction was successful
    """
    async with self._page_lock:
        return await self.chat_manager.react_to_last_message(emoji)

reconnect() async

Reconnect and rebind every helper to the new page.

The base reconnect opens a new page; helpers created for the old one would otherwise keep driving a closed page.

Source code in src/whatsplay/client.py
async def reconnect(self) -> None:
    """Reconnect and rebind every helper to the new page.

    The base reconnect opens a new page; helpers created for the old one
    would otherwise keep driving a closed page.
    """
    await super().reconnect()
    self._bind_components()

refresh(timeout=180) async

Reload WhatsApp Web to release accumulated renderer memory.

WhatsApp Web accumulates detached DOM nodes and JS heap over hours of use. Left running, the renderer reaches V8's heap ceiling and crashes with SIGTRAP ("Target crashed"). A page reload destroys the JS context and frees all of it; cookies persist, so the session survives and no QR is needed.

Intended to be called periodically by the consumer (the schedule is an operational policy, not a library concern).

Parameters:

Name Type Description Default
timeout int

Maximum seconds to wait for the client to log back in.

180

Returns:

Type Description
bool

True when the client is logged in again after the reload.

Source code in src/whatsplay/client.py
async def refresh(self, timeout: int = 180) -> bool:
    """
    Reload WhatsApp Web to release accumulated renderer memory.

    WhatsApp Web accumulates detached DOM nodes and JS heap over hours of
    use. Left running, the renderer reaches V8's heap ceiling and crashes
    with SIGTRAP ("Target crashed"). A page reload destroys the JS context
    and frees all of it; cookies persist, so the session survives and no QR
    is needed.

    Intended to be called periodically by the consumer (the schedule is an
    operational policy, not a library concern).

    Args:
        timeout: Maximum seconds to wait for the client to log back in.

    Returns:
        True when the client is logged in again after the reload.
    """
    if not self._page:
        return False
    # Force a fresh state read: current_state is stale right after a
    # reload, and wait_until_logged_in would return immediately on it.
    self.current_state = None
    # No other page operation may run while the page is being replaced.
    async with self._page_lock:
        try:
            await self._page.reload(wait_until="domcontentloaded", timeout=60000)
        except Exception as e:
            await self.emit("on_error", f"refresh: reload failed: {e}")
            return False
        # A tick may have read the old DOM during the reload; read again.
        self.current_state = None
        if getattr(self, "wa_elements", None):
            self.wa_elements._search_active = False
    await self.emit("on_refresh")
    return await self.wait_until_logged_in(timeout=timeout)

search_conversations(query, close=True) async

Search for conversations.

Parameters:

Name Type Description Default
query str

Search term

required
close bool

Close search after completion

True

Returns:

Type Description
List[Dict[str, Any]]

List of matching conversations

Source code in src/whatsplay/client.py
async def search_conversations(
    self, query: str, close: bool = True
) -> List[Dict[str, Any]]:
    """
    Search for conversations.

    Args:
        query: Search term
        close: Close search after completion

    Returns:
        List of matching conversations
    """
    async with self._page_lock:
        return await self.chat_manager.search_conversations(query, close)

send_file(chat_name, path, open_via_url=False, is_group=None) async

Send a file attachment.

Parameters:

Name Type Description Default
chat_name str

Name of the chat

required
path str

Absolute path to the file

required
open_via_url bool

Open chat via URL before sending (required for phone numbers)

False
is_group Optional[bool]

If set, the chat must be a group (True) or a contact (False)

None

Returns:

Type Description
bool

True if file was sent successfully

Source code in src/whatsplay/client.py
async def send_file(
    self,
    chat_name: str,
    path: str,
    open_via_url: bool = False,
    is_group: Optional[bool] = None,
) -> bool:
    """
    Send a file attachment.

    Args:
        chat_name: Name of the chat
        path: Absolute path to the file
        open_via_url: Open chat via URL before sending (required for phone numbers)
        is_group: If set, the chat must be a group (True) or a contact (False)

    Returns:
        True if file was sent successfully
    """
    async with self._page_lock:
        return await self.chat_manager.send_file(
            chat_name, path, open_via_url=open_via_url, is_group=is_group
        )

send_message(chat_query, message, open_via_url=False, is_group=None) async

Send a text message.

Parameters:

Name Type Description Default
chat_query str

Chat name or identifier

required
message str

Message text to send

required
open_via_url bool

Open chat via URL before sending

False
is_group Optional[bool]

If set, the chat must be a group (True) or a contact (False)

None

Returns:

Type Description
bool

True if message was sent successfully

Source code in src/whatsplay/client.py
async def send_message(
    self,
    chat_query: str,
    message: str,
    open_via_url: bool = False,
    is_group: Optional[bool] = None,
) -> bool:
    """
    Send a text message.

    Args:
        chat_query: Chat name or identifier
        message: Message text to send
        open_via_url: Open chat via URL before sending
        is_group: If set, the chat must be a group (True) or a contact (False)

    Returns:
        True if message was sent successfully
    """
    async with self._page_lock:
        return await self.chat_manager.send_message(
            chat_query, message, open_via_url=open_via_url, is_group=is_group
        )

start() async

Start the WhatsApp Web client.

Initializes all components and begins the main event loop. This method will run until the client is stopped.

Raises:

Type Description
Exception

If initialization or main loop fails

Source code in src/whatsplay/client.py
async def start(self) -> None:
    """
    Start the WhatsApp Web client.

    Initializes all components and begins the main event loop.
    This method will run until the client is stopped.

    Raises:
        Exception: If initialization or main loop fails
    """
    try:
        await super().start()
        self._bind_components()
        self._is_running = True
        await self._main_loop()

    except asyncio.CancelledError:
        await self.emit("on_info", "Operation cancelled")
        raise
    except Exception as e:
        await self.emit("on_error", f"Error in main loop: {e}")
        raise
    finally:
        await self.stop()

stop() async

Stop the client and clean up resources.

This method ensures all resources are properly released including browser instances, pages, and the Playwright instance.

Source code in src/whatsplay/client.py
async def stop(self) -> None:
    """
    Stop the client and clean up resources.

    This method ensures all resources are properly released including
    browser instances, pages, and the Playwright instance.
    """
    if not getattr(self, "_is_running", False):
        return

    self._is_running = False

    try:
        # Close page
        if hasattr(self, "_page") and self._page:
            try:
                await self._page.close()
            except Exception as e:
                await self.emit("on_error", f"Error closing page: {e}")
            finally:
                self._page = None

        # Call parent stop
        await super().stop()

        # Close browser
        if hasattr(self, "_browser") and self._browser:
            try:
                await self._browser.close()
            except Exception as e:
                await self.emit("on_error", f"Error closing browser: {e}")
            finally:
                self._browser = None

        # Stop playwright
        if hasattr(self, "playwright") and self.playwright:
            try:
                await self.playwright.stop()
            except Exception as e:
                await self.emit("on_error", f"Error stopping Playwright: {e}")
            finally:
                self.playwright = None

    except Exception as e:
        await self.emit("on_error", f"Error during cleanup: {e}")
    finally:
        await self.emit("on_stop")
        self._shutdown_event.set()

wait_until_logged_in(timeout=DEFAULT_LOGIN_TIMEOUT) async

Wait until the client is logged in.

Parameters:

Name Type Description Default
timeout int

Maximum time to wait in seconds

DEFAULT_LOGIN_TIMEOUT

Returns:

Type Description
bool

True if logged in within timeout, False otherwise

Source code in src/whatsplay/client.py
async def wait_until_logged_in(self, timeout: int = DEFAULT_LOGIN_TIMEOUT) -> bool:
    """
    Wait until the client is logged in.

    Args:
        timeout: Maximum time to wait in seconds

    Returns:
        True if logged in within timeout, False otherwise
    """
    start = time.time()
    while time.time() - start < timeout:
        if self.current_state == State.LOGGED_IN:
            return True
        await asyncio.sleep(self.poll_freq)

    await self.emit("on_error", "Login timeout expired")
    return False

Events

These events are emitted by the Client and can be handled using the @client.event decorator.

Event Name Trigger Condition Arguments
on_start The client has initialized and the browser page is open. None
on_auth The authentication screen (QR code page) is displayed. None
on_qr A new QR code is detected for the first time. qr_binary (bytes)
on_qr_change The displayed QR code has been refreshed/changed. qr_binary (bytes)
on_logged_in The client has successfully logged in to WhatsApp Web. None
on_loading The "Loading chats" screen is visible. is_loading (bool)
on_unread_chat Unread chats are detected in the sidebar (checked periodically). chats (List[Dict])
on_refresh client.refresh() reloaded the page. None
on_stop The client is stopping and cleaning up resources. None
on_disconnect The client has lost connection to the browser/WhatsApp. None
on_reconnect The client has successfully reconnected. None
on_state_change The connection state changed (e.g. CONNECTING). state (State enum)
on_tick Emitted on every iteration of the main event loop. None
on_error An error occurred. message (str)
on_warning A non-critical issue occurred (e.g. a dialog that could not be closed). message (str)
on_info Informational message. message (str)

The on_unread_chat payload is described in Handling Messages.

Note: The on_message event is reserved for future use. Currently, use on_unread_chat to detect new activity.


Message Objects

client.collect_messages() returns these objects.

Message

A text message. Main attributes: text, sender (str), timestamp (datetime), is_outgoing (bool), msg_id, direction_signal, sender_inherited, kind (WhatsApp's message type such as "chat", "image", "sticker", "ptt", or None when unknown). Use is_from_self(own_push_names) to check whether you sent it, react(emoji) to react, and dispose() to release its browser handles.

whatsplay.object.message.Message

Represents a WhatsApp message.

This object encapsulates all data related to a single message in a chat, including its content, sender, timestamp, and interactivity methods.

Attributes:

Name Type Description
page Page

The Playwright Page object.

sender str

The name or phone number of the sender.

timestamp datetime

The time the message was received.

text str

The text content of the message.

container ElementHandle

The DOM element containing the message.

is_outgoing bool

True if the message was sent by the user, False otherwise.

msg_id str

The unique identifier of the message.

kind Optional[str]

WhatsApp's message type ("chat", "image", "sticker", "ptt"...), set only by collect_messages; None otherwise or when unknown.

Source code in src/whatsplay/object/message.py
class Message:
    """
    Represents a WhatsApp message.

    This object encapsulates all data related to a single message in a chat,
    including its content, sender, timestamp, and interactivity methods.

    Attributes:
        page (Page): The Playwright Page object.
        sender (str): The name or phone number of the sender.
        timestamp (datetime): The time the message was received.
        text (str): The text content of the message.
        container (ElementHandle): The DOM element containing the message.
        is_outgoing (bool): True if the message was sent by the user, False otherwise.
        msg_id (str): The unique identifier of the message.
        kind (Optional[str]): WhatsApp's message type ("chat", "image", "sticker",
            "ptt"...), set only by collect_messages; None otherwise or when unknown.
    """

    def __init__(
        self,
        page: Page,
        sender: str,
        timestamp: datetime,
        text: str,
        container: ElementHandle,
        is_outgoing: bool = False,
        msg_id: str = "",
        sender_inherited: bool = False,
        direction_signal: str = "none",
    ):
        self.page = page
        self.sender = sender
        self.timestamp = timestamp
        self.text = text
        self.container = container
        self.is_outgoing = is_outgoing
        self.msg_id = msg_id
        # True when sender was inherited from a neighboring bubble in
        # collect_messages (sender-less continuation). Display-only: consumers
        # must use is_outgoing / is_from_self() for skip logic, never this.
        self.sender_inherited = sender_inherited
        # Which signal decided is_outgoing (a DirectionSignal value; see
        # DIRECTION_ORDER for precedence).
        self.direction_signal = direction_signal
        # WhatsApp's message type ("chat", "image", "sticker", "ptt"...), set
        # by collect_messages from the message model. None when unknown.
        self.kind: Optional[str] = None

    def is_from_self(self, own_push_names: Optional[Iterable[str]] = None) -> bool:
        """Safe skip decision for bot consumers.

        Returns True when the bubble is structurally outgoing OR its sender
        is the account identity ("Tu" or one of own_push_names). An
        inherited display sender alone never counts as self.
        """
        if self.is_outgoing:
            return True
        if self.sender_inherited or not self.sender:
            return False
        own = normalize_own_push_names(own_push_names) | OWN_SENDER_TOKENS
        return normalize_sender_name(self.sender) in own

    async def dispose(self) -> None:
        """Release the DOM handle held by this message.

        The container ElementHandle pins its DOM node in the renderer until
        disposed. A long-running consumer that only reads text/sender/
        timestamp should call this after each message (or after each batch)
        so handles do not accumulate until the renderer runs out of
        committable V8 heap and crashes. Safe to call more than once and on
        messages whose interactive methods are never used.
        """
        await _safe_dispose(self.container)
        self.container = None

    @classmethod
    async def from_element(
        cls,
        elem: ElementHandle,
        page: Page,
        own_push_names: Optional[Iterable[str]] = None,
        model_texts: Optional[Dict[str, str]] = None,
    ) -> Optional["Message"]:
        """
        Create a Message instance from a DOM element.

        Args:
            elem: The message container element.
            page: The Playwright page.
            own_push_names: Account push names identifying own bubbles
                (e.g. ["Bikes Amigorena"]). Compared accent/case-insensitively.

        Direction precedence is DIRECTION_ORDER (see module constants):
        tail is ground truth for group leaders; class and data-id are
        opportunistic (dead in some WA Web builds, never required) and
        outrank group inheritance; group inheritance (ChatManager, applied
        after this method) outranks positional; positional measures the
        inner bubble and abstains on inconclusive geometry; sender identity
        ("Tu", or own_push_names when explicitly passed) is an optional
        last resort. A bubble with no signal in either direction defaults
        to incoming with direction_signal "none" (documented fail-safe;
        ChatManager flags survivors via the fallback counter + log).

        Returns:
            A new Message instance or None if parsing fails.
        """
        # Handles created for parsing only: they stay referenced by Playwright
        # until disposed, so every one of them is released in the finally
        # below. The returned Message keeps only elem (the container) alive for
        # interactive methods (react); collect_messages owns the container.
        pre_plain = remitente_span = None
        tail_out = tail_in = message_out = message_in = delivery_status = None
        selectable = None
        try:
            # 0) ID if exists (outer container first, inner row fallback:
            #    data-id may live on a descendant, not on the conv-msg node).
            msg_id = (await elem.get_attribute("data-id")) or ""
            msg_id = await _resolve_data_id(elem, msg_id)
            testid = (await elem.get_attribute("data-testid")) or ""

            # 1) Sender + Timestamp: ambos desde data-pre-plain-text
            #    Formato: "[HH:MM(:SS)?] Sender Name: message text"
            sender = ""
            timestamp = datetime.now()
            pre_plain = await elem.query_selector("[data-pre-plain-text]")
            if pre_plain:
                raw = await pre_plain.get_attribute("data-pre-plain-text")
                if raw:
                    # Sender (después del "] ")
                    if "] " in raw:
                        sender = raw.split("] ", 1)[1].rstrip(": ").strip()
                    # Timestamp (desde el bracket)
                    parsed_ts = parse_timestamp(raw)
                    if parsed_ts:
                        timestamp = parsed_ts
            if not sender:
                # Fallback: aria-label del span remitente (solo primer msg de cada uno)
                remitente_span = await elem.query_selector(
                    'xpath=.//span[@aria-label and substring(@aria-label, string-length(@aria-label))=":"]'
                )
                if remitente_span:
                    raw_label = await remitente_span.get_attribute("aria-label")
                    if raw_label:
                        sender = raw_label.rstrip(":").strip()

            # Direction layers in DIRECTION_ORDER precedence (tail first).
            # Class + data-id stay opportunistic (dead in some builds);
            # positional is the primary continuation signal; sender identity
            # is an optional last resort (never required).
            is_outgoing = False
            direction_signal = DirectionSignal.NONE

            tail_out = await elem.query_selector('[data-testid="tail-out"]')
            tail_in = await elem.query_selector('[data-testid="tail-in"]')
            # Only outgoing messages carry a delivery status ("Enviado",
            # "Entregado", "Leído"), tail or not (verified live 2026-10-20).
            delivery_status = await elem.query_selector(_DELIVERY_STATUS)
            # Direction classes may sit on the container itself
            # (el.classList) or on a descendant; check both at once.
            # The descendant query_selector is kept as a fallback for
            # handles where evaluate is unavailable.
            message_out = await elem.query_selector(".message-out")
            message_in = await elem.query_selector(".message-in")
            has_message_out = message_out is not None or await _self_or_descendant_has_class(
                elem, "message-out"
            )
            has_message_in = message_in is not None or await _self_or_descendant_has_class(
                elem, "message-in"
            )

            # data-id direction bit: "true_<chat>_<id>" = own, "false_..." = peer.
            data_id_outgoing: Optional[bool] = None
            if msg_id:
                head = msg_id.split("_", 1)[0].casefold()
                if head == "true":
                    data_id_outgoing = True
                elif head == "false":
                    data_id_outgoing = False

            positional_side = await _resolve_positional_side(elem)

            # Sender identity is a last resort: "Tu" always counts as own
            # (WhatsApp's own-message label, not per-account config), while
            # account push names only count when explicitly passed
            # (own_push_names is not None). Consulted solely when tail +
            # class + data-id + positional are all inconclusive.
            if own_push_names is None:
                configured_own: frozenset = frozenset()
            else:
                configured_own = normalize_own_push_names(own_push_names)
            own_names = configured_own | OWN_SENDER_TOKENS
            sender_is_own = bool(sender) and normalize_sender_name(sender) in own_names

            if tail_out is not None:
                is_outgoing, direction_signal = True, DirectionSignal.TAIL_OUT
            elif tail_in is not None:
                direction_signal = DirectionSignal.TAIL_IN
            elif delivery_status is not None:
                is_outgoing, direction_signal = True, DirectionSignal.STATUS_OUT
            elif has_message_out:
                is_outgoing, direction_signal = True, DirectionSignal.CLASS_OUT
            elif has_message_in:
                direction_signal = DirectionSignal.CLASS_IN
            elif data_id_outgoing is True:
                is_outgoing, direction_signal = True, DirectionSignal.DATA_ID_OUT
            elif data_id_outgoing is False:
                direction_signal = DirectionSignal.DATA_ID_IN
            elif positional_side == "right":
                is_outgoing, direction_signal = True, DirectionSignal.POSITION_OUT
            elif positional_side == "left":
                direction_signal = DirectionSignal.POSITION_IN
            elif sender_is_own:
                # Optional last resort for sender-signed bubbles when every
                # structural and geometric signal is inconclusive. (The
                # legacy conv-msg-AC prefix fallback was removed in v2.5.0:
                # Sept 2026 live evidence showed the AC prefix on every row
                # in both directions, so it only produced false outgoing.)
                is_outgoing, direction_signal = True, DirectionSignal.SENDER_OWN

            # 3) Text
            texto = ""
            selectable = await elem.query_selector('[data-testid="selectable-text"]')
            if selectable:
                raw_inner = await selectable.inner_text()
                if raw_inner:
                    lineas = raw_inner.split("\n")
                    if len(lineas) > 1 and (lineas[0].strip().startswith(sender) or ":" in lineas[0]):
                        texto = "\n".join(lineas[1:]).strip()
                    else:
                        texto = raw_inner.strip()
            if model_texts is not None:
                # Batch read by collect_messages: no page round trip per bubble.
                model_text = model_texts.get(_text_key(msg_id)) if msg_id else None
            else:
                model_text = await _model_text(page, msg_id)
            if model_text is not None:
                if model_text.split() != texto.split():  # blank lines are not news
                    # Captions and replies: worth seeing in the consumer's log.
                    logger.info("message %s: model text %r replaces DOM text %r",
                                msg_id, model_text[:60], texto[:60])
                texto = model_text

            return cls(
                page=page,
                sender=sender,
                timestamp=timestamp,
                text=texto,
                container=elem,
                is_outgoing=is_outgoing,
                msg_id=msg_id,
                direction_signal=direction_signal,
            )
        except Exception as ex:
            logger.debug("Message.from_element EXCEPTION for %s: %s: %s", testid, type(ex).__name__, ex)
            return None
        finally:
            # Release parse-only handles: they pin DOM nodes in the renderer
            # and, multiplied across every chat read, are the reason memory
            # climbs without bound until the renderer crashes.
            await _safe_dispose(pre_plain)
            await _safe_dispose(remitente_span)
            await _safe_dispose(tail_out)
            await _safe_dispose(tail_in)
            await _safe_dispose(delivery_status)
            await _safe_dispose(message_out)
            await _safe_dispose(message_in)
            await _safe_dispose(selectable)

    async def react(self, emoji: str):
        """
        Reacts to this message with the given emoji.

        This method simulates the user interaction of hovering over the message,
        clicking the reaction button, and selecting an emoji.

        Args:
            emoji (str): The emoji character to react with (e.g., "👍", "❤️").
        """

        try:
            # 1. Hover over the message to make the action bar appear.
            await self.container.hover()
            await asyncio.sleep(0.5)

            # 2. Find reaction button
            reaction_bar = self.page.locator('[aria-label="Reaccionar"]')
            if not reaction_bar:
                return None
            await reaction_bar.click()

            # 3. Find "More reactions" button
            more_reactions_button_handle = self.page.locator('[aria-label="Más reacciones"]')
            if not more_reactions_button_handle:
                return None

            await more_reactions_button_handle.click()

            # 4. Find emoji in picker
            emoji_in_picker = self.page.locator(f'[data-emoji="{emoji}"]')

            # 5. Click emoji
            await emoji_in_picker.wait_for(state="visible", timeout=5000)
            await emoji_in_picker.click()

        except Exception as e:
            logger.warning(f"An error occurred while reacting to message {self.msg_id}: {e}")

dispose() async

Release the DOM handle held by this message.

The container ElementHandle pins its DOM node in the renderer until disposed. A long-running consumer that only reads text/sender/ timestamp should call this after each message (or after each batch) so handles do not accumulate until the renderer runs out of committable V8 heap and crashes. Safe to call more than once and on messages whose interactive methods are never used.

Source code in src/whatsplay/object/message.py
async def dispose(self) -> None:
    """Release the DOM handle held by this message.

    The container ElementHandle pins its DOM node in the renderer until
    disposed. A long-running consumer that only reads text/sender/
    timestamp should call this after each message (or after each batch)
    so handles do not accumulate until the renderer runs out of
    committable V8 heap and crashes. Safe to call more than once and on
    messages whose interactive methods are never used.
    """
    await _safe_dispose(self.container)
    self.container = None

from_element(elem, page, own_push_names=None, model_texts=None) async classmethod

Create a Message instance from a DOM element.

Parameters:

Name Type Description Default
elem ElementHandle

The message container element.

required
page Page

The Playwright page.

required
own_push_names Optional[Iterable[str]]

Account push names identifying own bubbles (e.g. ["Bikes Amigorena"]). Compared accent/case-insensitively.

None

Direction precedence is DIRECTION_ORDER (see module constants): tail is ground truth for group leaders; class and data-id are opportunistic (dead in some WA Web builds, never required) and outrank group inheritance; group inheritance (ChatManager, applied after this method) outranks positional; positional measures the inner bubble and abstains on inconclusive geometry; sender identity ("Tu", or own_push_names when explicitly passed) is an optional last resort. A bubble with no signal in either direction defaults to incoming with direction_signal "none" (documented fail-safe; ChatManager flags survivors via the fallback counter + log).

Returns:

Type Description
Optional[Message]

A new Message instance or None if parsing fails.

Source code in src/whatsplay/object/message.py
@classmethod
async def from_element(
    cls,
    elem: ElementHandle,
    page: Page,
    own_push_names: Optional[Iterable[str]] = None,
    model_texts: Optional[Dict[str, str]] = None,
) -> Optional["Message"]:
    """
    Create a Message instance from a DOM element.

    Args:
        elem: The message container element.
        page: The Playwright page.
        own_push_names: Account push names identifying own bubbles
            (e.g. ["Bikes Amigorena"]). Compared accent/case-insensitively.

    Direction precedence is DIRECTION_ORDER (see module constants):
    tail is ground truth for group leaders; class and data-id are
    opportunistic (dead in some WA Web builds, never required) and
    outrank group inheritance; group inheritance (ChatManager, applied
    after this method) outranks positional; positional measures the
    inner bubble and abstains on inconclusive geometry; sender identity
    ("Tu", or own_push_names when explicitly passed) is an optional
    last resort. A bubble with no signal in either direction defaults
    to incoming with direction_signal "none" (documented fail-safe;
    ChatManager flags survivors via the fallback counter + log).

    Returns:
        A new Message instance or None if parsing fails.
    """
    # Handles created for parsing only: they stay referenced by Playwright
    # until disposed, so every one of them is released in the finally
    # below. The returned Message keeps only elem (the container) alive for
    # interactive methods (react); collect_messages owns the container.
    pre_plain = remitente_span = None
    tail_out = tail_in = message_out = message_in = delivery_status = None
    selectable = None
    try:
        # 0) ID if exists (outer container first, inner row fallback:
        #    data-id may live on a descendant, not on the conv-msg node).
        msg_id = (await elem.get_attribute("data-id")) or ""
        msg_id = await _resolve_data_id(elem, msg_id)
        testid = (await elem.get_attribute("data-testid")) or ""

        # 1) Sender + Timestamp: ambos desde data-pre-plain-text
        #    Formato: "[HH:MM(:SS)?] Sender Name: message text"
        sender = ""
        timestamp = datetime.now()
        pre_plain = await elem.query_selector("[data-pre-plain-text]")
        if pre_plain:
            raw = await pre_plain.get_attribute("data-pre-plain-text")
            if raw:
                # Sender (después del "] ")
                if "] " in raw:
                    sender = raw.split("] ", 1)[1].rstrip(": ").strip()
                # Timestamp (desde el bracket)
                parsed_ts = parse_timestamp(raw)
                if parsed_ts:
                    timestamp = parsed_ts
        if not sender:
            # Fallback: aria-label del span remitente (solo primer msg de cada uno)
            remitente_span = await elem.query_selector(
                'xpath=.//span[@aria-label and substring(@aria-label, string-length(@aria-label))=":"]'
            )
            if remitente_span:
                raw_label = await remitente_span.get_attribute("aria-label")
                if raw_label:
                    sender = raw_label.rstrip(":").strip()

        # Direction layers in DIRECTION_ORDER precedence (tail first).
        # Class + data-id stay opportunistic (dead in some builds);
        # positional is the primary continuation signal; sender identity
        # is an optional last resort (never required).
        is_outgoing = False
        direction_signal = DirectionSignal.NONE

        tail_out = await elem.query_selector('[data-testid="tail-out"]')
        tail_in = await elem.query_selector('[data-testid="tail-in"]')
        # Only outgoing messages carry a delivery status ("Enviado",
        # "Entregado", "Leído"), tail or not (verified live 2026-10-20).
        delivery_status = await elem.query_selector(_DELIVERY_STATUS)
        # Direction classes may sit on the container itself
        # (el.classList) or on a descendant; check both at once.
        # The descendant query_selector is kept as a fallback for
        # handles where evaluate is unavailable.
        message_out = await elem.query_selector(".message-out")
        message_in = await elem.query_selector(".message-in")
        has_message_out = message_out is not None or await _self_or_descendant_has_class(
            elem, "message-out"
        )
        has_message_in = message_in is not None or await _self_or_descendant_has_class(
            elem, "message-in"
        )

        # data-id direction bit: "true_<chat>_<id>" = own, "false_..." = peer.
        data_id_outgoing: Optional[bool] = None
        if msg_id:
            head = msg_id.split("_", 1)[0].casefold()
            if head == "true":
                data_id_outgoing = True
            elif head == "false":
                data_id_outgoing = False

        positional_side = await _resolve_positional_side(elem)

        # Sender identity is a last resort: "Tu" always counts as own
        # (WhatsApp's own-message label, not per-account config), while
        # account push names only count when explicitly passed
        # (own_push_names is not None). Consulted solely when tail +
        # class + data-id + positional are all inconclusive.
        if own_push_names is None:
            configured_own: frozenset = frozenset()
        else:
            configured_own = normalize_own_push_names(own_push_names)
        own_names = configured_own | OWN_SENDER_TOKENS
        sender_is_own = bool(sender) and normalize_sender_name(sender) in own_names

        if tail_out is not None:
            is_outgoing, direction_signal = True, DirectionSignal.TAIL_OUT
        elif tail_in is not None:
            direction_signal = DirectionSignal.TAIL_IN
        elif delivery_status is not None:
            is_outgoing, direction_signal = True, DirectionSignal.STATUS_OUT
        elif has_message_out:
            is_outgoing, direction_signal = True, DirectionSignal.CLASS_OUT
        elif has_message_in:
            direction_signal = DirectionSignal.CLASS_IN
        elif data_id_outgoing is True:
            is_outgoing, direction_signal = True, DirectionSignal.DATA_ID_OUT
        elif data_id_outgoing is False:
            direction_signal = DirectionSignal.DATA_ID_IN
        elif positional_side == "right":
            is_outgoing, direction_signal = True, DirectionSignal.POSITION_OUT
        elif positional_side == "left":
            direction_signal = DirectionSignal.POSITION_IN
        elif sender_is_own:
            # Optional last resort for sender-signed bubbles when every
            # structural and geometric signal is inconclusive. (The
            # legacy conv-msg-AC prefix fallback was removed in v2.5.0:
            # Sept 2026 live evidence showed the AC prefix on every row
            # in both directions, so it only produced false outgoing.)
            is_outgoing, direction_signal = True, DirectionSignal.SENDER_OWN

        # 3) Text
        texto = ""
        selectable = await elem.query_selector('[data-testid="selectable-text"]')
        if selectable:
            raw_inner = await selectable.inner_text()
            if raw_inner:
                lineas = raw_inner.split("\n")
                if len(lineas) > 1 and (lineas[0].strip().startswith(sender) or ":" in lineas[0]):
                    texto = "\n".join(lineas[1:]).strip()
                else:
                    texto = raw_inner.strip()
        if model_texts is not None:
            # Batch read by collect_messages: no page round trip per bubble.
            model_text = model_texts.get(_text_key(msg_id)) if msg_id else None
        else:
            model_text = await _model_text(page, msg_id)
        if model_text is not None:
            if model_text.split() != texto.split():  # blank lines are not news
                # Captions and replies: worth seeing in the consumer's log.
                logger.info("message %s: model text %r replaces DOM text %r",
                            msg_id, model_text[:60], texto[:60])
            texto = model_text

        return cls(
            page=page,
            sender=sender,
            timestamp=timestamp,
            text=texto,
            container=elem,
            is_outgoing=is_outgoing,
            msg_id=msg_id,
            direction_signal=direction_signal,
        )
    except Exception as ex:
        logger.debug("Message.from_element EXCEPTION for %s: %s: %s", testid, type(ex).__name__, ex)
        return None
    finally:
        # Release parse-only handles: they pin DOM nodes in the renderer
        # and, multiplied across every chat read, are the reason memory
        # climbs without bound until the renderer crashes.
        await _safe_dispose(pre_plain)
        await _safe_dispose(remitente_span)
        await _safe_dispose(tail_out)
        await _safe_dispose(tail_in)
        await _safe_dispose(delivery_status)
        await _safe_dispose(message_out)
        await _safe_dispose(message_in)
        await _safe_dispose(selectable)

is_from_self(own_push_names=None)

Safe skip decision for bot consumers.

Returns True when the bubble is structurally outgoing OR its sender is the account identity ("Tu" or one of own_push_names). An inherited display sender alone never counts as self.

Source code in src/whatsplay/object/message.py
def is_from_self(self, own_push_names: Optional[Iterable[str]] = None) -> bool:
    """Safe skip decision for bot consumers.

    Returns True when the bubble is structurally outgoing OR its sender
    is the account identity ("Tu" or one of own_push_names). An
    inherited display sender alone never counts as self.
    """
    if self.is_outgoing:
        return True
    if self.sender_inherited or not self.sender:
        return False
    own = normalize_own_push_names(own_push_names) | OWN_SENDER_TOKENS
    return normalize_sender_name(self.sender) in own

react(emoji) async

Reacts to this message with the given emoji.

This method simulates the user interaction of hovering over the message, clicking the reaction button, and selecting an emoji.

Parameters:

Name Type Description Default
emoji str

The emoji character to react with (e.g., "👍", "❤️").

required
Source code in src/whatsplay/object/message.py
async def react(self, emoji: str):
    """
    Reacts to this message with the given emoji.

    This method simulates the user interaction of hovering over the message,
    clicking the reaction button, and selecting an emoji.

    Args:
        emoji (str): The emoji character to react with (e.g., "👍", "❤️").
    """

    try:
        # 1. Hover over the message to make the action bar appear.
        await self.container.hover()
        await asyncio.sleep(0.5)

        # 2. Find reaction button
        reaction_bar = self.page.locator('[aria-label="Reaccionar"]')
        if not reaction_bar:
            return None
        await reaction_bar.click()

        # 3. Find "More reactions" button
        more_reactions_button_handle = self.page.locator('[aria-label="Más reacciones"]')
        if not more_reactions_button_handle:
            return None

        await more_reactions_button_handle.click()

        # 4. Find emoji in picker
        emoji_in_picker = self.page.locator(f'[data-emoji="{emoji}"]')

        # 5. Click emoji
        await emoji_in_picker.wait_for(state="visible", timeout=5000)
        await emoji_in_picker.click()

    except Exception as e:
        logger.warning(f"An error occurred while reacting to message {self.msg_id}: {e}")

FileMessage

A document or media attachment. Adds filename and download(page, downloads_dir).

whatsplay.object.message.FileMessage

Bases: Message

Represents a message containing a downloadable file.

Inherits from Message and adds specific functionality for handling media and document attachments.

Attributes:

Name Type Description
filename str

The name of the file (e.g., "document.pdf").

download_icon ElementHandle

The DOM element for the download button.

Source code in src/whatsplay/object/message.py
class FileMessage(Message):
    """
    Represents a message containing a downloadable file.

    Inherits from `Message` and adds specific functionality for handling
    media and document attachments.

    Attributes:
        filename (str): The name of the file (e.g., "document.pdf").
        download_icon (ElementHandle): The DOM element for the download button.
    """

    def __init__(
        self,
        page: Page,
        sender: str,
        timestamp: datetime,
        text: str,
        container: ElementHandle,
        filename: str,
        download_icon: ElementHandle,
        is_outgoing: bool = False,
        msg_id: str = "",
        sender_inherited: bool = False,
        direction_signal: str = "none",
    ):
        super().__init__(
            page,
            sender,
            timestamp,
            text,
            container,
            is_outgoing=is_outgoing,
            msg_id=msg_id,
            sender_inherited=sender_inherited,
            direction_signal=direction_signal,
        )
        self.filename = filename
        self.download_icon = download_icon

    @classmethod
    async def from_element(
        cls,
        elem: ElementHandle,
        page: Page,
        own_push_names: Optional[Iterable[str]] = None,
        model_texts: Optional[Dict[str, str]] = None,
    ) -> Optional["FileMessage"]:
        """
        Create a FileMessage from a DOM element.

        Checks for the presence of a download/document icon and extracts the filename.

        Args:
            elem: The message container element.
            page: The Playwright page.
            own_push_names: Account push names identifying own bubbles.

        Returns:
            A new FileMessage instance or None if not a valid file message.
        """
        try:
            # 1) Find file icon (try multiple selectors for compatibility)
            icon = await _find_file_icon(elem)
            if not icon:
                return None

            # 2) Extract filename from DOM
            filename = await _extract_filename(icon)
            if not filename:
                # Icon is not a real file attachment: release it now.
                await _safe_dispose(icon)
                return None

            # 3) Extract base message data
            base_msg = await Message.from_element(elem, page, own_push_names, model_texts=model_texts)
            if not base_msg:
                await _safe_dispose(icon)
                return None

            return cls(
                page=page,
                sender=base_msg.sender,
                timestamp=base_msg.timestamp,
                text=base_msg.text,
                container=elem,
                filename=filename,
                download_icon=icon,
                is_outgoing=base_msg.is_outgoing,
                msg_id=base_msg.msg_id,
                sender_inherited=base_msg.sender_inherited,
                direction_signal=base_msg.direction_signal,
            )

        except Exception:
            return None

    async def download(self, page: Page, downloads_dir: Path) -> Optional[Path]:
        """
        Download the attached file.

        Clicks the download icon and waits for the download to complete.

        Args:
            page: The Playwright Page object.
            downloads_dir: The directory where the file should be saved.

        Returns:
            The Path to the saved file, or None if the download failed.
        """
        try:
            # 1) Create directory
            downloads_dir.mkdir(parents=True, exist_ok=True)

            # 2) Wait for download
            async with page.expect_download() as evento:
                await self.download_icon.click()
            descarga: Download = await evento.value

            # 3) Get filename and path
            suggested = descarga.suggested_filename or self.filename
            destino = downloads_dir / suggested

            # 4) Save to disk
            await descarga.save_as(str(destino))
            return destino

        except Exception:
            return None

    async def dispose(self) -> None:
        """Release the container and download-icon handles held by this file message."""
        await _safe_dispose(self.download_icon)
        self.download_icon = None
        await super().dispose()

    def get_codec_info(self, file_path: Path) -> Optional[Dict[str, Any]]:
        """
        Get codec information from a downloaded audio file.

        Args:
            file_path: Path to the downloaded audio file

        Returns:
            Dict with codec info or None if detection fails
        """
        return detect_codec(file_path)

dispose() async

Release the container and download-icon handles held by this file message.

Source code in src/whatsplay/object/message.py
async def dispose(self) -> None:
    """Release the container and download-icon handles held by this file message."""
    await _safe_dispose(self.download_icon)
    self.download_icon = None
    await super().dispose()

download(page, downloads_dir) async

Download the attached file.

Clicks the download icon and waits for the download to complete.

Parameters:

Name Type Description Default
page Page

The Playwright Page object.

required
downloads_dir Path

The directory where the file should be saved.

required

Returns:

Type Description
Optional[Path]

The Path to the saved file, or None if the download failed.

Source code in src/whatsplay/object/message.py
async def download(self, page: Page, downloads_dir: Path) -> Optional[Path]:
    """
    Download the attached file.

    Clicks the download icon and waits for the download to complete.

    Args:
        page: The Playwright Page object.
        downloads_dir: The directory where the file should be saved.

    Returns:
        The Path to the saved file, or None if the download failed.
    """
    try:
        # 1) Create directory
        downloads_dir.mkdir(parents=True, exist_ok=True)

        # 2) Wait for download
        async with page.expect_download() as evento:
            await self.download_icon.click()
        descarga: Download = await evento.value

        # 3) Get filename and path
        suggested = descarga.suggested_filename or self.filename
        destino = downloads_dir / suggested

        # 4) Save to disk
        await descarga.save_as(str(destino))
        return destino

    except Exception:
        return None

from_element(elem, page, own_push_names=None, model_texts=None) async classmethod

Create a FileMessage from a DOM element.

Checks for the presence of a download/document icon and extracts the filename.

Parameters:

Name Type Description Default
elem ElementHandle

The message container element.

required
page Page

The Playwright page.

required
own_push_names Optional[Iterable[str]]

Account push names identifying own bubbles.

None

Returns:

Type Description
Optional[FileMessage]

A new FileMessage instance or None if not a valid file message.

Source code in src/whatsplay/object/message.py
@classmethod
async def from_element(
    cls,
    elem: ElementHandle,
    page: Page,
    own_push_names: Optional[Iterable[str]] = None,
    model_texts: Optional[Dict[str, str]] = None,
) -> Optional["FileMessage"]:
    """
    Create a FileMessage from a DOM element.

    Checks for the presence of a download/document icon and extracts the filename.

    Args:
        elem: The message container element.
        page: The Playwright page.
        own_push_names: Account push names identifying own bubbles.

    Returns:
        A new FileMessage instance or None if not a valid file message.
    """
    try:
        # 1) Find file icon (try multiple selectors for compatibility)
        icon = await _find_file_icon(elem)
        if not icon:
            return None

        # 2) Extract filename from DOM
        filename = await _extract_filename(icon)
        if not filename:
            # Icon is not a real file attachment: release it now.
            await _safe_dispose(icon)
            return None

        # 3) Extract base message data
        base_msg = await Message.from_element(elem, page, own_push_names, model_texts=model_texts)
        if not base_msg:
            await _safe_dispose(icon)
            return None

        return cls(
            page=page,
            sender=base_msg.sender,
            timestamp=base_msg.timestamp,
            text=base_msg.text,
            container=elem,
            filename=filename,
            download_icon=icon,
            is_outgoing=base_msg.is_outgoing,
            msg_id=base_msg.msg_id,
            sender_inherited=base_msg.sender_inherited,
            direction_signal=base_msg.direction_signal,
        )

    except Exception:
        return None

get_codec_info(file_path)

Get codec information from a downloaded audio file.

Parameters:

Name Type Description Default
file_path Path

Path to the downloaded audio file

required

Returns:

Type Description
Optional[Dict[str, Any]]

Dict with codec info or None if detection fails

Source code in src/whatsplay/object/message.py
def get_codec_info(self, file_path: Path) -> Optional[Dict[str, Any]]:
    """
    Get codec information from a downloaded audio file.

    Args:
        file_path: Path to the downloaded audio file

    Returns:
        Dict with codec info or None if detection fails
    """
    return detect_codec(file_path)

VoiceMessage

A voice note. Adds duration and download(page, downloads_dir).

whatsplay.object.message.VoiceMessage

Bases: Message

Represents a voice message without visible download icon.

This class handles voice messages that need to be played first to trigger the download capability.

Source code in src/whatsplay/object/message.py
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
class VoiceMessage(Message):
    """
    Represents a voice message without visible download icon.

    This class handles voice messages that need to be played first
    to trigger the download capability.
    """

    def __init__(
        self,
        page: Page,
        sender: str,
        timestamp: datetime,
        text: str,
        container: ElementHandle,
        duration: str = "",
        is_outgoing: bool = False,
        msg_id: str = "",
        sender_inherited: bool = False,
        direction_signal: str = "none",
    ):
        super().__init__(
            page,
            sender,
            timestamp,
            text,
            container,
            is_outgoing=is_outgoing,
            msg_id=msg_id,
            sender_inherited=sender_inherited,
            direction_signal=direction_signal,
        )
        self.duration = duration

    @classmethod
    async def from_element(
        cls,
        elem: ElementHandle,
        page: Page,
        own_push_names: Optional[Iterable[str]] = None,
        model_texts: Optional[Dict[str, str]] = None,
    ) -> Optional["VoiceMessage"]:
        """
        Create a VoiceMessage from a DOM element.

        Checks for voice message indicators (mic icon, voice container).

        Args:
            elem: The message container element.
            page: The Playwright page.
            own_push_names: Account push names identifying own bubbles.

        Returns:
            A new VoiceMessage instance or None if not a valid voice message.
        """
        try:
            is_quoted = await elem.query_selector('[aria-label="Mensaje citado"]')
            if is_quoted:
                await _safe_dispose(is_quoted)
                return None

            has_play_button = await elem.query_selector('button[aria-label*="voz"], button[aria-label*="voice" i]')
            has_voice_container = await elem.query_selector('span[aria-label*="voz"], span[aria-label*="voice" i]')
            # These two are only probed for presence; release them now so they
            # do not pin DOM nodes for the whole collect_messages pass.
            await _safe_dispose(has_play_button)
            await _safe_dispose(has_voice_container)
            has_play_button = has_play_button is not None
            has_voice_container = has_voice_container is not None

            # Check for voice icon using evaluate (more reliable than :has selector)
            has_voice_icon = await elem.evaluate(
                """(el) => {
                    const svgs = el.querySelectorAll('svg');
                    for (const svg of svgs) {
                        const title = svg.querySelector('title');
                        if (title && title.textContent.includes('ic-keyboard-voice')) {
                            return true;
                        }
                    }
                    return false;
                }"""
            )

            if not has_play_button and not has_voice_container and not has_voice_icon:
                return None

            duration = ""
            try:
                # Method 1: native audio.duration (works when audio element exists)
                seconds = await elem.evaluate(
                    """(el) => {
                        const audio = el.querySelector('audio');
                        if (!audio) return null;
                        const d = audio.duration;
                        return (typeof d === 'number' && !isNaN(d) && d >= 0) ? d : null;
                    }"""
                )
                if seconds is not None:
                    duration = _format_duration(seconds)
                else:
                    # Method 2: fallback — parse from slider aria-valuetext "0:00/MM:SS"
                    slider_dur = await elem.evaluate(
                        """(el) => {
                            const slider = el.querySelector('[role="slider"][aria-valuetext]');
                            if (!slider) return null;
                            const vt = slider.getAttribute('aria-valuetext');
                            if (!vt) return null;
                            // format: "0:00/MM:SS" or "M:SS/MM:SS"
                            const parts = vt.split('/');
                            if (parts.length < 2) return null;
                            const total = parts[parts.length - 1].trim();
                            const m = total.match(/^(\\d{1,2}):(\\d{2})$/);
                            if (!m) return null;
                            return parseInt(m[1], 10) * 60 + parseInt(m[2], 10);
                        }"""
                    )
                    if slider_dur is not None:
                        duration = _format_duration(slider_dur)
            except Exception:
                logger.warning("VoiceMessage: failed to extract voice duration")

            base_msg = await Message.from_element(elem, page, own_push_names, model_texts=model_texts)
            if not base_msg:
                return None

            return cls(
                page=page,
                sender=base_msg.sender,
                timestamp=base_msg.timestamp,
                text=base_msg.text,
                container=elem,
                duration=duration,
                is_outgoing=base_msg.is_outgoing,
                msg_id=base_msg.msg_id,
                sender_inherited=base_msg.sender_inherited,
                direction_signal=base_msg.direction_signal,
            )

        except Exception:
            return None

    async def dispose(self) -> None:
        """Release the container handle held by this voice message."""
        await super().dispose()

    async def download_via_play(self, page: Page, downloads_dir: Path) -> Optional[Path]:
        """
        Download voice message by clicking play first, then download.

        Method 1: Click play button → wait for download icon → download

        Args:
            page: The Playwright Page object.
            downloads_dir: The directory where the file should be saved.

        Returns:
            The Path to the saved file, or None if download failed.
        """
        try:
            downloads_dir.mkdir(parents=True, exist_ok=True)

            play_button = await self.container.query_selector('button[aria-label="Reproducir mensaje de voz"]')
            if not play_button:
                return None

            await play_button.click()
            await asyncio.sleep(1)

            download_icon = await self.container.query_selector('span[data-icon="audio-download"]')
            if not download_icon:
                return None

            async with page.expect_download() as evento:
                await download_icon.click()
            descarga: Download = await evento.value

            filename = descarga.suggested_filename or f"voice_{self.timestamp.strftime('%Y%m%d_%H%M%S')}.ogg"
            destino = downloads_dir / filename

            await descarga.save_as(str(destino))
            return destino

        except Exception:
            return None

    async def download_via_context_menu(self, page: Page, downloads_dir: Path) -> Optional[Path]:
        """
        Download voice message via right-click context menu.

        Method 3: Right-click → select "Descargar" → download

        Args:
            page: The Playwright page.
            downloads_dir: The directory where the file should be saved.

        Returns:
            The Path to the saved file, or None if download failed.
        """
        try:
            downloads_dir.mkdir(parents=True, exist_ok=True)

            await self.container.scroll_into_view_if_needed()
            await asyncio.sleep(0.3)

            async with page.expect_download() as download_info:
                target_found = await page.evaluate(
                    """(el) => {
                        // Priority: play button is the most stable voice target
                        // Support both Spanish (voz) and English (voice) locale
                        const target = el.querySelector('button[aria-label*="voz"], button[aria-label*="voice" i]')
                            || el.querySelector('[class*="_ak4"]');
                        if (!target) return false;
                        const rect = target.getBoundingClientRect();
                        const event = new MouseEvent('contextmenu', {
                            bubbles: true,
                            cancelable: true,
                            view: window,
                            clientX: rect.left + rect.width / 2,
                            clientY: rect.top + rect.height / 2
                        });
                        target.dispatchEvent(event);
                        return true;
                    }""",
                    self.container,
                )
                if not target_found:
                    logger.warning(
                        "VoiceMessage.download_via_context_menu: no target element found for msg %s",
                        self.msg_id,
                    )

                await asyncio.sleep(0.5)

                await page.evaluate(
                    """
                    () => {
                        const menu = document.querySelector('[role="menu"]');
                        if (menu) {
                            const items = menu.querySelectorAll('[role="menuitem"]');
                            for (const item of items) {
                                if (item.textContent.includes('Descargar')) {
                                    item.click();
                                }
                            }
                        }
                    }"""
                )

            download = await download_info.value

            filename = download.suggested_filename or f"voice_{self.timestamp.strftime('%Y%m%d_%H%M%S')}.ogg"
            destino = downloads_dir / filename

            await download.save_as(str(destino))
            return destino

        except Exception:
            return None

    async def download_via_blob(self, page: Page, downloads_dir: Path) -> Optional[Path]:
        """
        Download voice message by extracting audio blob directly.

        Method 2: Extract audio src/blob via JavaScript → download

        Args:
            page: The Playwright Page object.
            downloads_dir: The directory where the file should be saved.

        Returns:
            The Path to the saved file, or None if download failed.
        """
        try:
            downloads_dir.mkdir(parents=True, exist_ok=True)

            audio_data = await self.container.evaluate(
                """
                () => {
                    const audio = this.querySelector('audio') || this.querySelector('video');
                    if (!audio) return null;

                    if (audio.src && audio.src.startsWith('blob:')) {
                        return { type: 'blob', src: audio.src };
                    }
                    if (audio.currentSrc) {
                        return { type: 'src', src: audio.currentSrc };
                    }
                    return null;
                }
                """
            )

            if not audio_data or not audio_data.get("src"):
                return None

            filename = f"voice_{self.timestamp.strftime('%Y%m%d_%H%M%S')}.ogg"
            destino = downloads_dir / filename

            if audio_data["type"] == "blob":
                return await self._download_blob_audio(page, audio_data["src"], destino)
            else:
                return await self._download_url_audio(page, audio_data["src"], destino)

        except Exception:
            return None

    async def _download_blob_audio(self, page: Page, blob_url: str, destino: Path) -> Optional[Path]:
        """Download audio from blob URL."""
        try:
            import base64

            audio_base64 = await page.evaluate(
                f"""
                async () => {{
                    const response = await fetch('{blob_url}');
                    const blob = await response.blob();
                    return new Promise((resolve) => {{
                        const reader = new FileReader();
                        reader.onloadend = () => resolve(reader.result.split(',')[1]);
                        reader.readAsDataURL(blob);
                    }});
                }}
                """
            )

            if audio_base64:
                audio_bytes = base64.b64decode(audio_base64)
                destino.write_bytes(audio_bytes)
                return destino

            return None
        except Exception:
            return None

    async def _download_url_audio(self, page: Page, audio_url: str, destino: Path) -> Optional[Path]:
        """Download audio from direct URL."""
        try:
            import httpx

            response = await httpx.AsyncClient().get(audio_url)
            if response.status_code == 200:
                destino.write_bytes(response.content)
                return destino
            return None
        except Exception:
            return None

    async def download(self, page: Page, downloads_dir: Path) -> Optional[Path]:
        """
        Download voice message using combined methods.

        Tries: 1) play → download icon, 2) context menu, 3) blob.

        Args:
            page: The Playwright page.
            downloads_dir: The directory where the file should be saved.

        Returns:
            The Path to the saved file, or None if download failed.
        """
        file_path = await self.download_via_play(page, downloads_dir)
        if not file_path:
            file_path = await self.download_via_context_menu(page, downloads_dir)
        if not file_path:
            file_path = await self.download_via_blob(page, downloads_dir)
        return file_path

    def get_codec_info(self, file_path: Path) -> Optional[Dict[str, Any]]:
        """Get codec information from downloaded audio file."""
        return detect_codec(file_path)

dispose() async

Release the container handle held by this voice message.

Source code in src/whatsplay/object/message.py
async def dispose(self) -> None:
    """Release the container handle held by this voice message."""
    await super().dispose()

download(page, downloads_dir) async

Download voice message using combined methods.

Tries: 1) play → download icon, 2) context menu, 3) blob.

Parameters:

Name Type Description Default
page Page

The Playwright page.

required
downloads_dir Path

The directory where the file should be saved.

required

Returns:

Type Description
Optional[Path]

The Path to the saved file, or None if download failed.

Source code in src/whatsplay/object/message.py
async def download(self, page: Page, downloads_dir: Path) -> Optional[Path]:
    """
    Download voice message using combined methods.

    Tries: 1) play → download icon, 2) context menu, 3) blob.

    Args:
        page: The Playwright page.
        downloads_dir: The directory where the file should be saved.

    Returns:
        The Path to the saved file, or None if download failed.
    """
    file_path = await self.download_via_play(page, downloads_dir)
    if not file_path:
        file_path = await self.download_via_context_menu(page, downloads_dir)
    if not file_path:
        file_path = await self.download_via_blob(page, downloads_dir)
    return file_path

download_via_blob(page, downloads_dir) async

Download voice message by extracting audio blob directly.

Method 2: Extract audio src/blob via JavaScript → download

Parameters:

Name Type Description Default
page Page

The Playwright Page object.

required
downloads_dir Path

The directory where the file should be saved.

required

Returns:

Type Description
Optional[Path]

The Path to the saved file, or None if download failed.

Source code in src/whatsplay/object/message.py
async def download_via_blob(self, page: Page, downloads_dir: Path) -> Optional[Path]:
    """
    Download voice message by extracting audio blob directly.

    Method 2: Extract audio src/blob via JavaScript → download

    Args:
        page: The Playwright Page object.
        downloads_dir: The directory where the file should be saved.

    Returns:
        The Path to the saved file, or None if download failed.
    """
    try:
        downloads_dir.mkdir(parents=True, exist_ok=True)

        audio_data = await self.container.evaluate(
            """
            () => {
                const audio = this.querySelector('audio') || this.querySelector('video');
                if (!audio) return null;

                if (audio.src && audio.src.startsWith('blob:')) {
                    return { type: 'blob', src: audio.src };
                }
                if (audio.currentSrc) {
                    return { type: 'src', src: audio.currentSrc };
                }
                return null;
            }
            """
        )

        if not audio_data or not audio_data.get("src"):
            return None

        filename = f"voice_{self.timestamp.strftime('%Y%m%d_%H%M%S')}.ogg"
        destino = downloads_dir / filename

        if audio_data["type"] == "blob":
            return await self._download_blob_audio(page, audio_data["src"], destino)
        else:
            return await self._download_url_audio(page, audio_data["src"], destino)

    except Exception:
        return None

download_via_context_menu(page, downloads_dir) async

Download voice message via right-click context menu.

Method 3: Right-click → select "Descargar" → download

Parameters:

Name Type Description Default
page Page

The Playwright page.

required
downloads_dir Path

The directory where the file should be saved.

required

Returns:

Type Description
Optional[Path]

The Path to the saved file, or None if download failed.

Source code in src/whatsplay/object/message.py
async def download_via_context_menu(self, page: Page, downloads_dir: Path) -> Optional[Path]:
    """
    Download voice message via right-click context menu.

    Method 3: Right-click → select "Descargar" → download

    Args:
        page: The Playwright page.
        downloads_dir: The directory where the file should be saved.

    Returns:
        The Path to the saved file, or None if download failed.
    """
    try:
        downloads_dir.mkdir(parents=True, exist_ok=True)

        await self.container.scroll_into_view_if_needed()
        await asyncio.sleep(0.3)

        async with page.expect_download() as download_info:
            target_found = await page.evaluate(
                """(el) => {
                    // Priority: play button is the most stable voice target
                    // Support both Spanish (voz) and English (voice) locale
                    const target = el.querySelector('button[aria-label*="voz"], button[aria-label*="voice" i]')
                        || el.querySelector('[class*="_ak4"]');
                    if (!target) return false;
                    const rect = target.getBoundingClientRect();
                    const event = new MouseEvent('contextmenu', {
                        bubbles: true,
                        cancelable: true,
                        view: window,
                        clientX: rect.left + rect.width / 2,
                        clientY: rect.top + rect.height / 2
                    });
                    target.dispatchEvent(event);
                    return true;
                }""",
                self.container,
            )
            if not target_found:
                logger.warning(
                    "VoiceMessage.download_via_context_menu: no target element found for msg %s",
                    self.msg_id,
                )

            await asyncio.sleep(0.5)

            await page.evaluate(
                """
                () => {
                    const menu = document.querySelector('[role="menu"]');
                    if (menu) {
                        const items = menu.querySelectorAll('[role="menuitem"]');
                        for (const item of items) {
                            if (item.textContent.includes('Descargar')) {
                                item.click();
                            }
                        }
                    }
                }"""
            )

        download = await download_info.value

        filename = download.suggested_filename or f"voice_{self.timestamp.strftime('%Y%m%d_%H%M%S')}.ogg"
        destino = downloads_dir / filename

        await download.save_as(str(destino))
        return destino

    except Exception:
        return None

download_via_play(page, downloads_dir) async

Download voice message by clicking play first, then download.

Method 1: Click play button → wait for download icon → download

Parameters:

Name Type Description Default
page Page

The Playwright Page object.

required
downloads_dir Path

The directory where the file should be saved.

required

Returns:

Type Description
Optional[Path]

The Path to the saved file, or None if download failed.

Source code in src/whatsplay/object/message.py
async def download_via_play(self, page: Page, downloads_dir: Path) -> Optional[Path]:
    """
    Download voice message by clicking play first, then download.

    Method 1: Click play button → wait for download icon → download

    Args:
        page: The Playwright Page object.
        downloads_dir: The directory where the file should be saved.

    Returns:
        The Path to the saved file, or None if download failed.
    """
    try:
        downloads_dir.mkdir(parents=True, exist_ok=True)

        play_button = await self.container.query_selector('button[aria-label="Reproducir mensaje de voz"]')
        if not play_button:
            return None

        await play_button.click()
        await asyncio.sleep(1)

        download_icon = await self.container.query_selector('span[data-icon="audio-download"]')
        if not download_icon:
            return None

        async with page.expect_download() as evento:
            await download_icon.click()
        descarga: Download = await evento.value

        filename = descarga.suggested_filename or f"voice_{self.timestamp.strftime('%Y%m%d_%H%M%S')}.ogg"
        destino = downloads_dir / filename

        await descarga.save_as(str(destino))
        return destino

    except Exception:
        return None

from_element(elem, page, own_push_names=None, model_texts=None) async classmethod

Create a VoiceMessage from a DOM element.

Checks for voice message indicators (mic icon, voice container).

Parameters:

Name Type Description Default
elem ElementHandle

The message container element.

required
page Page

The Playwright page.

required
own_push_names Optional[Iterable[str]]

Account push names identifying own bubbles.

None

Returns:

Type Description
Optional[VoiceMessage]

A new VoiceMessage instance or None if not a valid voice message.

Source code in src/whatsplay/object/message.py
@classmethod
async def from_element(
    cls,
    elem: ElementHandle,
    page: Page,
    own_push_names: Optional[Iterable[str]] = None,
    model_texts: Optional[Dict[str, str]] = None,
) -> Optional["VoiceMessage"]:
    """
    Create a VoiceMessage from a DOM element.

    Checks for voice message indicators (mic icon, voice container).

    Args:
        elem: The message container element.
        page: The Playwright page.
        own_push_names: Account push names identifying own bubbles.

    Returns:
        A new VoiceMessage instance or None if not a valid voice message.
    """
    try:
        is_quoted = await elem.query_selector('[aria-label="Mensaje citado"]')
        if is_quoted:
            await _safe_dispose(is_quoted)
            return None

        has_play_button = await elem.query_selector('button[aria-label*="voz"], button[aria-label*="voice" i]')
        has_voice_container = await elem.query_selector('span[aria-label*="voz"], span[aria-label*="voice" i]')
        # These two are only probed for presence; release them now so they
        # do not pin DOM nodes for the whole collect_messages pass.
        await _safe_dispose(has_play_button)
        await _safe_dispose(has_voice_container)
        has_play_button = has_play_button is not None
        has_voice_container = has_voice_container is not None

        # Check for voice icon using evaluate (more reliable than :has selector)
        has_voice_icon = await elem.evaluate(
            """(el) => {
                const svgs = el.querySelectorAll('svg');
                for (const svg of svgs) {
                    const title = svg.querySelector('title');
                    if (title && title.textContent.includes('ic-keyboard-voice')) {
                        return true;
                    }
                }
                return false;
            }"""
        )

        if not has_play_button and not has_voice_container and not has_voice_icon:
            return None

        duration = ""
        try:
            # Method 1: native audio.duration (works when audio element exists)
            seconds = await elem.evaluate(
                """(el) => {
                    const audio = el.querySelector('audio');
                    if (!audio) return null;
                    const d = audio.duration;
                    return (typeof d === 'number' && !isNaN(d) && d >= 0) ? d : null;
                }"""
            )
            if seconds is not None:
                duration = _format_duration(seconds)
            else:
                # Method 2: fallback — parse from slider aria-valuetext "0:00/MM:SS"
                slider_dur = await elem.evaluate(
                    """(el) => {
                        const slider = el.querySelector('[role="slider"][aria-valuetext]');
                        if (!slider) return null;
                        const vt = slider.getAttribute('aria-valuetext');
                        if (!vt) return null;
                        // format: "0:00/MM:SS" or "M:SS/MM:SS"
                        const parts = vt.split('/');
                        if (parts.length < 2) return null;
                        const total = parts[parts.length - 1].trim();
                        const m = total.match(/^(\\d{1,2}):(\\d{2})$/);
                        if (!m) return null;
                        return parseInt(m[1], 10) * 60 + parseInt(m[2], 10);
                    }"""
                )
                if slider_dur is not None:
                    duration = _format_duration(slider_dur)
        except Exception:
            logger.warning("VoiceMessage: failed to extract voice duration")

        base_msg = await Message.from_element(elem, page, own_push_names, model_texts=model_texts)
        if not base_msg:
            return None

        return cls(
            page=page,
            sender=base_msg.sender,
            timestamp=base_msg.timestamp,
            text=base_msg.text,
            container=elem,
            duration=duration,
            is_outgoing=base_msg.is_outgoing,
            msg_id=base_msg.msg_id,
            sender_inherited=base_msg.sender_inherited,
            direction_signal=base_msg.direction_signal,
        )

    except Exception:
        return None

get_codec_info(file_path)

Get codec information from downloaded audio file.

Source code in src/whatsplay/object/message.py
def get_codec_info(self, file_path: Path) -> Optional[Dict[str, Any]]:
    """Get codec information from downloaded audio file."""
    return detect_codec(file_path)

Managers

Internal managers that handle different aspects of the client's functionality.

Chat Manager

Responsible for finding and managing chats.

whatsplay.chat_manager.ChatManager

Manages chat operations for WhatsApp Web.

This class handles all chat-related operations including: - Opening and closing chats - Searching for conversations - Sending messages and files - Detecting unread chats - Downloading files from chats - Managing group operations

Attributes:

Name Type Description
client

Reference to the main WhatsApp client

_page

Playwright page object for browser interactions

wa_elements

WhatsApp Web elements helper

Source code in src/whatsplay/chat_manager.py
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
class ChatManager:
    """
    Manages chat operations for WhatsApp Web.

    This class handles all chat-related operations including:
    - Opening and closing chats
    - Searching for conversations
    - Sending messages and files
    - Detecting unread chats
    - Downloading files from chats
    - Managing group operations

    Attributes:
        client: Reference to the main WhatsApp client
        _page: Playwright page object for browser interactions
        wa_elements: WhatsApp Web elements helper
    """

    def __init__(self, client: "Client") -> None:
        """
        Initialize ChatManager with client reference.

        Args:
            client: The main WhatsApp client instance
        """
        self.client = client
        self._page = client._page
        self.wa_elements = client.wa_elements

    async def _reset_chat_list(self) -> None:
        """
        Show the "All" filter scrolled to the top before a scan.

        The chat list is virtualized: only rendered rows can be swept, and new
        activity lands at the top. If the list was left on another filter or
        scrolled down (e.g. after opening an older chat), unread chats stay
        invisible until something scrolls it back.
        """
        try:
            tab = self._page.locator(loc.ALL_CHATS_BUTTON).first
            if await tab.count() and not await filter_is_selected(tab):
                await tab.click()
        except Exception as e:
            logger.debug(f"Could not select the 'All' filter: {e}")
        try:
            await self._page.evaluate(
                """() => {
                    const pane = document.querySelector('#pane-side');
                    if (pane) pane.scrollTop = 0;
                }"""
            )
            await self._page.wait_for_timeout(300)  # let the top rows render
        except Exception as e:
            logger.debug(f"Could not scroll the chat list to the top: {e}")

    async def _check_unread_chats(self, debug: bool = True) -> List[Dict[str, Any]]:
        """
        Detect all unread chats in the sidebar.

        This method scans the chat list to identify unread messages using multiple
        heuristics including aria-labels, badges, and font weight detection.

        Args:
            debug: If True, prints debug information during execution

        Returns:
            List of dictionaries containing unread chat information

        Note:
            The method uses multiple detection strategies:
            1. aria-label matching for 'unread' or 'mensaje(s) no leído'
            2. Explicit unread badge detection
            3. Bold font weight detection on chat titles
        """
        unread_chats: List[Dict[str, Any]] = []
        _scan_start = time.monotonic()
        async with self.client._page_lock:
            await self.close()  # Ensure no chat is currently open

            def log(msg: str, level: int = logging.DEBUG) -> None:
                """Loguea el detalle del escaneo vía logging.

                Antes era un print() gateado por `debug=True` (default), lo que
                generaba ~217k líneas/día de ruido en el consumidor. Ahora el
                nivel del logger decide: silencioso por defecto, visible con
                ``logging.getLogger('whatsplay.chat_manager').setLevel(DEBUG)``.
                """
                if debug:
                    logger.log(level, msg)

            async def _wait_for_grid() -> None:
                """Wait for the chat grid to be present and hydrated."""
                try:
                    await self._page.locator(loc.CHAT_LIST_GRID).wait_for(timeout=30000)
                except Exception:
                    # Retry once more after a longer pause (WhatsApp Web may still be loading)
                    log("DEBUG: Grid not found on first wait, retrying...")
                    await self._page.wait_for_timeout(3000)
                    try:
                        await self._page.locator(loc.CHAT_LIST_GRID).wait_for(timeout=30000)
                    except Exception:
                        log("DEBUG: Grid still not found after retry")

            async def _get_scroller_handle():
                """
                Resolve the scrolling container to confirm the virtualized list
                is mounted. The handle is not needed by the caller, so every
                handle created here is released before returning. This runs on
                every scan tick (~every poll_freq): undisposed handles pin DOM
                nodes in the renderer until it cannot commit heap and crashes.
                """
                grid = self._page.locator(loc.CHAT_LIST_GRID)
                grid_h = await grid.element_handle()

                if not grid_h:
                    await _safe_dispose(
                        await self._page.locator("#pane-side").element_handle()
                    )
                    return

                try:
                    await _safe_dispose(await grid_h.evaluate_handle(
                        """(el) => {
                            let cur = el;
                            while (cur && cur !== document.body) {
                                const s = getComputedStyle(cur);
                                if ((s.overflowY === 'auto' || s.overflowY === 'scroll') &&
                                    cur.clientHeight < cur.scrollHeight) return cur;
                                cur = cur.parentElement;
                            }
                            return document.querySelector('#pane-side');
                        }"""
                    ))
                finally:
                    await _safe_dispose(grid_h)

            async def _is_row_unread(row_loc) -> bool:
                """
                Determine if a chat row represents an unread conversation.

                Uses multiple detection strategies:
                1. aria-label with 'unread' or 'mensaje(s) no leído'
                2. Explicit unread badge
                3. Bold font weight on title (>= 600)

                Args:
                    row_loc: Locator for the chat row

                Returns:
                    True if the chat is unread, False otherwise
                """
                try:
                    # Strategy 1: Check aria-label for unread indicators
                    has_aria = await row_loc.locator("[aria-label]").evaluate_all(
                        "(els, rx) => els.some(el => (el.getAttribute('aria-label')||'').match(new RegExp(rx,'i')))",
                        UNREAD_ARIA_PATTERN,
                    )
                    if has_aria:
                        return True

                    # Strategy 2: Check for explicit unread badge
                    try:
                        if await row_loc.locator(f"xpath={loc.UNREAD_BADGE}").count() > 0:
                            return True
                    except Exception:
                        pass

                    # Strategy 3: Check for bold font weight on title
                    title = row_loc.locator(f"xpath={loc.SPAN_TITLE}")
                    if await title.count() == 0:
                        return False

                    is_bold = await title.evaluate(
                        """(el) => {
                            const w = getComputedStyle(el).fontWeight;
                            const n = parseInt(w, 10);
                            return isNaN(n) ? /bold/i.test(w) : n >= 600;
                        }"""
                    )
                    # Strategy 4: Check for inline "X mensaje(s) no leido(s)" text in title
                    try:
                        if await row_loc.locator(f"xpath={loc.UNREAD_BADGE_TEXT}").count() > 0:
                            return True
                    except Exception:
                        pass

                    return bool(is_bold)

                except Exception:
                    return False

            async def _parse_row(row_loc):
                """
                Parse a chat row into structured data.

                Args:
                    row_loc: Locator for the chat row

                Returns:
                    Dictionary with chat information or None if parsing fails
                """
                handle = await row_loc.element_handle()
                if not handle:
                    return None
                try:
                    return await self._parse_search_result(handle, "CHATS")
                finally:
                    # The parsed dict carries plain data only; release the row
                    # handle so it does not pin the node across scan ticks.
                    await _safe_dispose(handle)

            try:
                # Step 0: Wait for UI to be ready
                await _wait_for_grid()
                await self._reset_chat_list()

                # Step 1: Debug initial state
                try:
                    total_rows_now = await self._page.locator(f"xpath={loc.CHAT_LIST_ROWS}").count()
                    log(f"DEBUG: Initially visible rows: {total_rows_now}")

                    if total_rows_now <= MIN_VISIBLE_CHATS_THRESHOLD:
                        tab = self._page.locator(loc.ALL_CHATS_BUTTON).first
                        if not await tab.count():
                            log("DEBUG: Few chats visible, 'All' filter not found")
                        elif await filter_is_selected(tab):
                            log("DEBUG: Few chats visible, 'All' already selected")
                        else:
                            await tab.click()  # a pressed toggle would un-press
                            log("DEBUG: Few chats visible, clicked 'All'")

                except Exception as e:
                    log(f"DEBUG: Few-rows check failed: {type(e).__name__}: {str(e).splitlines()[0] if str(e) else ''}")

                # Step 2: Get correct scroller for virtualized list
                await _get_scroller_handle()

                # Step 3: Sweep visible rows
                async def sweep(tag: str) -> None:
                    """
                    Scan visible chat rows for unread messages.

                    Args:
                        tag: Label for this sweep operation (for debugging)
                    """
                    nonlocal unread_chats
                    rows = self._page.locator(f"xpath={loc.CHAT_LIST_ROWS}")
                    count = await rows.count()
                    log(f"DEBUG: {tag}: Currently visible rows: {count}")

                    for i in range(count):
                        row = rows.nth(i)
                        try:
                            if await _is_row_unread(row):
                                chat = await _parse_row(row)
                                if chat:
                                    unread_chats.append(chat)
                                    log(f"✓ Unread ({tag}): {chat.get('name', 'No name')}")
                        except Exception as e:
                            log(f"DEBUG: Error evaluating row {i} ({tag}): {e}")

                # Step 4: Initial sweep
                await sweep("initial")

                # Step 5: Deduplication
                def _get_chat_key(ch: Dict[str, Any]) -> tuple:
                    """Generate a unique key for a chat to enable deduplication."""
                    return ch.get("id") or (
                        ch.get("name"),
                        ch.get("last_message"),
                        ch.get("last_activity"),
                    )

                seen = set()
                dedup = []
                for ch in unread_chats:
                    k = _get_chat_key(ch)
                    if k in seen:
                        continue
                    seen.add(k)
                    dedup.append(ch)
                unread_chats = dedup

            except Exception as e:
                await self.client.emit("on_warning", f"Error detecting unread chats: {e}")
                log(f"DEBUG: General error: {e}")

        # Step 6: Final summary
        # Una sola línea a INFO con el resultado del escaneo (útil y barata),
        # y el detalle por chat a DEBUG. Antes eran 5 líneas por ciclo ×43k
        # ciclos/día; ahora una línea por ciclo, y el detalle on-demand.
        logger.info(
            "unread_scan: found=%d duration_ms=%.0f",
            len(unread_chats),
            (time.monotonic() - _scan_start) * 1000,
        )
        if logger.isEnabledFor(logging.DEBUG):
            for i, chat in enumerate(unread_chats, 1):
                logger.debug("  unread %d. %s", i, chat.get("name", "No name"))

        return unread_chats

    async def _parse_search_result(self, element, result_type: str = "CHATS") -> Optional[Dict[str, Any]]:
        """
        Parse a search result element into structured data.

        Args:
            element: ElementHandle of the search result row
            result_type: Type of result (default: "CHATS")

        Returns:
            Dictionary containing parsed chat information or None if parsing fails

        Note:
            Handles two main layouts:
            - 3 components: Group chats (group name, title, last message)
            - 2 components: Direct chats (title, last message)

            Every ElementHandle created here is released in the finally block.
            This runs on every scan tick, and undisposed handles pin DOM nodes
            in the renderer until it cannot commit heap and crashes (SIGTRAP).
        """
        components: list = []
        unread_el = mic_span = span_title_0 = span_title_1 = None
        datetime_children: list = []
        info_children: list = []
        try:
            components = await element.query_selector_all(
                "xpath=.//div[@role='gridcell' and @aria-colindex='2']/parent::div/div"
            )
            count = len(components)

            # Extract unread count
            unread_el = await element.query_selector(f"xpath={loc.SEARCH_ITEM_UNREAD_MESSAGES}")
            unread_count = await unread_el.inner_text() if unread_el else "0"

            # Check for audio message
            mic_span = await components[1].query_selector(loc.CHAT_LIST_VOICE_ICON)

            if count == 3:
                # Group chat layout
                span_title_0 = await components[0].query_selector(f"xpath={loc.SPAN_TITLE}")
                group_title = await span_title_0.get_attribute("title") if span_title_0 else ""

                datetime_children = await components[0].query_selector_all("xpath=./*")
                datetime_text = await datetime_children[1].text_content() if len(datetime_children) > 1 else ""

                span_title_1 = await components[1].query_selector(f"xpath={loc.SPAN_TITLE}")
                title = await span_title_1.get_attribute("title") if span_title_1 else ""

                info_text = (await components[2].text_content()) or ""
                info_text = info_text.replace("\n", "")

                # Skip invalid states
                if any(x in info_text for x in ["loading", "status-", "typing"]):
                    return None

                return {
                    "type": result_type,
                    "group": group_title,
                    "name": title,
                    "last_activity": datetime_text,
                    "last_message": info_text,
                    "last_message_type": "audio" if mic_span else "text",
                    "unread_count": unread_count,
                }

            elif count == 2:
                # Direct chat layout
                span_title_0 = await components[0].query_selector(f"xpath={loc.SPAN_TITLE}")
                title = await span_title_0.get_attribute("title") if span_title_0 else ""

                datetime_children = await components[0].query_selector_all("xpath=./*")
                datetime_text = await datetime_children[1].text_content() if len(datetime_children) > 1 else ""

                info_children = await components[1].query_selector_all("xpath=./*")
                info_text = (await info_children[0].text_content() if len(info_children) > 0 else "") or ""
                info_text = info_text.replace("\n", "")

                # Skip invalid states
                if any(x in info_text for x in ["loading", "status-", "typing"]):
                    return None

                return {
                    "type": result_type,
                    "name": title,
                    "last_activity": datetime_text,
                    "last_message": info_text,
                    "last_message_type": "audio" if mic_span else "text",
                    "unread_count": unread_count,
                    "group": None,
                }

            return None

        except Exception as e:
            logger.warning(f"Error parsing result: {e}")
            return None
        finally:
            for _h in components:
                await _safe_dispose(_h)
            await _safe_dispose(unread_el)
            await _safe_dispose(mic_span)
            await _safe_dispose(span_title_0)
            await _safe_dispose(span_title_1)
            for _h in datetime_children:
                await _safe_dispose(_h)
            for _h in info_children:
                await _safe_dispose(_h)

    async def close(self) -> None:
        """
        Close an active search first, otherwise close the current chat.

        Search owns its Escape event so it cannot bubble through and close
        the underlying chat in the same operation.
        """
        if self._page:
            try:
                close_search = getattr(self.wa_elements, "close_search", None)
                if close_search:
                    try:
                        result = close_search()
                        if inspect.isawaitable(result):
                            if await result:
                                return
                        elif result is True:
                            return
                    except Exception as e:
                        await self.client.emit("on_warning", f"Error trying to close search: {e}")
                await self._page.keyboard.press("Escape")
                await asyncio.sleep(0.5)  # Allow UI to react
            except Exception as e:
                await self.client.emit("on_warning", f"Error trying to close chat with Escape: {e}")

    async def open(
        self,
        chat_name: str,
        timeout: int = DEFAULT_WAIT_TIMEOUT,
        open_via_url: bool = False,
        is_group: Optional[bool] = None,
    ) -> bool:
        """
        Open a chat by name.

        Args:
            chat_name: Name of the chat to open
            timeout: Maximum time to wait in milliseconds
            open_via_url: If True, forces opening via URL (for phone numbers)
            is_group: If set, the chat must be a group (True) or a contact (False)

        Returns:
            True if chat was opened successfully, False otherwise
        """
        return await self.wa_elements.open(
            chat_name, timeout, open_via_url=open_via_url, is_group=is_group
        )

    async def search_conversations(self, query: str, close: bool = True) -> List[Dict[str, Any]]:
        """
        Search for conversations by term.

        Args:
            query: Search term
            close: If True, closes the search after completion

        Returns:
            List of matching conversations
        """
        if not await self.client.wait_until_logged_in():
            return []
        try:
            return await self.wa_elements.search_chats(query, close)
        except Exception as e:
            await self.client.emit("on_error", f"Search error: {e}")
            return []

    async def collect_messages(
        self,
        own_push_names: Optional[Union[str, list]] = None,
        dispose: bool = False,
    ) -> List[Union[Message, FileMessage, VoiceMessage]]:
        """
        Collect all currently visible messages in the active chat.

        Scans all visible message containers and returns a list of Message,
        FileMessage, or VoiceMessage instances.

        Args:
            own_push_names: Optional account push names identifying own
                bubbles (e.g. ["Bikes Amigorena"]). Last-resort fallback
                only: forwarded to Message.from_element and consulted when
                tail + class + data-id + positional + group are all
                inconclusive. Compared accent/case-insensitively. The
                dispose: When True, release each message's container handle
                before returning. Use for data-only consumers (bots that
                only read text/sender/timestamp) to avoid accumulating DOM
                handles in the renderer; keep False (default) so react()
                and download() still work.
                default path (None) classifies direction config-free via
                positional alignment and group inheritance.

        Direction contract (precedence is DIRECTION_ORDER in
        whatsplay.object.message; config-free first):
        tail (ground truth) > class / data-id (opportunistic, outrank
        group) > group inheritance (tail-delimited groups, direction never
        leaks across an outgoing/incoming boundary) > positional
        inner-bubble alignment (right = outgoing, left = incoming;
        inconclusive geometry abstains) > sender identity (last resort).

        Sender inheritance contract:
            Sender-less continuation bubbles inherit the previous bubble's
            sender for DISPLAY only (sender_inherited=True). Consumers must
            use is_outgoing / is_from_self() for skip logic, never the
            inherited sender. Direction is preserved through inheritance: a
            sender-less bubble with no direction signal of its own inherits
            the group direction; a bubble with its own positive signal
            (including position-out/position-in) keeps it.

        Returns:
            List of Message, FileMessage, or VoiceMessage instances
        """
        results: List[Union[Message, FileMessage, VoiceMessage]] = []

        # ── Scroll up to trigger WhatsApp's virtual list to load older messages ──
        try:
            await self._page.evaluate("""
                () => {
                    const scroller = document.querySelector('div[role="application"]')?.parentElement
                        || document.querySelector('[data-virtualized="false"]')?.closest('[style*="overflow"]')
                        || document.querySelector('div[tabindex="-1"]');
                    if (scroller && scroller.scrollTop !== undefined) {
                        scroller.scrollTop = 0;
                    }
                }
            """)
            await asyncio.sleep(1.5)
        except Exception:
            pass

        # Wait for message containers to appear in the DOM
        for _ in range(10):
            count = await self._page.evaluate(
                """() => document.querySelectorAll('div[data-testid^="conv-msg-"]').length"""
            )
            if count > 0:
                break
            await asyncio.sleep(0.5)
        else:
            # Logear QUE chat y en que URL fallo: sin esto no se puede
            # distinguir un chat vacio de un selector roto o una pestana
            # en la pantalla equivocada.
            try:
                _url = self._page.url
                _title = await self._page.title()
                _pane = await self._page.evaluate(
                    """() => document.querySelector('#main') ? 'main-present' : 'no-main'"""
                )
            except Exception:
                _url, _title, _pane = "?", "?", "?"
            logger.warning(
                "collect_messages: no message containers found after 5s "
                "(url=%s pane=%s title=%r)", _url, _pane, _title[:60]
            )

        msg_elements = await self._page.query_selector_all('div[data-testid^="conv-msg-"]')
        logger.debug("collect_messages: %d containers found", len(msg_elements))
        # One page round trip for every bubble instead of one per bubble.
        bubbles = await _model_bubbles(self._page)
        # Modules unreachable: DOM text, no per-bubble retries, kinds unknown.
        model_texts, model_kinds = bubbles if bubbles is not None else ({}, {})

        last_sender = ""
        last_is_outgoing = False
        for i, elem in enumerate(msg_elements):
            voice_msg = await VoiceMessage.from_element(elem, self._page, own_push_names, model_texts=model_texts)
            if voice_msg:
                self._inherit_sender(voice_msg, last_sender, last_is_outgoing)
                if voice_msg.sender:
                    last_sender = voice_msg.sender
                    last_is_outgoing = voice_msg.is_outgoing
                results.append(voice_msg)
                continue

            file_msg = await FileMessage.from_element(elem, self._page, own_push_names, model_texts=model_texts)
            if file_msg:
                self._inherit_sender(file_msg, last_sender, last_is_outgoing)
                if file_msg.sender:
                    last_sender = file_msg.sender
                    last_is_outgoing = file_msg.is_outgoing
                results.append(file_msg)
                continue

            simple_msg = await Message.from_element(elem, self._page, own_push_names, model_texts=model_texts)
            if simple_msg:
                self._inherit_sender(simple_msg, last_sender, last_is_outgoing)
                if simple_msg.sender:
                    last_sender = simple_msg.sender
                    last_is_outgoing = simple_msg.is_outgoing
                results.append(simple_msg)

        self._apply_group_tail_inheritance(results)
        self._attach_kinds(results, model_kinds)

        if dispose:
            # Data-only consumers (bots that read text/sender/timestamp and
            # never call react/download) should release the container handles
            # right away: each one pins a DOM node in the renderer, and a poll
            # loop reading chats every few seconds accumulates thousands of
            # them until the V8 heap cannot commit and the renderer crashes
            # with SIGTRAP ("Target crashed"). Interactive consumers keep the
            # default dispose=False so react()/download() still work.
            for _msg in results:
                await _msg.dispose()

        return results

    @staticmethod
    def _inherit_sender(
        msg: Union[Message, FileMessage, VoiceMessage],
        last_sender: str,
        last_is_outgoing: bool,
    ) -> None:
        """Stamp a sender-less continuation bubble with display attribution.

        Inherits the previous sender for display only (sender_inherited=True)
        so skip logic keyed on sender can never see a propagated own push
        name. Direction is preserved at this stage: bubbles without their
        own positive signal (direction_signal == "none") inherit the
        previous direction; bubbles carrying their own signal keep the
        is_outgoing computed from the DOM. The group-tail step running
        after collection may still override a positional signal with the
        group leader direction (group outranks positional).
        """
        if msg.sender or not last_sender:
            return
        msg.sender = last_sender
        msg.sender_inherited = True
        if msg.direction_signal == DirectionSignal.NONE:
            msg.is_outgoing = last_is_outgoing

    @staticmethod
    def _attach_kinds(messages, model_kinds: Dict[str, str]) -> None:
        """Set each message's kind from WhatsApp's message model (by bare id)."""
        for msg in messages:
            msg_id = getattr(msg, "msg_id", "") or ""
            msg.kind = model_kinds.get(_bare_msg_id(msg_id)) if msg_id else None

    @staticmethod
    def _apply_group_tail_inheritance(
        msgs: List[Union[Message, FileMessage, VoiceMessage]],
    ) -> None:
        """Propagate tail ground truth within tail-delimited groups.

        Applies the group layers of DIRECTION_ORDER (group-out/group-in):
        continuations with no signal of their own (none: no tail, class,
        data-id, or positional side) inherit direction from the nearest
        sibling carrying an explicit tail signal in the same group — and so
        do continuations carrying a positional signal, because live
        evidence proved positional can lie (v3 row geometry; Sept 2026
        quoted-voice bubble). Groups start at tail-out/tail-in leaders, so
        direction never leaks across an outgoing/incoming boundary, and
        leaderless groups are left untouched. Bubbles carrying a class,
        data-id, or sender-own signal keep it. Bubbles still signalless
        after this step keep "none" (incoming default) and are flagged via
        the fallback counter + log (fail-safe, never silent).
        """
        if not msgs:
            return
        groups: List[List[Union[Message, FileMessage, VoiceMessage]]] = []
        current: List[Union[Message, FileMessage, VoiceMessage]] = []
        for msg in msgs:
            if msg.direction_signal in (
                DirectionSignal.TAIL_OUT,
                DirectionSignal.TAIL_IN,
            ) and current:
                groups.append(current)
                current = [msg]
            else:
                current.append(msg)
        if current:
            groups.append(current)
        for group in groups:
            leader_outgoing: Optional[bool] = None
            for msg in group:
                if msg.direction_signal == DirectionSignal.TAIL_OUT:
                    leader_outgoing = True
                    break
                if msg.direction_signal == DirectionSignal.TAIL_IN:
                    leader_outgoing = False
                    break
            if leader_outgoing is None:
                continue
            for msg in group:
                if msg.direction_signal in (
                    DirectionSignal.NONE,
                    DirectionSignal.POSITION_OUT,
                    DirectionSignal.POSITION_IN,
                ):
                    msg.is_outgoing = leader_outgoing
                    msg.direction_signal = (
                        DirectionSignal.GROUP_OUT
                        if leader_outgoing
                        else DirectionSignal.GROUP_IN
                    )
        for msg in msgs:
            if msg.direction_signal == DirectionSignal.NONE:
                _flag_direction_fallback(msg.msg_id)

    async def react_to_last_message(self, emoji: str) -> bool:
        """
        React to the last visible message in the current chat.

        Args:
            emoji: The emoji to react with (e.g., "👍", "❤️")

        Returns:
            True if reaction was successful, False otherwise
        """
        try:
            messages = await self.collect_messages()
            if not messages:
                await self.client.emit("on_warning", "No messages found to react to.")
                return False

            last_message = messages[-1]
            await last_message.react(emoji)
            return True
        except Exception as e:
            await self.client.emit("on_error", f"Error reacting to last message: {e}")
            return False

    async def download_all_files(
        self, carpeta: Optional[str] = None, detect_codecs: bool = True
    ) -> List[Dict[str, Any]]:
        """
        Download all file attachments from the current chat.

        Args:
            carpeta: Optional custom download directory path
            detect_codecs: If True, detect codec info for each file

        Returns:
            List of dicts with file path and codec info
        """
        if not await self.client.wait_until_logged_in():
            return []

        downloads_dir = Path(carpeta) if carpeta else DEFAULT_DOWNLOADS_DIR

        saved_files: List[Dict[str, Any]] = []
        messages = await self.collect_messages()

        for msg in messages:
            file_path = None
            if isinstance(msg, FileMessage):
                file_path = await msg.download(self._page, downloads_dir)
            elif isinstance(msg, VoiceMessage):
                file_path = await msg.download(self._page, downloads_dir)

            if file_path:
                file_info = {"path": file_path, "type": type(msg).__name__}
                if detect_codecs:
                    file_info["codec"] = detect_codec(file_path)
                saved_files.append(file_info)

        return saved_files

    async def download_file_by_index(
        self, index: int, carpeta: Optional[str] = None, detect_codecs: bool = True
    ) -> Optional[Dict[str, Any]]:
        """
        Download a specific file by its index in the message list.

        Args:
            index: Zero-based index of the file to download
            carpeta: Optional custom download directory path
            detect_codecs: If True, detect codec info for the file

        Returns:
            Dict with path, type, and codec info, or None if failed
        """
        if not await self.client.wait_until_logged_in():
            return None

        downloads_dir = Path(carpeta) if carpeta else DEFAULT_DOWNLOADS_DIR

        messages = await self.collect_messages()
        downloadable = [m for m in messages if isinstance(m, (FileMessage, VoiceMessage))]

        if index < 0 or index >= len(downloadable):
            return None

        msg = downloadable[index]
        file_path = await msg.download(self._page, downloads_dir)

        if not file_path:
            return None

        result = {"path": file_path, "type": type(msg).__name__}
        if detect_codecs:
            result["codec"] = detect_codec(file_path)

        return result

    def _opened_target(self, chat_query: str, open_via_url: bool) -> str:
        """Title the composer must name after open(): a URL open of a saved
        contact shows the contact's name, which open() verified and recorded."""
        if open_via_url and self.wa_elements.last_opened_title:
            return self.wa_elements.last_opened_title
        return chat_query

    async def _ensure_composer_targets(
        self, input_box, chat_name: str, is_group: Optional[bool] = None
    ) -> bool:
        """Last check before typing, on the very element that will receive the text.

        Its own aria-label must name the target chat ("Escribir un mensaje para
        <chat>"). The header is not enough: it does not say which editor has
        the text, and an unknown label (another language, a caption box) is
        refused rather than guessed.
        """
        try:
            label = await input_box.get_attribute("aria-label")
        except Exception:
            label = None
        parsed = parse_composer_label(label)
        ok = parsed is not None and same_chat(parsed[1], chat_name)
        if ok and is_group is not None:
            ok = parsed[0] == ("group" if is_group else "chat")
        if ok:
            return True
        logger.error("Refusing to write: composer is %r, target is %r", label, chat_name)
        await self.client.emit(
            "on_error", f"Composer is {label!r}, not {chat_name!r}; nothing was written"
        )
        return False

    async def send_message(
        self,
        chat_query: str,
        message: str,
        open_via_url: bool = False,
        is_group: Optional[bool] = None,
    ) -> bool:
        """
        Send a text message to a chat.

        Args:
            chat_query: Name or identifier of the chat
            message: Text message to send
            open_via_url: If True, opens the chat via URL before sending

        Returns:
            True if message was sent successfully, False otherwise
        """
        async with self.client._page_lock:
            logger.info("Sending message to %r", chat_query)
            if not await self.client.wait_until_logged_in():
                return False

            try:
                opened = await self.open(chat_query, open_via_url=open_via_url, is_group=is_group)
                if not opened:
                    await self.client.emit("on_error", f"Could not open chat: {chat_query}")
                    return False
                logger.info("Chat %r opened, sending message", chat_query)

                input_box = await self._page.wait_for_selector(
                    loc.ACTIVE_CHAT_COMPOSER, timeout=DEFAULT_WAIT_TIMEOUT
                )
                if not input_box:
                    await self.client.emit(
                        "on_error",
                        "Could not find text input box for sending message",
                    )
                    return False
                target = self._opened_target(chat_query, open_via_url)
                if not await self._ensure_composer_targets(input_box, target, is_group):
                    return False

                await input_box.click()
                await input_box.fill(message)
                # Only send if the box holds the message: stray keystrokes that
                # landed here earlier would go out with it.
                typed = await input_box.inner_text()
                if not composer_holds(typed, message):
                    logger.error("Composer holds %r, not the message; not sending", typed[:80])
                    await input_box.fill("")
                    await self.client.emit(
                        "on_error", f"Composer text did not match the message for {chat_query!r}"
                    )
                    return False
                before_ids = await self._message_ids()
                # Enter goes to the composer itself, not to whatever has focus.
                await input_box.press("Enter")

                confirmed = await self.wait_for_sent_confirmation(before_ids, DEFAULT_WAIT_TIMEOUT)
                if not confirmed:
                    logger.warning(
                        "Message to %r sent but not confirmed by server", chat_query
                    )
                    return False

                return True

            except Exception as e:
                await self.client.emit("on_error", f"Error sending message: {e}")
                return False
            finally:
                await self.close()

    async def _bubbles(self) -> List[Dict[str, Any]]:
        """data-id of every message in the open chat, and whether it shows a
        delivery status (only outgoing messages do)."""
        status = loc.MSG_STATUS_CONFIRMED
        if status.startswith("css="):  # str.removeprefix needs 3.9; we support 3.8
            status = status[len("css="):]
        try:
            rows = await self._page.evaluate(
                """([container, status]) => Array.from(
                    document.querySelectorAll('#main ' + container)
                ).map(e => ({id: e.getAttribute('data-id'), status: !!e.querySelector(status)}))""",
                [loc.MESSAGE_CONTAINER, status],
            )
        except Exception:
            return []
        return rows if isinstance(rows, list) else []

    async def _message_ids(self) -> set:
        return {row.get("id") for row in await self._bubbles()}

    async def wait_for_sent_confirmation(self, before_ids: set, timeout: int = DEFAULT_WAIT_TIMEOUT) -> bool:
        """Wait until a message that was not in `before_ids` shows a delivery
        status ("Enviado", "Entregado", "Leído") in the open chat.

        An older outgoing message that is already read never counts. Verified
        live 2026-10-20: a just-sent bubble gets a new data-id and a status span.
        """
        deadline = time.monotonic() + timeout / 1000
        while True:
            for row in await self._bubbles():
                if row.get("id") not in before_ids and row.get("status"):
                    return True
            if time.monotonic() >= deadline:
                logger.warning("No new message with a delivery status within %dms", timeout)
                return False
            await asyncio.sleep(0.5)

    async def wait_for_whatsapp_ready(self, timeout=30000) -> bool:
        try:
            last_msg = self._page.locator(loc.MESSAGE_CONTAINER).last
            await last_msg.locator(loc.MSG_STATUS_CONFIRMED).wait_for(state="visible", timeout=timeout)
            logger.debug("Message confirmed by the server (tick seen)")
            return True
        except Exception:
            logger.warning(
                "Message not confirmed within %dms (server tick not seen)", timeout
            )
            return False

    # You continue with the message sending...
    async def send_file(
        self,
        chat_name: str,
        path: str,
        open_via_url: bool = False,
        is_group: Optional[bool] = None,
    ) -> bool:
        """
        Send a file attachment to a chat.

        Args:
            chat_name: Name of the chat to send the file to
            path: Absolute path to the file to send
            open_via_url: If True, opens the chat via URL (required for phone numbers)

        Returns:
            True if file was sent successfully, False otherwise
        """
        async with self.client._page_lock:
            try:
                if not os.path.isfile(path):
                    msg = f"File does not exist: {path}"
                    await self.client.emit("on_error", msg)
                    return False

                if not await self.client.wait_until_logged_in():
                    msg = "Could not log in"
                    await self.client.emit("on_error", msg)
                    return False

                if not await self.open(chat_name, open_via_url=open_via_url, is_group=is_group):
                    msg = f"Could not open chat: {chat_name}"
                    await self.client.emit("on_error", msg)
                    return False

                composer = await self._page.wait_for_selector(
                    loc.ACTIVE_CHAT_COMPOSER, timeout=DEFAULT_WAIT_TIMEOUT
                )
                try:
                    target = self._opened_target(chat_name, open_via_url)
                    if not await self._ensure_composer_targets(composer, target, is_group):
                        return False
                finally:
                    await _safe_dispose(composer)

                attach_btn = await self._page.wait_for_selector(loc.ATTACH_BUTTON, timeout=5000)
                await attach_btn.click()
                await asyncio.sleep(1.5)

                # Usar el file chooser de Playwright: intercepta el diálogo nativo de
                # selección de archivos y funciona TAMBIÉN en headless (el input accept="*"
                # solo se crea cuando se abre ese diálogo, que en headless no aparece).
                # 1) Registrar el file chooser ANTES de clickear "Documento"
                async with self._page.expect_file_chooser(timeout=15000) as fc_info:
                    doc_btn = self._page.locator(
                        "button[aria-label='Documento'], button[aria-label='Document']"
                    ).first
                    if await doc_btn.count():
                        await doc_btn.click()
                    else:
                        # fallback: usar el primer input de archivos
                        fallback = self._page.locator(loc.FILE_INPUT).first
                        await fallback.click()
                    file_chooser = await fc_info.value

                await file_chooser.set_files(path)
                await asyncio.sleep(5)
                # El botón de enviar real es el DIV role=button (el SPAN interno no dispara)
                send_btn_loc = self._page.locator(loc.SEND_BUTTON).first
                await send_btn_loc.wait_for(state="visible", timeout=DEFAULT_WAIT_TIMEOUT)
                before_ids = await self._message_ids()
                await send_btn_loc.click()
                confirmed = await self.wait_for_sent_confirmation(before_ids, DEFAULT_WAIT_TIMEOUT)
                if not confirmed:
                    logger.warning("File to %r sent but not confirmed by server", chat_name)
                return confirmed
            except Exception as e:
                await self.client.emit("on_error", f"Error sending file: {e}")
                return False

    async def new_group(self, group_name: str, members: List[str]) -> bool:
        """
        Create a new WhatsApp group.

        Args:
            group_name: Name for the new group
            members: List of member names to add to the group

        Returns:
            True if group was created successfully, False otherwise
        """
        return await self.wa_elements.new_group(group_name, members)

    async def add_members_to_group(self, group_name: str, members: List[str]) -> bool:
        """
        Add members to an existing group.

        Args:
            group_name: Name of the group
            members: List of member names to add

        Returns:
            True if members were added successfully, False otherwise
        """
        try:
            if not await self.open(group_name):
                await self.client.emit("on_error", f"Could not open group '{group_name}'")
                return False

            success = await self.wa_elements.add_members_to_group(group_name, members)
            return success

        except Exception as e:
            await self.client.emit("on_error", f"Error adding members to group '{group_name}': {e}")
            return False

__init__(client)

Initialize ChatManager with client reference.

Parameters:

Name Type Description Default
client Client

The main WhatsApp client instance

required
Source code in src/whatsplay/chat_manager.py
def __init__(self, client: "Client") -> None:
    """
    Initialize ChatManager with client reference.

    Args:
        client: The main WhatsApp client instance
    """
    self.client = client
    self._page = client._page
    self.wa_elements = client.wa_elements

add_members_to_group(group_name, members) async

Add members to an existing group.

Parameters:

Name Type Description Default
group_name str

Name of the group

required
members List[str]

List of member names to add

required

Returns:

Type Description
bool

True if members were added successfully, False otherwise

Source code in src/whatsplay/chat_manager.py
async def add_members_to_group(self, group_name: str, members: List[str]) -> bool:
    """
    Add members to an existing group.

    Args:
        group_name: Name of the group
        members: List of member names to add

    Returns:
        True if members were added successfully, False otherwise
    """
    try:
        if not await self.open(group_name):
            await self.client.emit("on_error", f"Could not open group '{group_name}'")
            return False

        success = await self.wa_elements.add_members_to_group(group_name, members)
        return success

    except Exception as e:
        await self.client.emit("on_error", f"Error adding members to group '{group_name}': {e}")
        return False

close() async

Close an active search first, otherwise close the current chat.

Search owns its Escape event so it cannot bubble through and close the underlying chat in the same operation.

Source code in src/whatsplay/chat_manager.py
async def close(self) -> None:
    """
    Close an active search first, otherwise close the current chat.

    Search owns its Escape event so it cannot bubble through and close
    the underlying chat in the same operation.
    """
    if self._page:
        try:
            close_search = getattr(self.wa_elements, "close_search", None)
            if close_search:
                try:
                    result = close_search()
                    if inspect.isawaitable(result):
                        if await result:
                            return
                    elif result is True:
                        return
                except Exception as e:
                    await self.client.emit("on_warning", f"Error trying to close search: {e}")
            await self._page.keyboard.press("Escape")
            await asyncio.sleep(0.5)  # Allow UI to react
        except Exception as e:
            await self.client.emit("on_warning", f"Error trying to close chat with Escape: {e}")

collect_messages(own_push_names=None, dispose=False) async

Collect all currently visible messages in the active chat.

Scans all visible message containers and returns a list of Message, FileMessage, or VoiceMessage instances.

Parameters:

Name Type Description Default
own_push_names Optional[Union[str, list]]

Optional account push names identifying own bubbles (e.g. ["Bikes Amigorena"]). Last-resort fallback only: forwarded to Message.from_element and consulted when tail + class + data-id + positional + group are all inconclusive. Compared accent/case-insensitively. The dispose: When True, release each message's container handle before returning. Use for data-only consumers (bots that only read text/sender/timestamp) to avoid accumulating DOM handles in the renderer; keep False (default) so react() and download() still work. default path (None) classifies direction config-free via positional alignment and group inheritance.

None

Direction contract (precedence is DIRECTION_ORDER in whatsplay.object.message; config-free first): tail (ground truth) > class / data-id (opportunistic, outrank group) > group inheritance (tail-delimited groups, direction never leaks across an outgoing/incoming boundary) > positional inner-bubble alignment (right = outgoing, left = incoming; inconclusive geometry abstains) > sender identity (last resort).

Sender inheritance contract

Sender-less continuation bubbles inherit the previous bubble's sender for DISPLAY only (sender_inherited=True). Consumers must use is_outgoing / is_from_self() for skip logic, never the inherited sender. Direction is preserved through inheritance: a sender-less bubble with no direction signal of its own inherits the group direction; a bubble with its own positive signal (including position-out/position-in) keeps it.

Returns:

Type Description
List[Union[Message, FileMessage, VoiceMessage]]

List of Message, FileMessage, or VoiceMessage instances

Source code in src/whatsplay/chat_manager.py
async def collect_messages(
    self,
    own_push_names: Optional[Union[str, list]] = None,
    dispose: bool = False,
) -> List[Union[Message, FileMessage, VoiceMessage]]:
    """
    Collect all currently visible messages in the active chat.

    Scans all visible message containers and returns a list of Message,
    FileMessage, or VoiceMessage instances.

    Args:
        own_push_names: Optional account push names identifying own
            bubbles (e.g. ["Bikes Amigorena"]). Last-resort fallback
            only: forwarded to Message.from_element and consulted when
            tail + class + data-id + positional + group are all
            inconclusive. Compared accent/case-insensitively. The
            dispose: When True, release each message's container handle
            before returning. Use for data-only consumers (bots that
            only read text/sender/timestamp) to avoid accumulating DOM
            handles in the renderer; keep False (default) so react()
            and download() still work.
            default path (None) classifies direction config-free via
            positional alignment and group inheritance.

    Direction contract (precedence is DIRECTION_ORDER in
    whatsplay.object.message; config-free first):
    tail (ground truth) > class / data-id (opportunistic, outrank
    group) > group inheritance (tail-delimited groups, direction never
    leaks across an outgoing/incoming boundary) > positional
    inner-bubble alignment (right = outgoing, left = incoming;
    inconclusive geometry abstains) > sender identity (last resort).

    Sender inheritance contract:
        Sender-less continuation bubbles inherit the previous bubble's
        sender for DISPLAY only (sender_inherited=True). Consumers must
        use is_outgoing / is_from_self() for skip logic, never the
        inherited sender. Direction is preserved through inheritance: a
        sender-less bubble with no direction signal of its own inherits
        the group direction; a bubble with its own positive signal
        (including position-out/position-in) keeps it.

    Returns:
        List of Message, FileMessage, or VoiceMessage instances
    """
    results: List[Union[Message, FileMessage, VoiceMessage]] = []

    # ── Scroll up to trigger WhatsApp's virtual list to load older messages ──
    try:
        await self._page.evaluate("""
            () => {
                const scroller = document.querySelector('div[role="application"]')?.parentElement
                    || document.querySelector('[data-virtualized="false"]')?.closest('[style*="overflow"]')
                    || document.querySelector('div[tabindex="-1"]');
                if (scroller && scroller.scrollTop !== undefined) {
                    scroller.scrollTop = 0;
                }
            }
        """)
        await asyncio.sleep(1.5)
    except Exception:
        pass

    # Wait for message containers to appear in the DOM
    for _ in range(10):
        count = await self._page.evaluate(
            """() => document.querySelectorAll('div[data-testid^="conv-msg-"]').length"""
        )
        if count > 0:
            break
        await asyncio.sleep(0.5)
    else:
        # Logear QUE chat y en que URL fallo: sin esto no se puede
        # distinguir un chat vacio de un selector roto o una pestana
        # en la pantalla equivocada.
        try:
            _url = self._page.url
            _title = await self._page.title()
            _pane = await self._page.evaluate(
                """() => document.querySelector('#main') ? 'main-present' : 'no-main'"""
            )
        except Exception:
            _url, _title, _pane = "?", "?", "?"
        logger.warning(
            "collect_messages: no message containers found after 5s "
            "(url=%s pane=%s title=%r)", _url, _pane, _title[:60]
        )

    msg_elements = await self._page.query_selector_all('div[data-testid^="conv-msg-"]')
    logger.debug("collect_messages: %d containers found", len(msg_elements))
    # One page round trip for every bubble instead of one per bubble.
    bubbles = await _model_bubbles(self._page)
    # Modules unreachable: DOM text, no per-bubble retries, kinds unknown.
    model_texts, model_kinds = bubbles if bubbles is not None else ({}, {})

    last_sender = ""
    last_is_outgoing = False
    for i, elem in enumerate(msg_elements):
        voice_msg = await VoiceMessage.from_element(elem, self._page, own_push_names, model_texts=model_texts)
        if voice_msg:
            self._inherit_sender(voice_msg, last_sender, last_is_outgoing)
            if voice_msg.sender:
                last_sender = voice_msg.sender
                last_is_outgoing = voice_msg.is_outgoing
            results.append(voice_msg)
            continue

        file_msg = await FileMessage.from_element(elem, self._page, own_push_names, model_texts=model_texts)
        if file_msg:
            self._inherit_sender(file_msg, last_sender, last_is_outgoing)
            if file_msg.sender:
                last_sender = file_msg.sender
                last_is_outgoing = file_msg.is_outgoing
            results.append(file_msg)
            continue

        simple_msg = await Message.from_element(elem, self._page, own_push_names, model_texts=model_texts)
        if simple_msg:
            self._inherit_sender(simple_msg, last_sender, last_is_outgoing)
            if simple_msg.sender:
                last_sender = simple_msg.sender
                last_is_outgoing = simple_msg.is_outgoing
            results.append(simple_msg)

    self._apply_group_tail_inheritance(results)
    self._attach_kinds(results, model_kinds)

    if dispose:
        # Data-only consumers (bots that read text/sender/timestamp and
        # never call react/download) should release the container handles
        # right away: each one pins a DOM node in the renderer, and a poll
        # loop reading chats every few seconds accumulates thousands of
        # them until the V8 heap cannot commit and the renderer crashes
        # with SIGTRAP ("Target crashed"). Interactive consumers keep the
        # default dispose=False so react()/download() still work.
        for _msg in results:
            await _msg.dispose()

    return results

download_all_files(carpeta=None, detect_codecs=True) async

Download all file attachments from the current chat.

Parameters:

Name Type Description Default
carpeta Optional[str]

Optional custom download directory path

None
detect_codecs bool

If True, detect codec info for each file

True

Returns:

Type Description
List[Dict[str, Any]]

List of dicts with file path and codec info

Source code in src/whatsplay/chat_manager.py
async def download_all_files(
    self, carpeta: Optional[str] = None, detect_codecs: bool = True
) -> List[Dict[str, Any]]:
    """
    Download all file attachments from the current chat.

    Args:
        carpeta: Optional custom download directory path
        detect_codecs: If True, detect codec info for each file

    Returns:
        List of dicts with file path and codec info
    """
    if not await self.client.wait_until_logged_in():
        return []

    downloads_dir = Path(carpeta) if carpeta else DEFAULT_DOWNLOADS_DIR

    saved_files: List[Dict[str, Any]] = []
    messages = await self.collect_messages()

    for msg in messages:
        file_path = None
        if isinstance(msg, FileMessage):
            file_path = await msg.download(self._page, downloads_dir)
        elif isinstance(msg, VoiceMessage):
            file_path = await msg.download(self._page, downloads_dir)

        if file_path:
            file_info = {"path": file_path, "type": type(msg).__name__}
            if detect_codecs:
                file_info["codec"] = detect_codec(file_path)
            saved_files.append(file_info)

    return saved_files

download_file_by_index(index, carpeta=None, detect_codecs=True) async

Download a specific file by its index in the message list.

Parameters:

Name Type Description Default
index int

Zero-based index of the file to download

required
carpeta Optional[str]

Optional custom download directory path

None
detect_codecs bool

If True, detect codec info for the file

True

Returns:

Type Description
Optional[Dict[str, Any]]

Dict with path, type, and codec info, or None if failed

Source code in src/whatsplay/chat_manager.py
async def download_file_by_index(
    self, index: int, carpeta: Optional[str] = None, detect_codecs: bool = True
) -> Optional[Dict[str, Any]]:
    """
    Download a specific file by its index in the message list.

    Args:
        index: Zero-based index of the file to download
        carpeta: Optional custom download directory path
        detect_codecs: If True, detect codec info for the file

    Returns:
        Dict with path, type, and codec info, or None if failed
    """
    if not await self.client.wait_until_logged_in():
        return None

    downloads_dir = Path(carpeta) if carpeta else DEFAULT_DOWNLOADS_DIR

    messages = await self.collect_messages()
    downloadable = [m for m in messages if isinstance(m, (FileMessage, VoiceMessage))]

    if index < 0 or index >= len(downloadable):
        return None

    msg = downloadable[index]
    file_path = await msg.download(self._page, downloads_dir)

    if not file_path:
        return None

    result = {"path": file_path, "type": type(msg).__name__}
    if detect_codecs:
        result["codec"] = detect_codec(file_path)

    return result

new_group(group_name, members) async

Create a new WhatsApp group.

Parameters:

Name Type Description Default
group_name str

Name for the new group

required
members List[str]

List of member names to add to the group

required

Returns:

Type Description
bool

True if group was created successfully, False otherwise

Source code in src/whatsplay/chat_manager.py
async def new_group(self, group_name: str, members: List[str]) -> bool:
    """
    Create a new WhatsApp group.

    Args:
        group_name: Name for the new group
        members: List of member names to add to the group

    Returns:
        True if group was created successfully, False otherwise
    """
    return await self.wa_elements.new_group(group_name, members)

open(chat_name, timeout=DEFAULT_WAIT_TIMEOUT, open_via_url=False, is_group=None) async

Open a chat by name.

Parameters:

Name Type Description Default
chat_name str

Name of the chat to open

required
timeout int

Maximum time to wait in milliseconds

DEFAULT_WAIT_TIMEOUT
open_via_url bool

If True, forces opening via URL (for phone numbers)

False
is_group Optional[bool]

If set, the chat must be a group (True) or a contact (False)

None

Returns:

Type Description
bool

True if chat was opened successfully, False otherwise

Source code in src/whatsplay/chat_manager.py
async def open(
    self,
    chat_name: str,
    timeout: int = DEFAULT_WAIT_TIMEOUT,
    open_via_url: bool = False,
    is_group: Optional[bool] = None,
) -> bool:
    """
    Open a chat by name.

    Args:
        chat_name: Name of the chat to open
        timeout: Maximum time to wait in milliseconds
        open_via_url: If True, forces opening via URL (for phone numbers)
        is_group: If set, the chat must be a group (True) or a contact (False)

    Returns:
        True if chat was opened successfully, False otherwise
    """
    return await self.wa_elements.open(
        chat_name, timeout, open_via_url=open_via_url, is_group=is_group
    )

react_to_last_message(emoji) async

React to the last visible message in the current chat.

Parameters:

Name Type Description Default
emoji str

The emoji to react with (e.g., "👍", "❤️")

required

Returns:

Type Description
bool

True if reaction was successful, False otherwise

Source code in src/whatsplay/chat_manager.py
async def react_to_last_message(self, emoji: str) -> bool:
    """
    React to the last visible message in the current chat.

    Args:
        emoji: The emoji to react with (e.g., "👍", "❤️")

    Returns:
        True if reaction was successful, False otherwise
    """
    try:
        messages = await self.collect_messages()
        if not messages:
            await self.client.emit("on_warning", "No messages found to react to.")
            return False

        last_message = messages[-1]
        await last_message.react(emoji)
        return True
    except Exception as e:
        await self.client.emit("on_error", f"Error reacting to last message: {e}")
        return False

search_conversations(query, close=True) async

Search for conversations by term.

Parameters:

Name Type Description Default
query str

Search term

required
close bool

If True, closes the search after completion

True

Returns:

Type Description
List[Dict[str, Any]]

List of matching conversations

Source code in src/whatsplay/chat_manager.py
async def search_conversations(self, query: str, close: bool = True) -> List[Dict[str, Any]]:
    """
    Search for conversations by term.

    Args:
        query: Search term
        close: If True, closes the search after completion

    Returns:
        List of matching conversations
    """
    if not await self.client.wait_until_logged_in():
        return []
    try:
        return await self.wa_elements.search_chats(query, close)
    except Exception as e:
        await self.client.emit("on_error", f"Search error: {e}")
        return []

send_file(chat_name, path, open_via_url=False, is_group=None) async

Send a file attachment to a chat.

Parameters:

Name Type Description Default
chat_name str

Name of the chat to send the file to

required
path str

Absolute path to the file to send

required
open_via_url bool

If True, opens the chat via URL (required for phone numbers)

False

Returns:

Type Description
bool

True if file was sent successfully, False otherwise

Source code in src/whatsplay/chat_manager.py
async def send_file(
    self,
    chat_name: str,
    path: str,
    open_via_url: bool = False,
    is_group: Optional[bool] = None,
) -> bool:
    """
    Send a file attachment to a chat.

    Args:
        chat_name: Name of the chat to send the file to
        path: Absolute path to the file to send
        open_via_url: If True, opens the chat via URL (required for phone numbers)

    Returns:
        True if file was sent successfully, False otherwise
    """
    async with self.client._page_lock:
        try:
            if not os.path.isfile(path):
                msg = f"File does not exist: {path}"
                await self.client.emit("on_error", msg)
                return False

            if not await self.client.wait_until_logged_in():
                msg = "Could not log in"
                await self.client.emit("on_error", msg)
                return False

            if not await self.open(chat_name, open_via_url=open_via_url, is_group=is_group):
                msg = f"Could not open chat: {chat_name}"
                await self.client.emit("on_error", msg)
                return False

            composer = await self._page.wait_for_selector(
                loc.ACTIVE_CHAT_COMPOSER, timeout=DEFAULT_WAIT_TIMEOUT
            )
            try:
                target = self._opened_target(chat_name, open_via_url)
                if not await self._ensure_composer_targets(composer, target, is_group):
                    return False
            finally:
                await _safe_dispose(composer)

            attach_btn = await self._page.wait_for_selector(loc.ATTACH_BUTTON, timeout=5000)
            await attach_btn.click()
            await asyncio.sleep(1.5)

            # Usar el file chooser de Playwright: intercepta el diálogo nativo de
            # selección de archivos y funciona TAMBIÉN en headless (el input accept="*"
            # solo se crea cuando se abre ese diálogo, que en headless no aparece).
            # 1) Registrar el file chooser ANTES de clickear "Documento"
            async with self._page.expect_file_chooser(timeout=15000) as fc_info:
                doc_btn = self._page.locator(
                    "button[aria-label='Documento'], button[aria-label='Document']"
                ).first
                if await doc_btn.count():
                    await doc_btn.click()
                else:
                    # fallback: usar el primer input de archivos
                    fallback = self._page.locator(loc.FILE_INPUT).first
                    await fallback.click()
                file_chooser = await fc_info.value

            await file_chooser.set_files(path)
            await asyncio.sleep(5)
            # El botón de enviar real es el DIV role=button (el SPAN interno no dispara)
            send_btn_loc = self._page.locator(loc.SEND_BUTTON).first
            await send_btn_loc.wait_for(state="visible", timeout=DEFAULT_WAIT_TIMEOUT)
            before_ids = await self._message_ids()
            await send_btn_loc.click()
            confirmed = await self.wait_for_sent_confirmation(before_ids, DEFAULT_WAIT_TIMEOUT)
            if not confirmed:
                logger.warning("File to %r sent but not confirmed by server", chat_name)
            return confirmed
        except Exception as e:
            await self.client.emit("on_error", f"Error sending file: {e}")
            return False

send_message(chat_query, message, open_via_url=False, is_group=None) async

Send a text message to a chat.

Parameters:

Name Type Description Default
chat_query str

Name or identifier of the chat

required
message str

Text message to send

required
open_via_url bool

If True, opens the chat via URL before sending

False

Returns:

Type Description
bool

True if message was sent successfully, False otherwise

Source code in src/whatsplay/chat_manager.py
async def send_message(
    self,
    chat_query: str,
    message: str,
    open_via_url: bool = False,
    is_group: Optional[bool] = None,
) -> bool:
    """
    Send a text message to a chat.

    Args:
        chat_query: Name or identifier of the chat
        message: Text message to send
        open_via_url: If True, opens the chat via URL before sending

    Returns:
        True if message was sent successfully, False otherwise
    """
    async with self.client._page_lock:
        logger.info("Sending message to %r", chat_query)
        if not await self.client.wait_until_logged_in():
            return False

        try:
            opened = await self.open(chat_query, open_via_url=open_via_url, is_group=is_group)
            if not opened:
                await self.client.emit("on_error", f"Could not open chat: {chat_query}")
                return False
            logger.info("Chat %r opened, sending message", chat_query)

            input_box = await self._page.wait_for_selector(
                loc.ACTIVE_CHAT_COMPOSER, timeout=DEFAULT_WAIT_TIMEOUT
            )
            if not input_box:
                await self.client.emit(
                    "on_error",
                    "Could not find text input box for sending message",
                )
                return False
            target = self._opened_target(chat_query, open_via_url)
            if not await self._ensure_composer_targets(input_box, target, is_group):
                return False

            await input_box.click()
            await input_box.fill(message)
            # Only send if the box holds the message: stray keystrokes that
            # landed here earlier would go out with it.
            typed = await input_box.inner_text()
            if not composer_holds(typed, message):
                logger.error("Composer holds %r, not the message; not sending", typed[:80])
                await input_box.fill("")
                await self.client.emit(
                    "on_error", f"Composer text did not match the message for {chat_query!r}"
                )
                return False
            before_ids = await self._message_ids()
            # Enter goes to the composer itself, not to whatever has focus.
            await input_box.press("Enter")

            confirmed = await self.wait_for_sent_confirmation(before_ids, DEFAULT_WAIT_TIMEOUT)
            if not confirmed:
                logger.warning(
                    "Message to %r sent but not confirmed by server", chat_query
                )
                return False

            return True

        except Exception as e:
            await self.client.emit("on_error", f"Error sending message: {e}")
            return False
        finally:
            await self.close()

wait_for_sent_confirmation(before_ids, timeout=DEFAULT_WAIT_TIMEOUT) async

Wait until a message that was not in before_ids shows a delivery status ("Enviado", "Entregado", "Leído") in the open chat.

An older outgoing message that is already read never counts. Verified live 2026-10-20: a just-sent bubble gets a new data-id and a status span.

Source code in src/whatsplay/chat_manager.py
async def wait_for_sent_confirmation(self, before_ids: set, timeout: int = DEFAULT_WAIT_TIMEOUT) -> bool:
    """Wait until a message that was not in `before_ids` shows a delivery
    status ("Enviado", "Entregado", "Leído") in the open chat.

    An older outgoing message that is already read never counts. Verified
    live 2026-10-20: a just-sent bubble gets a new data-id and a status span.
    """
    deadline = time.monotonic() + timeout / 1000
    while True:
        for row in await self._bubbles():
            if row.get("id") not in before_ids and row.get("status"):
                return True
        if time.monotonic() >= deadline:
            logger.warning("No new message with a delivery status within %dms", timeout)
            return False
        await asyncio.sleep(0.5)

State Manager

Responsible for managing the client's internal state.

whatsplay.state_manager.StateManager

Manages WhatsApp Web client state transitions and QR code handling.

This class monitors the WhatsApp Web state and triggers appropriate actions for each state transition, including QR code display, authentication handling, and unread message detection.

Attributes:

Name Type Description
client

Reference to the main WhatsApp client

_page

Playwright page object for browser interactions

wa_elements

WhatsApp Web elements helper

last_qr_shown Optional[bytes]

Binary data of the last displayed QR code

qr_server_started bool

Flag indicating if QR server is running

Source code in src/whatsplay/state_manager.py
class StateManager:
    """
    Manages WhatsApp Web client state transitions and QR code handling.

    This class monitors the WhatsApp Web state and triggers appropriate
    actions for each state transition, including QR code display,
    authentication handling, and unread message detection.

    Attributes:
        client: Reference to the main WhatsApp client
        _page: Playwright page object for browser interactions
        wa_elements: WhatsApp Web elements helper
        last_qr_shown: Binary data of the last displayed QR code
        qr_server_started: Flag indicating if QR server is running
    """

    def __init__(self, client: "Client") -> None:
        """
        Initialize StateManager with client reference.

        Args:
            client: The main WhatsApp client instance
        """
        self.client = client
        self._page = client._page
        self.wa_elements = client.wa_elements
        self.last_qr_shown: Optional[bytes] = None
        self.qr_server_started: bool = False
        # Whether on_warning was already emitted for the current blocking dialog.
        self._dialog_warned: bool = False

    async def _get_state(self) -> Optional[State]:
        """
        Get the current state of WhatsApp Web.

        Returns:
            Current State enum value or None if state cannot be determined
        """
        return await self.wa_elements.get_state()

    async def _handle_qr_logic(self, qr_binary: bytes) -> bool:
        """
        Handle the logic for showing and updating the QR code.

        This method manages the QR code server lifecycle and updates
        the displayed QR code when it changes.

        Args:
            qr_binary: Binary data of the QR code image

        Returns:
            True if QR code was updated or shown, False otherwise
        """
        # El servidor del QR (puerto 8000, proxeado por nginx) TIENE que
        # arrancar aunque no hayamos podido leer la imagen del canvas todavia.
        # Antes, un qr_binary vacio hacia return False y el server no arrancaba
        # nunca: el portal daba 502 y no habia forma de escanear. Ahora
        # arrancamos con imagen vacia y se actualiza cuando llegue una.
        if qr_binary and qr_binary == self.last_qr_shown:
            return False

        if not self.qr_server_started:
            show_qr_window(qr_binary or b"")
            self.qr_server_started = True
        elif qr_binary:
            update_qr_code(qr_binary)

        if not qr_binary:
            return False

        self.last_qr_shown = qr_binary
        return True

    async def _handle_state_change(
        self, curr_state: State, prev_state: Optional[State]
    ) -> None:
        """
        Handle state transitions.

        This method is called when the WhatsApp Web state changes and
        triggers appropriate actions for each state.

        Args:
            curr_state: Current state
            prev_state: Previous state (may be None on first detection)
        """
        if curr_state == State.AUTH:
            await self._handle_auth_state()

        elif curr_state == State.QR_AUTH:
            await self._handle_qr_auth_state_change()

        elif curr_state == State.LOADING:
            await self._handle_loading_state()

        elif curr_state == State.LOGGED_IN:
            await self._handle_logged_in_state_change()

    async def _handle_auth_state(self) -> None:
        """Handle the authentication state."""
        await self.client.emit("on_auth")

    async def _handle_qr_auth_state_change(self) -> None:
        """Handle QR authentication state transition."""
        try:
            qr_code_canvas = await self._page.wait_for_selector(
                loc.QR_CODE, timeout=QR_CODE_TIMEOUT
            )
            qr_binary = await self._extract_image_from_canvas(qr_code_canvas)

            if await self._handle_qr_logic(qr_binary):
                await self.client.emit("on_qr", qr_binary)

        except PlaywrightTimeoutError:
            await self.client.emit(
                "on_warning", "Timeout waiting for QR code"
            )
        except Exception as e:
            await self.client.emit("on_error", f"Error processing QR code: {e}")

    async def _handle_loading_state(self) -> None:
        """Handle the loading state."""
        loading_chats = (
            await self.wa_elements.wait_for_selector(loc.LOADING_CHATS) is not None
        )
        await self.client.emit("on_loading", loading_chats)

    async def _handle_logged_in_state_change(self) -> None:
        """Handle logged-in state transition."""
        if self.qr_server_started:
            close_qr_window()
            self.qr_server_started = False

        logger.debug("_handle_logged_in_state_change: emitting on_logged_in")
        await self.client.emit("on_logged_in")
        logger.debug("_handle_logged_in_state_change: on_logged_in done, waiting for chat list to load...")
        # Esperar a que el chat list se hidrate (WhatsApp Web tarda en cargar los chats)
        await asyncio.sleep(10)
        logger.debug("_handle_logged_in_state_change: calling _handle_logged_in_state")
        await self._handle_logged_in_state()

    async def _handle_same_state(self, state: State) -> None:
        """
        Handle logic when the state hasn't changed.

        This method is called on each tick when the state remains the same,
        allowing for periodic actions like QR code refresh or unread message checks.

        Args:
            state: Current state
        """
        if state == State.QR_AUTH:
            await self._handle_qr_auth_state()
        elif state == State.LOGGED_IN:
            await self._handle_logged_in_state()

    async def _handle_qr_auth_state(self) -> None:
        """
        Handle QR authentication state (periodic check).

        Checks if the QR code has changed and updates the display if necessary.
        Handles expired QR codes by clicking the refresh button.
        """
        try:
            # Detectar QR expirado (boton de refresh visible)
            refresh_btn = await self._page.query_selector(loc.QR_REFRESH_BUTTON)
            try:
                if refresh_btn and await refresh_btn.is_visible():
                    logger.info("QR expired, clicking refresh")
                    try:
                        await refresh_btn.click()
                        await asyncio.sleep(3)
                    except Exception as e:
                        logger.warning(f"Error clicking the QR refresh button: {e}")
                    # The expired canvas stays in the page under the button:
                    # never hand out a QR that can no longer be scanned.
                    if await refresh_btn.is_visible():
                        logger.warning("QR still expired after refresh; not reporting it")
                        return
            finally:
                await _safe_dispose(refresh_btn)

            # Re-query canvas despues de posible refresh (canvas viejo se desadjunta)
            qr_code_canvas = await self._page.query_selector(loc.QR_CODE)
            if not qr_code_canvas:
                return

            curr_qr_binary = await self._extract_image_from_canvas(qr_code_canvas)

            if await self._handle_qr_logic(curr_qr_binary):
                await self.client.emit("on_qr_change", curr_qr_binary)

        except Exception as e:
            await self.client.emit("on_warning", f"Error updating QR code: {e}")

    async def _handle_logged_in_state(self) -> None:
        """
        Handle logged-in state (periodic check).

        Checks for continue buttons and unread chats when in logged-in state.
        """
        # ── guard: si el page ya fue cerrado por user handler, salir ──
        if not self._page:
            logger.debug("_handle_logged_in_state: skipped, page is None (client stopped)")
            return
        if not getattr(self.client, "_is_running", False):
            logger.debug("_handle_logged_in_state: skipped, client not running")
            return

        try:
            # Another page operation is in progress (it may have opened a dialog
            # of its own, e.g. send_file's media preview): touch nothing.
            if self.client._page_lock.locked():
                logger.debug("Skipping logged-in tick: page locked by another operation")
                return

            # A modal dialog ("Novedades en WhatsApp Web", …) blocks every click.
            # Only its X is used, under the page lock; a dialog without one (it
            # may ask to accept something) is reported once, never clicked through.
            async with self.client._page_lock:
                dismissed = await self.wa_elements.dismiss_blocking_dialog()
            if not dismissed:
                if not self._dialog_warned:
                    self._dialog_warned = True
                    await self.client.emit(
                        "on_warning",
                        "A modal dialog blocks WhatsApp Web and could not be closed",
                    )
                return
            self._dialog_warned = False

            # Check for unread chats
            unread_chats = await self.client.chat_manager._check_unread_chats()
            if unread_chats:
                await self.client.emit("on_unread_chat", unread_chats)

        except Exception as e:
            await self.client.emit("on_error", f"Error in logged-in state: {e}")

    async def _extract_image_from_canvas(
        self, canvas_element: Optional[ElementHandle]
    ) -> Optional[bytes]:
        """
        Extract image data from a canvas element.

        Args:
            canvas_element: Canvas element containing the image

        Returns:
            Binary image data or None if extraction fails
        """
        if not canvas_element:
            return None

        # El canvas del QR se re-anima en WhatsApp Web, asi que un screenshot
        # normal (scroll_into_view + esperar estabilidad) falla con
        # "element is not stable" / "not attached to the DOM". Leemos el canvas
        # por JS, que no depende de estabilidad, y si falla probamos un
        # screenshot con las animaciones deshabilitadas. Nunca cortamos el flujo
        # por esto: el servidor del QR debe arrancar igual.
        try:
            data_url = await canvas_element.evaluate(
                "el => el.toDataURL ? el.toDataURL('image/png') : null"
            )
            if data_url and "," in data_url:
                return base64.b64decode(data_url.split(",", 1)[1])
        except Exception:
            pass

        try:
            return await canvas_element.screenshot(animations="disabled")
        except Exception as e:
            # No es fatal: show_qr_window arranca el server con imagen vacia y
            # se actualiza cuando el canvas vuelva a estar disponible.
            logger.warning(f"QR screenshot fallo (no fatal): {e}")
            return None

__init__(client)

Initialize StateManager with client reference.

Parameters:

Name Type Description Default
client Client

The main WhatsApp client instance

required
Source code in src/whatsplay/state_manager.py
def __init__(self, client: "Client") -> None:
    """
    Initialize StateManager with client reference.

    Args:
        client: The main WhatsApp client instance
    """
    self.client = client
    self._page = client._page
    self.wa_elements = client.wa_elements
    self.last_qr_shown: Optional[bytes] = None
    self.qr_server_started: bool = False
    # Whether on_warning was already emitted for the current blocking dialog.
    self._dialog_warned: bool = False

Authentication

Authentication handlers are used to manage the WhatsApp session.

Local Profile Auth

The recommended handler for saving your session locally to avoid repeated QR scans.

whatsplay.auth.local_profile_auth.LocalProfileAuth

Bases: AuthBase

Authentication using a local browser profile

Source code in src/whatsplay/auth/local_profile_auth.py
class LocalProfileAuth(AuthBase):
    """Authentication using a local browser profile"""

    def __init__(self, data_dir: str, profile: str = "Default"):
        super().__init__()
        self.data_dir = os.path.abspath(data_dir)
        self.profile = profile
        self.profile_path = os.path.join(self.data_dir, self.profile)
        os.makedirs(self.profile_path, exist_ok=True)

    def get_browser_args(self) -> Dict[str, Any]:
        """Get browser launch arguments for profile"""
        return {
            "headless": False,  # Profile persistence doesn't work well in headless mode
            "args": [
                "--no-sandbox",
                "--disable-setuid-sandbox",
                "--disable-dev-shm-usage",
            ],
        }

    async def setup_context(self, context: BrowserContext) -> None:
        """Configure browser context with profile settings.

        NOTA: NO guardar storage_state aquí — context.storage_state(path=...)
        cierra/cancela el contexto en versiones recientes de Playwright, causando
        "Target page, context or browser has been closed". El perfil ya persiste
        en el user_data_dir, así que no hace falta este paso.
        """
        pass

    async def save_session(self) -> bool:
        """Save browser session state"""
        try:
            os.makedirs(self.profile_path, exist_ok=True)
            return True
        except Exception as e:
            logger.warning(f"Error saving session: {e}")
            return False

    async def load_session(self) -> bool:
        """Check if profile exists and has state"""
        state_file = os.path.join(self.profile_path, "state.json")
        return os.path.exists(self.profile_path) and os.path.exists(state_file)

get_browser_args()

Get browser launch arguments for profile

Source code in src/whatsplay/auth/local_profile_auth.py
def get_browser_args(self) -> Dict[str, Any]:
    """Get browser launch arguments for profile"""
    return {
        "headless": False,  # Profile persistence doesn't work well in headless mode
        "args": [
            "--no-sandbox",
            "--disable-setuid-sandbox",
            "--disable-dev-shm-usage",
        ],
    }

load_session() async

Check if profile exists and has state

Source code in src/whatsplay/auth/local_profile_auth.py
async def load_session(self) -> bool:
    """Check if profile exists and has state"""
    state_file = os.path.join(self.profile_path, "state.json")
    return os.path.exists(self.profile_path) and os.path.exists(state_file)

save_session() async

Save browser session state

Source code in src/whatsplay/auth/local_profile_auth.py
async def save_session(self) -> bool:
    """Save browser session state"""
    try:
        os.makedirs(self.profile_path, exist_ok=True)
        return True
    except Exception as e:
        logger.warning(f"Error saving session: {e}")
        return False

setup_context(context) async

Configure browser context with profile settings.

NOTA: NO guardar storage_state aquí — context.storage_state(path=...) cierra/cancela el contexto en versiones recientes de Playwright, causando "Target page, context or browser has been closed". El perfil ya persiste en el user_data_dir, así que no hace falta este paso.

Source code in src/whatsplay/auth/local_profile_auth.py
async def setup_context(self, context: BrowserContext) -> None:
    """Configure browser context with profile settings.

    NOTA: NO guardar storage_state aquí — context.storage_state(path=...)
    cierra/cancela el contexto en versiones recientes de Playwright, causando
    "Target page, context or browser has been closed". El perfil ya persiste
    en el user_data_dir, así que no hace falta este paso.
    """
    pass

No Auth

A handler that does not save any session data, requiring a new login on every run.

whatsplay.auth.no_auth.NoAuth

Bases: AuthBase

Authentication strategy that doesn't persist any data

Source code in src/whatsplay/auth/no_auth.py
class NoAuth(AuthBase):
    """Authentication strategy that doesn't persist any data"""

    def __init__(self):
        super().__init__()

    def get_browser_args(self) -> Dict[str, Any]:
        """Get browser launch arguments"""
        return {"headless": False}

    async def setup_context(self, context: BrowserContext) -> None:
        """No special configuration needed"""
        pass

    async def save_session(self) -> bool:
        """No session to save"""
        return False

    async def load_session(self) -> bool:
        """No session to load"""
        return False

get_browser_args()

Get browser launch arguments

Source code in src/whatsplay/auth/no_auth.py
def get_browser_args(self) -> Dict[str, Any]:
    """Get browser launch arguments"""
    return {"headless": False}

load_session() async

No session to load

Source code in src/whatsplay/auth/no_auth.py
async def load_session(self) -> bool:
    """No session to load"""
    return False

save_session() async

No session to save

Source code in src/whatsplay/auth/no_auth.py
async def save_session(self) -> bool:
    """No session to save"""
    return False

setup_context(context) async

No special configuration needed

Source code in src/whatsplay/auth/no_auth.py
async def setup_context(self, context: BrowserContext) -> None:
    """No special configuration needed"""
    pass

Filters

The filters module provides classes and instances to filter events.

Predefined Message Filters

A collection of ready-to-use filters for the on_message event.

whatsplay.filters.message_filter

Message filtering utilities for WhatsApp messages

MessageFilter

Helper class for filtering WhatsApp messages

Source code in src/whatsplay/filters/message_filter.py
class MessageFilter:
    """Helper class for filtering WhatsApp messages"""

    @classmethod
    def filter_search_result(cls, text: str) -> list[str]:
        """Filtra y formatea un resultado de búsqueda

        Returns:
            List[str]: (texto_formateado)
        """
        text = text.strip()

        # Formatear el resultado
        lines = text.split("\n")
        if len(lines) >= 2:
            name = lines[0].strip()
            date = lines[1].strip()
            message = " ".join(lines[2:]).strip() if len(lines) > 2 else ""

            # No mostrar si el mensaje está vacío o muy corto
            if not message or len(message) < 2:
                return text

            # No mostrar si el mensaje solo contiene números o caracteres especiales
            if all(c.isdigit() or c in ".,-_+=/\\" for c in message.replace(" ", "")):
                return text

            text_formatted = {"name": name, "date": date, "message": message}
            return text_formatted

        return text

filter_search_result(text) classmethod

Filtra y formatea un resultado de búsqueda

Returns:

Type Description
list[str]

List[str]: (texto_formateado)

Source code in src/whatsplay/filters/message_filter.py
@classmethod
def filter_search_result(cls, text: str) -> list[str]:
    """Filtra y formatea un resultado de búsqueda

    Returns:
        List[str]: (texto_formateado)
    """
    text = text.strip()

    # Formatear el resultado
    lines = text.split("\n")
    if len(lines) >= 2:
        name = lines[0].strip()
        date = lines[1].strip()
        message = " ".join(lines[2:]).strip() if len(lines) > 2 else ""

        # No mostrar si el mensaje está vacío o muy corto
        if not message or len(message) < 2:
            return text

        # No mostrar si el mensaje solo contiene números o caracteres especiales
        if all(c.isdigit() or c in ".,-_+=/\\" for c in message.replace(" ", "")):
            return text

        text_formatted = {"name": name, "date": date, "message": message}
        return text_formatted

    return text

Custom Filter Base Class

Inherit from this class to create your own powerful, reusable filters.

whatsplay.filters.filters.CustomFilter

Bases: Filter

A filter that uses a custom function to test values.

Source code in src/whatsplay/filters/filters.py
class CustomFilter(Filter):
    """
    A filter that uses a custom function to test values.
    """

    def __init__(self, func: Callable[[Any], bool]):
        self.func = func

    def test(self, value: Any) -> bool:
        return self.func(value)