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 会继续工作