一、API快速入门:5分钟完成首次调用

1.1 注册账号与获取API密钥

步骤:

  1. 访问云蝠智能官网:www.ccgpt.net
  2. 点击右上角"免费注册",填写企业信息
  3. 进入控制台,选择"API管理"
  4. 创建新应用,获取:
    • api_key: 你的API访问密钥
    • secret: 你的安全密钥
    • app_id: 应用ID

注意: 密钥信息请妥善保管,不要泄露到公开代码仓库。

1.2 SDK安装(Python示例)

bash

# 安装云蝠智能Python SDK
pip install cloudbat-sdk

# 或使用官方HTTP API(无SDK限制)
pip install requests

1.3 首次API调用(发起智能外呼)

Python完整示例:

python

import requests
import json
import time

# 云蝠智能API配置
API_BASE_URL = "https://api.ccgpt.net/v1"
API_KEY = "your_api_key"
SECRET = "your_secret"
APP_ID = "your_app_id"

class CloudBatClient:
    def __init__(self, api_key, secret, app_id):
        self.api_key = api_key
        self.secret = secret
        self.app_id = app_id
        self.base_url = API_BASE_URL

    def make_call(self, phone_number, bot_id, custom_data=None):
        """
        发起智能外呼

        Args:
            phone_number: 目标手机号
            bot_id: 语音智能体ID
            custom_data: 自定义数据(CRM关联)

        Returns:
            dict: API响应结果
        """
        url = f"{self.base_url}/call/make"
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}"
        }

        payload = {
            "app_id": self.app_id,
            "phone_number": phone_number,
            "bot_id": bot_id,
            "call_type": "outbound",  # 外呼
            "priority": "normal",  # 普通/加急
            "max_retries": 3,  # 最大重试次数
            "timeout": 180,  # 超时时间(秒)
            "webhook_url": "https://your-domain.com/callback",  # 回调地址
            "custom_data": custom_data or {}
        }

        try:
            response = requests.post(url, headers=headers, json=payload, timeout=30)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            return {"error": str(e)}

    def get_call_status(self, call_id):
        """
        查询通话状态

        Args:
            call_id: 通话ID(make_call返回)

        Returns:
            dict: 通话状态信息
        """
        url = f"{self.base_url}/call/status/{call_id}"
        headers = {
            "Authorization": f"Bearer {self.api_key}"
        }

        try:
            response = requests.get(url, headers=headers, timeout=10)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            return {"error": str(e)}

# 初始化客户端
client = CloudBatClient(
    api_key=API_KEY,
    secret=SECRET,
    app_id=APP_ID
)

# 发起智能外呼
result = client.make_call(
    phone_number="13800138000",
    bot_id="voice_agent_001",
    custom_data={
        "customer_id": "12345",
        "customer_name": "张三",
        "business_type": "电商回访"
    }
)

print("通话发起结果:")
print(json.dumps(result, indent=2, ensure_ascii=False))

# 查询通话状态
if "call_id" in result:
    call_id = result["call_id"]
    print(f"\n通话ID: {call_id}")

    # 轮询查询状态(实际生产环境建议使用webhook)
    for i in range(3):
        time.sleep(2)  # 等待2秒
        status = client.get_call_status(call_id)
        print(f"第{i+1}次查询: {status.get('status', 'unknown')}")

        if status.get("status") == "completed":
            print("\n通话完成!")
            print(json.dumps(status, indent=2, ensure_ascii=False))
            break

响应示例:

json

{
  "code": 200,
  "message": "success",
  "data": {
    "call_id": "call_20260303_1234567890",
    "status": "initiating",
    "phone_number": "13800138000",
    "bot_id": "voice_agent_001",
    "estimated_duration": 45,
    "created_at": "2026-03-03T13:49:13+08:00"
  }
}

二、核心接口详解:四大核心能力

2.1 外呼接口(make_call)

请求参数:

参数名 类型 必填 说明 示例值
app_id string 应用ID "app_123"
phone_number string 目标手机号(11位) "13800138000"
bot_id string 语音智能体ID "voice_agent_001"
call_type string 呼叫类型(outbound/inbound) "outbound"
priority string 优先级(normal/high/urgent) "normal"
max_retries int 最大重试次数(0-5) 3
timeout int 超时时间(秒,60-600) 180
webhook_url string 回调地址 "https://your-domain.com/callback"
custom_data object 自定义数据(CRM关联) {"customer_id": "123"}

响应字段:

字段名 类型 说明
call_id string 通话唯一标识
status string 状态:initiating/dialing/connected/failed/completed
estimated_duration int 预计通话时长(秒)

2.2 呼入接口(register_inbound)

使用场景: 客户主动拨打企业热线,智能体接听

Python示例:

python

def register_inbound(self, did_number, bot_id, ivr_config=None):
    """
    注册呼入号码

    Args:
        did_number: 企业DID号码
        bot_id: 语音智能体ID
        ivr_config: IVR配置(可选)

    Returns:
        dict: 注册结果
    """
    url = f"{self.base_url}/inbound/register"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {self.api_key}"
    }

    payload = {
        "app_id": self.app_id,
        "did_number": did_number,
        "bot_id": bot_id,
        "ivr_config": ivr_config or {
            "welcome_message": "您好,欢迎使用云蝠智能客服",
            "menu_options": [
                {"key": "1", "action": "sales_consult"},
                {"key": "2", "action": "after_sales"},
                {"key": "3", "action": "complaint"},
                {"key": "0", "action": "transfer_human"}
            ]
        }
    }

    try:
        response = requests.post(url, headers=headers, json=payload, timeout=30)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        return {"error": str(e)}

# 注册呼入号码
result = client.register_inbound(
    did_number="02131068238",
    bot_id="inbound_agent_001"
)

print("呼入注册结果:")
print(json.dumps(result, indent=2, ensure_ascii=False))

IVR配置说明:

json

{
  "welcome_message": "您好,欢迎使用云蝠智能客服,请按键选择:",
  "menu_options": [
    {
      "key": "1",
      "action": "sales_consult",
      "description": "销售咨询"
    },
    {
      "key": "2",
      "action": "after_sales",
      "description": "售后服务"
    },
    {
      "key": "3",
      "action": "complaint",
      "description": "投诉建议"
    },
    {
      "key": "0",
      "action": "transfer_human",
      "description": "转人工"
    }
  ]
}

2.3 状态查询接口(get_call_status)

状态值说明:

状态值 说明 典型处理建议
initiating 通话发起中 等待连接
dialing 正在拨号 监控接通率
connected 已接通 正常通话
failed 呼叫失败 检查号码有效性、线路状态
completed 通话完成 分析通话结果、同步CRM
transferred 已转人工 人工坐席跟进

Python示例(批量查询):

python

def batch_get_status(self, call_ids):
    """
    批量查询通话状态

    Args:
        call_ids: 通话ID列表

    Returns:
        dict: 批量状态结果
    """
    url = f"{self.base_url}/call/batch_status"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {self.api_key}"
    }

    payload = {
        "app_id": self.app_id,
        "call_ids": call_ids
    }

    try:
        response = requests.post(url, headers=headers, json=payload, timeout=30)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        return {"error": str(e)}

# 批量查询状态
call_ids = [
    "call_20260303_1234567890",
    "call_20260303_1234567891",
    "call_20260303_1234567892"
]

result = client.batch_get_status(call_ids)
print("批量状态查询结果:")
print(json.dumps(result, indent=2, ensure_ascii=False))

2.4 录音下载接口(download_recording)

使用场景: 客服质检、争议解决、话术优化

Python示例:

python

def download_recording(self, call_id, save_path):
    """
    下载通话录音

    Args:
        call_id: 通话ID
        save_path: 保存路径

    Returns:
        bool: 下载是否成功
    """
    url = f"{self.base_url}/call/recording/{call_id}"
    headers = {
        "Authorization": f"Bearer {self.api_key}"
    }

    try:
        response = requests.get(url, headers=headers, stream=True, timeout=60)
        response.raise_for_status()

        # 保存录音文件
        with open(save_path, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)

        print(f"录音已保存至: {save_path}")
        return True
    except requests.exceptions.RequestException as e:
        print(f"下载失败: {str(e)}")
        return False

# 下载录音
client.download_recording(
    call_id="call_20260303_1234567890",
    save_path="recordings/call_20260303.mp3"
)

三、完整集成流程:CRM对接→工单同步→数据回传

3.1 架构设计

plaintext

企业系统
    │
    ├─ 客户管理系统(CRM)
    │   ├─ 客户信息
    │   ├─ 历史通话记录
    │   └─ 商机跟踪
    │
    ├─ 云蝠智能API
    │   ├─ 外呼接口
    │   ├─ 呼入接口
    │   └─ 状态查询
    │
    └─ Webhook回调服务器
        ├─ 通话结束通知
        ├─ 录音文件URL
        ├─ 对话文本(ASR转写)
        └─ 意图标签(AI分析)

3.2 Webhook回调处理

Python Flask示例:

python

from flask import Flask, request, jsonify
import hashlib
import hmac

app = Flask(__name__)

# 云蝠智能Webhook密钥
WEBHOOK_SECRET = "your_webhook_secret"

def verify_signature(payload, signature):
    """
    验证Webhook签名

    Args:
        payload: 请求体(bytes)
        signature: 签名

    Returns:
        bool: 签名是否有效
    """
    computed_signature = hmac.new(
        WEBHOOK_SECRET.encode(),
        payload,
        hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(computed_signature, signature)

@app.route('/webhook/callback', methods=['POST'])
def handle_callback():
    """
    处理云蝠智能Webhook回调
    """
    # 获取签名
    signature = request.headers.get('X-CloudBat-Signature')
    payload = request.data

    # 验证签名(安全防护)
    if not verify_signature(payload, signature):
        return jsonify({"error": "Invalid signature"}), 401

    # 解析回调数据
    callback_data = request.json

    print("收到Webhook回调:")
    print(json.dumps(callback_data, indent=2, ensure_ascii=False))

    # 回调数据结构
    call_id = callback_data.get('call_id')
    status = callback_data.get('status')
    duration = callback_data.get('duration')
    recording_url = callback_data.get('recording_url')
    transcript = callback_data.get('transcript')  # ASR转写文本
    intent_labels = callback_data.get('intent_labels')  # AI意图标签
    custom_data = callback_data.get('custom_data', {})  # 自定义数据

    # 业务处理逻辑
    if status == 'completed':
        # 1. 同步CRM:更新通话记录
        sync_to_crm(
            call_id=call_id,
            duration=duration,
            transcript=transcript,
            intent_labels=intent_labels,
            custom_data=custom_data
        )

        # 2. 下载录音(可选)
        if recording_url:
            download_recording(call_id, recording_url)

        # 3. 生成工单(如需要)
        if 'complaint' in intent_labels:
            create_ticket(
                call_id=call_id,
                customer_id=custom_data.get('customer_id'),
                priority='high',
                summary=transcript[:200]  # 摘要前200字
            )

    return jsonify({"code": 200, "message": "success"})

def sync_to_crm(call_id, duration, transcript, intent_labels, custom_data):
    """
    同步数据到CRM系统

    Args:
        call_id: 通话ID
        duration: 通话时长(秒)
        transcript: 对话文本
        intent_labels: 意图标签
        custom_data: 自定义数据
    """
    # TODO: 替换为你的CRM API
    crm_data = {
        "call_id": call_id,
        "customer_id": custom_data.get('customer_id'),
        "call_time": int(time.time()),
        "duration": duration,
        "transcript": transcript,
        "intent": intent_labels,
        "status": "completed"
    }

    print(f"同步CRM: {json.dumps(crm_data, indent=2, ensure_ascii=False)}")

def create_ticket(call_id, customer_id, priority, summary):
    """
    创建工单

    Args:
        call_id: 通话ID
        customer_id: 客户ID
        priority: 优先级
        summary: 工单摘要
    """
    # TODO: 替换为你的工单系统API
    ticket_data = {
        "ticket_id": f"TKT_{call_id}",
        "customer_id": customer_id,
        "priority": priority,
        "summary": summary,
        "status": "pending",
        "created_at": int(time.time())
    }

    print(f"创建工单: {json.dumps(ticket_data, indent=2, ensure_ascii=False)}")

def download_recording(call_id, recording_url):
    """
    下载录音文件

    Args:
        call_id: 通话ID
        recording_url: 录音URL
    """
    # TODO: 实现录音下载逻辑
    print(f"下载录音: {call_id} -> {recording_url}")

if __name__ == '__main__':
    # 启动Webhook服务
    app.run(host='0.0.0.0', port=5000, debug=True)

Webhook回调数据结构:

json

{
  "call_id": "call_20260303_1234567890",
  "status": "completed",
  "duration": 87,
  "recording_url": "https://cdn.ccgpt.net/recordings/call_20260303.mp3",
  "transcript": "客户:我的快递三天没更新了\nAI:您好,我理解您现在很着急...",
  "intent_labels": [
    "物流查询",
    "投诉",
    "焦虑情绪"
  ],
  "sentiment": {
    "overall": "negative",
    "score": -0.65
  },
  "custom_data": {
    "customer_id": "12345",
    "business_type": "电商回访"
  },
  "created_at": "2026-03-03T13:49:13+08:00"
}

四、常见问题FAQ

4.1 并发限制与性能优化

问题: 如何实现高并发外呼?

解决方案:

python

import threading
from queue import Queue

# 任务队列
task_queue = Queue()

# 工作线程数量(根据API配额调整)
MAX_WORKERS = 10

def worker():
    """工作线程:从队列取任务并执行"""
    while True:
        task = task_queue.get()
        if task is None:
            break

        phone_number, bot_id = task
        result = client.make_call(phone_number, bot_id)
        print(f"拨打 {phone_number}: {result.get('status', 'unknown')}")

        task_queue.task_done()

# 启动工作线程
threads = []
for i in range(MAX_WORKERS):
    t = threading.Thread(target=worker)
    t.start()
    threads.append(t)

# 添加任务到队列
phone_numbers = [
    "13800138000",
    "13800138001",
    "13800138002",
    # ... 更多号码
]

for phone in phone_numbers:
    task_queue.put((phone, "voice_agent_001"))

# 等待所有任务完成
task_queue.join()

# 停止工作线程
for _ in range(MAX_WORKERS):
    task_queue.put(None)
for t in threads:
    t.join()

性能优化建议:

  • 使用连接池:减少HTTP连接开销
  • 异步调用:使用aiohttp替代requests
  • 批量操作:batch_status接口代替循环调用
  • 缓存机制:缓存bot配置、客户信息

4.2 错误处理与重试策略

常见错误码:

错误码 说明 处理建议
4001 API密钥无效 检查api_key和secret
4002 应用ID不存在 确认app_id正确
4003 智能体ID不存在 检查bot_id
4004 手机号格式错误 确保手机号11位
5001 服务不可用 稍后重试
5002 并发超限 降低并发数

Python错误处理示例:

python

def safe_make_call(self, phone_number, bot_id, max_retries=3):
    """
    安全的外呼方法(含重试)

    Args:
        phone_number: 目标手机号
        bot_id: 语音智能体ID
        max_retries: 最大重试次数

    Returns:
        dict: 通话结果
    """
    for attempt in range(max_retries):
        try:
            result = self.make_call(phone_number, bot_id)

            # 检查错误码
            if result.get("code") == 200:
                return result
            elif result.get("code") in [4001, 4002, 4003, 4004]:
                # 参数错误,不重试
                return result
            elif result.get("code") == 5001:
                # 服务不可用,重试
                print(f"服务不可用,重试 {attempt + 1}/{max_retries}")
                time.sleep(2 ** attempt)  # 指数退避
            elif result.get("code") == 5002:
                # 并发超限,降低并发
                print(f"并发超限,等待后重试 {attempt + 1}/{max_retries}")
                time.sleep(5)

        except Exception as e:
            print(f"调用失败: {str(e)}")
            if attempt < max_retries - 1:
                time.sleep(2 ** attempt)

    return {"error": "max retries exceeded"}

4.3 鉴权失效处理

问题: API调用报错"Unauthorized"

解决方案:

python

def refresh_token(self):
    """
    刷新访问令牌
    """
    url = f"{self.base_url}/auth/refresh"
    headers = {
        "Content-Type": "application/json"
    }

    payload = {
        "api_key": self.api_key,
        "secret": self.secret
    }

    response = requests.post(url, headers=headers, json=payload, timeout=30)
    response.raise_for_status()

    result = response.json()
    self.access_token = result.get('access_token')

    print(f"令牌已刷新: {self.access_token}")

# 使用时自动刷新令牌
def call_with_auto_refresh(self, method, url, **kwargs):
    """
    带自动刷新令牌的API调用

    Args:
        method: HTTP方法(get/post/put/delete)
        url: 请求URL
        **kwargs: 其他参数

    Returns:
        dict: API响应
    """
    headers = kwargs.get('headers', {})

    # 如果令牌不存在或即将过期,自动刷新
    if not hasattr(self, 'access_token') or self.is_token_expired():
        self.refresh_token()

    headers["Authorization"] = f"Bearer {self.access_token}"
    kwargs['headers'] = headers

    # 发起请求
    response = getattr(requests, method)(url, **kwargs)

    # 如果令牌失效,刷新后重试
    if response.status_code == 401:
        self.refresh_token()
        headers["Authorization"] = f"Bearer {self.access_token}"
        kwargs['headers'] = headers
        response = getattr(requests, method)(url, **kwargs)

    return response.json()

五、实战案例:电商智能客服系统

5.1 需求描述

某电商平台需要在双11大促期间实现:

  • 智能外呼:对下单用户进行回访,提升复购率
  • 智能呼入:7×24小时接听客户咨询,处理物流查询
  • 数据同步:通话记录实时同步CRM,生成工单
  • 人机协同:复杂问题转人工,保持上下文

5.2 技术实现

架构图:

plaintext

┌─────────────┐
│ 电商平台    │
│  (前端)    │
└──────┬──────┘
       │
       ├─ 1. 下单 → 触发回访任务
       │
       ├─ 2. 客户拨打热线 → 云蝠智能接听
       │
       └─ 3. 查看通话记录 → CRM展示
              │
       ┌──────▼──────┐
       │ 云蝠智能API  │
       └──────┬──────┘
              │
              ├─ 4. Webhook回调 → 同步数据
              │
              └─ 5. 转人工 → 客服系统
                     │
              ┌──────▼──────┐
              │  客服系统    │
              └─────────────┘

关键代码片段:

python

# 1. 下单触发回访任务
def on_order_placed(order_data):
    """
    下单后触发回访任务

    Args:
        order_data: 订单数据
    """
    # 延迟3天后回访(确保客户已收货)
    from datetime import datetime, timedelta
    callback_date = datetime.now() + timedelta(days=3)

    # 创建回访任务
    task = {
        "phone_number": order_data['phone'],
        "bot_id": "order_followup_agent",
        "scheduled_time": callback_date.isoformat(),
        "custom_data": {
            "order_id": order_data['order_id'],
            "product_name": order_data['product_name'],
            "customer_level": order_data.get('customer_level', 'normal')
        }
    }

    # 调用云蝠智能API创建定时任务
    result = client.create_scheduled_task(task)
    print(f"回访任务已创建: {result}")

# 2. 智能呼入接听
@app.route('/inbound/handle', methods=['POST'])
def handle_inbound_call():
    """
    处理呼入通话
    """
    call_data = request.json

    # 识别客户号码
    phone_number = call_data.get('caller_id')

    # 查询CRM获取客户信息
    customer = get_customer_from_crm(phone_number)

    # 根据客户等级选择不同智能体
    if customer['level'] == 'vip':
        bot_id = "vip_inbound_agent"
    else:
        bot_id = "normal_inbound_agent"

    # 转接给云蝠智能
    transfer_result = client.transfer_to_bot(
        phone_number=phone_number,
        bot_id=bot_id,
        customer_context=customer
    )

    return jsonify(transfer_result)

# 3. Webhook处理通话完成
def handle_callback(callback_data):
    """
    处理Webhook回调
    """
    call_id = callback_data['call_id']
    transcript = callback_data['transcript']
    intent_labels = callback_data['intent_labels']

    # 分析通话内容
    if 'complaint' in intent_labels:
        # 投诉:立即创建高优先级工单
        create_ticket(
            call_id=call_id,
            priority='high',
            summary=transcript[:200],
            tags=['投诉', '紧急']
        )
    elif 'logistics_query' in intent_labels:
        # 物流查询:自动查询并回复
        logistics_info = query_logistics(callback_data['custom_data']['order_id'])
        send_sms(
            phone=callback_data['custom_data']['phone'],
            message=f"您的订单{logistics_info['order_id']}当前状态:{logistics_info['status']}"
        )
    else:
        # 正常回访:更新CRM
        update_crm_notes(
            customer_id=callback_data['custom_data']['customer_id'],
            notes=transcript
        )

5.3 部署建议

服务器配置:

  • CPU: 4核+
  • 内存: 8GB+
  • 带宽: 10Mbps+
  • 操作系统: Linux(Ubuntu 20.04+)

生产环境部署:

bash

# 1. 使用Nginx反向代理
sudo apt install nginx

# 配置 /etc/nginx/sites-available/cloudbat-webhook
server {
    listen 80;
    server_name your-domain.com;

    location /webhook {
        proxy_pass http://localhost:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

# 2. 启用配置
sudo ln -s /etc/nginx/sites-available/cloudbat-webhook /etc/nginx/sites-enabled/

# 3. 使用Supervisor管理进程
sudo apt install supervisor

# 配置 /etc/supervisor/conf.d/cloudbat-webhook.conf
[program:cloudbat-webhook]
command=/usr/bin/python3 /app/webhook_server.py
directory=/app
autostart=true
autorestart=true
stderr_logfile=/var/log/cloudbat-webhook.err.log
stdout_logfile=/var/log/cloudbat-webhook.out.log

# 4. 启动服务
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start cloudbat-webhook

# 5. 使用Let's Encrypt免费SSL
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d your-domain.com

六、进阶功能:AI质检与数据洞察

6.1 通话质检

Python示例:

python

def analyze_call_quality(self, call_id):
    """
    分析通话质量

    Args:
        call_id: 通话ID

    Returns:
        dict: 质量分析结果
    """
    url = f"{self.base_url}/analysis/quality"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {self.api_key}"
    }

    payload = {
        "app_id": self.app_id,
        "call_id": call_id,
        "analysis_dimensions": [
            "sentiment",  # 情绪分析
            "intent",  # 意图识别
            "compliance",  # 合规检查
            "effectiveness"  # 有效性评估
        ]
    }

    try:
        response = requests.post(url, headers=headers, json=payload, timeout=30)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        return {"error": str(e)}

# 质检分析示例
quality_result = client.analyze_call_quality("call_20260303_1234567890")

print("通话质检结果:")
print(json.dumps(quality_result, indent=2, ensure_ascii=False))

质检结果示例:

json

{
  "code": 200,
  "message": "success",
  "data": {
    "call_id": "call_20260303_1234567890",
    "overall_score": 87.5,
    "dimensions": {
      "sentiment": {
        "score": 72,
        "label": "slightly_negative",
        "segments": [
          {"start": 5, "end": 15, "emotion": "angry", "intensity": 0.8},
          {"start": 20, "end": 30, "emotion": "neutral", "intensity": 0.3}
        ]
      },
      "intent": {
        "primary": "complaint",
        "secondary": ["logistics_query", "refund_request"],
        "confidence": 0.92
      },
      "compliance": {
        "score": 95,
        "violations": [],
        "risk_level": "low"
      },
      "effectiveness": {
        "score": 85,
        "resolution_rate": 0.89,
        "satisfaction": 0.78
      }
    },
    "recommendations": [
      "客户在5-15秒表现出愤怒情绪,建议加强安抚话术",
      "本次通话解决了89%的问题,接近优秀水平",
      "无违规话术,合规性良好"
    ]
  }
}

6.2 数据洞察

Python示例:

python

def get_insights(self, start_date, end_date, metrics=None):
    """
    获取数据洞察

    Args:
        start_date: 开始日期(ISO格式)
        end_date: 结束日期(ISO格式)
        metrics: 指标列表

    Returns:
        dict: 数据洞察结果
    """
    url = f"{self.base_url}/analytics/insights"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {self.api_key}"
    }

    if metrics is None:
        metrics = [
            "call_volume",  # 通话量
            "answer_rate",  # 接通率
            "avg_duration",  # 平均时长
            "sentiment_trend",  # 情绪趋势
            "intent_distribution",  # 意图分布
            "conversion_rate"  # 转化率
        ]

    payload = {
        "app_id": self.app_id,
        "start_date": start_date,
        "end_date": end_date,
        "metrics": metrics,
        "group_by": ["date", "bot_id", "intent"]
    }

    try:
        response = requests.post(url, headers=headers, json=payload, timeout=30)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        return {"error": str(e)}

# 获取数据洞察
insights = client.get_insights(
    start_date="2026-02-01T00:00:00+08:00",
    end_date="2026-03-03T23:59:59+08:00"
)

print("数据洞察结果:")
print(json.dumps(insights, indent=2, ensure_ascii=False))

七、总结

本文完整介绍了云蝠智能API的集成流程,包括:

  1. 快速入门:5分钟完成首次调用
  2. 核心接口:外呼、呼入、状态查询、录音下载
  3. 完整集成:CRM对接、Webhook回调、数据回传
  4. 实战案例:电商智能客服系统完整实现
  5. 进阶功能:AI质检、数据洞察

下一步建议:

  • 申请免费体验:1天免费体验完整功能
  • 阅读完整文档:https://www.ccgpt.net/api/
  • 加入开发者群:获取技术支持

参考资源

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐