Metadata-Version: 2.4
Name: wwebjs-python-client
Version: 1.0.0
Summary: Python WhatsApp Web client powered by Playwright
Author: Poojan Anghan
License-Expression: MIT
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: playwright>=1.44.0
Requires-Dist: pyee>=11.0.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: httpx>=0.27.0
Requires-Dist: python-magic>=0.4.27
Requires-Dist: Pillow>=10.0.0
Requires-Dist: ffmpeg-python>=0.2.0
Requires-Dist: aiofiles>=23.0.0
Requires-Dist: qrcode>=7.4.2
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
Requires-Dist: black>=24.0.0; extra == "dev"
Requires-Dist: mypy>=1.9.0; extra == "dev"

# wwebjs-python-client 🚀

`wwebjs-python-client` (whatsapp-py) is a powerful, production-grade Python automation library for WhatsApp Web. Built on **Playwright**, it provides a stable, high-performance, and feature-rich API for building robust bots, notification services, and multi-tenant messaging platforms.

> [!CAUTION]
> **Legal Disclaimer:** This project is not affiliated, associated, authorized, endorsed by, or in any way officially connected with WhatsApp or any of its subsidiaries or its affiliates. The official WhatsApp website can be found at https://www.whatsapp.com. "WhatsApp" as well as related names, marks, emblems and images are registered trademarks of their respective owners.
> 
> **Risk of Account Ban:** Using automation tools on WhatsApp is against their Terms of Service. By using this library, you acknowledge the risk that your account may be temporarily or permanently banned. Always follow the [Best Practices](#-best-practices) section to minimize risks. Use this library at your own risk.

---

## 📑 Table of Contents
- [🏗 Getting Started](#-getting-started)
- [🔑 Authentication](#-authentication)
- [📩 Messaging Deep-Dive](#-messaging-deep-dive)
- [👥 Group Management](#-group-management)
- [📡 Event Reference](#-event-reference)
- [🏗 Class Structures](#-class-structures)
- [🛡 Best Practices](#-best-practices)
- [❓ Troubleshooting](#-troubleshooting)

---

## 🏗 Getting Started

### 1. Installation
Install the package and the required Playwright browser engine:

```bash
pip install wwebjs-python-client
python -m playwright install chromium
```

### 2. A Production-Ready Example
```python
import asyncio
from whatsapp import Client, LocalAuth

async def main():
    # Use LocalAuth to persist your session (no need to scan QR every time)
    client = Client(auth_strategy=LocalAuth(client_id="primary-bot"))

    @client.on('qr')
    async def on_qr(qr):
        print("QR Code Received! Scan it in your WhatsApp mobile app.")

    @client.on('ready')
    async def on_ready():
        print(f"Logged in as {client.info.pushname}!")

    @client.on('message')
    async def on_message(msg):
        if msg.body.lower() == "!ping":
            await msg.reply("pong 🏓")
        
        if msg.body.lower() == "!info":
            chat = await msg.get_chat()
            await msg.reply(f"Chat Name: {chat.name}\nType: {chat.is_group}")

    await client.initialize()

if __name__ == "__main__":
    asyncio.run(main())
```

---

## 🔑 Authentication
Authentication is handled via **Strategies**.

### LocalAuth (Recommended)
Stores session data (cookies, storage) in a local directory.
```python
from whatsapp import LocalAuth
client = Client(auth_strategy=LocalAuth(client_id="unique-id"))
```
*   **Location**: `.wwebjs_auth/session-<client_id>`
*   **Benefit**: Once you scan, the session is saved for next time.

### RemoteAuth
Allows you to store session data in a database or cloud storage (requires custom store implementation).

### NoAuth
Default strategy. Does not save any session data.

---

## 📩 Messaging Deep-Dive

### 1. Text & Reactions
```python
@client.on('message')
async def handle(msg):
    # Standard reply (quotes the original message)
    await msg.reply("Hello!")

    # Reaction (emoji)
    await msg.react("👍")
```

### 2. Sending Media
Supports images, videos, audio, and documents.
```python
from whatsapp import MessageMedia

# From a local file
media = MessageMedia.from_file("./docs/report.pdf")
await client.send_message("12345@c.us", media)

# From a URL
media_url = await MessageMedia.from_url("https://example.com/image.jpg")
await client.send_message(chat_id, media_url, options={"caption": "Look at this!"})
```

### 3. Interactive Polls
```python
from whatsapp import Poll

poll = Poll("What is your favorite language?", ["Python", "JavaScript", "Go"])
await client.send_message(chat_id, poll)

@client.on('vote_update')
async def on_vote(vote):
    print(f"{vote.voter} voted for {vote.selected_options}")
```

---

## 👥 Group Management
Manage groups with administrative precision.

```python
# Create a group
res = await client.create_group("Project Alpha", ["123@c.us", "456@c.us"])
group_id = res['gid']['_serialized']

# Manage existing group
group = await client.get_chat_by_id(group_id)
await group.set_description("Official project updates.")
await group.add_participants(["789@c.us"])
await group.promote_participants(["123@c.us"]) # Make admin
```

---

## 📡 Event Reference
The `Client` emits several events you can listen for:

| Event | Payload | Description |
| :--- | :--- | :--- |
| `qr` | `qr_string` | Emitted when a new QR code is generated. |
| `ready` | `None` | Emitted when the client is fully logged in. |
| `message` | `Message` | Emitted when a new message is received. |
| `message_create` | `Message` | Emitted when any message is created (including yours). |
| `message_ack` | `Message` | Emitted when a message status changes (Read/Delivered). |
| `group_join` | `Notification`| Emitted when a user joins a group. |
| `group_leave`| `Notification`| Emitted when a user leaves/is removed from a group. |
| `disconnected`| `Reason` | Emitted when the client is logged out. |

---

## 🏗 Class Structures

### `Message`
*   `body`: The text content.
*   `from_`: Sender ID.
*   `has_media`: Boolean.
*   `download_media()`: Download the attached media.
*   `get_chat()`: Get the `Chat` object.

### `Chat`
*   `name`: Chat display name.
*   `is_group`: Boolean.
*   `send_state_typing()`: Shows "typing..." in the app.
*   `fetch_messages(limit)`: Get chat history.

---

## 🛡 Best Practices

### Human-Like Automation
Avoid getting banned by mimicking human behavior:
1.  **Add Delays**: Never respond in milliseconds.
    ```python
    import random
    await asyncio.sleep(random.uniform(2, 5))
    ```
2.  **Typing States**: Show the typing indicator before sending.
    ```python
    chat = await msg.get_chat()
    await chat.send_state_typing()
    await asyncio.sleep(2)
    await msg.reply("Hi!")
    ```

### Resource Management
Always close the client properly when stopping your script:
```python
@client.on('disconnected')
async def on_disconnect(reason):
    await client.destroy()
```

---

## ❓ Troubleshooting

*   **Browser Crash**: Ensure you have run `python -m playwright install`.
*   **Auth Timeout**: If your internet is slow, increase `auth_timeout_ms` in the Client options.
*   **QR not showing**: If the console doesn't show the QR, ensure you have the `qrcode` library installed (`pip install qrcode`).

---

*Built with ❤️ for developers who love automation.*
