Python SDK
Official HueChat SDK for Python applications.
Installation
pip install huechat
# or
poetry add huechat
Requirements: Python 3.8+
Quick Start
import os
from huechat import Client
client = Client(api_key=os.environ['HUECHAT_API_KEY'])
# Create a contact
contact = client.contacts.create(
phone='+1234567890',
first_name='John',
last_name='Doe'
)
# Send a message
message = client.messages.send(contact.id, {
'channel': 'whatsapp',
'message_type': 'text',
'content': 'Hello from HueChat!'
})
print(f'Message sent: {message.id}')
Configuration
Basic Setup
from huechat import Client
client = Client(api_key='sk_live_your_key')
With Options
from huechat import Client
client = Client(
api_key=os.environ['HUECHAT_API_KEY'],
base_url='https://api.huechat.ai/v2', # Default
timeout=30, # Request timeout in seconds
max_retries=3,
debug=True
)
Async Client
from huechat import AsyncClient
async_client = AsyncClient(api_key=os.environ['HUECHAT_API_KEY'])
async def main():
contact = await async_client.contacts.create(
phone='+1234567890',
first_name='John'
)
Contacts
Create Contact
contact = client.contacts.create(
phone='+1234567890',
email='john@example.com',
first_name='John',
last_name='Doe',
preferred_channel='whatsapp',
metadata={
'customer_id': 'cust_123',
'plan': 'premium'
}
)
Get Contact
# By ID
contact = client.contacts.get('cnt_abc123')
# By phone
contact = client.contacts.get('+1234567890')
# By email
contact = client.contacts.get('john@example.com')
Update Contact
updated = client.contacts.update('cnt_abc123', {
'first_name': 'Johnny',
'metadata': {'plan': 'enterprise'}
})
Delete Contact
client.contacts.delete('cnt_abc123')
Get Contact Conversations
conversations = client.contacts.conversations(
'cnt_abc123',
status='open',
limit=20
)
for conv in conversations.data:
print(f'{conv.contact.full_name}: {conv.last_message_preview}')
Messages
Send Text Message
message = client.messages.send('cnt_abc123', {
'channel': 'whatsapp',
'message_type': 'text',
'content': 'Hello! How can I help you today?'
})
Send Template Message
message = client.messages.send('cnt_abc123', {
'channel': 'whatsapp',
'message_type': 'template',
'template_name': 'order_confirmation',
'template_parameters': {
'order_id': 'ORD-12345',
'total': '$99.99',
'delivery_date': 'January 27'
}
})
Send Media Message
# Image
message = client.messages.send('cnt_abc123', {
'channel': 'whatsapp',
'message_type': 'image',
'media_url': 'https://example.com/image.jpg',
'content': 'Check out this product!'
})
# Document
message = client.messages.send('cnt_abc123', {
'channel': 'whatsapp',
'message_type': 'document',
'media_url': 'https://example.com/invoice.pdf',
'content': 'Here is your invoice'
})
Conversations
List Conversations
conversations = client.conversations.list(
status='open',
channel='whatsapp',
limit=50
)
for conv in conversations.data:
print(f'{conv.contact.full_name}: {conv.last_message_preview}')
Get Conversation
conversation = client.conversations.get('conv_xyz789')
Get Messages
messages = client.conversations.messages(
'conv_xyz789',
limit=100,
sort='created_at:asc'
)
Send Message in Conversation
message = client.conversations.send_message('conv_xyz789', {
'message_type': 'text',
'content': 'Thanks for your patience!'
})
Assign Conversation
client.conversations.assign('conv_xyz789', {
'assigned_to': 'usr_agent1',
'internal_note': 'Please handle this VIP customer'
})
Add Labels
client.conversations.add_labels('conv_xyz789', ['urgent', 'billing'])
Resolve Conversation
client.conversations.resolve('conv_xyz789', {
'resolution_reason': 'issue_resolved',
'internal_note': 'Refund processed',
'send_satisfaction_survey': True
})
Webhooks
Create Webhook
webhook = client.webhooks.create({
'url': 'https://your-server.com/webhooks/huechat',
'events': ['message.received', 'conversation.created']
})
# Save the signing secret!
print(f'Signing secret: {webhook.signing_secret}')
Verify Signature
from huechat.webhook import verify_signature
is_valid = verify_signature(
payload=request.get_data(as_text=True),
signature=request.headers['X-HueChat-Signature'],
timestamp=request.headers['X-HueChat-Timestamp'],
secret=os.environ['HUECHAT_WEBHOOK_SECRET']
)
Error Handling
from huechat import Client
from huechat.exceptions import (
HueChatError,
BadRequestError,
UnauthorizedError,
NotFoundError,
RateLimitError
)
try:
contact = client.contacts.create(phone='invalid-phone')
except BadRequestError as e:
print(f'Validation error: {e.message}')
print(f'Details: {e.details}')
except UnauthorizedError:
print('Invalid API key')
except NotFoundError:
print('Resource not found')
except RateLimitError as e:
print(f'Rate limited, retry after: {e.retry_after}')
except HueChatError as e:
print(f'HueChat error: {e}')
Flask Integration
from flask import Flask, request, jsonify
from huechat import Client
from huechat.webhook import verify_signature
import os
app = Flask(__name__)
client = Client(api_key=os.environ['HUECHAT_API_KEY'])
@app.route('/webhooks/huechat', methods=['POST'])
def handle_webhook():
# Verify signature
if not verify_signature(
payload=request.get_data(as_text=True),
signature=request.headers.get('X-HueChat-Signature'),
timestamp=request.headers.get('X-HueChat-Timestamp'),
secret=os.environ['HUECHAT_WEBHOOK_SECRET']
):
return jsonify({'error': 'Invalid signature'}), 401
event = request.get_json()
if event['type'] == 'message.received':
print(f"New message: {event['data']['content']}")
return '', 200
Django Integration
# views.py
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from huechat import Client
from huechat.webhook import verify_signature
import json
import os
client = Client(api_key=os.environ['HUECHAT_API_KEY'])
@csrf_exempt
@require_POST
def webhook(request):
# Verify signature
if not verify_signature(
payload=request.body.decode('utf-8'),
signature=request.headers.get('X-HueChat-Signature'),
timestamp=request.headers.get('X-HueChat-Timestamp'),
secret=os.environ['HUECHAT_WEBHOOK_SECRET']
):
return JsonResponse({'error': 'Invalid signature'}, status=401)
event = json.loads(request.body)
if event['type'] == 'message.received':
# Handle new message
pass
return HttpResponse(status=200)
FastAPI Integration
from fastapi import FastAPI, Request, HTTPException
from huechat import AsyncClient
from huechat.webhook import verify_signature
import os
app = FastAPI()
client = AsyncClient(api_key=os.environ['HUECHAT_API_KEY'])
@app.post('/webhooks/huechat')
async def handle_webhook(request: Request):
body = await request.body()
if not verify_signature(
payload=body.decode('utf-8'),
signature=request.headers.get('X-HueChat-Signature'),
timestamp=request.headers.get('X-HueChat-Timestamp'),
secret=os.environ['HUECHAT_WEBHOOK_SECRET']
):
raise HTTPException(status_code=401, detail='Invalid signature')
event = await request.json()
if event['type'] == 'message.received':
await handle_new_message(event['data'])
return {'status': 'ok'}