# Web Chat SDK 操作指令

使用 MaiAgent SDK 提供了一套完整的 JavaScript API，讓開發者可以輕鬆地將 MaiAgent 聊天機器人整合到任何網站中。

## **一、初始化說明**

{% hint style="info" %}
如何獲取嵌入腳本？請參考 [🌐串接對話平台：網站](https://docs.maiagent.ai/release/website)

依此說明操作，腳本將會自動帶入 webChatId 參數
{% endhint %}

嵌入腳本載入後系統會自動註冊 `document.body.onload` 事件處理器來執行 Web Chat 初始化，不需要手動呼叫註冊。若需要控制初始化時機（例如等待其他資源載入完成或延遲渲染），可採用以下方式：

1. **延遲載入腳本**：控制 `embed.min.js` 的載入時機
2. **手動觸發初始化**：在適當時機調用 `document.body.onload()` 方法

此機制允許開發者將 DOM 渲染與 Web Chat 初始化解耦，提供更靈活的整合方式

#### 注意事項

* 系統經由聯絡人 API 確認已帶有 Contact ID 後才會進行初始化。
* 可使用 Query Metadata 使 Web Chat 在初始化時就帶有[知識管理權限](/tech/authorization-integration/zhi-shi-guan-li-quan-xian-query-metadata-cha-xun-yuan-zi-liao-zong-lan/json-interfaces.md#webchat-chu-shi-hua-she-ding)

了解更多關於知識管理權限內容，請參考 [🌐知識管理權限(Query Metadata / 查詢元資料) 總覽↗](/tech/authorization-integration/zhi-shi-guan-li-quan-xian-query-metadata-cha-xun-yuan-zi-liao-zong-lan.md)

## 二、快速開始

### 1. 引入 SDK

```html
<script>
  window.maiagentChatbotConfig = {
    webChatId: 'your-web-chat-id',
    baseUrl: '<https://yourdomain.com/web-chats>',
    primaryColor: '#1890ff',
    allowDrag: true,
  }
</script>
<script src="<https://yourdomain.com/js/embed.min.js>"></script>

```

### 2. 使用 API

```jsx
// 等待 SDK 初始化完成
document.addEventListener('DOMContentLoaded', () => {
  // 監聽消息回覆
  MaiAgent.events.on('messageReply', (data) => {
    console.log('收到新消息:', data)
  })

  // 發送消息
  MaiAgent.chat.send('你好！')

  // 打開聊天視窗
  MaiAgent.control.open()
})

```

## 三、基本配置

在引入 SDK 之前，需要先配置 `maiagentChatbotConfig` 物件：

{% hint style="info" %}
詳細參數說明請參考下方 [配置選項](#si-pei-zhi-xuan-xiang) 說明
{% endhint %}

```jsx
window.maiagentChatbotConfig = {
  webChatId: 'your-web-chat-id', // 必填：聊天機器人 ID
  baseUrl: '<https://yourdomain.com/web-chats>', // 必填：API 基礎 URL
  primaryColor: '#1890ff', // 主題顏色
  allowDrag: true, // 是否允許拖拽按鈕
  buttonSize: '48', // 按鈕大小（像素）
  buttonRadius: '50%', // 按鈕圓角
  buttonPositionBottom: '16', // 按鈕距離底部距離
  buttonPositionRight: '16', // 按鈕距離右側距離
  windowWidth: '24rem', // 聊天視窗寬度
  windowHeight: '40rem', // 聊天視窗高度
  windowRadius: '0.75rem', // 聊天視窗圓角
  windowPositionBottom: '5rem', // 聊天視窗距離底部距離
  windowPositionRight: '1rem', // 聊天視窗距離右側距離
  boxShadow: '0.125rem 0.125rem 0.5rem #00000044', // 陰影效果
  contactId: 'contact-id', // 可選：聯絡人 ID
  queryMetadata: { key: 'value' }, // 可選：查詢元數據
  closeIconHtml: '<svg>...</svg>', // 可選：自定義關閉圖示
  openIconHtml: '<svg>...</svg>' // 可選：自定義開啟圖示
}

```

## 四、API 功能

### 1. 聊天控制

#### `MaiAgent.control.open()`

打開聊天視窗

```jsx
// 打開聊天視窗
MaiAgent.control.open()

```

#### `MaiAgent.control.close()`

關閉聊天視窗

```jsx
// 關閉聊天視窗
MaiAgent.control.close()

```

#### `MaiAgent.control.isOpen()`

檢查聊天視窗是否開啟

```jsx
// 檢查聊天視窗狀態
const isOpen = MaiAgent.control.isOpen()
console.log('聊天視窗狀態:', isOpen ? '開啟' : '關閉')

```

### 2. 訊息管理

#### `MaiAgent.chat.send(content)`

發送消息到聊天機器人

```jsx
// 發送簡單文字消息
MaiAgent.chat.send('你好，我需要幫助')

```

#### `MaiAgent.chat.clearHistory()`

清除聊天歷史記錄

```jsx
// 清除所有聊天歷史
MaiAgent.chat.clearHistory()

```

#### `MaiAgent.chat.newConversation()`

開始新的對話

```jsx
// 開始新對話
MaiAgent.chat.newConversation()

```

### 3. 事件監聽

#### `MaiAgent.events.on(eventType, callback)`

註冊事件監聽器

```jsx
// 監聽消息回覆 - 使用字符串
MaiAgent.events.on('messageReply', (data) => {
  console.log('收到回覆:', data)
  // data 包含消息內容、時間戳等資訊
})

// 或者使用 EVENT_TYPES 常量（推薦用於生產環境）
MaiAgent.events.on(MaiAgent.EVENT_TYPES.MESSAGE_REPLY, (data) => {
  console.log('收到回覆:', data)
})

```

#### `MaiAgent.events.off(eventType, callback)`

移除事件監聽器

```jsx
// 移除特定的事件監聽器
function messageHandler(data) {
  console.log('消息事件:', data)
}

MaiAgent.events.on('messageReply', messageHandler)
// ... 稍後移除
MaiAgent.events.off('messageReply', messageHandler)

```

### 4. 語言設定

**Web Chat 語言與語音控制**

{% hint style="info" %}
MaiAgent 支援語言說明請參考 [多國語言支援](https://docs.maiagent.ai/build/multi-language-support)
{% endhint %}

* Web Chat 支援繁簡中、英、日、韓、泰等多種語言，未來還會持續擴充
* 嵌入後可全域存取 globalThis.MaiAgent 物件，並設定文字或語音語言
* 除 「 繁體中文 」 及 「 簡體中文 」 以外，其他語言只需指定 「 語言碼 」

**語言設定範例**

您可以根據網站需求，設定不同的語言介面與語音選項：

* 文字介面：可設定為繁體中文 ( zh-TW )、簡體中文 ( zh-CN )、英文 ( en ) 等
* 語音設定：可設定 ASR ( 語音識別 ) 和 TTS ( 語音合成 ) 使用的語言

#### `MaiAgent.speech.set(lang, provider)`

設定語音語言和提供商

```jsx
// 設定語音為中文，使用 Azure 提供商
MaiAgent.speech.set('zh-TW', 'azure')

// 設定語音為英文，使用預設提供商
MaiAgent.speech.set('en-US')

```

#### `MaiAgent.locale.set(lang)`

設定介面語言

```jsx
// 設定為繁體中文
MaiAgent.locale.set('zh-TW')

// 設定為簡體中文
MaiAgent.locale.set('zh-CN')

// 設定為英文
MaiAgent.locale.set('en')

```

## 五、配置選項

### 1. 基本配置

| 選項              | 類型            | 必填 | 預設值 | 說明            |
| --------------- | ------------- | -- | --- | ------------- |
| `webChatId`     | string        | 是  | -   | 聊天機器人的唯一識別碼   |
| `baseUrl`       | string        | 是  | -   | API 服務的基礎 URL |
| `contactId`     | string        | 否  | -   | 聯絡人識別碼        |
| `queryMetadata` | object/string | 否  | -   | 額外的查詢元數據      |

### 2. 外觀配置

| 選項             | 類型     | 預設值                                  | 說明       |
| -------------- | ------ | ------------------------------------ | -------- |
| `primaryColor` | string | `#1890ff`                            | 主題顏色     |
| `buttonSize`   | string | `48`                                 | 按鈕大小（像素） |
| `buttonRadius` | string | `50%`                                | 按鈕圓角     |
| `windowWidth`  | string | `24rem`                              | 聊天視窗寬度   |
| `windowHeight` | string | `40rem`                              | 聊天視窗高度   |
| `windowRadius` | string | `0.75rem`                            | 聊天視窗圓角   |
| `boxShadow`    | string | `0.125rem 0.125rem 0.5rem #00000044` | 陰影效果     |

### 3. 位置配置

| 選項                     | 類型     | 預設值    | 說明           |
| ---------------------- | ------ | ------ | ------------ |
| `buttonPositionBottom` | string | `16`   | 按鈕距離底部距離（像素） |
| `buttonPositionRight`  | string | `16`   | 按鈕距離右側距離（像素） |
| `windowPositionBottom` | string | `5rem` | 聊天視窗距離底部距離   |
| `windowPositionRight`  | string | `1rem` | 聊天視窗距離右側距離   |

### 4. 行為配置

| 選項          | 類型      | 預設值    | 說明         |
| ----------- | ------- | ------ | ---------- |
| `allowDrag` | boolean | `true` | 是否允許拖拽聊天按鈕 |

#### 5. 自定義圖示

| 選項              | 類型     | 預設值    | 說明            |
| --------------- | ------ | ------ | ------------- |
| `closeIconHtml` | string | 預設 SVG | 自定義關閉圖示的 HTML |
| `openIconHtml`  | string | 預設 SVG | 自定義開啟圖示的 HTML |

## 六、事件類型

### 1. 可監聽的事件

| 事件名稱           | 說明           | 資料格式                                          |
| -------------- | ------------ | --------------------------------------------- |
| `messageReply` | 收到聊天機器人回覆時觸發 | `{ content: string, timestamp: number, ... }` |

### 2. 內部事件（供參考）

| 事件名稱                | 說明       |
| ------------------- | -------- |
| `setSpeechLanguage` | 設定語音語言   |
| `setLocale`         | 設定介面語言   |
| `sendMessage`       | 發送消息     |
| `clearHistory`      | 清除歷史記錄   |
| `newConversation`   | 開始新對話    |
| `closeBubbleWindow` | 關閉聊天視窗   |
| `sdkReady`          | SDK 準備就緒 |

## 七、完整範例

以下是一個完整的整合範例：

```html
<!doctype html>
<html lang="zh-TW">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>MaiAgent SDK 整合範例</title>
  </head>
  <body>
    <h1>我的網站</h1>
    <p>這裡是網站內容...</p>

    <!-- 一些互動按鈕 -->
    <button onclick="openChatBot()">開啟客服</button>
    <button onclick="sendWelcomeMessage()">發送歡迎消息</button>
    <button onclick="clearChatHistory()">清除對話</button>
    <button onclick="startNewChat()">新對話</button>

    <!-- MaiAgent SDK 配置 -->
    <script>
      window.maiagentChatbotConfig = {
        webChatId: 'your-web-chat-id',
        baseUrl: '<https://your-domain.com/web-chats>',
        primaryColor: '#007bff',
        allowDrag: true,
        buttonSize: '56',
        buttonRadius: '50%',
        windowWidth: '28rem',
        windowHeight: '45rem',
        contactId: 'website-visitor',
        queryMetadata: {
          source: 'website',
          page: window.location.pathname,
        },
      }
    </script>

    <!-- 引入 MaiAgent SDK -->
    <script src="<https://your-domain.com/js/embed.min.js>"></script>

    <!-- 應用程式邏輯 -->
    <script>
      // 等待 DOM 和 SDK 載入完成
      document.addEventListener('DOMContentLoaded', function () {
        // 設定事件監聽器
        setupEventListeners()

        // 設定語言
        MaiAgent.locale.set('zh-TW')
        MaiAgent.speech.set('zh-TW', 'azure')

        console.log('MaiAgent SDK 已就緒')
      })

      function setupEventListeners() {
        // 監聽消息回覆
        MaiAgent.events.on('messageReply', function (data) {
          console.log('收到機器人回覆:', data)

          // 可以在這裡處理回覆，例如：
          // - 收到的 data 為JSON 需要 JSON.parse(data) 一下
          // - 記錄分析數據
          // - 更新 UI 狀態
          // - 觸發其他業務邏輯
        })
      }

      // 互動函數
      function openChatBot() {
        MaiAgent.control.open()
      }

      function closeChatBot() {
        MaiAgent.control.close()
      }

      function sendWelcomeMessage() {
        MaiAgent.chat.send('你好！我想了解你們的服務')

        // 確保聊天視窗是開啟的
        MaiAgent.control.open()
      }

      function clearChatHistory() {
        if (confirm('確定要清除所有對話歷史嗎？')) {
          MaiAgent.chat.clearHistory()
          console.log('對話歷史已清除')
        }
      }

      function startNewChat() {
        MaiAgent.chat.newConversation()
        MaiAgent.control.open()
        console.log('已開始新對話')
      }

      // 監聽頁面可見性變化，在用戶回到頁面時可以發送消息
      document.addEventListener('visibilitychange', function () {
        if (!document.hidden && MaiAgent.control.isOpen()) {
          console.log('用戶回到頁面，聊天視窗仍開啟')
          // 可以在這裡執行一些操作
        }
      })
    </script>
  </body>
</html>

```

## 八、進階使用技巧

### 1. 動態配置更新

```jsx
// 動態更新主題顏色
function updateTheme(color) {
  // 注意：需要重新初始化才能生效
  window.maiagentChatbotConfig.primaryColor = color
  initializeChatbot()
  // 重新載入 SDK 或重新整理頁面
}

```

### 2. 錯誤處理

```jsx
// 檢查 SDK 是否可用
function checkSDKAvailability() {
  if (typeof MaiAgent === 'undefined') {
    console.error('MaiAgent SDK 未載入')
    return false
  }

  if (!MaiAgent.control) {
    console.error('MaiAgent SDK 未完全初始化')
    return false
  }

  return true
}

// 安全地使用 SDK
function safeOpenChat() {
  if (checkSDKAvailability()) {
    MaiAgent.control.open()
  }
  else {
    alert('聊天服務暫時無法使用，請稍後再試')
  }
}

```

### 3. 與其他系統整合

```jsx
// 與 Google Analytics 整合
MaiAgent.events.on('messageReply', (data) => {
  // 記錄聊天互動事件
  if (typeof gtag !== 'undefined') {
    gtag('event', 'chat_interaction', {
      event_category: 'engagement',
      event_label: 'bot_reply',
      value: 1
    })
  }
})

```

## 九、疑難排解

### 1. 常見問題

1. **SDK 未載入**
   * 確認 `maiagentChatbotConfig` 在 SDK 腳本之前定義
   * 檢查網路連線和腳本 URL 是否正確
2. **聊天視窗無法開啟**
   * 確認 `webChatId` 和 `baseUrl` 配置正確
   * 檢查瀏覽器主控台是否有錯誤訊息
3. **事件監聽器無效**
   * 確保在 DOM 載入完成後註冊事件監聽器
   * 檢查事件名稱是否正確
4. **按鈕位置異常**
   * 檢查 CSS 衝突
   * 確認位置參數格式正確


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.maiagent.ai/tech/api-integration/web-chat-sdk.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
