跳至主要内容

On Channel Ready

onChannelReady 在 chat channel 真正準備好接收訊息時觸發一次。 適合在 chatbot mount 後立刻送一筆訊息(例如把 SQL 帶入新對話), 取代「polling 等 sendMessage 變可用」的 hack。

Channel 重新建立(手動 resetChannel)時也會重新 fire, 若只想做一次可在上層用 useRef guard。

設定

Ready 事件 (0)

等待第一次 onChannelReady...

驗證

每筆事件記錄 callback 觸發當下 ref.current.serviceContext.sendMessage 是否可用。兩個欄位都應為 true。

聊天機器人載入中…

程式範例

import { Chatbot, ChatbotRef } from "@asgard-js/react";
import { useCallback, useRef } from "react";

function MyChatbot({ initialText }: { initialText?: string }) {
const chatbotRef = useRef<ChatbotRef>(null);

const handleChannelReady = useCallback(() => {
if (initialText) {
chatbotRef.current?.serviceContext?.sendMessage?.({
text: initialText,
blobIds: [],
});
}
}, [initialText]);

return (
<Chatbot
ref={chatbotRef}
config={{ botProviderEndpoint: "..." }}
customChannelId="my-channel"
onChannelReady={handleChannelReady}
/>
);
}

行為

  • Channel 第一次建立完成且 ref 更新後 fire 一次
  • 手動 resetChannel 後重新 fire
  • Callback 觸發當下,ref.current.serviceContext.sendMessage 已綁定到新的 channel