# Flex Message

Flex Message 是用 JSON 描述版面的訊息格式，概念類似網頁的 CSS Flexbox：用「盒子（box）」把文字、圖片、按鈕排成水平或垂直方向。它是 LINE Bot 最有表現力的介面，商品卡片、電子收據、訂單明細、天氣卡、記帳統計都是用 Flex 做的。本頁說明 Flex 的結構，並用官方 Simulator 設計一張咖啡商品卡，再分別用 Python 與 Apps Script 送出。

## Flex 的三層結構

```
Container（容器）
├── bubble：一張卡片
└── carousel：多張 bubble 左右滑動（最多 12 張）

Bubble 的區塊（Block），由上到下：
├── header   標題區
├── hero     主圖區（通常放一張大圖）
├── body     內容區
└── footer   按鈕區

區塊裡放元件（Component）：
├── box      盒子，layout = vertical / horizontal / baseline，可以巢狀
├── text     文字
├── image    圖片
├── button   按鈕（搭配 Action）
├── icon     小圖示（只能放在 baseline box）
├── separator 分隔線
└── video    影片（只能放在 hero）
```

### 排版的關鍵屬性

| 屬性 | 用在 | 說明 |
| --- | --- | --- |
| `layout` | box | `vertical` 由上往下、`horizontal` 由左往右、`baseline` 水平且文字基線對齊 |
| `flex` | 元件 | 在水平 box 中占的比例，例如左 `flex: 3`、右 `flex: 2`；`0` 表示依內容寬度 |
| `spacing` | box | 子元件之間的間距：`none`、`xs`、`sm`、`md`、`lg`、`xl`、`xxl` |
| `margin` | 元件 | 和前一個元件的距離 |
| `align`／`gravity` | text 等 | 水平對齊（`start`／`center`／`end`）與垂直對齊 |
| `wrap` | text | `true` 時文字自動換行，否則超出部分顯示「…」 |
| `size`／`weight`／`color` | text | 字級（`xs`～`5xl`）、粗細、顏色 |
| `aspectRatio`／`aspectMode` | image | 圖片比例與裁切方式（`cover` 填滿、`fit` 完整顯示） |

## 用 Flex Message Simulator 設計

手寫 JSON 很容易出錯，建議先用官方工具設計：

1. 打開 [Flex Message Simulator](<https://developers.line.biz/flex-simulator/>)，用 LINE 帳號登入。
2. 點 **Showcase** 可以選官方範本（餐廳、購物、收據、交通等）當起點。
3. 左側點元件、右側修改屬性，中間即時預覽。
4. 點 **View as JSON** 複製 JSON，存成檔案。

> [!TIP]
>
> **也可以把現有 JSON 貼回 Simulator**
>
> 點 **View as JSON** 後直接貼上 JSON 並套用，就能預覽與修改本站的範例。

## 範例：咖啡商品卡

下面是一張含主圖、評分、說明、價格與兩個按鈕的商品卡，存成 `flex/coffee.json`：

flex/coffee.json

```
{
  "type": "bubble",
  "hero": {
    "type": "image",
    "url": "https://picsum.photos/id/766/800/520.jpg",
    "size": "full",
    "aspectRatio": "20:13",
    "aspectMode": "cover"
  },
  "body": {
    "type": "box",
    "layout": "vertical",
    "spacing": "md",
    "contents": [
      { "type": "text", "text": "招牌拿鐵", "weight": "bold", "size": "xl" },
      {
        "type": "box",
        "layout": "baseline",
        "spacing": "sm",
        "contents": [
          { "type": "text", "text": "★★★★☆", "size": "sm", "color": "#F5A623", "flex": 0 },
          { "type": "text", "text": "4.6（128 則評價）", "size": "sm", "color": "#999999" }
        ]
      },
      {
        "type": "text",
        "text": "使用中焙衣索比亞豆，搭配鮮乳，口感滑順帶有果香。",
        "size": "sm",
        "color": "#666666",
        "wrap": true
      },
      {
        "type": "box",
        "layout": "horizontal",
        "contents": [
          { "type": "text", "text": "價格", "size": "sm", "color": "#999999" },
          { "type": "text", "text": "NT$120", "size": "lg", "weight": "bold", "align": "end", "color": "#06C755" }
        ]
      }
    ]
  },
  "footer": {
    "type": "box",
    "layout": "vertical",
    "spacing": "sm",
    "contents": [
      {
        "type": "button",
        "style": "primary",
        "color": "#06C755",
        "action": { "type": "postback", "label": "加入購物車", "data": "action=add&item=latte", "displayText": "我要一杯招牌拿鐵" }
      },
      {
        "type": "button",
        "style": "link",
        "action": { "type": "uri", "label": "查看門市地圖", "uri": "https://www.google.com/maps?q=台北車站" }
      }
    ]
  }
}
```

結構拆解：

- `hero`：滿版主圖，`aspectRatio: 20:13`、`aspectMode: cover`。
- `body`：垂直 box，依序放商品名、評分列（`baseline` box 讓星星與文字對齊）、說明（`wrap: true` 自動換行）、價格列（水平 box，左「價格」、右金額 `align: end`）。
- `footer`：一個 `postback` 主按鈕「加入購物車」、一個 `uri` 連結按鈕。

## 送出 Flex Message

把 JSON 讀進來，用 `FlexContainer.from_dict()` 轉成 SDK 物件：

```
def flex_message():
    bubble = json.loads(FLEX_FILE.read_text(encoding="utf-8"))
    return FlexMessage(alt_text="招牌拿鐵 NT$120", contents=FlexContainer.from_dict(bubble))
```

也可以像 [記帳小幫手](<https://www.vcdemy.com/linebot/python/expense-bot/index.md>) 一樣，在程式裡用 dict 動態組出 Flex，把資料庫查到的內容填進去。

Flex 就是一般的 JavaScript 物件，直接放進 `contents`：

```
function replyCoffeeCard(replyToken) {
  const bubble = {
    type: 'bubble',
    hero: { type: 'image', url: 'https://picsum.photos/id/766/800/520.jpg', size: 'full', aspectRatio: '20:13', aspectMode: 'cover' },
    body: {
      type: 'box', layout: 'vertical', spacing: 'md',
      contents: [
        { type: 'text', text: '招牌拿鐵', weight: 'bold', size: 'xl' },
        { type: 'text', text: 'NT$120', size: 'lg', color: '#06C755' },
      ],
    },
    footer: {
      type: 'box', layout: 'vertical',
      contents: [
        { type: 'button', style: 'primary', color: '#06C755',
          action: { type: 'postback', label: '加入購物車', data: 'action=add&item=latte' } },
      ],
    },
  };
  replyMessage(replyToken, [{ type: 'flex', altText: '招牌拿鐵 NT$120', contents: bubble }]);
}
```

`replyMessage()` 沿用 [Apps Script Echo Bot](<https://www.vcdemy.com/linebot/gas/echo-bot/index.md>) 的函式。JSON 較長時，可以把 Simulator 產生的 JSON 存在試算表儲存格或 Drive 檔案，用 `JSON.parse()` 讀進來。

## 多張卡片：Carousel

把多個 bubble 放進 carousel，就能左右滑動：

```
carousel = {"type": "carousel", "contents": [bubble1, bubble2, bubble3]}
FlexMessage(alt_text="今日菜單", contents=FlexContainer.from_dict(carousel))
```

## 設計建議

- **一張卡片只講一件事**：資訊太多時拆成 carousel，或改用 LIFF 網頁。
- **動態資料用程式組**：固定的外框寫在 JSON 檔，變動的文字與數字在程式中替換。
- **`altText` 寫有意義的摘要**：例如「訂單 \#1234 已出貨」，而不是「Flex Message」。
- **圖片用 HTTPS 且比例固定**：同一個 carousel 的主圖比例一致，看起來才整齊。
- **在手機上實測**：Simulator 和實機在字型、寬度上略有差異，深色模式下的顏色也要確認。

> [!WARNING]
>
> **JSON 大小與格式錯誤**
>
> Flex JSON 有大小上限，carousel 太多張或內容太長會被拒絕。API 回傳 `400 A message (messages[0]) in the request body is invalid` 時，把 JSON 貼到 Simulator 檢查是哪個欄位不合法。

## 相關資料

- [Flex Message 說明](<https://developers.line.biz/en/docs/messaging-api/using-flex-messages/>)
- [Flex Message layout](<https://developers.line.biz/en/docs/messaging-api/flex-message-layout/>)
- [Flex Message Simulator](<https://developers.line.biz/flex-simulator/>)
