纸飞机消息API提供了一套完整的消息发送、接收和管理功能,支持多种消息类型,包括文本、图片、视频、音频、文件、位置等。API采用RESTful设计,同时提供WebSocket接口用于实时消息推送。
所有消息API端点都需要使用HTTPS协议,并在请求头中包含有效的访问令牌。
纸飞机消息的典型生命周期包括:
纸飞机支持多种消息类型,每种类型都有特定的数据结构和处理方式。
| 类型 | 类型ID | 描述 |
|---|---|---|
| 文本消息 | text | 纯文本消息,支持基本格式化 |
| 图片消息 | photo | 图片文件,支持缩略图 |
| 视频消息 | video | 视频文件,支持缩略图和时长信息 |
| 音频消息 | audio | 音频文件,支持时长信息 |
| 文件消息 | document | 任意类型的文件 |
| 位置消息 | location | 地理位置信息 |
| 联系人消息 | contact | 联系人信息 |
| 语音通话 | voice_call | 语音通话邀请 |
| 视频通话 | video_call | 视频通话邀请 |
| 贴纸消息 | sticker | 表情贴纸 |
| 投票消息 | poll | 投票和调查 |
| 引用回复 | reply | 引用并回复特定消息 |
所有消息都包含以下基本字段:
{
"id": "msg1234567890",
"chat_id": "chat1234567890",
"sender_id": "user1234567890",
"type": "text",
"content": {
// 根据消息类型不同而变化
},
"timestamp": 1625097600000,
"status": "read",
"edited": false,
"forwarded": false,
"reply_to_message_id": null,
"expire_in": 0
}
消息内容在传输和存储过程中都是端到端加密的,服务器无法查看消息的实际内容。
所有消息API的基础URL为:https://api.paperplane.com/v8/messages
发送新消息到指定的聊天会话。
POST /messages/send
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json
{
"chat_id": "chat1234567890",
"type": "text",
"content": {
"text": "Hello, this is a test message!"
},
"reply_to_message_id": null,
"expire_in": 0,
"disable_notification": false
}
{
"ok": true,
"result": {
"id": "msg1234567890",
"chat_id": "chat1234567890",
"sender_id": "user1234567890",
"type": "text",
"content": {
"text": "Hello, this is a test message!"
},
"timestamp": 1625097600000,
"status": "sent",
"edited": false,
"forwarded": false,
"reply_to_message_id": null,
"expire_in": 0
}
}
POST /messages/send
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json
{
"chat_id": "chat1234567890",
"type": "photo",
"content": {
"file_id": "file1234567890",
"caption": "Check out this photo!",
"width": 1280,
"height": 720
}
}
获取指定聊天会话的消息列表。
GET /messages?chat_id=chat1234567890&limit=50&offset=0 Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
| 参数 | 类型 | 必需 | 描述 |
|---|---|---|---|
| chat_id | string | 是 | 聊天会话ID |
| limit | integer | 否 | 返回消息的最大数量,默认50,最大100 |
| offset | integer | 否 | 偏移量,用于分页 |
| before | string | 否 | 返回此消息ID之前的消息 |
| after | string | 否 | 返回此消息ID之后的消息 |
| search | string | 否 | 搜索关键词 |
{
"ok": true,
"result": {
"messages": [
{
"id": "msg1234567890",
"chat_id": "chat1234567890",
"sender_id": "user1234567890",
"type": "text",
"content": {
"text": "Hello, this is a test message!"
},
"timestamp": 1625097600000,
"status": "read",
"edited": false,
"forwarded": false,
"reply_to_message_id": null,
"expire_in": 0
},
// 更多消息...
],
"total_count": 120,
"has_more": true
}
}
更新已发送的消息内容(仅支持文本消息)。
PUT /messages/{message_id}
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json
{
"content": {
"text": "This is the updated message content!"
}
}
{
"ok": true,
"result": {
"id": "msg1234567890",
"chat_id": "chat1234567890",
"sender_id": "user1234567890",
"type": "text",
"content": {
"text": "This is the updated message content!"
},
"timestamp": 1625097600000,
"edit_timestamp": 1625098000000,
"status": "read",
"edited": true,
"forwarded": false,
"reply_to_message_id": null,
"expire_in": 0
}
}
消息更新后,所有接收方都会看到更新后的内容,并会显示消息已被编辑的标记。
删除已发送的消息。
DELETE /messages/{message_id}
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json
{
"delete_for_all": true
}
| 参数 | 类型 | 必需 | 描述 |
|---|---|---|---|
| delete_for_all | boolean | 否 | 是否为所有人删除消息,默认为false(仅自己) |
{
"ok": true,
"result": {
"message_id": "msg1234567890",
"deleted": true,
"deleted_for_all": true
}
}
为所有人删除消息的功能有时间限制,通常只能在发送后48小时内使用。
转发消息到其他聊天会话。
POST /messages/forward
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json
{
"message_id": "msg1234567890",
"chat_id": "chat9876543210",
"disable_notification": false
}
{
"ok": true,
"result": {
"id": "msg9876543210",
"chat_id": "chat9876543210",
"sender_id": "user1234567890",
"type": "text",
"content": {
"text": "Hello, this is a test message!"
},
"timestamp": 1625099000000,
"status": "sent",
"edited": false,
"forwarded": true,
"forward_from": {
"message_id": "msg1234567890",
"chat_id": "chat1234567890",
"sender_id": "user1234567890",
"sender_name": "John Doe"
},
"reply_to_message_id": null,
"expire_in": 0
}
}
纸飞机提供WebSocket接口,用于实时接收消息和更新消息状态。
wss://api.paperplane.com/v8/ws?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
| 事件类型 | 描述 |
|---|---|
| message | 收到新消息 |
| message_status | 消息状态更新 |
| message_edit | 消息被编辑 |
| message_delete | 消息被删除 |
| typing | 对方正在输入 |
| read_receipt | 收到已读回执 |
| connection_status | 连接状态更新 |
{
"type": "message",
"data": {
"id": "msg1234567890",
"chat_id": "chat1234567890",
"sender_id": "user1234567890",
"type": "text",
"content": {
"text": "Hello, this is a test message!"
},
"timestamp": 1625097600000,
"status": "sent",
"edited": false,
"forwarded": false,
"reply_to_message_id": null,
"expire_in": 0
}
}
WebSocket连接会自动处理重连和心跳检测,确保实时通讯的稳定性。
消息API使用标准HTTP状态码表示请求结果,并在响应体中提供详细的错误信息。
| 状态码 | 错误代码 | 描述 |
|---|---|---|
| 400 | INVALID_MESSAGE_TYPE | 不支持的消息类型 |
| 400 | MESSAGE_TOO_LONG | 消息内容过长 |
| 401 | UNAUTHORIZED | 未授权或令牌过期 |
| 403 | CHAT_FORBIDDEN | 没有权限访问该聊天 |
| 403 | MESSAGE_DELETE_TIME_LIMIT | 超过消息删除时间限制 |
| 404 | MESSAGE_NOT_FOUND | 消息不存在 |
| 404 | CHAT_NOT_FOUND | 聊天会话不存在 |
| 429 | RATE_LIMITED | 发送消息过于频繁 |
| 500 | SERVER_ERROR | 服务器内部错误 |
{
"ok": false,
"error": {
"code": "MESSAGE_TOO_LONG",
"message": "Message text is too long. Maximum allowed length is 4096 characters.",
"status_code": 400
}
}
以下是使用不同编程语言调用消息API的示例代码。
// 发送文本消息
async function sendTextMessage(chatId, text) {
try {
const response = await fetch('https://api.paperplane.com/v8/messages/send', {
method: 'POST',
headers: {
'Authorization': `Bearer ${localStorage.getItem('accessToken')}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
chat_id: chatId,
type: 'text',
content: {
text: text
}
})
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error?.message || 'Failed to send message');
}
const data = await response.json();
return data.result;
} catch (error) {
console.error('Error sending message:', error);
throw error;
}
}
// 使用WebSocket接收消息
function connectWebSocket() {
const token = localStorage.getItem('accessToken');
const ws = new WebSocket(`wss://api.paperplane.com/v8/ws?token=${token}`);
ws.onopen = () => {
console.log('WebSocket connected');
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
switch (data.type) {
case 'message':
console.log('New message received:', data.data);
// 处理新消息
break;
case 'message_status':
console.log('Message status updated:', data.data);
// 处理消息状态更新
break;
case 'typing':
console.log('User is typing:', data.data);
// 处理正在输入状态
break;
// 处理其他事件类型
}
};
ws.onclose = () => {
console.log('WebSocket disconnected');
// 可以在这里实现重连逻辑
setTimeout(connectWebSocket, 5000);
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
return ws;
}
// 使用示例
sendTextMessage('chat1234567890', 'Hello from JavaScript!')
.then(message => console.log('Message sent:', message))
.catch(error => console.error('Failed to send message:', error));
const ws = connectWebSocket();
import requests
import json
import websocket
import threading
import time
# 发送文本消息
def send_text_message(chat_id, text, token):
url = 'https://api.paperplane.com/v8/messages/send'
headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
}
data = {
'chat_id': chat_id,
'type': 'text',
'content': {
'text': text
}
}
try:
response = requests.post(url, headers=headers, data=json.dumps(data))
response.raise_for_status()
result = response.json()
return result['result']
except requests.exceptions.HTTPError as http_err:
error_data = response.json()
print(f'HTTP error occurred: {error_data.get("error", {}).get("message", "Unknown error")}')
raise
except Exception as err:
print(f'Other error occurred: {err}')
raise
# WebSocket消息处理
def on_message(ws, message):
data = json.loads(message)
if data['type'] == 'message':
print(f'New message received: {data["data"]}')
# 处理新消息
elif data['type'] == 'message_status':
print(f'Message status updated: {data["data"]}')
# 处理消息状态更新
elif data['type'] == 'typing':
print(f'User is typing: {data["data"]}')
# 处理正在输入状态
# 处理其他事件类型
def on_error(ws, error):
print(f'WebSocket error: {error}')
def on_close(ws):
print('WebSocket disconnected')
# 实现重连逻辑
time.sleep(5)
connect_websocket(token)
def on_open(ws):
print('WebSocket connected')
def connect_websocket(token):
ws_url = f'wss://api.paperplane.com/v8/ws?token={token}'
ws = websocket.WebSocketApp(
ws_url,
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close
)
# 在后台线程中运行WebSocket
ws_thread = threading.Thread(target=ws.run_forever)
ws_thread.daemon = True
ws_thread.start()
return ws
# 使用示例
if __name__ == '__main__':
token = 'your_access_token_here'
# 发送消息
try:
message = send_text_message('chat1234567890', 'Hello from Python!', token)
print(f'Message sent: {message}')
except Exception as e:
print(f'Failed to send message: {e}')
# 连接WebSocket
ws = connect_websocket(token)
# 保持程序运行
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print('Program terminated')
ws.close()
遵循以下最佳实践,确保您的应用高效、安全地使用纸飞机消息API。
纸飞机的端到端加密确保了消息的安全性,但您仍应采取措施保护用户设备上的消息数据。
当消息发送失败时,您应该:
您可以使用本地数据库(如SQLite、Realm或Room)存储消息。对于敏感消息,建议在存储前进行加密。当用户重新上线时,可以将本地消息与服务器同步。
优化大量消息加载的策略包括:
处理WebSocket断开连接的最佳实践包括:
消息搜索可以通过以下方式实现:
处理阅后即焚消息的步骤包括:
帮助我们改进文档,提供反馈或寻求支持