Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,23 @@ repos:
hooks:
- id: black
language_version: python3
args: [--line-length=88]
args: [--line-length=120]

- repo: https://github.com/pycqa/isort
rev: 5.12.0
hooks:
- id: isort
args: [--profile=black, --line-length=88]
args: [--profile=black, --line-length=120]

- repo: https://github.com/pycqa/flake8
rev: 6.0.0
hooks:
- id: flake8
args: [--max-line-length=88, --extend-ignore=E203,W503]
args: ["--max-line-length=120", "--extend-ignore=E203,W503"]

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.3.0
hooks:
- id: mypy
additional_dependencies: [pydantic, requests, types-requests]
args: [--ignore-missing-imports]
# - repo: https://github.com/pre-commit/mirrors-mypy
# rev: v1.3.0
# hooks:
# - id: mypy
# additional_dependencies: [pydantic, requests, types-requests]
# args: [--ignore-missing-imports, --python-version=3.9]
161 changes: 161 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
# Devo Global Communications SDK - Examples

This directory contains comprehensive examples for using the Devo Global Communications SDK. Each resource has its own dedicated example file with detailed demonstrations of the available functionality.

## 📁 Example Files

### 🚀 Overview
- **`basic_usage.py`** - Interactive overview and launcher for all examples

### 📱 Communication Resources
- **`sms_example.py`** - ✅ **Complete SMS API implementation**
- Send SMS messages via quick-send API
- Get available senders
- Search and purchase phone numbers
- Legacy compatibility methods

- **`email_example.py`** - 🚧 **Placeholder** (Email functionality)
- **`whatsapp_example.py`** - 🚧 **Placeholder** (WhatsApp functionality)
- **`rcs_example.py`** - 🚧 **Placeholder** (RCS functionality)

### 👥 Management Resources
- **`contacts_example.py`** - 🚧 **Placeholder** (Contact management)

## 🚀 Getting Started

### Prerequisites
1. **API Key**: Get your API key from the Devo dashboard
2. **Environment**: Set the `DEVO_API_KEY` environment variable
```bash
# Windows (PowerShell)
$env:DEVO_API_KEY = "your_api_key_here"

# Windows (Command Prompt)
set DEVO_API_KEY=your_api_key_here

# Unix/Linux/macOS
export DEVO_API_KEY=your_api_key_here
```

### Running Examples

#### Option 1: Interactive Overview (Recommended)
```bash
python examples/basic_usage.py
```
This provides an interactive menu to choose and run specific examples.

#### Option 2: Run Individual Examples
```bash
# SMS functionality (fully implemented)
python examples/sms_example.py

# Other resources (placeholder examples)
python examples/email_example.py
python examples/whatsapp_example.py
python examples/contacts_example.py
python examples/rcs_example.py
```

## 📱 SMS Examples (Fully Implemented)

The SMS resource is fully implemented with all four API endpoints:

### 🔧 Available Functions
1. **Send SMS** - `client.sms.send_sms()`
- Uses POST `/user-api/sms/quick-send`
- High-quality routing validation
- Comprehensive response data

2. **Get Senders** - `client.sms.get_senders()`
- Uses GET `/user-api/me/senders`
- Lists all available sender numbers/IDs

3. **Search Numbers** - `client.sms.get_available_numbers()`
- Uses GET `/user-api/numbers`
- Filter by region, type, and limit results

4. **Purchase Numbers** - `client.sms.buy_number()`
- Uses POST `/user-api/numbers/buy`
- Complete number purchasing workflow

### 🔄 Legacy Compatibility
The SMS resource maintains backward compatibility with legacy methods while using the new API implementation underneath.

## 🚧 Placeholder Examples

The following examples show the structure and planned functionality but are not yet implemented:

- **Email**: Send emails, attachments, templates
- **WhatsApp**: Text messages, media, templates, business features
- **RCS**: Rich messaging, cards, carousels, capability checks
- **Contacts**: CRUD operations, contact management

## 🔧 Configuration Notes

### Phone Numbers
- Replace placeholder phone numbers (`+1234567890`) with actual numbers
- Ensure phone numbers are in E.164 format (e.g., `+1234567890`)
- Use valid sender numbers from your Devo dashboard

### Testing vs Production
- Some examples include test mode flags
- Number purchase examples are commented out to prevent accidental charges
- Always test with small limits when exploring available numbers

### Error Handling
All examples include comprehensive error handling with:
- Detailed error messages
- HTTP status codes
- API-specific error codes
- Response data debugging

## 🆔 Authentication

All examples use API key authentication:
```python
from devo_global_comms_python import DevoClient

client = DevoClient(api_key="your_api_key_here")
```

## 📋 Example Output

### SMS Example Output
```
📱 SMS QUICK-SEND API EXAMPLE
------------------------------
📤 Sending SMS to +1234567890...
✅ SMS sent successfully!
📋 Message ID: msg_123456789
📊 Status: sent
📱 Recipient: +1234567890
🔄 Direction: outbound

👥 GET AVAILABLE SENDERS EXAMPLE
------------------------------
✅ Found 3 available senders:
1. 📞 Phone: +0987654321
🏷️ Type: longcode
🧪 Test Mode: No
```

## 🤝 Contributing

When implementing new resources:

1. **Create Resource Example**: Copy the structure from `sms_example.py`
2. **Update Basic Usage**: Add the new resource to `basic_usage.py`
3. **Update This README**: Document the new functionality
4. **Follow Patterns**: Use consistent emoji, formatting, and error handling

## 📚 Additional Resources

- **SDK Documentation**: [Link to main documentation]
- **API Reference**: [Link to API docs]
- **Devo Dashboard**: [Link to dashboard]
- **Support**: [Link to support]

---

**Need help?** Check the individual example files for detailed comments and error handling patterns.
166 changes: 111 additions & 55 deletions examples/basic_usage.py
Original file line number Diff line number Diff line change
@@ -1,70 +1,126 @@
import os
import subprocess
import sys

from devo_global_comms_python import DevoClient, DevoException


def main():
# Initialize the client with your API key
# You can get your API key from the Devo dashboard
print("🚀 Devo Global Communications SDK")
print("=" * 60)

# Check if API key is set
api_key = os.getenv("DEVO_API_KEY")
if not api_key:
print("Please set DEVO_API_KEY environment variable")
print("❌ Please set DEVO_API_KEY environment variable")
print(" You can get your API key from the Devo dashboard")
return

# Initialize the client
try:
client = DevoClient(api_key=api_key)
print("✅ Devo SDK Client initialized successfully")
except Exception as e:
print(f"❌ Failed to initialize client: {e}")
return

client = DevoClient(api_key=api_key)
print("\n📋 Available Resources:")
print("-" * 30)

# Check available resources
resources = []
if hasattr(client, "sms"):
resources.append(("📱 SMS", "Implemented", "sms_example.py"))
if hasattr(client, "email"):
resources.append(("📧 Email", "Placeholder", "email_example.py"))
if hasattr(client, "whatsapp"):
resources.append(("💬 WhatsApp", "Placeholder", "whatsapp_example.py"))
if hasattr(client, "contacts"):
resources.append(("👥 Contacts", "Placeholder", "contacts_example.py"))
if hasattr(client, "rcs"):
resources.append(("🎴 RCS", "Placeholder", "rcs_example.py"))

for resource, status, example_file in resources:
print(f" {resource:<12} - {status:<12} -> {example_file}")

# Quick SMS test if available
if hasattr(client, "sms"):
print("\n🧪 Quick SMS Test:")
print("-" * 30)
try:
# Try to get senders as a connectivity test
senders = client.sms.get_senders()
print(f"✅ SMS connection successful - {len(senders.senders)} senders available")

if senders.senders:
print(" Sample senders:")
for i, sender in enumerate(senders.senders[:3], 1):
print(f" {i}. {sender.phone_number} ({sender.type})")
if len(senders.senders) > 3:
print(f" ... and {len(senders.senders) - 3} more")

except DevoException as e:
print(f"⚠️ SMS connection test failed: {e}")

# Show example usage
print("\n💡 Getting Started:")
print("-" * 30)
print("1. Run individual resource examples:")
print(" python examples/sms_example.py # Complete SMS functionality")
print(" python examples/email_example.py # Email examples (placeholder)")
print(" python examples/whatsapp_example.py # WhatsApp examples (placeholder)")
print(" python examples/contacts_example.py # Contact management (placeholder)")
print(" python examples/rcs_example.py # RCS examples (placeholder)")
print()
print("2. Quick SMS example:")
print(" from devo_global_comms_python import DevoClient")
print(" client = DevoClient(api_key='your_api_key')")
print(" response = client.sms.send_sms(")
print(" recipient='+1234567890',")
print(" message='Hello from Devo!',")
print(" sender='your_sender_id'")
print(" )")

# Interactive menu
print("\n🎯 Interactive Examples:")
print("-" * 30)
print("Would you like to run a specific example?")
print("1. SMS Example (full functionality)")
print("2. Email Example (placeholder)")
print("3. WhatsApp Example (placeholder)")
print("4. Contacts Example (placeholder)")
print("5. RCS Example (placeholder)")
print("0. Exit")

try:
# Example 1: Send an SMS
print("Sending SMS...")
sms = client.sms.send(
to="+1234567890", # Replace with actual phone number
body="Hello from Devo SDK! This is a test SMS message.",
)
print(f"SMS sent successfully! Message SID: {sms.sid}")
print(f"Status: {sms.status}")

# Example 2: Send an email
print("\nSending email...")
email = client.email.send(
to="[email protected]", # Replace with actual email
subject="Test Email from Devo SDK",
body="This is a test email sent using the Devo Global Communications SDK.",
html_body="<h1>Test Email</h1><p>This is a <strong>test email</strong> sent using the Devo SDK.</p>",
)
print(f"Email sent successfully! Message ID: {email.id}")
print(f"Status: {email.status}")

# Example 3: Send a WhatsApp message
print("\nSending WhatsApp message...")
whatsapp = client.whatsapp.send_text(
to="+1234567890", # Replace with actual WhatsApp number
text="Hello from Devo SDK! This is a WhatsApp message.",
)
print(f"WhatsApp message sent successfully! Message ID: {whatsapp.id}")
print(f"Status: {whatsapp.status}")

# Example 4: Create a contact
print("\nCreating contact...")
contact = client.contacts.create(
phone_number="+1234567890",
email="[email protected]",
first_name="John",
last_name="Doe",
company="Example Corp",
metadata={"source": "sdk_example"},
)
print(f"Contact created successfully! Contact ID: {contact.id}")
print(f"Name: {contact.first_name} {contact.last_name}")

# Example 5: List recent messages
print("\nListing recent messages...")
messages = client.messages.list(limit=5, date_sent_after="2024-01-01")
print(f"Found {len(messages)} recent messages:")
for message in messages:
print(f" - {message.channel}: {message.id} ({message.status})")

except DevoException as e:
print(f"Error: {e}")
choice = input("\nEnter your choice (0-5): ").strip()
example_files = {
"1": "sms_example.py",
"2": "email_example.py",
"3": "whatsapp_example.py",
"4": "contacts_example.py",
"5": "rcs_example.py",
}

if choice in example_files:
example_file = example_files[choice]
example_path = os.path.join(os.path.dirname(__file__), example_file)

if os.path.exists(example_path):
print(f"\n🚀 Running {example_file}...")
print("=" * 60)
subprocess.run([sys.executable, example_path], check=True)
else:
print(f"❌ Example file {example_file} not found")
elif choice == "0":
print("👋 Goodbye!")
else:
print("❌ Invalid choice")

except KeyboardInterrupt:
print("\n👋 Goodbye!")
except Exception as e:
print(f"❌ Error running example: {e}")


if __name__ == "__main__":
Expand Down
Loading
Loading