Skip to main content

Python SDK for SDKWA WhatsApp HTTP API

Project description

SDKWA WhatsApp API Client - Python SDK

PyPI version Python License: MIT

Python SDK for the SDKWA WhatsApp HTTP API. Send messages, files, and manage WhatsApp accounts programmatically.

Features

  • 🚀 Simple & Modern: Clean, type-safe API following Python best practices
  • 📱 Full API Coverage: Support for all SDKWA WhatsApp API endpoints
  • 🔒 Type Safe: Complete type hints for better development experience
  • 🪝 Webhook Support: Built-in webhook handling for real-time notifications
  • 📁 File Handling: Send files by URL or upload with automatic type detection
  • 🔄 Async Support: Optional async/await support for better performance
  • 📦 Zero Config: Works out of the box with minimal setup

Installation

pip install sdkwa-whatsapp-api-client

Quick Start

from sdkwa import SDKWA

# Initialize the client
client = SDKWA(
    id_instance="YOUR_INSTANCE_ID",
    api_token_instance="YOUR_API_TOKEN"
)

# Send a text message
response = client.send_message(
    chat_id="1234567890@c.us",
    message="Hello from SDKWA! 👋"
)
print(f"Message sent with ID: {response['idMessage']}")

# Send a file
response = client.send_file_by_url(
    chat_id="1234567890@c.us",
    url_file="https://example.com/image.jpg",
    file_name="image.jpg",
    caption="Check out this image!"
)

# Get account state
state = client.get_state_instance()
print(f"Account state: {state['stateInstance']}")

API Reference

Account Management

# Get account settings
settings = client.get_settings()

# Update settings
client.set_settings({
    "webhook_url": "https://your-webhook-url.com",
    "delay_send_messages_milliseconds": 1000
})

# Get QR code for authorization
qr_data = client.get_qr()

# Get account state
state = client.get_state_instance()
print(f"Account state: {state['stateInstance']}")

# Reboot instance
client.reboot()

# Logout
client.logout()

Sending Messages

# Text message
client.send_message(
    chat_id="1234567890@c.us",
    message="Hello World!",
    quoted_message_id="optional_message_id",  # Reply to message
    link_preview=True  # Enable link previews
)

# Send contact
client.send_contact(
    chat_id="1234567890@c.us",
    contact={
        "phone_contact": 1234567890,
        "first_name": "John",
        "last_name": "Doe",
        "company": "Example Corp"
    }
)

# Send location
client.send_location(
    chat_id="1234567890@c.us",
    name_location="My Location",
    address="123 Main St",
    latitude=40.7128,
    longitude=-74.0060
)

File Operations

# Send file by URL
client.send_file_by_url(
    chat_id="1234567890@c.us",
    url_file="https://example.com/document.pdf",
    file_name="document.pdf",
    caption="Important document"
)

# Upload and send file
with open("image.jpg", "rb") as file:
    client.send_file_by_upload(
        chat_id="1234567890@c.us",
        file=file,
        file_name="image.jpg",
        caption="Photo from vacation"
    )

# Download received file
file_data = client.download_file(
    chat_id="1234567890@c.us",
    id_message="MESSAGE_ID"
)

Receiving Messages

# Get notifications
notification = client.receive_notification()
if notification:
    print(f"New notification: {notification}")
    # Process notification...
    
    # Delete notification after processing
    client.delete_notification(notification['receiptId'])

# Get chat history
history = client.get_chat_history(
    chat_id="1234567890@c.us",
    count=50
)

Groups and Contacts

# Create group
group = client.create_group(
    group_name="My Group",
    chat_ids=["1234567890@c.us", "0987654321@c.us"]
)

# Get group data
group_info = client.get_group_data("GROUP_ID@g.us")

# Add participants to group
client.add_group_participant(
    group_id="GROUP_ID@g.us",
    participant_chat_id="1111111111@c.us"
)

# Remove participant from group
client.remove_group_participant(
    group_id="GROUP_ID@g.us",
    participant_chat_id="1111111111@c.us"
)

# Set group admin
client.set_group_admin(
    group_id="GROUP_ID@g.us",
    participant_chat_id="1111111111@c.us"
)

# Remove admin rights
client.remove_admin(
    group_id="GROUP_ID@g.us",
    participant_chat_id="1111111111@c.us"
)

# Update group name
client.update_group_name(
    group_id="GROUP_ID@g.us",
    group_name="New Group Name"
)

# Set group picture
with open("group_pic.jpg", "rb") as file:
    client.set_group_picture("GROUP_ID@g.us", file)

# Leave group
client.leave_group("GROUP_ID@g.us")

# Get contacts
contacts = client.get_contacts()

# Get chats
chats = client.get_chats()

# Get contact info
contact_info = client.get_contact_info("1234567890@c.us")

# Check if number has WhatsApp
has_whatsapp = client.check_whatsapp(1234567890)

# Get avatar
avatar = client.get_avatar("1234567890@c.us")

# Set profile picture
with open("profile_pic.jpg", "rb") as file:
    client.set_profile_picture(file)

Chat Management

# Mark chat as read
client.read_chat("1234567890@c.us")

# Mark specific message as read
client.read_chat("1234567890@c.us", id_message="MESSAGE_ID")

# Archive chat
client.archive_chat("1234567890@c.us")

# Unarchive chat
client.unarchive_chat("1234567890@c.us")

# Delete message
client.delete_message("1234567890@c.us", "MESSAGE_ID")

Queue Management

# Show messages in queue
queue = client.show_messages_queue()

# Clear messages queue
client.clear_messages_queue()

Message History

# Get last outgoing messages (last 24 hours by default)
outgoing = client.last_outgoing_messages()

# Get last outgoing messages from last 60 minutes
outgoing = client.last_outgoing_messages(minutes=60)

# Get last incoming messages
incoming = client.last_incoming_messages()

Webhook Handling

from flask import Flask, request
from sdkwa import WebhookHandler, WebhookType

app = Flask(__name__)
webhook_handler = WebhookHandler()

# Register event handlers
@webhook_handler.on(WebhookType.INCOMING_MESSAGE_RECEIVED)
def handle_message(notification):
    """Handle incoming message notifications."""
    sender_data = notification.get('senderData', {})
    message_data = notification.get('messageData', {})
    
    sender = sender_data.get('chatId', 'Unknown')
    sender_name = sender_data.get('senderName', 'Unknown')
    message_type = message_data.get('typeMessage', 'unknown')
    
    print(f"📥 Incoming message from {sender_name} ({sender})")
    
    if message_type == 'textMessage':
        text = message_data.get('textMessageData', {}).get('textMessage', '')
        print(f"Message: {text}")

@webhook_handler.on(WebhookType.OUTGOING_MESSAGE_STATUS)
def handle_status(notification):
    """Handle outgoing message status notifications."""
    status = notification.get('status', 'unknown')
    id_message = notification.get('idMessage', '')
    print(f"📤 Message {id_message} status: {status}")

@app.route('/webhook', methods=['POST'])
def webhook():
    webhook_handler.handle(request.json)
    return "OK"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

Configuration

Environment Variables

export SDKWA_ID_INSTANCE="your_instance_id"
export SDKWA_API_TOKEN="your_api_token"
export SDKWA_API_HOST="https://api.sdkwa.pro"  # Optional

Constructor Options

client = SDKWA(
    id_instance="your_instance_id",
    api_token_instance="your_api_token",
    api_host="https://api.sdkwa.pro",  # Optional, defaults to official API
    user_id="your_user_id",  # Optional, for additional authentication
    user_token="your_user_token",  # Optional, for additional authentication
    timeout=30,  # Request timeout in seconds
    verify_ssl=True  # SSL verification
)

Error Handling

from sdkwa import APIError, AuthenticationError, ValidationError

try:
    response = client.send_message(
        chat_id="invalid_chat_id",
        message="Test message"
    )
except AuthenticationError:
    print("Invalid credentials")
except ValidationError as e:
    print(f"Validation error: {e}")
except APIError as e:
    print(f"API error: {e}")

Development

Setting up development environment

# Clone the repository
git clone https://github.com/sdkwa/whatsapp-api-client-python.git
cd whatsapp-api-client-python

# Install in development mode
pip install -e .

# Format code
python scripts/dev.py format

# Clean build artifacts
python scripts/dev.py clean

# Build package
python scripts/dev.py build

# Publish to PyPI (requires API token)
python scripts/dev.py publish

Contributing

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

License

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

Support

Changelog

v1.0.0

  • Initial release
  • Full API coverage for SDKWA WhatsApp API
  • Type-safe implementation
  • Webhook support
  • Comprehensive documentation and examples

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

sdkwa_whatsapp_api_client-1.0.1.tar.gz (21.5 kB view details)

Uploaded Source

Built Distribution

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

sdkwa_whatsapp_api_client-1.0.1-py3-none-any.whl (13.6 kB view details)

Uploaded Python 3

File details

Details for the file sdkwa_whatsapp_api_client-1.0.1.tar.gz.

File metadata

File hashes

Hashes for sdkwa_whatsapp_api_client-1.0.1.tar.gz
Algorithm Hash digest
SHA256 8122dd06f8cc6ab0b7d08579b73c880bf9f4a291020fb442c802d0ed2ed22d58
MD5 d2a9b7e42e026dea993ee4bbfc21dc16
BLAKE2b-256 ba6187538044a9308eddae774bc7884f87951c6ad7e77bfa0dea988610508479

See more details on using hashes here.

File details

Details for the file sdkwa_whatsapp_api_client-1.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for sdkwa_whatsapp_api_client-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 f371ef65f7558f1fbcfb6af818439716c8eca06d97312db2d276f705ebdb019a
MD5 63ab56ee565722e43692a48510452d07
BLAKE2b-256 1226db1da6eeffb8f6b47abf4349da3eb6c17c8c91597981ced5a174038bd3a0

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