程式化控制
透過 React ref 從外部操作聊天室。常見用法包括:程式化填入輸入框文字,
或直接送出訊息(不需要使用者按 Enter)。
程式化控制
透過 ref 取得 ChatbotRef,可以從外部操作聊天室:呼叫 setInputValue 填入文字、透過 serviceContext 存取對話狀態。
快速填入
自訂文字
載入中…
程式範例
import { useRef } from "react";
import { Chatbot, ChatbotRef } from "@asgard-js/react";
export function App() {
const chatbotRef = useRef<ChatbotRef>(null);
return (
<>
<button onClick={() => chatbotRef.current?.setInputValue?.("你好")}>
快速填入
</button>
<Chatbot
ref={chatbotRef}
title="我的聊天室"
config={{ botProviderEndpoint: "..." }}
customChannelId="my-channel"
/>
</>
);
}
透過 sendMessage 直接送出
setInputValue 只填字,使用者還要自己按 Enter。要直接送出訊息,
用 serviceContext.sendMessage:
import { useRef } from "react";
import { Chatbot, type ChatbotRef } from "@asgard-js/react";
export function App() {
const chatbotRef = useRef<ChatbotRef>(null);
return (
<>
<button
onClick={() =>
chatbotRef.current?.serviceContext?.sendMessage?.({
text: "查詢訂單",
payload: { intent: "query-order" },
})
}
>
查訂單
</button>
<Chatbot
ref={chatbotRef}
title="我的聊天室"
config={{ botProviderEndpoint: "..." }}
customChannelId="my-channel"
/>
</>
);
}
參數
| 欄位 | 型別 | 說明 |
|---|---|---|
text | string | 訊息文字(必填) |
payload | Record<string, unknown> | (() => Record<string, unknown>) | 附加 metadata,會跟訊息一起送給 bot;全域注入見 自訂 Payload |
blobIds | string[] | 已上傳檔案的 blob ID |
filePreviewUrls | string[] | 圖片預覽 URL |
documentNames | string[] | 文件名稱 |
場景:外部 preset 按鈕
把常用的 quick-reply 抽到對話視窗外面:
const presets = [
{ label: "查訂單", text: "我想查詢訂單" },
{ label: "客服", text: "我需要真人客服" },
];
{presets.map((p) => (
<button
key={p.label}
onClick={() =>
chatbotRef.current?.serviceContext?.sendMessage?.({ text: p.text })
}
>
{p.label}
</button>
))}
ChatbotRef
| 欄位 | 型別 | 說明 |
|---|---|---|
setInputValue | (value: string) => void | 程式化設定輸入框文字 |
serviceContext | AsgardServiceContextValue | 存取完整 service context(messages、sendMessage、resetChannel、closeChannel) |