获取变量
getVariables
获取变量表。
typescript
function getVariables({ type, message_id }?: VariableOption): Record<string, any>
参数
option?
一个可选的配置对象,包含以下属性:
type?
:string
- 指定操作的变量类型,默认为
'chat'
。 - 可选值:
'message'
: 针对特定消息楼层的变量。'chat'
: 整个聊天会话的变量(默认)。'character'
: 当前角色卡的变量。'global'
: 全局变量。
- 指定操作的变量类型,默认为
message_id?
:number | 'latest'
- 当
type
为'message'
时,此参数指定目标消息的楼层号。 - 如果是数字,表示具体的楼层 ID。
- 如果是负数,表示相对于最新消息的深度索引 (例如,
-1
表示最新的消息,-2
表示倒数第二条)。 'latest'
(默认值): 表示最新的消息楼层。- 此参数仅在
type
为'message'
时有效。
- 当
返回值
- 包含变量键值对的对象:
Record<string, any>
示例
typescript
const variables = getVariables();
alert(variables);
typescript
const variables = getVariables({type: 'global'});
// 酒馆助手内置了 lodash 库,你能用它做很多事,比如查询某个变量是否存在
if (_.has(variables, "神乐光.好感度")) {
/* ... */
}
typescript
// 获取倒数第二楼层的聊天变量
const variables = getVariables({type: 'message', message_id: -2});
在提示词中获取变量
你可以通过以下格式在提示词中获取变量:
变量示例
typescript
const 全局变量 = {
神乐光: {
好感度: 50,
},
};
const 聊天变量 = {
商品: [{ 内容: '...' }, { 内容: '...' }],
};
const 消息楼层变量 = {
当前剧情阶段: '...',
};
你可以通过以下格式在提示词中获取他们:
- 全局变量:
{{get_global_variable::神乐光.好感度}}
- 聊天变量:
{{get_chat_variable::商品.1.内容}}
- 消息楼层变量 (通过
setChatMessage
设置), 将会获取到最新绑定的消息楼层变量:{{get_message_variable::当前剧情阶段}}
获取到的结果与 JSON.stringify(变量)
一致, 例如:
{{get_global_variable::神乐光.好感度}}
:'50'
;{{get_global_variable::神乐光}}
:'{"好感度":50}'
;{{get_chat_variable::商品}}
:'[{"内容":"..."},{"内容":"..."}]'
;
监听变量更新
通过 iframe_events.VARIABLES_UPDATED
, 你可以监听通过 replaceVariables
或 setChatMessage
进行的变量修改操作, 从而触发对应的事件:
typescript
eventOn(iframe_events.VARIABLES_UPDATED, (type, variables) => {
if (type === 'chat' && variables.好感度 > 10) {
/* ... */
}
});
html
<script src="https://cdnjs.cloudflare.com/ajax/libs/deep-diff/1.0.2/deep-diff.min.js"></script>
<script>
eventOn(iframe_events.VARIABLES_UPDATED, (type, old_variables, new_variables) => {
const changed = diff(new_variables, old_variables);
if (type === 'chat' && changed.好感度 > 10) {
/* ... */
}
});
</script>