Skip to main content

WhatsPlay 🚀

Modern WhatsApp Web automation with Playwright and Python

PyPI version Downloads Python License Docs

📖 Documentation: https://markbus-ai.github.io/whatsplay/


✨ Features

  • Stable selectors — attribute-based (data-pre-plain-text, aria-label, data-testid), not minified CSS classes that break on every WA update
  • Safe sending — text is only typed into the chat you asked for, and send_message() returns True only once WhatsApp shows the new message with a delivery status
  • Exact chat matching — is_group tells groups from contacts, phone numbers match in full, ambiguous titles are refused instead of guessed
  • Accurate message text — read from WhatsApp's own message model (captions and replies included), with the DOM as fallback
  • Multi-language — works with WhatsApp Web in Spanish and English out of the box
  • Voice messages — duration, download, and codec detection
  • Persistent sessions — scan QR once, reuse the session
  • Unread chat detection — scans from the top of the All filter every time
  • File & media support — send any file; download documents, images, and voice notes
  • Event-driven — on_logged_in, on_unread_chat, on_error, on_refresh, etc.
  • Concurrency-safe — every page operation runs under one re-entrant lock (client.page_lock)
  • Long-running bots — client.refresh() and collect_messages(dispose=True) keep renderer memory in check
  • Standard logging — everything goes through logging under the whatsplay namespace
  • Headless mode — works on servers without GUI

Quick Start

pip install whatsplay
python -m playwright install chromium
import asyncio
from pathlib import Path
from whatsplay import Client
from whatsplay.auth import LocalProfileAuth

async def main():
    auth = LocalProfileAuth(Path.home() / "whatsapp_session")
    client = Client(auth=auth, headless=False)

    @client.event("on_unread_chat")
    async def on_unread_chat(chats):
        for chat in chats:
            await client.send_message(chat["name"], "🤖 Automated with WhatsPlay!")

    await client.start()

asyncio.run(main())

📦 Installation

From PyPI

pip install whatsplay

After installing, download the Playwright browser:

python -m playwright install chromium

If a system Chromium (/usr/bin/chromium) or Google Chrome (/usr/bin/google-chrome) is installed, WhatsPlay uses it instead.

From source

git clone https://github.com/markbus-ai/whatsplay.git
cd whatsplay
pip install -e .
python -m playwright install chromium

📖 Usage Guide

Basic connection

from pathlib import Path
from whatsplay import Client
from whatsplay.auth import LocalProfileAuth

auth = LocalProfileAuth(data_dir=Path.home() / "whatsapp_session")
client = Client(auth=auth, headless=False)

Events

@client.event("on_logged_in")
async def on_logged_in():
    print("✅ Logged in")

@client.event("on_qr")
async def on_qr(qr_bytes):
    print("📸 Scan the QR code")

@client.event("on_unread_chat")
async def on_unread_chat(chats):
    # chats: [{"name": ..., "unread_count": ..., "last_message": ..., ...}, ...]
    for chat in chats:
        print(f"📩 {chat['unread_count']} unread in {chat['name']}")

@client.event("on_error")
async def on_error(message):
    print(f"❌ {message}")

Reading messages

if await client.open("My Group", is_group=True):
    messages = await client.collect_messages()
    for msg in messages:
        direction = "→" if msg.is_outgoing else "←"
        print(f"{direction} [{msg.timestamp}] {msg.sender}: {msg.text}")
    await client.close()

Sending messages

# By chat name (exact title)
await client.send_message("My Group", "Hello!", is_group=True)

# By phone number (full international number)
await client.send_message("5491123456789", "Direct message", open_via_url=True)

# Files
await client.send_file("My Group", "/path/to/report.pdf")

Both return True only after WhatsApp shows the new message with a delivery status. On failure they return False and log why — WhatsPlay never raises custom exceptions.

Voice messages and files

from whatsplay import VoiceMessage

await client.open("My Friend")

for msg in await client.collect_messages():
    if isinstance(msg, VoiceMessage):
        print(f"🎤 Voice message: {msg.duration}")

# Download every file and voice note in the open chat
files = await client.download_all_files(carpeta="./downloads")
for info in files:
    print(info["type"], info["path"], info.get("codec"))

Running several operations atomically

async with client.page_lock:
    await client.open("Work Chat")
    messages = await client.collect_messages()
    await client.close()

Long-running bots

messages = await client.collect_messages(dispose=True)  # release browser handles right away
await client.refresh()  # reload WhatsApp Web to free renderer memory; no new QR needed

Logging

import logging

logging.getLogger("whatsplay").setLevel(logging.WARNING)            # quiet
logging.getLogger("whatsplay.wa_elements").setLevel(logging.DEBUG)  # DOM detail

If your app doesn't configure logging, WhatsPlay prints INFO messages to stdout.


📚 Examples

The examples/ directory includes ready-to-run scripts:

File Description
simple_example.py Basic event-driven auto-reply
collect_messages_event.py Collect messages from a chat after login
open_example.py Open a specific chat programmatically
search_example.py Search conversations with detailed results
send_file.py Send a file to a chat
react.py React to a collected message
wsp.py CLI tool for quick message sending
verify_selectors.py E2E validation of selectors against live WA Web
investigate_voice.py Live DOM investigation for voice message structure

🛠 Development

Setup

pip install -e . pytest pytest-asyncio
python -m playwright install chromium

Running tests

pytest tests/ -v

Documentation

The docs live in docs/ (English and Spanish) and are built with MkDocs Material. They are deployed to GitHub Pages on every push to main.

pip install -r requirements-docs.txt
mkdocs serve

🗺 Roadmap

Completed ✅

  • Async event system
  • Persistent session (QR once)
  • Message sending / receiving with delivery confirmation
  • File & media support, codec detection
  • Voice message detection, duration & download
  • Unread chat detection
  • Search with exact, unambiguous matching
  • Stable attribute-based selectors (no more fragile CSS classes)
  • Multi-language (Spanish / English)
  • Group management (create, add / remove members)
  • Reactions (react_to_last_message(), Message.react())
  • Structured logging
  • Page lock for concurrent handlers
  • Memory management for long-running bots (refresh(), dispose)

In progress 🚧

  • Real on_message event (no more manual open + collect polling)
  • Selector health check that warns loudly when WhatsApp Web changes its DOM

Planned 🔮

  • Send results that explain why a send failed (ambiguous chat, wrong composer, no delivery status)
  • Reading older chat history by scrolling
  • Warning for unsupported (non English / Spanish) locales

❓ FAQ

Is it safe? It uses WhatsApp Web's official interface — as safe as using WhatsApp in a browser.

Can WhatsApp detect it? There's always risk with automation. Use responsibly.

Does it work headless? Yes, Playwright's headless mode is supported.

Does it work in Spanish? Yes. WhatsApp Web interfaces in Spanish and English are supported; with any other interface language, sending is refused instead of risking the wrong chat.

Why did send_message() return False? The chat couldn't be verified (wrong or ambiguous title), the composer belonged to another chat, or no delivery status appeared. Check the whatsplay logs — see Troubleshooting.


🐞 Report a bug

Open an issue with:

  • Problem description
  • Reproduction steps
  • Python version and dependencies
  • Relevant logs (logging.getLogger("whatsplay").setLevel(logging.DEBUG))

🤝 Contributing

  1. Fork the repo
  2. Create a branch (git checkout -b feature/amazing)
  3. Commit using Conventional Commits (git commit -m 'feat: add amazing feature')
  4. Push (git push origin feature/amazing)
  5. Open a Pull Request

📄 License

Apache 2.0 — see LICENSE.


⭐ Star on GitHub if you find it useful

Made with ❤️ by @markbus-ai

Metadata

Release files for whatsplay 2.7.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for whatsplay 2.7.0
File Size Uploaded Provenance Actions
whatsplay-2.7.0.tar.gz 92.3 kB Without provenance Details for whatsplay-2.7.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for whatsplay 2.7.0
File Interpreter ABI Platform Actions
whatsplay-2.7.0-py3-none-any.whl Python 3 none any Details for whatsplay-2.7.0-py3-none-any.whl

Total release size: 166.0 kB

Release files / whatsplay-2.7.0.tar.gz

Download URL whatsplay-2.7.0.tar.gz
Size 92.3 kB
Tags Source
SHA-256 checksum
How to use checksums
e866635eea934b45193882016d1aa84a663f7f811be3b6ba084a074338c18145
BLAKE2b-256 checksum
How to use checksums
073097f7daac2e476d524ff5c7321641b121f3de82578db0bfe111663fd5ce10
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.12

Release files / whatsplay-2.7.0-py3-none-any.whl

Download URL whatsplay-2.7.0-py3-none-any.whl
Size 73.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8ad073ab1622b7f2fb5301b7abe335b676464d942a90144ffb00fa46db828ab3
BLAKE2b-256 checksum
How to use checksums
dbf381dc4359b66c05d6d6b92601866ec652cbe4d0351ba3bfb0bfd0bcd4ffdc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.12

Security for whatsplay 2.7.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

2.7.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page