---
doc_id: message-format-spec
title: Aile 消息格式完整規格說明書
description: Aile 消息模型、消息類型、模板內容、標籤、發送 DTO、群發與 Gateway 外發格式規格，供開發團隊參考。
slug: /specifications/message-format-spec
product: Aile
category: specification
audience:
  - developer
  - architect
  - qa
visibility: public
status: published
version: 1.0.0
owner: aile-platform
updated_at: 2026-06-13
tags:
  - Aile
  - Message
  - Gateway
  - 規格說明書
rendered_html: /rendered/specifications/message-format-spec/
download: true
sidebar_position: 6
---

# Aile 消息格式完整規格說明書

**版本：** v1.0  
**最後更新：** 2026-06-13  
**服務範圍：** `aile-service-room`（核心）、`aile-common-dependency`（通用類型）  
**儲存引擎：** Elasticsearch（index: `aile.message`）

---

## 1. 概述

Aile 的消息系統支援 13 種基礎消息類型、4 種模板類型、8 種消息標籤（Tag）和 5 種消息來源。消息以 `MessageModel` 為核心載體，透過 `content` 欄位（Object 類型）承載各類型專屬的結構化內容。

---

## 2. MessageModel（消息核心模型）

### 2.1 資料結構

```java
// aile-api/aile-room-api/.../model/MessageModel.java
@Document(indexName = "aile.message", dynamic = Dynamic.TRUE)
public class MessageModel implements Serializable {
    String id;                    // Elasticsearch 文檔 ID
    String messageId;             // 業務消息編號
    MessageType type;             // 消息類型
    MessageSourceType sourceType; // 消息來源類型
    String senderName;            // 發送者名稱
    String senderId;              // 發送者 ID
    String accountId;             // 帳號 ID
    long sendTime;                // 發送時間（epoch ms）
    String roomId;                // 聊天室 ID
    long sequence;                // 消息序號（房間內遞增）
    String tenantId;              // 租戶 ID
    OsType osType;                // 設備類型
    Channel channel;              // 渠道
    Channel appointChannel;       // 指定渠道（多渠道發送時）
    Object content;               // 消息內容（類型相關）
    Tag tag;                      // 消息標籤
    String themeId;               // 主題 ID
    String nearMessageId;         // 關聯消息 ID（回覆引用）
    String sessionId;             // 關聯會話 ID
    String channelMessageId;      // 渠道側消息 ID（Gateway 回傳）
    List<String> excludeMemberIds;// 排除的成員 ID
    String recipientId;           // 接收者 ID（私聊）
    String recipientAccountId;    // 接收者帳號 ID
    Integer flag;                 // 消息狀態標記
}
```

### 2.2 消息狀態標記（MessageFlag）

```java
// aile-api/aile-room-api/.../enums/MessageFlag.java
public enum MessageFlag {
    Deleted(-2),   // 已刪除
    Send(-1),      // 發送中
    Arrive(0),     // 已送達
    Received(1),   // 已接收
    Read(2),       // 已讀
    Retract(3)     // 已撤回
}
```

### 2.3 消息來源類型（MessageSourceType）

```java
// aile-api/aile-room-api/.../enums/MessageSourceType.java
public enum MessageSourceType {
    User,        // 用戶（員工或客戶）
    Assistant,   // AI 助手
    System,      // 系統自動消息
    Consult,     // 諮詢消息（客服場景）
    Broadcast    // 群發消息
}
```

---

## 3. MessageType（13 種消息類型）

```java
// aile-api/aile-room-api/.../enums/MessageType.java
public enum MessageType {
    At,        // @提及消息
    Text,      // 純文字消息
    Event,     // 事件消息（系統事件）
    Image,     // 圖片消息
    File,      // 文件消息
    Video,     // 影片消息
    Audio,     // 音頻消息
    Voice,     // 語音消息
    Sticker,   // 貼圖消息
    Template,  // 模板/卡片消息
    Location,  // 位置消息
    Action,    // 動作消息（按鈕點擊回傳）
    Json       // 結構化 JSON 消息
}
```

---

## 4. 各消息類型詳解與示例

### 4.1 Text（純文字）

最基礎的消息類型。`content` 為純文字字串。

```json
{
  "type": "Text",
  "content": "您好，歡迎使用 Aile 客服系統！",
  "roomId": "room_abc123",
  "senderId": "emp_001",
  "senderName": "客服小王",
  "sourceType": "User"
}
```

---

### 4.2 At（@提及）

用於在群聊中 @ 特定成員。`content` 中包含提及對象資訊。

```json
{
  "type": "At",
  "content": {
    "text": "@張三 請確認一下訂單狀態",
    "mentions": [
      {
        "memberId": "member_zhangsan",
        "name": "張三",
        "type": "User"
      }
    ]
  },
  "roomId": "room_group_001"
}
```

---

### 4.3 Image（圖片）

`content` 為圖片資源的結構化描述。透過 `MessageSendV2Dto` 上傳時，`file` 欄位攜帶 MultipartFile。

```json
{
  "type": "Image",
  "content": {
    "fileId": "file_img_001",
    "url": "https://cdn.aile.com/images/abc123.jpg",
    "thumbnailUrl": "https://cdn.aile.com/images/abc123_thumb.jpg",
    "width": 800,
    "height": 600,
    "size": 102400,
    "fileName": "product_photo.jpg"
  },
  "roomId": "room_abc123"
}
```

---

### 4.4 File（文件）

```json
{
  "type": "File",
  "content": {
    "fileId": "file_doc_001",
    "url": "https://cdn.aile.com/files/contract.pdf",
    "fileName": "合約文件.pdf",
    "fileSize": 2048000,
    "mimeType": "application/pdf"
  },
  "roomId": "room_abc123"
}
```

---

### 4.5 Video（影片）

```json
{
  "type": "Video",
  "content": {
    "fileId": "file_vid_001",
    "url": "https://cdn.aile.com/videos/demo.mp4",
    "thumbnailUrl": "https://cdn.aile.com/videos/demo_thumb.jpg",
    "duration": 120,
    "width": 1920,
    "height": 1080,
    "size": 15728640,
    "fileName": "產品介紹.mp4"
  },
  "roomId": "room_abc123"
}
```

---

### 4.6 Audio（音頻）

```json
{
  "type": "Audio",
  "content": {
    "fileId": "file_aud_001",
    "url": "https://cdn.aile.com/audio/recording.mp3",
    "duration": 45,
    "size": 360000,
    "fileName": "語音留言.mp3"
  },
  "roomId": "room_abc123"
}
```

---

### 4.7 Voice（語音）

與 Audio 類似，但語義上強調即時語音消息（如 LINE 語音輸入）。

```json
{
  "type": "Voice",
  "content": {
    "fileId": "file_voice_001",
    "url": "https://cdn.aile.com/voice/msg_001.aac",
    "duration": 15,
    "size": 48000
  },
  "roomId": "room_abc123"
}
```

---

### 4.8 Sticker（貼圖）

用於表情貼圖。`content` 中包含貼圖 ID 和套餐 ID。

```json
{
  "type": "Sticker",
  "content": {
    "packageId": "11537",
    "stickerId": "52002734",
    "url": "https://stickershop.line-scdn.net/stickershop/v1/sticker/52002734/iPhone/sticker.png"
  },
  "roomId": "room_abc123",
  "channel": "Line"
}
```

---

### 4.9 Location（位置）

```json
{
  "type": "Location",
  "content": {
    "title": "台北 101",
    "address": "台北市信義區信義路五段7號",
    "latitude": 25.033964,
    "longitude": 121.564468,
    "staticMapUrl": "https://map.example.com/static?lat=25.033964&lng=121.564468"
  },
  "roomId": "room_abc123"
}
```

---

### 4.10 Template（模板/卡片消息）

Template 是功能最豐富的消息類型，支援按鈕、確認框、流程卡、輪播等子類型。

#### 4.10.1 GenericMessage（模板基底）

```java
// aile-common/.../message/GenericMessage.java
public abstract class GenericMessage {
    Object quickReply;  // 快速回覆選項
}
```

#### 4.10.2 TemplateMessage（模板消息結構）

```java
// aile-common/.../message/type/TemplateMessage.java
public class TemplateMessage extends GenericMessage {
    String title;              // 標題
    String subTitle;           // 副標題
    String text;               // 正文
    TemplateType type;         // 模板類型：Buttons / Confirm / Process / Carousel
    List<Element> elements;    // 元素列表（Carousel 時使用）
    OrientationType orientation; // 排版方向：Vertical / Horizontal
    String imageUrl;           // 主題圖片
    Action defaultAction;      // 默認點擊動作
    List<Action> actions;      // 按鈕動作列表
}
```

#### 4.10.3 TemplateType（模板子類型）

| 類型 | 值 | 說明 |
|------|-----|------|
| 按鈕模板 | `Buttons` | 標題 + 文字 + 多個操作按鈕 |
| 確認模板 | `Confirm` | 標題 + 文字 + 確認/取消按鈕 |
| 流程模板 | `Process` | 多步驟流程卡片 |
| 輪播模板 | `Carousel` | 多張卡片水平/垂直輪播 |

#### 4.10.4 Template 示例：Buttons（按鈕卡片）

```json
{
  "type": "Template",
  "content": {
    "title": "訂單確認",
    "text": "您的訂單 #12345 已出貨，預計 3 天內送達。需要進一步協助嗎？",
    "type": "Buttons",
    "imageUrl": "https://cdn.aile.com/card/order_banner.jpg",
    "actions": [
      {
        "type": "Postback",
        "label": "查詢物流",
        "text": "查詢物流",
        "data": "action=track&orderId=12345",
        "displayText": "正在查詢物流狀態..."
      },
      {
        "type": "Url",
        "label": "查看詳情",
        "text": "查看詳情",
        "url": "https://shop.example.com/orders/12345"
      },
      {
        "type": "Action",
        "label": "聯絡客服",
        "text": "聯絡客服",
        "data": "action=contact_support"
      }
    ]
  }
}
```

#### 4.10.5 Template 示例：Confirm（確認卡片）

```json
{
  "type": "Template",
  "content": {
    "title": "取消訂單",
    "text": "確定要取消訂單 #12345 嗎？此操作無法復原。",
    "type": "Confirm",
    "actions": [
      {
        "type": "Postback",
        "label": "確認取消",
        "text": "確認取消",
        "data": "action=cancel_order&orderId=12345",
        "isDefault": true
      },
      {
        "type": "Action",
        "label": "保留訂單",
        "text": "保留訂單"
      }
    ]
  }
}
```

#### 4.10.6 Template 示例：Carousel（輪播卡片）

```json
{
  "type": "Template",
  "content": {
    "type": "Carousel",
    "orientation": "Horizontal",
    "elements": [
      {
        "title": "商品 A — NT$999",
        "subtitle": "限時優惠中",
        "imageUrl": "https://cdn.aile.com/product/a.jpg",
        "defaultAction": {
          "type": "Url",
          "url": "https://shop.example.com/product/a"
        },
        "actions": [
          {
            "type": "Postback",
            "label": "加入購物車",
            "data": "action=add_cart&product=A"
          }
        ]
      },
      {
        "title": "商品 B — NT$1,299",
        "subtitle": "新品上市",
        "imageUrl": "https://cdn.aile.com/product/b.jpg",
        "defaultAction": {
          "type": "Url",
          "url": "https://shop.example.com/product/b"
        },
        "actions": [
          {
            "type": "Postback",
            "label": "加入購物車",
            "data": "action=add_cart&product=B"
          }
        ]
      }
    ]
  }
}
```

#### 4.10.7 Action（按鈕動作類型）

```java
// aile-common/.../message/template/Action.java
public class Action {
    ActionType type;     // Action / Postback / Url / Aiff
    String text;         // 顯示文字
    String imageUrl;     // 按鈕圖示
    String url;          // 外部連結（type=Url 時）
    String label;        // 按鈕標籤
    String title;        // 按鈕標題
    String data;         // 回傳資料（type=Postback 時）
    String privateData;  // 私有資料（不可見於前端）
    String displayText;  // 點擊後顯示文字
    Boolean isDefault;   // 是否為默認按鈕
    String code;         // 動作代碼
}
```

#### 4.10.8 ActionType

| 類型 | 值 | 說明 |
|------|-----|------|
| 前端行為 | `Action` | 前端本地處理（如關閉卡片） |
| 後端回傳 | `Postback` | 提交到後端伺服器處理 |
| 外部連結 | `Url` | 前端打開外部 URL |
| AIFF 容器 | `Aiff` | 開啟 AIFF 內嵌容器 |

#### 4.10.9 Element（輪播元素）

```java
// aile-common/.../message/template/Element.java
public class Element {
    String title;
    String subtitle;
    String imageUrl;
    Action defaultAction;    // 點擊整張卡片的默認行為
    List<Action> actions;    // 卡片上的按鈕列表
}
```

---

### 4.11 Event（事件消息）

系統級事件，不直接對用戶展示，用於觸發後端邏輯。

```json
{
  "type": "Event",
  "content": {
    "eventCode": "SessionStart",
    "sessionId": "sess_abc123",
    "timestamp": 1718256000000,
    "data": {}
  },
  "sourceType": "System",
  "roomId": "room_abc123"
}
```

---

### 4.12 Action（動作消息）

用戶點擊按鈕後的回傳消息，`content` 中包含按鈕回傳的 `data`。

```json
{
  "type": "Action",
  "content": {
    "actionType": "Postback",
    "data": "action=cancel_order&orderId=12345",
    "label": "確認取消",
    "sourceTemplateId": "tpl_xyz789"
  },
  "roomId": "room_abc123",
  "sourceType": "User"
}
```

---

### 4.13 Json（結構化 JSON）

用於傳遞任意結構化資料，前端根據內部欄位自行解析渲染。

```json
{
  "type": "Json",
  "content": {
    "customType": "satisfaction_survey",
    "question": "請為本次服務評分",
    "options": [
      { "score": 5, "label": "非常滿意" },
      { "score": 4, "label": "滿意" },
      { "score": 3, "label": "普通" },
      { "score": 2, "label": "不滿意" },
      { "score": 1, "label": "非常不滿意" }
    ],
    "sessionId": "sess_abc123"
  },
  "sourceType": "System"
}
```

---

## 5. Tag（消息標籤）

消息標籤用於標記消息的業務屬性，`content` 不變時透過 Tag 注入上下文。Tag 使用 Jackson 多態序列化。

```java
// aile-common/.../message/tag/Tag.java
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
    @JsonSubTypes.Type(value = BroadcastTag.class, name = "Broadcast"),
    @JsonSubTypes.Type(value = LinkTag.class, name = "Link"),
    @JsonSubTypes.Type(value = PostTag.class, name = "Post"),
    @JsonSubTypes.Type(value = PageTag.class, name = "Page"),
    @JsonSubTypes.Type(value = ToDoTag.class, name = "Todo"),
    @JsonSubTypes.Type(value = ReplyUrlTag.class, name = "ReplyUrl"),
    @JsonSubTypes.Type(value = EchoTag.class, name = "Echo"),
    @JsonSubTypes.Type(value = ServiceIdentityTag.class, name = "ServiceIdentity")
})
```

### 5.1 Tag 類型詳解

| Tag | 用途 | 關鍵欄位 |
|-----|------|----------|
| `Broadcast` | 群發消息標記 | `broadcastId`, `batched` |
| `Link` | 外部連結預覽 | `link` |
| `Post` | 貼文/動態關聯 | `postId`, `commentId`, `channel` |
| `Page` | 頁面導航標記 | `label`, `direction`, `osTypes` |
| `Todo` | 待辦事項關聯 | `toDoId` |
| `ReplyUrl` | 回覆連結渠道 | `channel` |
| `Echo` | 消息回聲標記 | `isEcho` |
| `ServiceIdentity` | 服務號身份標記 | `name`, `avatarId`, `id` |

---

## 6. 消息發送 DTO 對比

### 6.1 MessageSendDto（通用發送）

```java
// aile-api/aile-room-api/.../dto/MessageSendDto.java
public class MessageSendDto {
    String id;            // 客戶端消息 ID（冪等鍵）
    MessageType type;     // 消息類型（必填）
    String roomId;        // 聊天室 ID（必填）
    Object content;       // 消息內容（必填）
    Tag tag;              // 消息標籤
    String messageKey;    // 客戶端本地預存消息鍵
}
```

### 6.2 MessageSendV2Dto（V2 發送，支援文件上傳）

```java
// aile-api/aile-room-api/.../dto/MessageSendV2Dto.java
public class MessageSendV2Dto {
    String id;
    MessageType type;
    String roomId;
    Object content;
    Tag tag;
    MultipartFile file;   // 直接上傳文件（Image/File/Video/Audio 時使用）
}
```

### 6.3 ServiceMessageSendDto（服務號發送）

```java
// aile-api/aile-room-api/.../dto/ServiceMessageSendDto.java
public class ServiceMessageSendDto {
    MessageType type;               // 消息類型
    MessageSourceType sourceType;   // 來源類型
    String senderName;              // 發送者名稱
    String senderId;                // 發送者 ID
    String roomId;                  // 聊天室 ID
    Object content;                 // 消息內容
    Tag tag;                        // 標籤
    Channel channel;                // 目標渠道
    Channel appointChannel;         // 指定渠道
    List<String> excludeMemberIds;  // 排除的成員
    String sessionId;               // 會話 ID
    String nearMessageId;           // 引用消息 ID
}
```

### 6.4 CustomMessageDto（自定義消息，系統間傳遞）

```java
// aile-api/aile-room-api/.../dto/CustomMessageDto.java
public class CustomMessageDto {
    String id;
    MessageType type;
    MessageSourceType sourceType;
    String senderName;
    String senderId;
    String accountId;
    long sendTime;
    String roomId;
    long sequence;
    String tenantId;
    OsType osType;
    Channel channel;
    Channel appointChannel;
    Object content;
    Tag tag;
    String themeId;
    String nearMessageId;
    String sessionId;
    String channelMessageId;
    List<String> excludeMemberIds;
}
```

---

## 7. 群發消息格式

群發使用 `BroadcastBody` 定義內容，支援多條消息組合發送：

```java
// aile-api/aile-tenant-api/.../model/servicenumber/BroadcastBody.java
public class BroadcastBody {
    Integer index;       // 消息序號（順序發送）
    MessageType type;    // 消息類型
    String content;      // 消息內容（JSON 字串）
}
```

群發消息示例（3 條消息順序發送）：

```json
[
  {
    "index": 0,
    "type": "Text",
    "content": "\"親愛的會員您好，本季新品已上架！\""
  },
  {
    "index": 1,
    "type": "Image",
    "content": "{\"fileId\":\"file_img_spring\",\"url\":\"https://cdn.aile.com/promo/spring2026.jpg\"}"
  },
  {
    "index": 2,
    "type": "Template",
    "content": "{\"title\":\"新品搶先看\",\"text\":\"點擊下方按鈕查看詳情\",\"type\":\"Buttons\",\"actions\":[{\"type\":\"Url\",\"label\":\"立即查看\",\"url\":\"https://shop.example.com/new\"}]}"
  }
]
```

---

## 8. Gateway 外發消息格式

Aile 向外部渠道（LINE 等）發送消息時，使用 `AileMessageDto` 封裝：

```java
// aile-api/aile-tenant-api/.../dto/gateway/AileMessageDto.java
public class AileMessageDto {
    ServiceSessionModel sessionModel;  // 會話對象
    List<MessageModel> messages;       // 消息列表
    RoomModel roomModel;               // 聊天室對象
}
```

---

## 9. 完整消息類型速查表

| Type | content 類型 | 說明 | 支援渠道 |
|------|-------------|------|----------|
| `Text` | `String` | 純文字 | 全部 |
| `At` | `Object{text, mentions[]}` | @提及 | 群聊 |
| `Image` | `Object{fileId, url, width, height}` | 圖片 | 全部 |
| `File` | `Object{fileId, url, fileName, fileSize}` | 文件 | LINE / WhatsApp |
| `Video` | `Object{fileId, url, duration, thumbnailUrl}` | 影片 | LINE / WhatsApp |
| `Audio` | `Object{fileId, url, duration}` | 音頻 | LINE / WhatsApp |
| `Voice` | `Object{fileId, url, duration}` | 語音 | LINE |
| `Sticker` | `Object{packageId, stickerId}` | 貼圖 | LINE |
| `Template` | `TemplateMessage` | 卡片/按鈕/輪播 | LINE / App |
| `Location` | `Object{title, address, lat, lng}` | 位置 | LINE |
| `Event` | `Object{eventCode, data}` | 系統事件 | 內部 |
| `Action` | `Object{actionType, data, label}` | 按鈕回傳 | 內部 |
| `Json` | `Object`（自由結構） | 自定義 JSON | App |

---

## 10. 關鍵檔案索引

| 層級 | 檔案 | 說明 |
|------|------|------|
| Enum | `aile-api/aile-room-api/.../enums/MessageType.java` | 13 種消息類型枚舉 |
| Enum | `aile-api/aile-room-api/.../enums/MessageSourceType.java` | 5 種消息來源類型 |
| Enum | `aile-api/aile-room-api/.../enums/MessageFlag.java` | 6 種消息狀態標記 |
| Model | `aile-api/aile-room-api/.../model/MessageModel.java` | 消息核心模型（ES） |
| DTO | `aile-api/aile-room-api/.../dto/MessageSendDto.java` | 通用發送 DTO |
| DTO | `aile-api/aile-room-api/.../dto/MessageSendV2Dto.java` | V2 發送 DTO（支援文件） |
| DTO | `aile-api/aile-room-api/.../dto/ServiceMessageSendDto.java` | 服務號發送 DTO |
| DTO | `aile-api/aile-room-api/.../dto/CustomMessageDto.java` | 自定義消息 DTO |
| DTO | `aile-api/aile-tenant-api/.../dto/gateway/AileMessageDto.java` | Gateway 外發封裝 |
| Model | `aile-api/aile-tenant-api/.../model/servicenumber/BroadcastBody.java` | 群發內容 |
| Common | `aile-common/.../message/type/TemplateMessage.java` | 模板消息結構 |
| Common | `aile-common/.../message/template/Action.java` | 按鈕動作 |
| Common | `aile-common/.../message/template/Element.java` | 輪播元素 |
| Common | `aile-common/.../message/enums/template/TemplateType.java` | 模板子類型 |
| Common | `aile-common/.../message/enums/template/ActionType.java` | 按鈕動作類型 |
| Common | `aile-common/.../message/enums/template/OrientationType.java` | 排版方向 |
| Common | `aile-common/.../message/tag/Tag.java` | 消息標籤基底（8 種子類型） |
| Common | `aile-common/.../message/GenericMessage.java` | 泛型消息基底 |
