A professional Python library for WhatsApp-Evie integration with comprehensive messaging capabilities
Project description
WhatsApp-Evie Integration Library
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
- Email: a.maxhuni@evolvis.ai
- Website: https://evolvis.ai
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 keyWEBHOOK_URL: The URL where WhatsApp will send messages
Message Types
The library supports the following message types:
TEXT: Plain text messagesIMAGE: Image messagesAUDIO: Audio messagesVIDEO: Video messagesDOCUMENT: 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
- API Reference: Full API documentation
- Examples: Practical examples
- Configuration: Configuration guide
- Contributing: Contributing guidelines
๐ค Contributing
We welcome contributions! Please see our Contributing Guidelines for details.
Quick Contribution Guide
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Add tests for your changes
- Ensure all tests pass (
pytest) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - 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
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Email: contact@evolvis.ai
๐บ๏ธ 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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7ee1223ad924556fec507ac1bbc542788b46b3b93c3335590cc84a7c48efdee9
|
|
| MD5 |
a0200a82992c3eb06c7ef1cbec92999a
|
|
| BLAKE2b-256 |
463c0f780b03c4c95ef729de6fb796ad567b4c925bea268d3763560d507b33d6
|
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7f884d1f80634a106e0ff212b150bbff0713503a561b5ef64a9a373b4f4673d9
|
|
| MD5 |
a070a0d9645bacd158c51766c713aaab
|
|
| BLAKE2b-256 |
5f9b4a3040382ec9d3d1edd7a949e22c489a753d35220ac2b19a19106b2ce5d5
|