跳至主要内容

REFERENCE

SDK 範例

@asgard-js/core 與 @asgard-js/react 的用法與可以直接操作的範例。

程式化控制

透過 React ref 從外部操作聊天室。常見用法包括:程式化填入輸入框文字, 或直接送出訊息(不需要使用者按 Enter)。

  1. 程式範例​

    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"
    />
    </>
    );
    }
  2. 透過 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"
    />
    </>
    );
    }

    參數​

    欄位型別說明
    textstring訊息文字(必填)
    payloadRecord<string, unknown> | (() => Record<string, unknown>)附加 metadata,會跟訊息一起送給 bot;全域注入見 自訂 Payload
    blobIdsstring[]已上傳檔案的 blob ID
    filePreviewUrlsstring[]圖片預覽 URL
    documentNamesstring[]文件名稱

    場景:外部 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>
    ))}
  3. ChatbotRef​

    欄位型別說明
    setInputValue(value: string) => void程式化設定輸入框文字
    serviceContextAsgardServiceContextValue存取完整 service context(messages、sendMessage、resetChannel、closeChannel)

準備好開始了嗎?

想知道 Asgard 怎麼用在你的團隊?跟我們聊聊。

聯絡我們