Skip to main content

Python package for WAHA (WhatsApp HTTP API)

Project description

WAHA - Python

PyPI version Python versions License: MIT Tests

A comprehensive Python package for the WAHA (WhatsApp HTTP API) service. This package provides a clean, type-safe, and easy-to-use interface for interacting with WhatsApp through the WAHA API.

๐ŸŒŸ Features

  • ๐Ÿ”„ Full API Coverage: Complete implementation of all WAHA API endpoints
  • โšก Async & Sync Support: Both synchronous and asynchronous operation modes
  • ๐Ÿ›ก๏ธ Type Safety: Full typing with Pydantic models for request/response validation
  • ๐ŸŽฏ Organized Namespaces: Intuitive organization by functionality (auth, sessions, messages, etc.)
  • ๐Ÿ“ Rich Documentation: Comprehensive docstrings and examples
  • ๐Ÿงช Well Tested: Extensive test coverage with pytest
  • ๐Ÿ Modern Python: Support for Python 3.8+ with modern async/await patterns

๐Ÿš€ Quick Start

Installation

pip install waha

Basic Usage

from waha import WahaClient

# Initialize the client
client = WahaClient(
    base_url="http://localhost:3000",
    api_key="your-api-key"  # Optional, can use WAHA_API_KEY env var
)

# Start a session
session = client.sessions.start("default")

# Send a text message
message = client.messages.send_text(
    session="default",
    chat_id="1234567890@c.us",
    text="Hello from WAHA! ๐Ÿ‘‹"
)

print(f"Message sent: {message.id}")

Async Usage

import asyncio
from waha import AsyncWahaClient

async def main():
    async with AsyncWahaClient(
        base_url="http://localhost:3000",
        api_key="your-api-key"
    ) as client:
        # Start a session
        session = await client.sessions.start("default")
        
        # Send a message
        message = await client.messages.send_text(
            session="default",
            chat_id="1234567890@c.us",
            text="Hello from async WAHA! ๐Ÿš€"
        )
        
        print(f"Message sent: {message.id}")

asyncio.run(main())

๐Ÿ“š Documentation

Core Components

The SDK is organized into several namespaces, each handling a specific area of functionality:

๐Ÿ”‘ Authentication (client.auth)

Handle QR code authentication and phone verification:

# Get QR code for authentication
qr_code = client.auth.get_qr_code("default", format="raw")
print(f"QR Code: {qr_code.qr}")

# Request authentication code
client.auth.request_code("default", phone_number="+1234567890")

๐Ÿ–ฅ๏ธ Sessions (client.sessions)

Manage WhatsApp sessions:

# Create and start a session
session = client.sessions.create("my-session", start=True)

# List all sessions
sessions = client.sessions.list()

# Get session info
info = client.sessions.get("default")

# Stop a session
client.sessions.stop("default")

# Get authenticated account info
me = client.sessions.get_me("default")
print(f"Logged in as: {me.pushName} ({me.id})")

๐Ÿ“ค Messages (client.messages)

Send various types of messages:

# Send text message
client.messages.send_text(
    chat_id="1234567890@c.us",
    text="Hello! ๐Ÿ‘‹",
    reply_to="message_id_to_reply_to"  # Optional
)

# Send image
client.messages.send_image(
    chat_id="1234567890@c.us",
    file="https://example.com/image.jpg",
    caption="Check this out!"
)

# Send document
client.messages.send_file(
    chat_id="1234567890@c.us",
    file="https://example.com/document.pdf",
    caption="Important document"
)

# Send location
client.messages.send_location(
    chat_id="1234567890@c.us",
    latitude=40.7128,
    longitude=-74.0060,
    title="New York City"
)

# Send contact
from waha.types import ContactVcard

contact = ContactVcard(
    fullName="John Doe",
    phoneNumber="+1234567890",
    email="john@example.com"
)
client.messages.send_contact_vcard(
    chat_id="1234567890@c.us",
    contacts=[contact]
)

# Send poll
client.messages.send_poll(
    chat_id="1234567890@c.us",
    poll_text="What's your favorite color?",
    options=["Red", "Green", "Blue", "Yellow"]
)

# Send buttons
buttons = [
    {"id": "btn1", "title": "Option 1"},
    {"id": "btn2", "title": "Option 2"},
]
client.messages.send_buttons(
    chat_id="1234567890@c.us",
    text="Choose an option:",
    buttons=buttons
)

# React to a message
client.messages.react(
    message_id="some_message_id",
    reaction="๐Ÿ‘"
)

# Forward a message
client.messages.forward_message(
    message_id="source_message_id",
    chat_id="target_chat_id"
)

๐Ÿ’ฌ Chats (client.chats)

Manage chats and retrieve messages:

# List chats
chats = client.chats.list(limit=50)

# Get messages from a chat
messages = client.chats.get_messages(
    chat_id="1234567890@c.us",
    limit=100
)

๐Ÿ‘ค Contacts (client.contacts)

Manage contacts:

# Check if a number exists on WhatsApp
result = client.contacts.check_exists("+1234567890")
if result.numberExists:
    print(f"Number exists! Chat ID: {result.chatId}")

๐Ÿ†” Profile (client.profile)

Manage your WhatsApp profile:

# Get profile info
profile = client.profile.get()
print(f"Name: {profile.name}, Status: {profile.status}")

# Update profile name
client.profile.set_name("New Name")

# Update profile status
client.profile.set_status("Available")

# Set profile picture
client.profile.set_picture("https://example.com/avatar.jpg")

๐Ÿ‘ฅ Groups (client.groups)

Manage WhatsApp groups:

# Create a group
group = client.groups.create(
    name="My Group",
    participants=["1234567890@c.us", "0987654321@c.us"]
)

# Add participants
client.groups.add_participants(
    group_id="group_id@g.us",
    participants=["newuser@c.us"]
)

๐Ÿ”ง Configuration

Environment Variables

You can configure the SDK using environment variables:

export WAHA_URL="http://localhost:3000"
export WAHA_API_KEY="your-api-key"

Client Configuration

client = WahaClient(
    base_url="http://localhost:3000",
    api_key="your-api-key",
    timeout=30.0,  # Request timeout in seconds
    headers={"Custom-Header": "value"}  # Additional headers
)

๐Ÿ“ File Handling

The SDK supports multiple ways to handle files:

Using URLs

client.messages.send_image(
    chat_id="1234567890@c.us",
    file="https://example.com/image.jpg"
)

Using Base64

from waha.types import Base64File

file = Base64File(
    mimetype="image/jpeg",
    filename="image.jpg",
    data="base64_encoded_data_here"
)

client.messages.send_image(
    chat_id="1234567890@c.us",
    file=file
)

Using URLFile Objects

from waha.types import URLFile

file = URLFile(
    url="https://example.com/image.jpg",
    filename="custom_name.jpg"
)

client.messages.send_image(
    chat_id="1234567890@c.us",
    file=file
)

๐Ÿšจ Error Handling

The SDK provides specific exception types for different error scenarios:

from waha.exceptions import (
    WahaException,
    WahaAPIError,
    WahaTimeoutError,
    WahaAuthenticationError,
    WahaSessionError
)

try:
    message = client.messages.send_text(
        chat_id="invalid_chat_id",
        text="Hello"
    )
except WahaAuthenticationError:
    print("Authentication failed - check your API key")
except WahaAPIError as e:
    print(f"API error: {e.message} (Status: {e.status_code})")
except WahaTimeoutError:
    print("Request timed out")
except WahaException as e:
    print(f"General WAHA error: {e}")

๐Ÿงช Testing

Run the test suite:

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run tests with coverage
pytest --cov=waha_sdk

# Run specific test file
pytest tests/test_client.py

๐Ÿ”„ Development

Setting up for development:

# Clone the repository
git clone https://github.com/devlikeapro/waha-python.git
cd waha-python

# Install in development mode
pip install -e ".[dev]"

# Install pre-commit hooks
pre-commit install

# Run tests
pytest

# Format code
black waha tests examples

# Type checking
mypy waha

Project Structure

waha-python/
โ”œโ”€โ”€ waha/
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ client.py              # Main client classes
โ”‚   โ”œโ”€โ”€ exceptions.py          # Custom exceptions
โ”‚   โ”œโ”€โ”€ types.py              # Pydantic models
โ”‚   โ”œโ”€โ”€ http_client.py        # HTTP client implementation
โ”‚   โ””โ”€โ”€ namespaces/           # API namespaces
โ”‚       โ”œโ”€โ”€ auth.py
โ”‚       โ”œโ”€โ”€ sessions.py
โ”‚       โ”œโ”€โ”€ messages.py
โ”‚       โ””โ”€โ”€ ...
โ”œโ”€โ”€ tests/                    # Test suite
โ”œโ”€โ”€ examples/                 # Usage examples
โ”œโ”€โ”€ pyproject.toml           # Package configuration
โ””โ”€โ”€ README.md

๐Ÿ“‹ Requirements

  • Python 3.8+
  • httpx >= 0.24.0
  • pydantic >= 2.0.0

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Add tests for your changes
  5. Ensure all tests pass (pytest)
  6. Commit your changes (git commit -m 'Add some amazing feature')
  7. Push to the branch (git push origin feature/amazing-feature)
  8. Open a Pull Request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ”— Links

๐Ÿ†˜ Support

If you encounter any issues or have questions:

  1. Check the documentation
  2. Search existing issues
  3. Create a new issue with detailed information about your problem

๐ŸŽฏ Roadmap

  • Add webhook handling utilities
  • Implement retry logic with exponential backoff
  • Add rate limiting support
  • Create CLI tool for common operations
  • Add more comprehensive examples
  • Support for WhatsApp Business API features

๐Ÿ™ Acknowledgments

  • Thanks to the WAHA project for providing the WhatsApp HTTP API
  • Built with httpx for HTTP client functionality
  • Uses Pydantic for data validation and serialization

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

waha-1.0.0.tar.gz (27.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

waha-1.0.0-py3-none-any.whl (26.0 kB view details)

Uploaded Python 3

File details

Details for the file waha-1.0.0.tar.gz.

File metadata

  • Download URL: waha-1.0.0.tar.gz
  • Upload date:
  • Size: 27.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for waha-1.0.0.tar.gz
Algorithm Hash digest
SHA256 5d4bffa43a2dc5d2b26359d382dfa3796965963eb2e082b6f8faa9744b946b48
MD5 65309622d9215b8837f5c853983e228e
BLAKE2b-256 ae29591e155794dffe8ae84fff555509a82033fa5653b54e5fd3f6815a4cdc99

See more details on using hashes here.

File details

Details for the file waha-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: waha-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 26.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for waha-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 37762f8b4f0766c08eaf83da55937f28b77dafc4327ed44e4b2c83c9eede5f35
MD5 1f322a2dfb958c8a8c79133080fb1ec5
BLAKE2b-256 e76d849afbbde4e006a7c7e6cab3d140879636d2110130546b96d71c80f42b51

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page