Skip to main content

A professional Python library for WhatsApp-Evie integration with comprehensive messaging capabilities

Project description

WhatsApp-Evie Integration Library

Bitzer Logo

PyPI version Python versions License: MIT CI/CD codecov

A professional Python library that provides a generic interface to integrate WhatsApp messaging with Evie. This library enables bidirectional communication between WhatsApp and Evie, allowing for seamless message exchange.

Author

Alban Maxhuni, PhD

Features

  • Send messages from Evie to WhatsApp
  • Receive messages from WhatsApp to Evie
  • Support for multiple message types (text, image, audio, video, document)
  • Webhook server for receiving WhatsApp messages
  • Asynchronous message handling
  • Type-safe message models using Pydantic

Installation

pip install whatsapp-evie

Quick Start

from whatsapp_evie import WhatsAppEvieClient, Message, MessageType

# Initialize the client
client = WhatsAppEvieClient(
    api_key="your_whatsapp_api_key",
    webhook_url="your_webhook_url"
)

# Register a message handler
def handle_text_message(message):
    print(f"Received message: {message.content}")

client.register_message_handler(MessageType.TEXT, handle_text_message)

# Send a message
message = Message(
    message_id="123",
    type=MessageType.TEXT,
    content="Hello from Evie!",
    sender_id="evie",
    recipient_id="whatsapp_user",
    timestamp=time.time()
)

await client.send_message(message)

# Start the webhook server
client.start_webhook_server()

Configuration

The library can be configured using environment variables:

  • WHATSAPP_API_KEY: Your WhatsApp API key
  • WEBHOOK_URL: The URL where WhatsApp will send messages

Message Types

The library supports the following message types:

  • TEXT: Plain text messages
  • IMAGE: Image messages
  • AUDIO: Audio messages
  • VIDEO: Video messages
  • DOCUMENT: Document messages

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

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

๐Ÿš€ Features

Core Messaging

  • ๐Ÿ“ฑ Comprehensive Message Support: Text, images, audio, video, documents, locations, contacts, and interactive messages
  • ๐Ÿ”„ Bidirectional Communication: Send and receive messages seamlessly
  • ๐Ÿ“Š Message Status Tracking: Track message delivery and read status
  • ๐ŸŽฏ Bulk Messaging: Efficient bulk operations with progress tracking

Advanced Capabilities

  • ๐ŸŒ Webhook Server: Built-in webhook server with signature verification and health checks
  • โšก Rate Limiting: Intelligent rate limiting to respect WhatsApp API limits
  • ๐Ÿ”„ Retry Logic: Automatic retry with exponential backoff for failed requests
  • ๐Ÿ›ก๏ธ Error Handling: Comprehensive error handling with custom exceptions
  • ๐Ÿ“ Logging: Structured logging with configurable levels and outputs

Developer Experience

  • ๐Ÿ”’ Type Safety: Full type hints and Pydantic models for data validation
  • โšก Async/Await: Built for modern async Python applications
  • ๐Ÿ–ฅ๏ธ CLI Interface: Command-line interface for testing and automation
  • ๐Ÿ”ง Configuration Management: Flexible configuration via environment variables or config objects
  • ๐Ÿ“š Comprehensive Documentation: Detailed documentation with examples
  • ๐Ÿ›ก๏ธ Code Protection: Optional PyArmor obfuscation for commercial distributions

๐Ÿ“ฆ Installation

pip install whatsapp-evie

Development Installation

git clone https://github.com/evolvis-ai/whatsapp-evie.git
cd whatsapp-evie
pip install -e ".[dev]"

๐Ÿš€ Quick Start

Basic Usage

import asyncio
from whatsapp_evie import WhatsAppEvieClient, Message, MessageType

async def main():
    # Initialize the client
    async with WhatsAppEvieClient(
        api_key="your_whatsapp_api_key",
        phone_number_id="your_phone_number_id"
    ) as client:

        # Send a text message
        message = Message.create_text(
            content="Hello from WhatsApp-Evie! ๐Ÿš€",
            recipient_id="+1234567890"
        )

        success = await client.send_message(message)
        print(f"Message sent: {success}")

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

Webhook Server

import asyncio
from whatsapp_evie import WhatsAppEvieClient, Message, MessageType, ClientConfig

async def main():
    # Load configuration from environment
    config = ClientConfig.from_env()

    async with WhatsAppEvieClient(config=config) as client:

        # Register message handlers
        async def handle_text_message(message: Message):
            print(f"Received: {message.content} from {message.sender_id}")

            # Echo the message back
            response = Message.create_text(
                content=f"Echo: {message.content}",
                recipient_id=message.sender_id
            )
            await client.send_message(response)

        client.register_message_handler(MessageType.TEXT, handle_text_message)

        # Start webhook server
        await client.start_webhook_server()

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

๐Ÿ”ง Configuration

Environment Variables

Create a .env file or set environment variables:

# Required
WHATSAPP_API_KEY=your_whatsapp_api_key
WHATSAPP_PHONE_NUMBER_ID=your_phone_number_id

# Optional
WHATSAPP_API_VERSION=v17.0
WHATSAPP_TIMEOUT=30
WHATSAPP_MAX_RETRIES=3

# Webhook configuration
WEBHOOK_URL=https://your-domain.com/webhook
WEBHOOK_HOST=0.0.0.0
WEBHOOK_PORT=8000
WEBHOOK_VERIFY_TOKEN=your_verify_token

# Logging
LOG_LEVEL=INFO
LOG_FILE_PATH=/var/log/whatsapp-evie.log

Configuration Object

from whatsapp_evie import ClientConfig, WhatsAppConfig, WebhookConfig

config = ClientConfig(
    whatsapp=WhatsAppConfig(
        api_key="your_api_key",
        phone_number_id="your_phone_id",
        timeout=30,
        max_retries=3
    ),
    webhook=WebhookConfig(
        host="0.0.0.0",
        port=8000,
        verify_signature=True,
        verify_token="your_verify_token"
    ),
    debug=True
)

client = WhatsAppEvieClient(config=config)

๐Ÿ“ฑ Message Types

Text Messages

message = Message.create_text(
    content="Hello, World! ๐Ÿ‘‹",
    recipient_id="+1234567890"
)

Media Messages

# Image
image_message = Message.create_media(
    media_type=MessageType.IMAGE,
    url="https://example.com/image.jpg",
    recipient_id="+1234567890",
    caption="Check out this image!"
)

# Document
doc_message = Message.create_media(
    media_type=MessageType.DOCUMENT,
    url="https://example.com/document.pdf",
    recipient_id="+1234567890",
    caption="Important document"
)

Location Messages

location_message = Message.create_location(
    latitude=37.7749,
    longitude=-122.4194,
    recipient_id="+1234567890",
    name="San Francisco",
    address="San Francisco, CA, USA"
)

Contact Messages

contact_message = Message.create_contact(
    name="John Doe",
    recipient_id="+1234567890",
    phone="+1987654321",
    email="john@example.com"
)

๐Ÿ”„ Advanced Features

Bulk Messaging

messages = [
    Message.create_text("Hello User 1", "+1234567890"),
    Message.create_text("Hello User 2", "+0987654321"),
    Message.create_text("Hello User 3", "+1122334455")
]

results = await client.send_bulk_messages(messages)
print(f"Sent {sum(results.values())} out of {len(messages)} messages")

Message Handlers

# Type-specific handlers
async def handle_text(message: Message):
    print(f"Text: {message.content}")

async def handle_image(message: Message):
    print(f"Image received from {message.sender_id}")
    if message.media_info:
        await client.download_media(
            message.media_info.media_id,
            f"/tmp/image_{message.message_id}.jpg"
        )

# Global handler for all messages
async def handle_all_messages(message: Message):
    print(f"Received {message.type} message")

client.register_message_handler(MessageType.TEXT, handle_text)
client.register_message_handler(MessageType.IMAGE, handle_image)
client.register_global_handler(handle_all_messages)

Error Handling

from whatsapp_evie.exceptions import RateLimitError, AuthenticationError

async def handle_errors(error: Exception, message: Message = None):
    if isinstance(error, RateLimitError):
        print(f"Rate limited. Retry after {error.retry_after} seconds")
    elif isinstance(error, AuthenticationError):
        print("Authentication failed. Check your API key")
    else:
        print(f"Unexpected error: {error}")

client.register_error_handler(handle_errors)

๐Ÿ–ฅ๏ธ CLI Usage

The library includes a command-line interface for testing and automation:

# Start webhook server
whatsapp-evie webhook --host 0.0.0.0 --port 8000

# Send a text message
whatsapp-evie send-message --to +1234567890 --text "Hello from CLI!"

# Send an image
whatsapp-evie send-message --to +1234567890 --image https://example.com/image.jpg

# Validate configuration
whatsapp-evie validate-config

# Test webhook endpoint
whatsapp-evie test-webhook --url https://your-domain.com/webhook

๐Ÿ›ก๏ธ Code Protection (Optional)

For commercial distributions, you can create obfuscated versions using PyArmor:

# Install PyArmor
pip install pyarmor

# Create obfuscated package
python scripts/build_obfuscated.py --all

# Build and publish obfuscated version
python scripts/build_and_publish.py --release-obfuscated

The obfuscated version provides:

  • Source code protection - Makes reverse engineering significantly harder
  • String obfuscation - Encrypts sensitive strings and constants
  • Runtime protection - Anti-debug and anti-tampering mechanisms
  • License control - Optional usage restrictions and expiration dates

See Obfuscation Guide for detailed instructions.


## ๐Ÿ“š Examples

Check out the [examples](examples/) directory for more comprehensive examples:

- [Basic Usage](examples/basic_usage.py) - Simple send/receive operations
- [Webhook Server](examples/webhook_server.py) - Complete chatbot implementation
- [Bulk Messaging](examples/bulk_messaging.py) - Bulk operations and CSV processing

## ๐Ÿงช Testing

Run the test suite:

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

# Run tests
pytest

# Run tests with coverage
pytest --cov=whatsapp_evie --cov-report=html

# Run specific test categories
pytest -m "not slow"  # Skip slow tests
pytest tests/test_client.py  # Run specific test file

๐Ÿ”ง Development

Setup Development Environment

# Clone the repository
git clone https://github.com/evolvis-ai/whatsapp-evie.git
cd whatsapp-evie

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

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

# Install pre-commit hooks
pre-commit install

Code Quality

The project uses several tools to maintain code quality:

  • Black: Code formatting
  • isort: Import sorting
  • flake8: Linting
  • mypy: Type checking
  • pytest: Testing
  • pre-commit: Git hooks
# Format code
black whatsapp_evie tests examples

# Sort imports
isort whatsapp_evie tests examples

# Lint code
flake8 whatsapp_evie

# Type checking
mypy whatsapp_evie

# Run all checks
pre-commit run --all-files

๐Ÿ“– Documentation

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guidelines for details.

Quick Contribution Guide

  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 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.

๐Ÿ™ Acknowledgments

  • WhatsApp Business API for providing the messaging platform
  • The Python community for excellent libraries and tools
  • All contributors who help improve this library

๐Ÿ“ž Support

๐Ÿ—บ๏ธ Roadmap

  • Support for WhatsApp Business API v18.0
  • Message templates support
  • Advanced interactive messages (buttons, lists)
  • Message scheduling
  • Analytics and reporting
  • Multi-account support
  • Plugin system for custom message processors

Made with โค๏ธ by Evolvis AI


whatsapp-evie/ โ”œโ”€โ”€ whatsapp_evie/ # Main package โ”‚ โ”œโ”€โ”€ init.py # Public API exports โ”‚ โ”œโ”€โ”€ client.py # Enhanced client with all features โ”‚ โ”œโ”€โ”€ models.py # Comprehensive data models โ”‚ โ”œโ”€โ”€ config.py # Configuration management โ”‚ โ”œโ”€โ”€ exceptions.py # Custom exceptions โ”‚ โ”œโ”€โ”€ utils.py # Utility functions โ”‚ โ”œโ”€โ”€ logging_utils.py # Logging utilities โ”‚ โ””โ”€โ”€ cli.py # Command-line interface โ”œโ”€โ”€ tests/ # Comprehensive test suite โ”‚ โ”œโ”€โ”€ conftest.py # Test configuration โ”‚ โ”œโ”€โ”€ test_client.py # Client tests โ”‚ โ”œโ”€โ”€ test_models.py # Model tests โ”‚ โ”œโ”€โ”€ test_config.py # Configuration tests โ”‚ โ””โ”€โ”€ test_utils.py # Utility tests โ”œโ”€โ”€ examples/ # Practical examples โ”‚ โ”œโ”€โ”€ basic_usage.py # Basic operations โ”‚ โ”œโ”€โ”€ webhook_server.py # Chatbot implementation โ”‚ โ””โ”€โ”€ bulk_messaging.py # Bulk operations โ”œโ”€โ”€ docs/ # Documentation โ”œโ”€โ”€ .github/workflows/ # CI/CD pipeline โ”œโ”€โ”€ scripts/ # Build and publish scripts โ”œโ”€โ”€ pyproject.toml # Modern Python packaging โ”œโ”€โ”€ setup.py # Package setup โ”œโ”€โ”€ requirements.txt # Dependencies โ”œโ”€โ”€ dev-requirements.txt # Development dependencies โ”œโ”€โ”€ CHANGELOG.md # Version history โ”œโ”€โ”€ CONTRIBUTING.md # Contribution guidelines โ””โ”€โ”€ README.md # Comprehensive documentation

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

whatsapp_evie-1.0.0.tar.gz (54.8 kB view details)

Uploaded Source

Built Distribution

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

whatsapp_evie-1.0.0-py3-none-any.whl (35.9 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: whatsapp_evie-1.0.0.tar.gz
  • Upload date:
  • Size: 54.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.9

File hashes

Hashes for whatsapp_evie-1.0.0.tar.gz
Algorithm Hash digest
SHA256 7ee1223ad924556fec507ac1bbc542788b46b3b93c3335590cc84a7c48efdee9
MD5 a0200a82992c3eb06c7ef1cbec92999a
BLAKE2b-256 463c0f780b03c4c95ef729de6fb796ad567b4c925bea268d3763560d507b33d6

See more details on using hashes here.

File details

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

File metadata

  • Download URL: whatsapp_evie-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 35.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.9

File hashes

Hashes for whatsapp_evie-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 7f884d1f80634a106e0ff212b150bbff0713503a561b5ef64a9a373b4f4673d9
MD5 a070a0d9645bacd158c51766c713aaab
BLAKE2b-256 5f9b4a3040382ec9d3d1edd7a949e22c489a753d35220ac2b19a19106b2ce5d5

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