Initial commit: Telegram Management System
Some checks failed
Deploy / deploy (push) Has been cancelled
Some checks failed
Deploy / deploy (push) Has been cancelled
Full-stack web application for Telegram management - Frontend: Vue 3 + Vben Admin - Backend: NestJS - Features: User management, group broadcast, statistics 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
600
marketing-agent/docs/api/examples.md
Normal file
600
marketing-agent/docs/api/examples.md
Normal file
@@ -0,0 +1,600 @@
|
||||
# API Usage Examples
|
||||
|
||||
Practical examples demonstrating common use cases for the Telegram Marketing Agent API.
|
||||
|
||||
## Complete Campaign Workflow
|
||||
|
||||
### 1. Authenticate
|
||||
|
||||
```bash
|
||||
# Login to get access token
|
||||
TOKEN=$(curl -s -X POST http://localhost:3000/api/v1/auth/login \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"username": "admin",
|
||||
"password": "password123"
|
||||
}' | jq -r '.data.tokens.accessToken')
|
||||
|
||||
echo "Token: $TOKEN"
|
||||
```
|
||||
|
||||
### 2. Create User Segment
|
||||
|
||||
```bash
|
||||
# Create a segment for active users
|
||||
SEGMENT_ID=$(curl -s -X POST http://localhost:3000/api/v1/segments \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"name": "Active Premium Users",
|
||||
"description": "Premium users active in last 7 days",
|
||||
"criteria": [
|
||||
{
|
||||
"field": "groups",
|
||||
"operator": "contains",
|
||||
"value": "Premium Users"
|
||||
},
|
||||
{
|
||||
"field": "engagement.lastActivity",
|
||||
"operator": "greater_than",
|
||||
"value": "7d"
|
||||
}
|
||||
],
|
||||
"logic": "AND"
|
||||
}' | jq -r '.data._id')
|
||||
|
||||
echo "Segment ID: $SEGMENT_ID"
|
||||
```
|
||||
|
||||
### 3. Create Message Template
|
||||
|
||||
```bash
|
||||
# Create a personalized message template
|
||||
TEMPLATE_ID=$(curl -s -X POST http://localhost:3000/api/v1/templates \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"name": "Premium Offer Template",
|
||||
"category": "promotional",
|
||||
"content": "Hi {{firstName}}! 🎉 As a valued premium member, enjoy 30% off your next purchase. Use code: PREMIUM30",
|
||||
"variables": [
|
||||
{
|
||||
"name": "firstName",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"defaultValue": "Valued Customer"
|
||||
}
|
||||
],
|
||||
"language": "en"
|
||||
}' | jq -r '.data.id')
|
||||
|
||||
echo "Template ID: $TEMPLATE_ID"
|
||||
```
|
||||
|
||||
### 4. Create Campaign
|
||||
|
||||
```bash
|
||||
# Create a marketing campaign
|
||||
CAMPAIGN_ID=$(curl -s -X POST http://localhost:3000/api/v1/campaigns \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"name": "Premium Member Exclusive Offer",
|
||||
"description": "30% discount for active premium members",
|
||||
"type": "message",
|
||||
"goals": {
|
||||
"targetAudience": 1000,
|
||||
"conversionRate": 15,
|
||||
"revenue": 50000
|
||||
},
|
||||
"targetAudience": {
|
||||
"segments": ["'$SEGMENT_ID'"]
|
||||
},
|
||||
"messages": [
|
||||
{
|
||||
"templateId": "'$TEMPLATE_ID'",
|
||||
"personalization": {
|
||||
"enabled": true,
|
||||
"fields": ["firstName"]
|
||||
}
|
||||
}
|
||||
],
|
||||
"budget": 5000
|
||||
}' | jq -r '.data.id')
|
||||
|
||||
echo "Campaign ID: $CAMPAIGN_ID"
|
||||
```
|
||||
|
||||
### 5. Schedule the Campaign
|
||||
|
||||
```bash
|
||||
# Schedule campaign to run daily at 10 AM
|
||||
curl -s -X POST http://localhost:3000/api/v1/scheduled-campaigns \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"campaignId": "'$CAMPAIGN_ID'",
|
||||
"campaignName": "Daily Premium Offers",
|
||||
"type": "recurring",
|
||||
"schedule": {
|
||||
"recurring": {
|
||||
"pattern": "daily",
|
||||
"timeOfDay": "10:00",
|
||||
"timezone": "America/New_York",
|
||||
"endDate": "2024-12-31T23:59:59Z"
|
||||
}
|
||||
},
|
||||
"targetAudience": {
|
||||
"type": "segment",
|
||||
"segmentId": "'$SEGMENT_ID'"
|
||||
},
|
||||
"messageConfig": {
|
||||
"templateId": "'$TEMPLATE_ID'"
|
||||
},
|
||||
"deliverySettings": {
|
||||
"priority": "normal",
|
||||
"rateLimiting": {
|
||||
"enabled": true,
|
||||
"messagesPerHour": 500
|
||||
}
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
### 6. Monitor Campaign Progress
|
||||
|
||||
```bash
|
||||
# Check campaign statistics
|
||||
curl -s -X GET "http://localhost:3000/api/v1/campaigns/$CAMPAIGN_ID/statistics" \
|
||||
-H "Authorization: Bearer $TOKEN" | jq '.data.overview'
|
||||
|
||||
# Get real-time progress
|
||||
curl -s -X GET "http://localhost:3000/api/v1/campaigns/$CAMPAIGN_ID/progress" \
|
||||
-H "Authorization: Bearer $TOKEN" | jq '.data.progress'
|
||||
```
|
||||
|
||||
## A/B Testing Example
|
||||
|
||||
### Create A/B Test
|
||||
|
||||
```bash
|
||||
# Create an A/B test for message variations
|
||||
AB_TEST_ID=$(curl -s -X POST http://localhost:3000/api/v1/experiments \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"name": "Emoji vs No Emoji Test",
|
||||
"description": "Test engagement with and without emojis",
|
||||
"type": "message",
|
||||
"status": "draft",
|
||||
"hypothesis": "Messages with emojis will have 20% higher engagement",
|
||||
"metrics": {
|
||||
"primary": "click_rate",
|
||||
"secondary": ["open_rate", "conversion_rate"]
|
||||
},
|
||||
"variants": [
|
||||
{
|
||||
"id": "control",
|
||||
"name": "No Emoji",
|
||||
"description": "Plain text message",
|
||||
"allocation": 50,
|
||||
"config": {
|
||||
"message": "Special offer: Get 25% off today!"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "variant_a",
|
||||
"name": "With Emoji",
|
||||
"description": "Message with emojis",
|
||||
"allocation": 50,
|
||||
"config": {
|
||||
"message": "🎉 Special offer: Get 25% off today! 🛍️"
|
||||
}
|
||||
}
|
||||
],
|
||||
"audience": {
|
||||
"segmentId": "'$SEGMENT_ID'",
|
||||
"size": 1000
|
||||
},
|
||||
"schedule": {
|
||||
"startDate": "2024-07-01T00:00:00Z",
|
||||
"endDate": "2024-07-07T23:59:59Z"
|
||||
}
|
||||
}' | jq -r '.data.id')
|
||||
|
||||
# Start the A/B test
|
||||
curl -s -X POST "http://localhost:3000/api/v1/experiments/$AB_TEST_ID/start" \
|
||||
-H "Authorization: Bearer $TOKEN"
|
||||
```
|
||||
|
||||
## Workflow Automation Example
|
||||
|
||||
### Create Welcome Workflow
|
||||
|
||||
```bash
|
||||
# Create an automated welcome workflow
|
||||
WORKFLOW_ID=$(curl -s -X POST http://localhost:3000/api/v1/workflows \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"name": "New User Welcome Series",
|
||||
"description": "3-step welcome series for new users",
|
||||
"trigger": {
|
||||
"type": "user_event",
|
||||
"event": "user_joined",
|
||||
"conditions": {
|
||||
"source": "telegram"
|
||||
}
|
||||
},
|
||||
"nodes": [
|
||||
{
|
||||
"id": "welcome_message",
|
||||
"type": "send_message",
|
||||
"name": "Welcome Message",
|
||||
"config": {
|
||||
"templateId": "welcome_template_1",
|
||||
"delay": {
|
||||
"value": 0,
|
||||
"unit": "minutes"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "wait_1_day",
|
||||
"type": "delay",
|
||||
"name": "Wait 1 Day",
|
||||
"config": {
|
||||
"duration": {
|
||||
"value": 1,
|
||||
"unit": "days"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "tips_message",
|
||||
"type": "send_message",
|
||||
"name": "Tips Message",
|
||||
"config": {
|
||||
"templateId": "tips_template"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "check_engagement",
|
||||
"type": "condition",
|
||||
"name": "Check Engagement",
|
||||
"config": {
|
||||
"condition": {
|
||||
"field": "engagement.messagesSent",
|
||||
"operator": "greater_than",
|
||||
"value": 0
|
||||
},
|
||||
"trueBranch": "engaged_user_path",
|
||||
"falseBranch": "re_engagement_path"
|
||||
}
|
||||
}
|
||||
],
|
||||
"edges": [
|
||||
{
|
||||
"source": "welcome_message",
|
||||
"target": "wait_1_day"
|
||||
},
|
||||
{
|
||||
"source": "wait_1_day",
|
||||
"target": "tips_message"
|
||||
},
|
||||
{
|
||||
"source": "tips_message",
|
||||
"target": "check_engagement"
|
||||
}
|
||||
]
|
||||
}' | jq -r '.data.id')
|
||||
|
||||
# Activate the workflow
|
||||
curl -s -X POST "http://localhost:3000/api/v1/workflows/$WORKFLOW_ID/activate" \
|
||||
-H "Authorization: Bearer $TOKEN"
|
||||
```
|
||||
|
||||
## User Management Example
|
||||
|
||||
### Import Users from CSV
|
||||
|
||||
```bash
|
||||
# First, create a CSV file
|
||||
cat > users.csv << EOF
|
||||
phone,firstName,lastName,tags,groups
|
||||
+1234567890,John,Doe,"VIP,Newsletter","Premium Users"
|
||||
+0987654321,Jane,Smith,Newsletter,"Standard Users"
|
||||
+1122334455,Bob,Johnson,"VIP,Beta","Premium Users,Beta Testers"
|
||||
EOF
|
||||
|
||||
# Import users
|
||||
curl -X POST http://localhost:3000/api/v1/users/import \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-F "file=@users.csv" \
|
||||
-F 'mapping={
|
||||
"phone": "phone",
|
||||
"firstName": "firstName",
|
||||
"lastName": "lastName",
|
||||
"tags": "tags",
|
||||
"groups": "groups"
|
||||
}'
|
||||
```
|
||||
|
||||
### Bulk Tag Users
|
||||
|
||||
```bash
|
||||
# Tag all users who made a purchase
|
||||
curl -X POST http://localhost:3000/api/v1/users/bulk-update \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"filter": {
|
||||
"attributes.hasPurchased": true
|
||||
},
|
||||
"updates": {
|
||||
"addTags": ["Customer"],
|
||||
"attributes": {
|
||||
"customerSince": "2024-06-20"
|
||||
}
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
## Analytics Example
|
||||
|
||||
### Get Real-time Dashboard Data
|
||||
|
||||
```bash
|
||||
# Get current metrics
|
||||
curl -s -X GET http://localhost:3000/api/v1/analytics/realtime/metrics \
|
||||
-H "Authorization: Bearer $TOKEN" | jq '.data'
|
||||
|
||||
# Get campaign performance
|
||||
curl -s -X GET "http://localhost:3000/api/v1/analytics/campaigns?period=7d" \
|
||||
-H "Authorization: Bearer $TOKEN" | jq '.data.campaigns[0]'
|
||||
```
|
||||
|
||||
### Generate Custom Report
|
||||
|
||||
```bash
|
||||
# Create a custom report
|
||||
REPORT_ID=$(curl -s -X POST http://localhost:3000/api/v1/analytics/reports \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"name": "Weekly Performance Report",
|
||||
"type": "performance",
|
||||
"period": {
|
||||
"start": "2024-06-01T00:00:00Z",
|
||||
"end": "2024-06-30T23:59:59Z"
|
||||
},
|
||||
"metrics": [
|
||||
"messages_sent",
|
||||
"delivery_rate",
|
||||
"engagement_rate",
|
||||
"conversion_rate"
|
||||
],
|
||||
"groupBy": "campaign",
|
||||
"format": "pdf"
|
||||
}' | jq -r '.data.id')
|
||||
|
||||
# Download the report
|
||||
curl -X GET "http://localhost:3000/api/v1/analytics/reports/$REPORT_ID/download" \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-o "weekly_report.pdf"
|
||||
```
|
||||
|
||||
## Webhook Integration Example
|
||||
|
||||
### Setup Webhook for Campaign Events
|
||||
|
||||
```bash
|
||||
# Create webhook endpoint
|
||||
WEBHOOK_ID=$(curl -s -X POST http://localhost:3000/api/v1/webhooks \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"name": "Campaign Status Webhook",
|
||||
"url": "https://your-server.com/webhooks/campaigns",
|
||||
"events": [
|
||||
"campaign.started",
|
||||
"campaign.completed",
|
||||
"campaign.failed"
|
||||
],
|
||||
"active": true,
|
||||
"headers": {
|
||||
"X-Custom-Header": "your-secret-value"
|
||||
},
|
||||
"retryPolicy": {
|
||||
"maxRetries": 3,
|
||||
"retryDelay": 60
|
||||
}
|
||||
}' | jq -r '.data.id')
|
||||
|
||||
# Test the webhook
|
||||
curl -X POST "http://localhost:3000/api/v1/webhooks/$WEBHOOK_ID/test" \
|
||||
-H "Authorization: Bearer $TOKEN"
|
||||
```
|
||||
|
||||
## Error Handling Examples
|
||||
|
||||
### Handle Rate Limiting
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# Script with retry logic for rate limits
|
||||
|
||||
function api_call_with_retry() {
|
||||
local url=$1
|
||||
local max_retries=3
|
||||
local retry_count=0
|
||||
|
||||
while [ $retry_count -lt $max_retries ]; do
|
||||
response=$(curl -s -w "\n%{http_code}" -X GET "$url" \
|
||||
-H "Authorization: Bearer $TOKEN")
|
||||
|
||||
http_code=$(echo "$response" | tail -n1)
|
||||
body=$(echo "$response" | sed '$d')
|
||||
|
||||
if [ "$http_code" -eq 200 ]; then
|
||||
echo "$body"
|
||||
return 0
|
||||
elif [ "$http_code" -eq 429 ]; then
|
||||
retry_after=$(echo "$body" | jq -r '.retryAfter // 60')
|
||||
echo "Rate limited. Retrying after $retry_after seconds..." >&2
|
||||
sleep "$retry_after"
|
||||
((retry_count++))
|
||||
else
|
||||
echo "Error: HTTP $http_code" >&2
|
||||
echo "$body" >&2
|
||||
return 1
|
||||
fi
|
||||
done
|
||||
|
||||
echo "Max retries exceeded" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
# Use the function
|
||||
api_call_with_retry "http://localhost:3000/api/v1/campaigns"
|
||||
```
|
||||
|
||||
### Handle Pagination
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
# Script to fetch all users with pagination
|
||||
|
||||
function fetch_all_users() {
|
||||
local page=1
|
||||
local limit=100
|
||||
local total_fetched=0
|
||||
|
||||
while true; do
|
||||
response=$(curl -s -X GET "http://localhost:3000/api/v1/users?page=$page&limit=$limit" \
|
||||
-H "Authorization: Bearer $TOKEN")
|
||||
|
||||
users=$(echo "$response" | jq -r '.data.users')
|
||||
pagination=$(echo "$response" | jq -r '.data.pagination')
|
||||
|
||||
# Process users
|
||||
echo "$users" | jq -c '.[]' | while read -r user; do
|
||||
# Process each user
|
||||
echo "Processing user: $(echo "$user" | jq -r '.phone')"
|
||||
done
|
||||
|
||||
# Check if there are more pages
|
||||
current_page=$(echo "$pagination" | jq -r '.page')
|
||||
total_pages=$(echo "$pagination" | jq -r '.pages')
|
||||
|
||||
if [ "$current_page" -ge "$total_pages" ]; then
|
||||
break
|
||||
fi
|
||||
|
||||
((page++))
|
||||
done
|
||||
}
|
||||
|
||||
fetch_all_users
|
||||
```
|
||||
|
||||
## SDK Examples
|
||||
|
||||
### Node.js Example
|
||||
|
||||
```javascript
|
||||
const MarketingAPI = require('telegram-marketing-sdk');
|
||||
|
||||
const client = new MarketingAPI({
|
||||
baseURL: 'http://localhost:3000/api/v1',
|
||||
auth: {
|
||||
username: 'admin',
|
||||
password: 'password123'
|
||||
}
|
||||
});
|
||||
|
||||
// Create and execute a campaign
|
||||
async function runCampaign() {
|
||||
try {
|
||||
// Create campaign
|
||||
const campaign = await client.campaigns.create({
|
||||
name: 'Flash Sale',
|
||||
type: 'message',
|
||||
targetAudience: {
|
||||
segments: ['segment123']
|
||||
},
|
||||
messages: [{
|
||||
templateId: 'template456'
|
||||
}]
|
||||
});
|
||||
|
||||
// Execute campaign
|
||||
const execution = await client.campaigns.execute(campaign.id);
|
||||
|
||||
// Monitor progress
|
||||
const interval = setInterval(async () => {
|
||||
const progress = await client.campaigns.getProgress(campaign.id);
|
||||
console.log(`Progress: ${progress.percentage}%`);
|
||||
|
||||
if (progress.status === 'completed') {
|
||||
clearInterval(interval);
|
||||
console.log('Campaign completed!');
|
||||
}
|
||||
}, 5000);
|
||||
} catch (error) {
|
||||
console.error('Campaign failed:', error.message);
|
||||
}
|
||||
}
|
||||
|
||||
runCampaign();
|
||||
```
|
||||
|
||||
### Python Example
|
||||
|
||||
```python
|
||||
import telegram_marketing_sdk as tg
|
||||
import time
|
||||
|
||||
# Initialize client
|
||||
client = tg.Client(
|
||||
base_url='http://localhost:3000/api/v1',
|
||||
username='admin',
|
||||
password='password123'
|
||||
)
|
||||
|
||||
# Create user segment
|
||||
segment = client.segments.create(
|
||||
name='Python SDK Users',
|
||||
criteria=[
|
||||
{
|
||||
'field': 'attributes.sdk',
|
||||
'operator': 'equals',
|
||||
'value': 'python'
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
# Create and schedule campaign
|
||||
campaign = client.campaigns.create(
|
||||
name='Python SDK Campaign',
|
||||
type='message',
|
||||
target_audience={
|
||||
'segments': [segment.id]
|
||||
}
|
||||
)
|
||||
|
||||
schedule = client.scheduled_campaigns.create(
|
||||
campaign_id=campaign.id,
|
||||
campaign_name=f'{campaign.name} - Daily',
|
||||
type='recurring',
|
||||
schedule={
|
||||
'recurring': {
|
||||
'pattern': 'daily',
|
||||
'time_of_day': '10:00',
|
||||
'timezone': 'UTC'
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
print(f'Campaign scheduled: {schedule.id}')
|
||||
```
|
||||
Reference in New Issue
Block a user