Skip to content

setChatInput:填寫聊天輸入框

setChatInput 把一段文字填入聊天輸入框。最典型的用法是選項式互動程式碼區塊 裡放幾個選項按鈕,使用者點擊後台詞自動填入輸入框,由使用者確認後發送。

函式簽名

ts
type ChatInputMode = 'roleplay' | 'guide'

declare function setChatInput(
  text: string,
  option?: { mode?: ChatInputMode },
): Promise<'roleplay' | 'guide'>

參數與行為

text 是要寫入輸入框的完整文字。該操作覆蓋目標輸入框的當前草稿,不是追加,也不會自動發送訊息——發送權始終在使用者手裡。

option 只能包含可選的 mode 欄位,出現多餘欄位會被拒絕:

mode目標行為
省略 / roleplay扮演輸入框預設;切換到「扮演」並填入文字
guide指導輸入框僅深度扮演開啟時可用;切換到「指導」並填入文字
  • 成功後 Promise 回傳實際使用的模式:roleplayguide
  • 填入一個目標不會清空另一個目標中已有的草稿

注意:指導輸入框只在使用者開啟深度扮演時存在。未開啟時請求 guide 會以 Guide input requires deep roleplay mode 拒絕——你無法假設使用者一定開著深度扮演,使用 guide 時務必處理失敗情況(提示使用者,或退回填入扮演輸入框,見下方範例)。

基本範例:選項按鈕

markdown
```html
<!doctype html>
<html>
  <head>
    <style>
      .choices { display: flex; gap: 8px; }
    </style>
  </head>
  <body>
    <div class="choices">
      <button data-text="我推開門,先觀察房間裡的動靜。">謹慎進入</button>
      <button data-text="我直接喊出她的名字。">呼喚對方</button>
    </div>

    <p id="status" aria-live="polite"></p>

    <script>
      const status = document.querySelector('#status');

      document.querySelectorAll('[data-text]').forEach((button) => {
        button.addEventListener('click', async () => {
          try {
            await setChatInput(button.dataset.text);
            status.textContent = '已填入輸入框';
          } catch (error) {
            status.textContent = error.message;
          }
        });
      });
    </script>
  </body>
</html>
```

使用「指導」輸入框

markdown
```html
<!doctype html>
<html>
  <body>
    <button id="guide">填入指導</button>

    <script>
      document.querySelector('#guide').onclick = async () => {
        const text = '讓場景轉入夜晚,並增加緊張感。';
        try {
          await setChatInput(text, { mode: 'guide' });
        } catch (error) {
          // 使用者未開啟深度扮演時 guide 不可用,退回填入扮演輸入框
          await setChatInput(text);
        }
      };
    </script>
  </body>
</html>
```

酒館助手相容:triggerSlash 與 /setinput

為讓既有酒館助手內容不改程式碼就能執行,程式碼區塊中還注入了相容函式 triggerSlash,目前支援其中最常用的 /setinput 用法:

ts
declare function triggerSlash(command: string): Promise<string>
js
await triggerSlash('/setinput 我推開門,走進房間。');

等價於:

js
await setChatInput('我推開門,走進房間。');
  • 指令名不區分大小寫
  • 成功時回傳空字串,保持與酒館助手的呼叫形式一致
  • /setinput 外的指令一律以 Only the /setinput slash command is supported 拒絕

新內容優先使用語義更明確、可以指定輸入模式的 setChatInput

能力檢測與錯誤處理

呼叫前先確認函式存在,並處理 Promise 拒絕(校驗失敗、操作失敗或逾時 10 秒都會 reject):

js
if (typeof window.setChatInput !== 'function') {
  // 當前環境不支援,隱藏相關按鈕或降級為純文字提示
} else {
  try {
    await window.setChatInput('要填入的內容');
  } catch (error) {
    console.error(error.message);
  }
}

小提示

  • 像基本範例那樣給使用者一個狀態提示(已填入 / 失敗原因),體驗會更完整
  • 已使用 /setinput 寫法的內容無需改寫,triggerSlash 會繼續運作