Files
你的用户名 237c7802e5
Some checks failed
Deploy / deploy (push) Has been cancelled
Initial commit: Telegram Management System
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>
2025-11-04 15:37:50 +08:00

2911 lines
58 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Telegram 管理系统 API 接口文档
> **版本**: v2.0.0
> **更新时间**: 2024-01-20
> **基础URL**: `https://api.telegram-system.com/v1`
> **维护者**: 开发团队
## 📋 文档目录
- [接口概述](#接口概述)
- [认证机制](#认证机制)
- [通用规范](#通用规范)
- [错误处理](#错误处理)
- [用户认证](#用户认证)
- [账号管理](#账号管理)
- [私信群发](#私信群发)
- [营销中心](#营销中心)
- [权限管理](#权限管理)
- [系统配置](#系统配置)
- [文件管理](#文件管理)
- [实时通信](#实时通信)
---
## 🔍 接口概述
### API特性
- **RESTful风格**: 遵循REST架构设计原则
- **JSON格式**: 所有请求和响应均使用JSON格式
- **统一认证**: 基于JWT的Token认证机制
- **版本控制**: URL路径包含版本号支持向后兼容
- **限流保护**: 每个用户每分钟最多100次请求
- **HTTPS加密**: 生产环境强制使用HTTPS协议
### 支持的HTTP方法
| 方法 | 说明 | 示例 |
| ------ | ------------ | -------------------------- |
| GET | 获取资源 | `GET /api/v1/users` |
| POST | 创建资源 | `POST /api/v1/users` |
| PUT | 更新整个资源 | `PUT /api/v1/users/123` |
| PATCH | 部分更新资源 | `PATCH /api/v1/users/123` |
| DELETE | 删除资源 | `DELETE /api/v1/users/123` |
### 环境地址
| 环境 | 地址 | 说明 |
| -------- | ----------------------------------------- | -------- |
| 开发环境 | `http://localhost:3001/api/v1` | 本地开发 |
| 测试环境 | `https://test-api.telegram-system.com/v1` | 测试验证 |
| 生产环境 | `https://api.telegram-system.com/v1` | 正式环境 |
---
## 🔐 认证机制
### JWT Token认证
所有需要认证的接口必须在请求头中携带Token
```http
Authorization: Bearer <your-jwt-token>
```
### Token获取流程
```mermaid
sequenceDiagram
participant C as Client
participant A as API Server
participant D as Database
C->>A: POST /auth/login (username, password)
A->>D: 验证用户凭据
D-->>A: 返回用户信息
A->>A: 生成JWT Token
A-->>C: 返回Token和用户信息
Note over C: 后续请求携带Token
C->>A: GET /users (Header: Authorization)
A->>A: 验证Token有效性
A-->>C: 返回数据
```
### Token结构
JWT Token包含以下信息
```json
{
"header": {
"alg": "HS256",
"typ": "JWT"
},
"payload": {
"userId": "user123",
"username": "admin",
"roles": ["admin", "user"],
"permissions": ["user:read", "user:write"],
"iat": 1642780800,
"exp": 1642867200
}
}
```
---
## 📝 通用规范
### 请求格式
#### Content-Type
所有POST、PUT、PATCH请求必须设置正确的Content-Type
```http
Content-Type: application/json
```
#### 分页参数
支持分页的接口使用统一的分页参数:
```json
{
"page": 1, // 页码从1开始
"pageSize": 20, // 每页数量默认20最大100
"sortBy": "createdAt", // 排序字段
"sortOrder": "desc" // 排序方向asc/desc
}
```
#### 筛选参数
支持筛选的接口使用统一的筛选格式:
```json
{
"filters": {
"status": "active", // 精确匹配
"name": { "$like": "admin" }, // 模糊匹配
"createdAt": {
// 范围查询
"$gte": "2024-01-01",
"$lte": "2024-12-31"
}
}
}
```
### 响应格式
#### 成功响应
```json
{
"success": true,
"code": 200,
"message": "操作成功",
"data": {
// 具体数据
},
"timestamp": "2024-01-20T10:30:00Z"
}
```
#### 分页响应
```json
{
"success": true,
"code": 200,
"message": "获取成功",
"data": {
"items": [...],
"pagination": {
"page": 1,
"pageSize": 20,
"total": 100,
"totalPages": 5
}
},
"timestamp": "2024-01-20T10:30:00Z"
}
```
---
## ❌ 错误处理
### 错误响应格式
```json
{
"success": false,
"code": 400,
"message": "请求参数错误",
"error": {
"type": "ValidationError",
"details": [
{
"field": "email",
"message": "邮箱格式不正确"
}
]
},
"timestamp": "2024-01-20T10:30:00Z",
"requestId": "req-123456789"
}
```
### HTTP状态码
| 状态码 | 说明 | 示例场景 |
| ------ | -------------- | ---------------- |
| 200 | 操作成功 | 数据获取成功 |
| 201 | 创建成功 | 用户创建成功 |
| 400 | 请求参数错误 | 参数格式不正确 |
| 401 | 未认证 | Token无效或过期 |
| 403 | 权限不足 | 没有访问权限 |
| 404 | 资源不存在 | 用户不存在 |
| 409 | 资源冲突 | 用户名已存在 |
| 422 | 数据验证失败 | 业务规则验证失败 |
| 429 | 请求过于频繁 | 超出限流阈值 |
| 500 | 内部服务器错误 | 系统异常 |
### 错误类型
| 错误类型 | 说明 | 示例 |
| ------------------- | ------------ | -------------- |
| ValidationError | 数据验证错误 | 邮箱格式不正确 |
| AuthenticationError | 认证错误 | Token无效 |
| AuthorizationError | 授权错误 | 权限不足 |
| NotFoundError | 资源不存在 | 用户不存在 |
| ConflictError | 资源冲突 | 用户名重复 |
| BusinessError | 业务逻辑错误 | 余额不足 |
| SystemError | 系统错误 | 数据库连接失败 |
---
## 👤 用户认证
### 用户登录
#### 接口信息
- **URL**: `/auth/login`
- **方法**: `POST`
- **认证**: 无需认证
#### 请求参数
```json
{
"username": "admin", // 用户名,必填
"password": "123456", // 密码,必填
"rememberMe": true, // 记住我可选默认false
"captcha": "ABCD", // 验证码,可选
"captchaId": "cap123" // 验证码ID可选
}
```
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "登录成功",
"data": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "refresh-token-here",
"expiresIn": 7200,
"user": {
"id": "user123",
"username": "admin",
"email": "admin@example.com",
"profile": {
"firstName": "管理员",
"lastName": "",
"avatar": "https://example.com/avatar.jpg"
},
"roles": ["admin"],
"permissions": ["*"],
"lastLogin": "2024-01-20T10:30:00Z"
}
}
}
```
#### 错误示例
```json
{
"success": false,
"code": 401,
"message": "用户名或密码错误",
"error": {
"type": "AuthenticationError",
"details": []
}
}
```
### 用户登出
#### 接口信息
- **URL**: `/auth/logout`
- **方法**: `POST`
- **认证**: 需要Token
#### 请求参数
```json
{
"refreshToken": "refresh-token-here" // 可选提供则同时注销refresh token
}
```
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "登出成功"
}
```
### 刷新Token
#### 接口信息
- **URL**: `/auth/refresh`
- **方法**: `POST`
- **认证**: 需要Refresh Token
#### 请求参数
```json
{
"refreshToken": "your-refresh-token"
}
```
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "Token刷新成功",
"data": {
"token": "new-jwt-token",
"refreshToken": "new-refresh-token",
"expiresIn": 7200
}
}
```
### 获取当前用户信息
#### 接口信息
- **URL**: `/auth/me`
- **方法**: `GET`
- **认证**: 需要Token
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "获取成功",
"data": {
"id": "user123",
"username": "admin",
"email": "admin@example.com",
"profile": {
"firstName": "管理员",
"lastName": "",
"avatar": "https://example.com/avatar.jpg",
"phone": "13800138000"
},
"roles": ["admin"],
"permissions": ["*"],
"settings": {
"language": "zh-CN",
"timezone": "Asia/Shanghai",
"theme": "light"
},
"status": "active",
"lastLogin": "2024-01-20T10:30:00Z",
"createdAt": "2024-01-01T00:00:00Z"
}
}
```
---
## 📋 账号管理
### 获取Telegram账号列表
#### 接口信息
- **URL**: `/telegram-accounts`
- **方法**: `GET`
- **认证**: 需要Token
- **权限**: `telegram-account:read`
#### 请求参数
```json
{
"page": 1,
"pageSize": 20,
"sortBy": "createdAt",
"sortOrder": "desc",
"filters": {
"status": "active", // 状态筛选
"username": { "$like": "test" }, // 用户名模糊搜索
"phone": { "$like": "138" }, // 手机号模糊搜索
"createdAt": {
// 创建时间范围
"$gte": "2024-01-01",
"$lte": "2024-12-31"
}
}
}
```
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "获取成功",
"data": {
"items": [
{
"id": "acc123",
"telegramId": "123456789",
"username": "testuser",
"firstName": "Test",
"lastName": "User",
"phone": "13800138000",
"status": "active",
"isVerified": true,
"isPremium": false,
"languageCode": "zh-CN",
"metadata": {
"joinDate": "2024-01-01",
"lastSeen": "2024-01-20T10:30:00Z",
"messageCount": 150
},
"managedBy": "user123",
"createdAt": "2024-01-01T00:00:00Z",
"updatedAt": "2024-01-20T10:30:00Z"
}
],
"pagination": {
"page": 1,
"pageSize": 20,
"total": 100,
"totalPages": 5
}
}
}
```
### 创建Telegram账号
#### 接口信息
- **URL**: `/telegram-accounts`
- **方法**: `POST`
- **认证**: 需要Token
- **权限**: `telegram-account:create`
#### 请求参数
```json
{
"telegramId": "123456789", // Telegram ID必填
"username": "testuser", // 用户名,可选
"firstName": "Test", // 名字,必填
"lastName": "User", // 姓氏,可选
"phone": "13800138000", // 手机号,可选
"languageCode": "zh-CN", // 语言代码,可选
"metadata": {
// 元数据,可选
"bio": "用户简介",
"location": "北京"
}
}
```
#### 响应数据
```json
{
"success": true,
"code": 201,
"message": "创建成功",
"data": {
"id": "acc123",
"telegramId": "123456789",
"username": "testuser",
"firstName": "Test",
"lastName": "User",
"phone": "13800138000",
"status": "active",
"managedBy": "user123",
"createdAt": "2024-01-20T10:30:00Z"
}
}
```
### 获取账号详情
#### 接口信息
- **URL**: `/telegram-accounts/{id}`
- **方法**: `GET`
- **认证**: 需要Token
- **权限**: `telegram-account:read`
#### URL参数
| 参数 | 类型 | 说明 |
| ---- | ------ | ------ |
| id | String | 账号ID |
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "获取成功",
"data": {
"id": "acc123",
"telegramId": "123456789",
"username": "testuser",
"firstName": "Test",
"lastName": "User",
"phone": "13800138000",
"status": "active",
"isVerified": true,
"isPremium": false,
"languageCode": "zh-CN",
"bio": "用户简介",
"profilePhoto": "https://example.com/photo.jpg",
"metadata": {
"joinDate": "2024-01-01",
"lastSeen": "2024-01-20T10:30:00Z",
"messageCount": 150,
"groupCount": 25,
"contactCount": 100
},
"statistics": {
"sentMessages": 50,
"receivedMessages": 100,
"joinedGroups": 25,
"successRate": 95.5
},
"managedBy": "user123",
"createdAt": "2024-01-01T00:00:00Z",
"updatedAt": "2024-01-20T10:30:00Z"
}
}
```
### 更新账号信息
#### 接口信息
- **URL**: `/telegram-accounts/{id}`
- **方法**: `PUT`
- **认证**: 需要Token
- **权限**: `telegram-account:update`
#### 请求参数
```json
{
"username": "newusername", // 用户名,可选
"firstName": "NewName", // 名字,可选
"lastName": "NewLastName", // 姓氏,可选
"phone": "13900139000", // 手机号,可选
"status": "active", // 状态,可选
"metadata": {
// 元数据,可选
"bio": "新的用户简介",
"location": "上海"
}
}
```
### 删除账号
#### 接口信息
- **URL**: `/telegram-accounts/{id}`
- **方法**: `DELETE`
- **认证**: 需要Token
- **权限**: `telegram-account:delete`
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "删除成功"
}
```
### 批量操作账号
#### 接口信息
- **URL**: `/telegram-accounts/batch`
- **方法**: `POST`
- **认证**: 需要Token
- **权限**: `telegram-account:batch`
#### 请求参数
```json
{
"action": "update_status", // 操作类型update_status, delete, export
"accountIds": ["acc1", "acc2"], // 账号ID列表
"data": {
// 操作数据根据action不同而不同
"status": "inactive"
}
}
```
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "批量操作成功",
"data": {
"total": 2,
"success": 2,
"failed": 0,
"errors": []
}
}
```
---
## 📨 私信群发
### 获取消息模板列表
#### 接口信息
- **URL**: `/message-templates`
- **方法**: `GET`
- **认证**: 需要Token
- **权限**: `message-template:read`
#### 请求参数
```json
{
"page": 1,
"pageSize": 20,
"filters": {
"type": "text", // 模板类型
"name": { "$like": "欢迎" }, // 模板名称搜索
"status": "active" // 状态筛选
}
}
```
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "获取成功",
"data": {
"items": [
{
"id": "tpl123",
"name": "欢迎消息模板",
"type": "text",
"content": "欢迎 {{firstName}} 加入我们!",
"variables": [
{
"name": "firstName",
"type": "string",
"description": "用户名字",
"required": true,
"defaultValue": "朋友"
}
],
"status": "active",
"createdBy": "user123",
"usageCount": 50,
"createdAt": "2024-01-01T00:00:00Z",
"updatedAt": "2024-01-20T10:30:00Z"
}
],
"pagination": {
"page": 1,
"pageSize": 20,
"total": 25,
"totalPages": 2
}
}
}
```
### 创建消息模板
#### 接口信息
- **URL**: `/message-templates`
- **方法**: `POST`
- **认证**: 需要Token
- **权限**: `message-template:create`
#### 请求参数
```json
{
"name": "新用户欢迎", // 模板名称,必填
"type": "text", // 模板类型text, media, sticker
"content": "欢迎 {{firstName}} 加入我们的群组!\n\n感谢您选择我们的服务。",
"variables": [
// 变量定义
{
"name": "firstName",
"type": "string",
"description": "用户名字",
"required": true,
"defaultValue": "朋友"
}
],
"media": {
// 媒体文件type为media时
"type": "photo",
"url": "https://example.com/welcome.jpg",
"caption": "欢迎图片"
}
}
```
### 获取群发任务列表
#### 接口信息
- **URL**: `/message-tasks`
- **方法**: `GET`
- **认证**: 需要Token
- **权限**: `message-task:read`
#### 请求参数
```json
{
"page": 1,
"pageSize": 20,
"sortBy": "createdAt",
"sortOrder": "desc",
"filters": {
"status": "running", // 任务状态
"name": { "$like": "新年" }, // 任务名称搜索
"createdBy": "user123", // 创建者筛选
"createdAt": {
// 创建时间范围
"$gte": "2024-01-01",
"$lte": "2024-12-31"
}
}
}
```
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "获取成功",
"data": {
"items": [
{
"id": "task123",
"name": "新年祝福群发",
"description": "向所有活跃用户发送新年祝福消息",
"template": {
"id": "tpl123",
"name": "新年祝福模板",
"content": "祝 {{firstName}} 新年快乐!"
},
"targetCount": 1000,
"status": "running",
"priority": "normal",
"scheduling": {
"type": "immediate",
"scheduledTime": null,
"recurrence": null
},
"progress": {
"total": 1000,
"sent": 750,
"failed": 10,
"pending": 240,
"percentage": 75.0
},
"statistics": {
"successRate": 98.7,
"averageResponseTime": 2.5,
"errorRate": 1.3
},
"createdBy": "user123",
"createdAt": "2024-01-20T08:00:00Z",
"updatedAt": "2024-01-20T10:30:00Z",
"estimatedCompletion": "2024-01-20T12:00:00Z"
}
],
"pagination": {
"page": 1,
"pageSize": 20,
"total": 50,
"totalPages": 3
}
}
}
```
### 创建群发任务
#### 接口信息
- **URL**: `/message-tasks`
- **方法**: `POST`
- **认证**: 需要Token
- **权限**: `message-task:create`
#### 请求参数
```json
{
"name": "春节祝福活动", // 任务名称,必填
"description": "向所有VIP用户发送春节祝福", // 任务描述,可选
"templateId": "tpl123", // 消息模板ID必填
"targetUsers": {
// 目标用户,必填
"type": "filter", // 选择方式filter, list, all
"filters": {
// 筛选条件
"status": "active",
"isPremium": true,
"lastSeen": {
"$gte": "2024-01-01"
}
},
"userIds": [], // 用户ID列表type为list时
"excludeIds": ["acc456"] // 排除的用户ID
},
"scheduling": {
// 调度设置
"type": "scheduled", // 执行类型immediate, scheduled, recurring
"scheduledTime": "2024-01-25T00:00:00Z", // 定时时间
"timezone": "Asia/Shanghai", // 时区
"recurrence": {
// 重复设置type为recurring时
"frequency": "daily", // 频率daily, weekly, monthly
"interval": 1, // 间隔
"endDate": "2024-02-25" // 结束日期
}
},
"settings": {
// 发送设置
"batchSize": 50, // 批次大小
"interval": 1000, // 发送间隔(毫秒)
"retryCount": 3, // 重试次数
"priority": "high" // 优先级low, normal, high
},
"variables": {
// 全局变量值
"companyName": "我们公司",
"eventDate": "2024-01-25"
}
}
```
#### 响应数据
```json
{
"success": true,
"code": 201,
"message": "任务创建成功",
"data": {
"id": "task123",
"name": "春节祝福活动",
"status": "pending",
"targetCount": 500,
"estimatedDuration": "00:30:00",
"estimatedCompletion": "2024-01-25T00:30:00Z",
"createdAt": "2024-01-20T10:30:00Z"
}
}
```
### 获取任务详情
#### 接口信息
- **URL**: `/message-tasks/{id}`
- **方法**: `GET`
- **认证**: 需要Token
- **权限**: `message-task:read`
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "获取成功",
"data": {
"id": "task123",
"name": "春节祝福活动",
"description": "向所有VIP用户发送春节祝福",
"template": {
"id": "tpl123",
"name": "春节祝福模板",
"content": "祝 {{firstName}} 春节快乐!恭喜发财!",
"type": "text"
},
"targetUsers": {
"type": "filter",
"filters": {
"status": "active",
"isPremium": true
},
"count": 500
},
"status": "running",
"priority": "high",
"scheduling": {
"type": "scheduled",
"scheduledTime": "2024-01-25T00:00:00Z",
"timezone": "Asia/Shanghai"
},
"progress": {
"total": 500,
"sent": 350,
"failed": 5,
"pending": 145,
"percentage": 70.0,
"estimatedRemaining": "00:15:00"
},
"statistics": {
"startTime": "2024-01-25T00:00:00Z",
"lastSentTime": "2024-01-25T00:35:00Z",
"averageResponseTime": 1.8,
"successRate": 98.6,
"errorRate": 1.4,
"throughput": 600 // 每小时发送数量
},
"settings": {
"batchSize": 50,
"interval": 1000,
"retryCount": 3
},
"errors": [
{
"userId": "acc789",
"error": "User blocked bot",
"timestamp": "2024-01-25T00:15:00Z",
"retryCount": 0
}
],
"createdBy": "user123",
"createdAt": "2024-01-20T10:30:00Z",
"updatedAt": "2024-01-25T00:35:00Z"
}
}
```
### 控制任务执行
#### 接口信息
- **URL**: `/message-tasks/{id}/control`
- **方法**: `POST`
- **认证**: 需要Token
- **权限**: `message-task:control`
#### 请求参数
```json
{
"action": "pause" // 操作类型start, pause, resume, cancel, retry
}
```
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "任务已暂停",
"data": {
"taskId": "task123",
"status": "paused",
"timestamp": "2024-01-25T00:40:00Z"
}
}
```
### 获取发送记录
#### 接口信息
- **URL**: `/message-records`
- **方法**: `GET`
- **认证**: 需要Token
- **权限**: `message-record:read`
#### 请求参数
```json
{
"page": 1,
"pageSize": 50,
"filters": {
"taskId": "task123", // 任务ID筛选
"userId": "acc456", // 用户ID筛选
"status": "sent", // 发送状态sent, failed, pending
"sentAt": {
// 发送时间范围
"$gte": "2024-01-25T00:00:00Z",
"$lte": "2024-01-25T23:59:59Z"
}
}
}
```
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "获取成功",
"data": {
"items": [
{
"id": "record123",
"taskId": "task123",
"taskName": "春节祝福活动",
"templateId": "tpl123",
"userId": "acc456",
"userInfo": {
"telegramId": "123456789",
"username": "testuser",
"firstName": "张三",
"lastName": ""
},
"message": {
"type": "text",
"content": "祝 张三 春节快乐!恭喜发财!",
"messageId": "msg789"
},
"status": "sent",
"sentAt": "2024-01-25T00:15:30Z",
"responseTime": 1200, // 响应时间(毫秒)
"retryCount": 0,
"error": null,
"metadata": {
"batchId": "batch001",
"priority": "high"
}
}
],
"pagination": {
"page": 1,
"pageSize": 50,
"total": 500,
"totalPages": 10
},
"summary": {
"totalSent": 450,
"totalFailed": 50,
"successRate": 90.0,
"averageResponseTime": 1800
}
}
}
```
---
## 🎯 营销中心
### 获取营销活动列表
#### 接口信息
- **URL**: `/marketing-campaigns`
- **方法**: `GET`
- **认证**: 需要Token
- **权限**: `marketing-campaign:read`
#### 请求参数
```json
{
"page": 1,
"pageSize": 20,
"filters": {
"status": "active", // 活动状态
"type": "promotion", // 活动类型
"name": { "$like": "双11" }, // 活动名称搜索
"startDate": {
// 开始时间范围
"$gte": "2024-01-01",
"$lte": "2024-12-31"
}
}
}
```
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "获取成功",
"data": {
"items": [
{
"id": "camp123",
"name": "双11购物节活动",
"description": "年度最大促销活动",
"type": "promotion",
"status": "active",
"startDate": "2024-11-01T00:00:00Z",
"endDate": "2024-11-11T23:59:59Z",
"budget": 100000.0,
"targetAudience": {
"totalCount": 50000,
"segments": [
{
"name": "VIP用户",
"count": 5000,
"criteria": {
"isPremium": true,
"purchaseAmount": { "$gte": 1000 }
}
}
]
},
"channels": ["telegram", "email", "sms"],
"metrics": {
"impressions": 45000,
"clicks": 9000,
"conversions": 1800,
"ctr": 20.0, // 点击率
"cvr": 4.0, // 转化率
"roi": 250.0 // 投资回报率
},
"createdBy": "user123",
"createdAt": "2024-10-15T00:00:00Z",
"updatedAt": "2024-11-05T10:30:00Z"
}
],
"pagination": {
"page": 1,
"pageSize": 20,
"total": 30,
"totalPages": 2
}
}
}
```
### 创建营销活动
#### 接口信息
- **URL**: `/marketing-campaigns`
- **方法**: `POST`
- **认证**: 需要Token
- **权限**: `marketing-campaign:create`
#### 请求参数
```json
{
"name": "春节促销活动", // 活动名称,必填
"description": "春节期间特惠促销", // 活动描述,可选
"type": "promotion", // 活动类型promotion, retention, acquisition
"startDate": "2024-01-20T00:00:00Z", // 开始时间,必填
"endDate": "2024-01-30T23:59:59Z", // 结束时间,必填
"budget": 50000.0, // 预算,可选
"targetAudience": {
// 目标受众,必填
"segments": [
{
"name": "活跃用户",
"criteria": {
"status": "active",
"lastSeen": { "$gte": "2024-01-01" },
"messageCount": { "$gte": 10 }
}
}
],
"excludeSegments": [
// 排除的用户群体
{
"name": "已购买用户",
"criteria": {
"hasPurchased": true,
"lastPurchase": { "$gte": "2024-01-01" }
}
}
]
},
"channels": ["telegram", "email"], // 营销渠道
"content": {
// 营销内容
"telegram": {
"templateId": "tpl123",
"variables": {
"discount": "20%",
"validUntil": "2024-01-30"
}
},
"email": {
"subject": "春节特惠来了!",
"templateId": "email_tpl456"
}
},
"scheduling": {
// 调度设置
"strategy": "immediate", // 策略immediate, scheduled, drip
"batchSize": 1000, // 批次大小
"interval": 3600, // 间隔(秒)
"timezone": "Asia/Shanghai"
},
"trackingSettings": {
// 跟踪设置
"enableClickTracking": true,
"enableConversionTracking": true,
"conversionEvents": ["purchase", "signup"],
"attributionWindow": 7 // 归因窗口(天)
}
}
```
### 获取客户分析
#### 接口信息
- **URL**: `/marketing/analytics/customers`
- **方法**: `GET`
- **认证**: 需要Token
- **权限**: `marketing-analytics:read`
#### 请求参数
```json
{
"dateRange": {
"startDate": "2024-01-01",
"endDate": "2024-01-31"
},
"segmentBy": "userType", // 分组维度userType, location, channel
"metrics": ["count", "revenue", "engagement"] // 需要的指标
}
```
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "获取成功",
"data": {
"overview": {
"totalCustomers": 10000,
"newCustomers": 1500,
"activeCustomers": 8500,
"retentionRate": 85.0,
"churnRate": 15.0,
"averageLifetimeValue": 1200.0
},
"segments": [
{
"name": "VIP用户",
"count": 1000,
"percentage": 10.0,
"metrics": {
"averageOrderValue": 500.0,
"purchaseFrequency": 3.2,
"lifetimeValue": 2400.0,
"engagementScore": 95.0
},
"characteristics": {
"avgAge": 35,
"primaryLocation": "北京",
"preferredChannel": "telegram"
}
}
],
"trends": {
"customerGrowth": [
{
"date": "2024-01-01",
"newCustomers": 50,
"totalCustomers": 9500
}
],
"retentionTrend": [
{
"cohort": "2024-01",
"week1": 95.0,
"week2": 87.0,
"week4": 82.0,
"week8": 78.0
}
]
},
"predictions": {
"churnRisk": [
{
"userId": "acc123",
"riskScore": 0.85,
"reasons": ["降低活跃度", "减少购买频率"],
"recommendedActions": ["发送优惠券", "个性化推荐"]
}
],
"lifetimeValuePrediction": {
"next30Days": 150.0,
"next90Days": 380.0,
"confidence": 0.82
}
}
}
}
```
### 获取效果统计
#### 接口信息
- **URL**: `/marketing/analytics/performance`
- **方法**: `GET`
- **认证**: 需要Token
- **权限**: `marketing-analytics:read`
#### 请求参数
```json
{
"campaignId": "camp123", // 活动ID可选
"dateRange": {
"startDate": "2024-01-01",
"endDate": "2024-01-31"
},
"groupBy": "day", // 分组hour, day, week, month
"channels": ["telegram", "email"], // 渠道筛选
"metrics": ["impressions", "clicks", "conversions", "revenue"]
}
```
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "获取成功",
"data": {
"summary": {
"impressions": 100000,
"clicks": 15000,
"conversions": 3000,
"revenue": 150000.0,
"cost": 25000.0,
"ctr": 15.0, // 点击率
"cvr": 20.0, // 转化率
"cpc": 1.67, // 单次点击成本
"cpa": 8.33, // 单次获客成本
"roi": 500.0, // 投资回报率
"roas": 6.0 // 广告支出回报率
},
"byChannel": [
{
"channel": "telegram",
"impressions": 60000,
"clicks": 10000,
"conversions": 2200,
"revenue": 110000.0,
"cost": 15000.0,
"metrics": {
"ctr": 16.7,
"cvr": 22.0,
"roi": 633.3
}
},
{
"channel": "email",
"impressions": 40000,
"clicks": 5000,
"conversions": 800,
"revenue": 40000.0,
"cost": 10000.0,
"metrics": {
"ctr": 12.5,
"cvr": 16.0,
"roi": 300.0
}
}
],
"timeline": [
{
"date": "2024-01-01",
"impressions": 3500,
"clicks": 525,
"conversions": 105,
"revenue": 5250.0
}
],
"topPerforming": {
"campaigns": [
{
"id": "camp123",
"name": "双11购物节",
"conversions": 1500,
"revenue": 75000.0,
"roi": 750.0
}
],
"templates": [
{
"id": "tpl123",
"name": "优惠券模板",
"usage": 50,
"conversionRate": 25.0
}
]
},
"insights": [
{
"type": "opportunity",
"title": "Telegram渠道表现优异",
"description": "Telegram渠道的转化率比邮件高37.5%,建议增加投入",
"impact": "high",
"recommendation": "将预算的60%分配给Telegram渠道"
}
]
}
}
```
---
## 🔒 权限管理
### 获取权限列表
#### 接口信息
- **URL**: `/permissions`
- **方法**: `GET`
- **认证**: 需要Token
- **权限**: `permission:read`
#### 请求参数
```json
{
"page": 1,
"pageSize": 50,
"filters": {
"resource": "user", // 资源类型筛选
"action": "read", // 操作类型筛选
"module": "account-management" // 模块筛选
}
}
```
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "获取成功",
"data": {
"items": [
{
"id": "perm123",
"code": "user:read",
"name": "查看用户",
"description": "查看用户基本信息和列表",
"resource": "user",
"action": "read",
"module": "account-management",
"isSystem": true,
"createdAt": "2024-01-01T00:00:00Z"
},
{
"id": "perm124",
"code": "user:create",
"name": "创建用户",
"description": "创建新的用户账号",
"resource": "user",
"action": "create",
"module": "account-management",
"isSystem": true,
"createdAt": "2024-01-01T00:00:00Z"
}
],
"pagination": {
"page": 1,
"pageSize": 50,
"total": 120,
"totalPages": 3
},
"groupedByModule": {
"account-management": [
{
"resource": "user",
"actions": ["create", "read", "update", "delete"]
},
{
"resource": "telegram-account",
"actions": ["create", "read", "update", "delete", "batch"]
}
],
"message-management": [
{
"resource": "message-template",
"actions": ["create", "read", "update", "delete"]
},
{
"resource": "message-task",
"actions": ["create", "read", "update", "delete", "control"]
}
]
}
}
}
```
### 获取角色列表
#### 接口信息
- **URL**: `/roles`
- **方法**: `GET`
- **认证**: 需要Token
- **权限**: `role:read`
#### 请求参数
```json
{
"page": 1,
"pageSize": 20,
"filters": {
"status": "active", // 状态筛选
"isSystem": false, // 是否系统角色
"name": { "$like": "管理" } // 角色名称搜索
}
}
```
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "获取成功",
"data": {
"items": [
{
"id": "role123",
"name": "账号管理员",
"description": "负责管理Telegram账号",
"code": "account_admin",
"status": "active",
"isSystem": false,
"permissions": [
{
"id": "perm123",
"code": "telegram-account:read",
"name": "查看账号"
},
{
"id": "perm124",
"code": "telegram-account:create",
"name": "创建账号"
}
],
"userCount": 5, // 拥有此角色的用户数量
"createdBy": "user123",
"createdAt": "2024-01-01T00:00:00Z",
"updatedAt": "2024-01-10T10:30:00Z"
}
],
"pagination": {
"page": 1,
"pageSize": 20,
"total": 15,
"totalPages": 1
}
}
}
```
### 创建角色
#### 接口信息
- **URL**: `/roles`
- **方法**: `POST`
- **认证**: 需要Token
- **权限**: `role:create`
#### 请求参数
```json
{
"name": "消息管理员", // 角色名称,必填
"description": "负责管理消息模板和群发任务", // 角色描述,可选
"code": "message_admin", // 角色代码,必填,唯一
"permissions": [
// 权限ID列表必填
"perm201",
"perm202",
"perm203"
],
"inherits": ["role456"], // 继承的角色ID列表可选
"status": "active" // 状态可选默认active
}
```
#### 响应数据
```json
{
"success": true,
"code": 201,
"message": "角色创建成功",
"data": {
"id": "role789",
"name": "消息管理员",
"description": "负责管理消息模板和群发任务",
"code": "message_admin",
"status": "active",
"permissions": [
{
"id": "perm201",
"code": "message-template:create",
"name": "创建消息模板"
}
],
"createdBy": "user123",
"createdAt": "2024-01-20T10:30:00Z"
}
}
```
### 分配用户角色
#### 接口信息
- **URL**: `/users/{userId}/roles`
- **方法**: `POST`
- **认证**: 需要Token
- **权限**: `user:assign-role`
#### 请求参数
```json
{
"roleIds": ["role123", "role456"], // 角色ID列表
"action": "assign" // 操作类型assign, revoke, replace
}
```
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "角色分配成功",
"data": {
"userId": "user456",
"roles": [
{
"id": "role123",
"name": "账号管理员",
"assignedAt": "2024-01-20T10:30:00Z"
},
{
"id": "role456",
"name": "消息管理员",
"assignedAt": "2024-01-20T10:30:00Z"
}
]
}
}
```
### 检查用户权限
#### 接口信息
- **URL**: `/auth/check-permission`
- **方法**: `POST`
- **认证**: 需要Token
#### 请求参数
```json
{
"permissions": [
// 需要检查的权限列表
"telegram-account:read",
"message-task:create"
],
"resource": {
// 资源信息(可选,用于资源级权限控制)
"type": "telegram-account",
"id": "acc123",
"ownerId": "user456"
}
}
```
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "权限检查完成",
"data": {
"hasAllPermissions": false,
"permissions": {
"telegram-account:read": true,
"message-task:create": false
},
"missingPermissions": ["message-task:create"],
"userId": "user123",
"checkedAt": "2024-01-20T10:30:00Z"
}
}
```
---
## ⚙️ 系统配置
### 获取系统配置
#### 接口信息
- **URL**: `/system/config`
- **方法**: `GET`
- **认证**: 需要Token
- **权限**: `system-config:read`
#### 请求参数
```json
{
"category": "telegram", // 配置分类telegram, email, sms, system
"keys": ["api_token", "rate_limit"] // 指定配置键,可选
}
```
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "获取成功",
"data": {
"telegram": {
"api_token": {
"value": "***masked***",
"type": "password",
"description": "Telegram Bot API Token",
"updatedAt": "2024-01-20T10:30:00Z",
"updatedBy": "user123"
},
"rate_limit": {
"value": 30,
"type": "number",
"description": "每秒最大请求数",
"min": 1,
"max": 50,
"updatedAt": "2024-01-15T08:00:00Z",
"updatedBy": "user123"
},
"webhook_url": {
"value": "https://api.example.com/webhook/telegram",
"type": "url",
"description": "Webhook回调地址",
"updatedAt": "2024-01-10T12:00:00Z",
"updatedBy": "user123"
}
},
"system": {
"site_name": {
"value": "Telegram管理系统",
"type": "string",
"description": "系统名称"
},
"max_file_size": {
"value": 10485760,
"type": "number",
"description": "最大文件上传大小(字节)",
"min": 1048576,
"max": 104857600
},
"default_language": {
"value": "zh-CN",
"type": "select",
"description": "默认语言",
"options": [
{ "value": "zh-CN", "label": "简体中文" },
{ "value": "en-US", "label": "English" }
]
}
}
}
}
```
### 更新系统配置
#### 接口信息
- **URL**: `/system/config`
- **方法**: `PUT`
- **认证**: 需要Token
- **权限**: `system-config:update`
#### 请求参数
```json
{
"telegram": {
"rate_limit": 25,
"webhook_url": "https://new-api.example.com/webhook/telegram"
},
"system": {
"site_name": "新的系统名称",
"max_file_size": 20971520
}
}
```
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "配置更新成功",
"data": {
"updated": [
{
"key": "telegram.rate_limit",
"oldValue": 30,
"newValue": 25
},
{
"key": "system.site_name",
"oldValue": "Telegram管理系统",
"newValue": "新的系统名称"
}
],
"updatedBy": "user123",
"updatedAt": "2024-01-20T10:30:00Z"
}
}
```
### 获取系统统计
#### 接口信息
- **URL**: `/system/statistics`
- **方法**: `GET`
- **认证**: 需要Token
- **权限**: `system:read`
#### 请求参数
```json
{
"dateRange": {
"startDate": "2024-01-01",
"endDate": "2024-01-31"
},
"metrics": ["users", "messages", "tasks", "performance"] // 需要的统计指标
}
```
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "获取成功",
"data": {
"overview": {
"totalUsers": 1500,
"activeUsers": 1200,
"totalAccounts": 50000,
"activeAccounts": 45000,
"totalMessages": 1000000,
"totalTasks": 500,
"systemUptime": "99.9%"
},
"users": {
"newUsers": 150,
"activeUsers": 1200,
"userGrowthRate": 11.1,
"userRetentionRate": 85.0,
"averageSessionDuration": 1800, // 秒
"byRole": {
"admin": 5,
"manager": 50,
"operator": 1145
}
},
"messages": {
"totalSent": 800000,
"totalFailed": 50000,
"successRate": 94.1,
"averageResponseTime": 1500, // 毫秒
"byChannel": {
"telegram": 700000,
"email": 100000,
"sms": 50000
},
"byType": {
"marketing": 600000,
"notification": 200000,
"support": 50000
}
},
"tasks": {
"totalCreated": 500,
"completed": 450,
"failed": 30,
"running": 20,
"successRate": 90.0,
"averageExecutionTime": 3600, // 秒
"byPriority": {
"high": 100,
"normal": 350,
"low": 50
}
},
"performance": {
"cpuUsage": 45.2,
"memoryUsage": 68.5,
"diskUsage": 72.1,
"networkIO": {
"inbound": 1024000, // bytes/sec
"outbound": 2048000
},
"databaseConnections": {
"active": 15,
"idle": 5,
"total": 20
},
"cacheHitRate": 95.5,
"averageApiResponseTime": 150 // 毫秒
},
"trends": [
{
"date": "2024-01-01",
"users": 1350,
"messages": 25000,
"tasks": 15
},
{
"date": "2024-01-02",
"users": 1355,
"messages": 26000,
"tasks": 18
}
]
}
}
```
---
## 📁 文件管理
### 上传文件
#### 接口信息
- **URL**: `/files/upload`
- **方法**: `POST`
- **认证**: 需要Token
- **权限**: `file:upload`
- **Content-Type**: `multipart/form-data`
#### 请求参数
```form-data
file: (binary) // 文件内容,必填
category: "avatar" // 文件分类avatar, document, image, video
description: "用户头像" // 文件描述,可选
isPublic: true // 是否公开可选默认false
```
#### 响应数据
```json
{
"success": true,
"code": 201,
"message": "文件上传成功",
"data": {
"id": "file123",
"filename": "avatar.jpg",
"originalName": "user-avatar.jpg",
"size": 102400,
"mimeType": "image/jpeg",
"category": "avatar",
"isPublic": true,
"url": "https://cdn.example.com/files/avatar.jpg",
"thumbnailUrl": "https://cdn.example.com/thumbs/avatar_thumb.jpg",
"metadata": {
"width": 300,
"height": 300,
"format": "JPEG",
"colorSpace": "sRGB"
},
"uploadedBy": "user123",
"uploadedAt": "2024-01-20T10:30:00Z",
"expiresAt": null
}
}
```
### 获取文件列表
#### 接口信息
- **URL**: `/files`
- **方法**: `GET`
- **认证**: 需要Token
- **权限**: `file:read`
#### 请求参数
```json
{
"page": 1,
"pageSize": 20,
"filters": {
"category": "image", // 文件分类筛选
"mimeType": "image/jpeg", // MIME类型筛选
"uploadedBy": "user123", // 上传者筛选
"uploadedAt": {
// 上传时间范围
"$gte": "2024-01-01",
"$lte": "2024-01-31"
},
"filename": { "$like": "avatar" } // 文件名搜索
}
}
```
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "获取成功",
"data": {
"items": [
{
"id": "file123",
"filename": "avatar.jpg",
"originalName": "user-avatar.jpg",
"size": 102400,
"mimeType": "image/jpeg",
"category": "avatar",
"isPublic": true,
"url": "https://cdn.example.com/files/avatar.jpg",
"thumbnailUrl": "https://cdn.example.com/thumbs/avatar_thumb.jpg",
"downloadCount": 25,
"uploadedBy": "user123",
"uploadedAt": "2024-01-20T10:30:00Z"
}
],
"pagination": {
"page": 1,
"pageSize": 20,
"total": 150,
"totalPages": 8
},
"summary": {
"totalSize": 52428800, // 总文件大小(字节)
"totalCount": 150,
"byCategory": {
"image": 80,
"document": 50,
"video": 20
},
"storageUsed": "50.0MB",
"storageLimit": "1.0GB",
"storageUsedPercentage": 5.0
}
}
}
```
### 获取文件详情
#### 接口信息
- **URL**: `/files/{id}`
- **方法**: `GET`
- **认证**: 需要Token
- **权限**: `file:read`
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "获取成功",
"data": {
"id": "file123",
"filename": "document.pdf",
"originalName": "重要文档.pdf",
"size": 2048000,
"mimeType": "application/pdf",
"category": "document",
"description": "项目需求文档",
"isPublic": false,
"url": "https://cdn.example.com/files/document.pdf",
"downloadUrl": "https://api.example.com/files/file123/download",
"metadata": {
"pages": 25,
"author": "作者名",
"title": "项目需求文档",
"createdDate": "2024-01-15T00:00:00Z"
},
"accessLog": [
{
"userId": "user456",
"action": "download",
"timestamp": "2024-01-20T09:00:00Z",
"ip": "192.168.1.100"
}
],
"downloadCount": 15,
"uploadedBy": "user123",
"uploadedAt": "2024-01-15T14:30:00Z",
"updatedAt": "2024-01-20T10:30:00Z",
"expiresAt": "2024-12-31T23:59:59Z"
}
}
```
### 下载文件
#### 接口信息
- **URL**: `/files/{id}/download`
- **方法**: `GET`
- **认证**: 需要Token
- **权限**: `file:download`
#### URL参数
| 参数 | 类型 | 说明 |
| ---- | ------ | ------ |
| id | String | 文件ID |
#### Query参数
| 参数 | 类型 | 说明 |
| --------- | ------- | -------------------------- |
| thumbnail | Boolean | 是否下载缩略图 |
| download | Boolean | 是否强制下载(设置下载头) |
#### 响应
成功时返回文件二进制内容,响应头包含:
```http
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="filename.ext"
Content-Length: 1024000
Cache-Control: private, max-age=3600
```
### 删除文件
#### 接口信息
- **URL**: `/files/{id}`
- **方法**: `DELETE`
- **认证**: 需要Token
- **权限**: `file:delete`
#### 响应数据
```json
{
"success": true,
"code": 200,
"message": "文件删除成功",
"data": {
"id": "file123",
"filename": "deleted-file.jpg",
"deletedAt": "2024-01-20T10:30:00Z",
"deletedBy": "user123"
}
}
```
---
## 🔄 实时通信
### WebSocket连接
#### 连接信息
- **URL**: `wss://api.example.com/ws`
- **协议**: WebSocket
- **认证**: 连接时需要传递Token
#### 连接参数
```javascript
const ws = new WebSocket('wss://api.example.com/ws', {
headers: {
Authorization: 'Bearer your-jwt-token',
},
});
// 或通过查询参数
const ws = new WebSocket('wss://api.example.com/ws?token=your-jwt-token');
```
#### 连接事件
```javascript
ws.onopen = function (event) {
console.log('WebSocket连接已建立');
// 发送认证消息
ws.send(
JSON.stringify({
type: 'auth',
token: 'your-jwt-token',
}),
);
};
ws.onmessage = function (event) {
const message = JSON.parse(event.data);
console.log('收到消息:', message);
};
ws.onclose = function (event) {
console.log('WebSocket连接已关闭:', event.code, event.reason);
};
ws.onerror = function (error) {
console.error('WebSocket错误:', error);
};
```
### 消息格式
#### 通用消息结构
```json
{
"type": "message_type", // 消息类型
"id": "msg123", // 消息ID可选
"timestamp": "2024-01-20T10:30:00Z", // 时间戳
"data": {
// 消息数据
// 具体内容根据消息类型不同
}
}
```
#### 认证消息
```json
{
"type": "auth",
"token": "your-jwt-token"
}
```
#### 认证响应
```json
{
"type": "auth_result",
"success": true,
"message": "认证成功",
"userId": "user123",
"sessionId": "session456"
}
```
### 订阅频道
#### 订阅消息
```json
{
"type": "subscribe",
"channels": [
"user.user123", // 用户个人频道
"task.task456", // 特定任务频道
"system.notifications", // 系统通知频道
"global.announcements" // 全局公告频道
]
}
```
#### 订阅响应
```json
{
"type": "subscribe_result",
"success": true,
"channels": [
{
"name": "user.user123",
"status": "subscribed"
},
{
"name": "task.task456",
"status": "subscribed"
}
]
}
```
#### 取消订阅
```json
{
"type": "unsubscribe",
"channels": ["task.task456"]
}
```
### 实时消息类型
#### 1. 任务进度更新
```json
{
"type": "task_progress",
"timestamp": "2024-01-20T10:30:00Z",
"data": {
"taskId": "task123",
"taskName": "春节祝福活动",
"progress": {
"total": 1000,
"sent": 750,
"failed": 10,
"pending": 240,
"percentage": 75.0
},
"estimatedCompletion": "2024-01-20T12:00:00Z",
"currentRate": 50 // 每分钟发送数量
}
}
```
#### 2. 任务状态变更
```json
{
"type": "task_status_change",
"timestamp": "2024-01-20T10:30:00Z",
"data": {
"taskId": "task123",
"taskName": "春节祝福活动",
"oldStatus": "running",
"newStatus": "completed",
"reason": "任务执行完成",
"statistics": {
"duration": 7200, // 执行时长(秒)
"totalSent": 990,
"totalFailed": 10,
"successRate": 99.0
}
}
}
```
#### 3. 系统通知
```json
{
"type": "system_notification",
"timestamp": "2024-01-20T10:30:00Z",
"data": {
"id": "notify123",
"title": "系统维护通知",
"message": "系统将在今晚22:00-24:00进行维护期间服务可能中断",
"level": "warning", // 级别info, warning, error, success
"category": "maintenance",
"targetUsers": ["user123", "user456"], // 目标用户null表示所有用户
"actions": [
{
"text": "查看详情",
"url": "/system/maintenance-notice"
}
],
"expiresAt": "2024-01-21T00:00:00Z"
}
}
```
#### 4. 用户在线状态
```json
{
"type": "user_status",
"timestamp": "2024-01-20T10:30:00Z",
"data": {
"userId": "user456",
"username": "testuser",
"status": "online", // 状态online, offline, away, busy
"lastSeen": "2024-01-20T10:30:00Z",
"device": "web" // 设备类型web, mobile, desktop
}
}
```
#### 5. 实时日志
```json
{
"type": "log_message",
"timestamp": "2024-01-20T10:30:00Z",
"data": {
"level": "error", // 日志级别debug, info, warn, error
"message": "消息发送失败: 用户已屏蔽机器人",
"source": "message-service",
"userId": "user123",
"taskId": "task456",
"context": {
"telegramId": "123456789",
"errorCode": "BLOCKED_BY_USER"
}
}
}
```
#### 6. 性能指标
```json
{
"type": "performance_metrics",
"timestamp": "2024-01-20T10:30:00Z",
"data": {
"cpu": 45.2, // CPU使用率
"memory": 68.5, // 内存使用率
"disk": 72.1, // 磁盘使用率
"network": {
"inbound": 1024, // 入站流量 KB/s
"outbound": 2048 // 出站流量 KB/s
},
"database": {
"connections": 15,
"queryTime": 150 // 平均查询时间(毫秒)
},
"activeUsers": 120,
"activeTasks": 5,
"messageRate": 50 // 每分钟消息数
}
}
```
### 心跳机制
#### 心跳消息
客户端每30秒发送一次心跳
```json
{
"type": "ping",
"timestamp": "2024-01-20T10:30:00Z"
}
```
#### 心跳响应
服务器响应心跳:
```json
{
"type": "pong",
"timestamp": "2024-01-20T10:30:00Z",
"serverTime": "2024-01-20T10:30:05Z"
}
```
### 错误处理
#### 错误消息格式
```json
{
"type": "error",
"timestamp": "2024-01-20T10:30:00Z",
"error": {
"code": "INVALID_TOKEN",
"message": "Token无效或已过期",
"details": {}
}
}
```
#### 常见错误代码
| 错误代码 | 说明 | 处理建议 |
| ------------------- | ------------ | -------------------- |
| INVALID_TOKEN | Token无效 | 重新登录获取新Token |
| TOKEN_EXPIRED | Token过期 | 刷新Token或重新登录 |
| PERMISSION_DENIED | 权限不足 | 检查用户权限设置 |
| RATE_LIMIT_EXCEEDED | 请求频率过高 | 减少请求频率 |
| CHANNEL_NOT_FOUND | 频道不存在 | 检查频道名称是否正确 |
| CONNECTION_LOST | 连接丢失 | 尝试重新连接 |
### 重连机制
#### 自动重连示例
```javascript
class WebSocketClient {
constructor(url, token) {
this.url = url;
this.token = token;
this.reconnectAttempts = 0;
this.maxReconnectAttempts = 5;
this.reconnectInterval = 1000; // 初始重连间隔
this.connect();
}
connect() {
this.ws = new WebSocket(this.url);
this.ws.onopen = () => {
console.log('Connected to WebSocket');
this.reconnectAttempts = 0;
this.reconnectInterval = 1000;
// 发送认证消息
this.authenticate();
};
this.ws.onmessage = (event) => {
const message = JSON.parse(event.data);
this.handleMessage(message);
};
this.ws.onclose = (event) => {
console.log('WebSocket connection closed:', event.code);
this.handleReconnect();
};
this.ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
}
authenticate() {
this.send({
type: 'auth',
token: this.token,
});
}
handleReconnect() {
if (this.reconnectAttempts < this.maxReconnectAttempts) {
this.reconnectAttempts++;
console.log(
`Attempting to reconnect (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`,
);
setTimeout(() => {
this.connect();
}, this.reconnectInterval);
// 指数退避策略
this.reconnectInterval = Math.min(this.reconnectInterval * 2, 30000);
} else {
console.error('Max reconnection attempts reached');
}
}
send(message) {
if (this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(message));
} else {
console.warn('WebSocket is not connected');
}
}
handleMessage(message) {
switch (message.type) {
case 'auth_result':
if (message.success) {
console.log('Authentication successful');
this.subscribeToChannels();
} else {
console.error('Authentication failed:', message.message);
}
break;
case 'task_progress':
this.onTaskProgress(message.data);
break;
case 'system_notification':
this.onSystemNotification(message.data);
break;
case 'error':
this.onError(message.error);
break;
default:
console.log('Received message:', message);
}
}
subscribeToChannels() {
this.send({
type: 'subscribe',
channels: [`user.${this.userId}`, 'system.notifications'],
});
}
onTaskProgress(data) {
// 处理任务进度更新
console.log('Task progress:', data);
}
onSystemNotification(data) {
// 处理系统通知
console.log('System notification:', data);
}
onError(error) {
console.error('WebSocket error:', error);
if (error.code === 'INVALID_TOKEN') {
// Token无效需要重新登录
this.handleTokenError();
}
}
handleTokenError() {
// 处理Token错误通常需要重新登录
window.location.href = '/login';
}
}
// 使用示例
const wsClient = new WebSocketClient('wss://api.example.com/ws', userToken);
```
---
## 📚 附录
### API变更历史
#### v2.0.0 (2024-01-20)
- 新增营销中心相关接口
- 新增WebSocket实时通信
- 优化权限管理接口
- 增加文件管理功能
#### v1.2.0 (2023-12-15)
- 新增批量操作接口
- 优化分页查询性能
- 增加更多筛选条件
#### v1.1.0 (2023-11-20)
- 新增消息模板管理
- 增加任务调度功能
- 完善错误处理机制
#### v1.0.0 (2023-10-01)
- 初始版本发布
- 基础的用户认证和账号管理
- 简单的消息发送功能
### SDK与示例
#### JavaScript SDK
```javascript
// 安装: npm install telegram-system-sdk
import TelegramSystemSDK from 'telegram-system-sdk';
const client = new TelegramSystemSDK({
baseURL: 'https://api.example.com/v1',
token: 'your-jwt-token',
});
// 获取账号列表
const accounts = await client.accounts.list({
page: 1,
pageSize: 20,
filters: { status: 'active' },
});
// 创建群发任务
const task = await client.messages.createTask({
name: '新年祝福',
templateId: 'tpl123',
targetUsers: { type: 'all' },
});
// 监听实时事件
client.on('task_progress', (data) => {
console.log('任务进度更新:', data);
});
```
#### Python SDK
```python
# 安装: pip install telegram-system-sdk
from telegram_system_sdk import TelegramSystemClient
client = TelegramSystemClient(
base_url='https://api.example.com/v1',
token='your-jwt-token'
)
# 获取账号列表
accounts = client.accounts.list(
page=1,
page_size=20,
filters={'status': 'active'}
)
# 创建消息模板
template = client.templates.create({
'name': '欢迎模板',
'type': 'text',
'content': '欢迎 {{firstName}} 加入!'
})
```
### 测试环境
#### Postman集合
提供完整的Postman集合文件包含所有接口的示例请求
```json
{
"info": {
"name": "Telegram管理系统API",
"description": "完整的API接口测试集合",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "{{access_token}}",
"type": "string"
}
]
},
"variable": [
{
"key": "base_url",
"value": "https://api.example.com/v1"
}
]
}
```
#### 测试数据
提供用于测试的示例数据:
```json
{
"testUsers": [
{
"username": "test_admin",
"password": "test123456",
"roles": ["admin"]
},
{
"username": "test_operator",
"password": "test123456",
"roles": ["operator"]
}
],
"testAccounts": [
{
"telegramId": "123456789",
"username": "testuser1",
"firstName": "测试",
"lastName": "用户1"
}
],
"testTemplates": [
{
"name": "测试模板",
"type": "text",
"content": "这是一个测试消息模板,用户名:{{firstName}}"
}
]
}
```
---
## 🤝 支持与反馈
### 技术支持
- **文档地址**: https://docs.telegram-system.com
- **API控制台**: https://console.telegram-system.com
- **状态页面**: https://status.telegram-system.com
### 联系方式
- **技术支持邮箱**: support@telegram-system.com
- **开发者邮箱**: dev@telegram-system.com
- **问题反馈**: https://github.com/telegram-system/api/issues
### 更新通知
关注API更新和维护通知
- **邮件订阅**: api-updates@telegram-system.com
- **Webhook通知**: 可配置Webhook接收API变更通知
- **版本发布**: 关注GitHub Release页面
---
**最后更新**: 2024-01-20
**文档版本**: v2.0.0
**API版本**: v1
> 本文档将随着API的演进持续更新请定期查看最新版本。如有疑问或建议欢迎通过上述渠道联系我们。