@cmach_socket/opencode-qq-bot 0.3.4 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +69 -0
- package/README.md +370 -44
- package/package.json +21 -2
- package/src/access.ts +79 -0
- package/src/bot-lock.ts +17 -26
- package/src/chat.ts +0 -20
- package/src/commands.ts +267 -0
- package/src/config.ts +602 -48
- package/src/emoji/command.ts +184 -0
- package/src/emoji/faces.ts +136 -0
- package/src/emoji/favorite-index.ts +150 -0
- package/src/emoji/favorites.ts +161 -0
- package/src/emoji/label.ts +318 -0
- package/src/events/notice.ts +139 -0
- package/src/events/store.ts +53 -0
- package/src/home.ts +45 -0
- package/src/index.ts +437 -63
- package/src/instance.ts +30 -17
- package/src/keepalive.ts +222 -0
- package/src/logger.ts +273 -17
- package/src/media-path.ts +186 -0
- package/src/model-view.ts +136 -0
- package/src/naplink/client.ts +14 -17
- package/src/naplink/history.ts +263 -0
- package/src/naplink/media.ts +34 -103
- package/src/naplink/render.ts +142 -33
- package/src/outbound.ts +174 -0
- package/src/overrides.ts +312 -0
- package/src/rate-limit.ts +228 -0
- package/src/safe-fetch.ts +143 -0
- package/src/sensitive.ts +309 -0
- package/src/session/manager.ts +488 -31
- package/src/session/proactive.ts +21 -0
- package/src/session/prompt.ts +4 -1
- package/src/session/soul.ts +46 -0
- package/src/tools/ask-guard.ts +5 -5
- package/src/tools/policy-guard.ts +45 -0
- package/src/tools/policy.ts +205 -0
- package/src/tools/qq.ts +353 -41
- package/src/tools/send-guard.ts +73 -0
- package/src/trace.ts +209 -0
- package/src/tui-commands.ts +70 -0
- package/src/version.ts +12 -0
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { type ChatTarget, targetLabel } from "../chat"
|
|
2
|
+
import type { CommandDefinition } from "../commands"
|
|
3
|
+
import type { QQBotConfig } from "../config"
|
|
4
|
+
import type { Logger } from "../logger"
|
|
5
|
+
import type { QQClient } from "../naplink/client"
|
|
6
|
+
import type { SendRateLimiter } from "../rate-limit"
|
|
7
|
+
import { createPlainSender } from "../tools/qq"
|
|
8
|
+
import { type CustomFace, faceTag, type FavoriteStore, formatFavoriteList } from "./favorites"
|
|
9
|
+
import { type FavoriteIndex, favoriteKey } from "./favorite-index"
|
|
10
|
+
import type { EmojiLabeler } from "./label"
|
|
11
|
+
|
|
12
|
+
export { formatFavoriteList } from "./favorites"
|
|
13
|
+
|
|
14
|
+
/** `/emoji-label` 支持的动作。 */
|
|
15
|
+
export type EmojiLabelAction = "all" | "inc" | "list" | "usage"
|
|
16
|
+
|
|
17
|
+
/** 命令名。TUI 侧注册为 `qq-emoji-label`,QQ 私聊里用 `/emoji-label`。 */
|
|
18
|
+
export const EMOJI_LABEL_COMMAND = "emoji-label"
|
|
19
|
+
|
|
20
|
+
/** 命令用法说明。 */
|
|
21
|
+
export const EMOJI_LABEL_USAGE = [
|
|
22
|
+
"用法:/emoji-label <all|inc|list>",
|
|
23
|
+
"all 重新标注全部收藏表情",
|
|
24
|
+
"inc 只标注还没有标签的收藏表情",
|
|
25
|
+
"list 列出收藏表情的编号与标签",
|
|
26
|
+
].join("\n")
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* 解析命令参数。
|
|
30
|
+
*
|
|
31
|
+
* 兼容 `/emoji-label all`、`/qq-emoji-label all`、`emoji-label all` 和只传 `all` 四种写法。
|
|
32
|
+
*/
|
|
33
|
+
export function parseEmojiLabelArgs(text: string): EmojiLabelAction {
|
|
34
|
+
const raw = text.trim()
|
|
35
|
+
const withoutName = raw.replace(/^\/?(?:qq-)?emoji-label\b[::]?/i, "").trim()
|
|
36
|
+
const arg = (withoutName.split(/\s+/)[0] ?? "").toLowerCase()
|
|
37
|
+
if (arg === "all") return "all"
|
|
38
|
+
if (arg === "inc" || arg === "incremental") return "inc"
|
|
39
|
+
if (arg === "list") return "list"
|
|
40
|
+
return "usage"
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** 标注模式:全部重标,或只补没有标签的。 */
|
|
44
|
+
export type EmojiLabelMode = "all" | "inc"
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 按模式挑出需要标注的表情。
|
|
48
|
+
*
|
|
49
|
+
* `inc` 只处理没有标签的,`all` 处理全部。
|
|
50
|
+
*/
|
|
51
|
+
export function selectFacesToLabel(
|
|
52
|
+
faces: readonly CustomFace[],
|
|
53
|
+
mode: EmojiLabelMode,
|
|
54
|
+
): CustomFace[] {
|
|
55
|
+
return mode === "inc" ? faces.filter((face) => !faceTag(face)) : [...faces]
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** 表情命令的执行依赖,不区分 TUI 还是 QQ。 */
|
|
59
|
+
export interface EmojiRunnerDeps {
|
|
60
|
+
config: QQBotConfig
|
|
61
|
+
logger: Logger
|
|
62
|
+
client: QQClient
|
|
63
|
+
favorites: FavoriteStore
|
|
64
|
+
favoriteIndex: FavoriteIndex
|
|
65
|
+
labeler: EmojiLabeler
|
|
66
|
+
limiter: SendRateLimiter
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** 表情命令的执行器:TUI 命令与 QQ 私聊共用。 */
|
|
70
|
+
export interface EmojiCommandRunner {
|
|
71
|
+
/** 在指定聊天里执行命令文本。 */
|
|
72
|
+
run(target: ChatTarget, text: string): Promise<void>
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 创建表情命令执行器;同一个实例保证标注任务排队。 */
|
|
76
|
+
export function createEmojiRunner(deps: EmojiRunnerDeps): EmojiCommandRunner {
|
|
77
|
+
const { config, logger, client, favorites, favoriteIndex, labeler, limiter } = deps
|
|
78
|
+
let running = false
|
|
79
|
+
|
|
80
|
+
const report = createPlainSender(client, {
|
|
81
|
+
delayMs: config.sendDelayMs,
|
|
82
|
+
limiter,
|
|
83
|
+
logger,
|
|
84
|
+
failure: (target) => `${targetLabel(target)} 发送表情标签结果失败`,
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
const runLabeling = async (target: ChatTarget, mode: EmojiLabelMode): Promise<void> => {
|
|
88
|
+
const faces = await favorites.list({ refresh: true })
|
|
89
|
+
// 先把编号分配好,标注结果里的编号才对得上。
|
|
90
|
+
const rows = await favoriteIndex.sync(faces)
|
|
91
|
+
const idByKey = new Map<string, number>()
|
|
92
|
+
for (const row of rows) {
|
|
93
|
+
const key = favoriteKey(row.face)
|
|
94
|
+
if (key) idByKey.set(key, row.id)
|
|
95
|
+
}
|
|
96
|
+
const pending = selectFacesToLabel(faces, mode)
|
|
97
|
+
if (pending.length === 0) {
|
|
98
|
+
await report(target, mode === "inc" ? "所有收藏表情都已经有标签了。" : "没有读取到收藏表情。")
|
|
99
|
+
return
|
|
100
|
+
}
|
|
101
|
+
await report(target, `开始为 ${pending.length} 个收藏表情生成标签…`)
|
|
102
|
+
|
|
103
|
+
const tagged: string[] = []
|
|
104
|
+
let failed = 0
|
|
105
|
+
for (const [index, face] of pending.entries()) {
|
|
106
|
+
// 插件卸载后停止标注,不再消耗模型额度。
|
|
107
|
+
if (labeler.signal.aborted) {
|
|
108
|
+
logger.info("表情标注已中止")
|
|
109
|
+
return
|
|
110
|
+
}
|
|
111
|
+
const tag = await labeler.labelFace(face)
|
|
112
|
+
const key = favoriteKey(face)
|
|
113
|
+
const id = key ? idByKey.get(key) : undefined
|
|
114
|
+
if (tag) tagged.push(`${id ?? "?"}. ${tag}`)
|
|
115
|
+
else failed += 1
|
|
116
|
+
const done = index + 1
|
|
117
|
+
if (done % 5 === 0 && done < pending.length) {
|
|
118
|
+
await report(target, `进度 ${done}/${pending.length}…`)
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const lines = [`标注完成:成功 ${tagged.length} / ${pending.length}`]
|
|
123
|
+
if (tagged.length > 0) {
|
|
124
|
+
lines.push(...tagged)
|
|
125
|
+
}
|
|
126
|
+
if (failed > 0) lines.push(`有 ${failed} 个表情没有标注成功。`)
|
|
127
|
+
await report(target, lines.join("\n"))
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const run = async (target: ChatTarget, text: string): Promise<void> => {
|
|
131
|
+
const action = parseEmojiLabelArgs(text)
|
|
132
|
+
if (action === "usage") {
|
|
133
|
+
await report(target, EMOJI_LABEL_USAGE)
|
|
134
|
+
return
|
|
135
|
+
}
|
|
136
|
+
if (action === "list") {
|
|
137
|
+
const faces = await favorites.list({ refresh: true })
|
|
138
|
+
const rows = await favoriteIndex.sync(faces)
|
|
139
|
+
await report(target, formatFavoriteList(rows))
|
|
140
|
+
return
|
|
141
|
+
}
|
|
142
|
+
if (running) {
|
|
143
|
+
await report(target, "已经有标注任务在跑了,请等它结束。")
|
|
144
|
+
return
|
|
145
|
+
}
|
|
146
|
+
running = true
|
|
147
|
+
// 标注可能要跑很久,放到后台执行,结果用 QQ 消息回。
|
|
148
|
+
void runLabeling(target, action)
|
|
149
|
+
.catch((error: unknown) => {
|
|
150
|
+
logger.error("表情标注任务失败", error)
|
|
151
|
+
return report(target, `标注失败:${error instanceof Error ? error.message : String(error)}`)
|
|
152
|
+
})
|
|
153
|
+
.finally(() => {
|
|
154
|
+
running = false
|
|
155
|
+
})
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
return { run }
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** 表情命令的用法行,`/help` 直接复用。 */
|
|
162
|
+
const EMOJI_LABEL_USAGE_LINES = [
|
|
163
|
+
"/emoji-label all — 重新标注全部收藏表情",
|
|
164
|
+
"/emoji-label inc — 只标注还没有标签的收藏表情",
|
|
165
|
+
"/emoji-label list — 列出收藏表情的编号与标签",
|
|
166
|
+
]
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* 把表情命令接进共享命令表。
|
|
170
|
+
*
|
|
171
|
+
* TUI 侧注册成 `/qq-emoji-label`,QQ 私聊里是 `/emoji-label`;
|
|
172
|
+
* 命令自己负责边跑边发进度,所以 `run` 不返回文本。
|
|
173
|
+
*/
|
|
174
|
+
export function emojiCommand(runner: EmojiCommandRunner): CommandDefinition {
|
|
175
|
+
return {
|
|
176
|
+
name: EMOJI_LABEL_COMMAND,
|
|
177
|
+
description:
|
|
178
|
+
"给收藏表情(表情包)生成中文标签:all 全部重标,inc 只补新的,list 列出编号与标签。",
|
|
179
|
+
usage: EMOJI_LABEL_USAGE_LINES,
|
|
180
|
+
run: async (context, args) => {
|
|
181
|
+
await runner.run(context.target, args.join(" "))
|
|
182
|
+
},
|
|
183
|
+
}
|
|
184
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* QQ 官方系统表情(EmojiType=1)的 ID → 名称对照表。
|
|
3
|
+
*
|
|
4
|
+
* 数据来自 QQ 官方机器人文档的公开表情表:
|
|
5
|
+
* https://github.com/tencent-connect/bot-docs/blob/main/docs/develop/api-v2/openapi/emoji/model.md
|
|
6
|
+
* 官方表本身不完整,未收录的 ID 统一回退成 `[表情:ID]`。
|
|
7
|
+
*/
|
|
8
|
+
export const QQ_FACE_NAMES: Readonly<Record<string, string>> = {
|
|
9
|
+
"4": "得意",
|
|
10
|
+
"5": "流泪",
|
|
11
|
+
"8": "睡",
|
|
12
|
+
"9": "大哭",
|
|
13
|
+
"10": "尴尬",
|
|
14
|
+
"12": "调皮",
|
|
15
|
+
"14": "微笑",
|
|
16
|
+
"16": "酷",
|
|
17
|
+
"21": "可爱",
|
|
18
|
+
"23": "傲慢",
|
|
19
|
+
"24": "饥饿",
|
|
20
|
+
"25": "困",
|
|
21
|
+
"26": "惊恐",
|
|
22
|
+
"27": "流汗",
|
|
23
|
+
"28": "憨笑",
|
|
24
|
+
"29": "悠闲",
|
|
25
|
+
"30": "奋斗",
|
|
26
|
+
"32": "疑问",
|
|
27
|
+
"33": "嘘",
|
|
28
|
+
"34": "晕",
|
|
29
|
+
"38": "敲打",
|
|
30
|
+
"39": "再见",
|
|
31
|
+
"41": "发抖",
|
|
32
|
+
"42": "爱情",
|
|
33
|
+
"43": "跳跳",
|
|
34
|
+
"49": "拥抱",
|
|
35
|
+
"53": "蛋糕",
|
|
36
|
+
"60": "咖啡",
|
|
37
|
+
"63": "玫瑰",
|
|
38
|
+
"66": "爱心",
|
|
39
|
+
"74": "太阳",
|
|
40
|
+
"75": "月亮",
|
|
41
|
+
"76": "赞",
|
|
42
|
+
"78": "握手",
|
|
43
|
+
"79": "胜利",
|
|
44
|
+
"85": "飞吻",
|
|
45
|
+
"89": "西瓜",
|
|
46
|
+
"96": "冷汗",
|
|
47
|
+
"97": "擦汗",
|
|
48
|
+
"98": "抠鼻",
|
|
49
|
+
"99": "鼓掌",
|
|
50
|
+
"100": "糗大了",
|
|
51
|
+
"101": "坏笑",
|
|
52
|
+
"102": "左哼哼",
|
|
53
|
+
"103": "右哼哼",
|
|
54
|
+
"104": "哈欠",
|
|
55
|
+
"106": "委屈",
|
|
56
|
+
"109": "左亲亲",
|
|
57
|
+
"111": "可怜",
|
|
58
|
+
"116": "示爱",
|
|
59
|
+
"118": "抱拳",
|
|
60
|
+
"120": "拳头",
|
|
61
|
+
"122": "爱你",
|
|
62
|
+
"123": "NO",
|
|
63
|
+
"124": "OK",
|
|
64
|
+
"125": "转圈",
|
|
65
|
+
"129": "挥手",
|
|
66
|
+
"144": "喝彩",
|
|
67
|
+
"147": "棒棒糖",
|
|
68
|
+
"171": "茶",
|
|
69
|
+
"173": "泪奔",
|
|
70
|
+
"174": "无奈",
|
|
71
|
+
"175": "卖萌",
|
|
72
|
+
"176": "小纠结",
|
|
73
|
+
"179": "doge",
|
|
74
|
+
"180": "惊喜",
|
|
75
|
+
"181": "骚扰",
|
|
76
|
+
"182": "笑哭",
|
|
77
|
+
"183": "我最美",
|
|
78
|
+
"201": "点赞",
|
|
79
|
+
"203": "托脸",
|
|
80
|
+
"212": "托腮",
|
|
81
|
+
"214": "啵啵",
|
|
82
|
+
"219": "蹭一蹭",
|
|
83
|
+
"222": "抱抱",
|
|
84
|
+
"227": "拍手",
|
|
85
|
+
"232": "佛系",
|
|
86
|
+
"240": "喷脸",
|
|
87
|
+
"243": "甩头",
|
|
88
|
+
"246": "加油抱抱",
|
|
89
|
+
"262": "脑阔疼",
|
|
90
|
+
"264": "捂脸",
|
|
91
|
+
"265": "辣眼睛",
|
|
92
|
+
"266": "哦哟",
|
|
93
|
+
"267": "头秃",
|
|
94
|
+
"268": "问号脸",
|
|
95
|
+
"269": "暗中观察",
|
|
96
|
+
"270": "emm",
|
|
97
|
+
"271": "吃瓜",
|
|
98
|
+
"272": "呵呵哒",
|
|
99
|
+
"273": "我酸了",
|
|
100
|
+
"277": "汪汪",
|
|
101
|
+
"278": "汗",
|
|
102
|
+
"281": "无眼笑",
|
|
103
|
+
"282": "敬礼",
|
|
104
|
+
"284": "面无表情",
|
|
105
|
+
"285": "摸鱼",
|
|
106
|
+
"287": "哦",
|
|
107
|
+
"289": "睁眼",
|
|
108
|
+
"290": "敲开心",
|
|
109
|
+
"293": "摸锦鲤",
|
|
110
|
+
"294": "期待",
|
|
111
|
+
"297": "拜谢",
|
|
112
|
+
"298": "元宝",
|
|
113
|
+
"299": "牛啊",
|
|
114
|
+
"305": "右亲亲",
|
|
115
|
+
"306": "牛气冲天",
|
|
116
|
+
"307": "喵喵",
|
|
117
|
+
"314": "仔细分析",
|
|
118
|
+
"315": "加油",
|
|
119
|
+
"318": "崇拜",
|
|
120
|
+
"319": "比心",
|
|
121
|
+
"320": "庆祝",
|
|
122
|
+
"322": "拒绝",
|
|
123
|
+
"324": "吃糖",
|
|
124
|
+
"326": "生气",
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** 查官方表情名称;未收录的 ID 返回 undefined。 */
|
|
128
|
+
export function faceName(id: string | number): string | undefined {
|
|
129
|
+
return QQ_FACE_NAMES[String(id)]
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** 渲染成提示词里的占位文本,例如 `[得意]`。 */
|
|
133
|
+
export function renderFace(id: string | number): string {
|
|
134
|
+
const name = faceName(id)
|
|
135
|
+
return name ? `[${name}]` : `[表情:${String(id)}]`
|
|
136
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import type { Plugin } from "@opencode/plugin"
|
|
2
|
+
import { Mutex } from "async-mutex"
|
|
3
|
+
import type { Logger } from "../logger"
|
|
4
|
+
import { type CustomFace, faceTag, type FavoriteRow } from "./favorites"
|
|
5
|
+
|
|
6
|
+
/** 插件存储里收藏表情编号索引的键。 */
|
|
7
|
+
export const FAVORITE_INDEX_KEY = "emoji-favorite-index"
|
|
8
|
+
|
|
9
|
+
/** 编号索引用到的插件存储接口。 */
|
|
10
|
+
export type IndexStorage = Pick<Plugin.Context["storage"], "get" | "set">
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 收藏表情的身份键。
|
|
14
|
+
*
|
|
15
|
+
* 绝对依据是图片的 `md5`:同一张图就是同一个收藏表情,NapCat 侧的
|
|
16
|
+
* `emo_id`、`res_id`、列表顺序变化都不影响认回。
|
|
17
|
+
*
|
|
18
|
+
* `md5` 缺失时退到 `res_id`,再退到 `emo_id`。
|
|
19
|
+
*/
|
|
20
|
+
export function favoriteKey(face: CustomFace): string | undefined {
|
|
21
|
+
const md5 = typeof face.md5 === "string" ? face.md5.trim().toLowerCase() : ""
|
|
22
|
+
if (md5.length > 0) return `md5:${md5}`
|
|
23
|
+
const resId = typeof face.resId === "string" ? face.resId.trim() : ""
|
|
24
|
+
if (resId.length > 0) return `res:${resId}`
|
|
25
|
+
if (face.emoId !== undefined && face.emoId !== null) return `emo:${String(face.emoId)}`
|
|
26
|
+
return undefined
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
interface StoredEntry {
|
|
30
|
+
key: string
|
|
31
|
+
id: number
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 从插件存储里读回编号记录,格式不对就当没有。 */
|
|
35
|
+
function parseEntries(stored: unknown): StoredEntry[] {
|
|
36
|
+
if (!stored || typeof stored !== "object" || Array.isArray(stored)) return []
|
|
37
|
+
const raw = (stored as { entries?: unknown }).entries
|
|
38
|
+
if (!Array.isArray(raw)) return []
|
|
39
|
+
const entries: StoredEntry[] = []
|
|
40
|
+
for (const item of raw) {
|
|
41
|
+
if (!item || typeof item !== "object") continue
|
|
42
|
+
const { key, id } = item as { key?: unknown; id?: unknown }
|
|
43
|
+
if (typeof key !== "string" || key.length === 0) continue
|
|
44
|
+
if (typeof id !== "number" || !Number.isInteger(id) || id <= 0) continue
|
|
45
|
+
entries.push({ key, id })
|
|
46
|
+
}
|
|
47
|
+
return entries
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 插件自维护的收藏表情编号。
|
|
52
|
+
*
|
|
53
|
+
* 编号只是发图片时的句柄,真正的身份依据是图片 `md5`;编号按首次出现的顺序
|
|
54
|
+
* 从 1 开始分配,写在插件存储里,之后每次读取都按身份键认回原来的编号,
|
|
55
|
+
* 所以 NapCat 侧的 `emo_id` 变化、列表顺序变化都不影响编号,
|
|
56
|
+
* 被删掉的收藏表情留下的编号也不会再分配给别的表情。
|
|
57
|
+
*/
|
|
58
|
+
export class FavoriteIndex {
|
|
59
|
+
private readonly entries = new Map<string, number>()
|
|
60
|
+
private readonly mutex = new Mutex()
|
|
61
|
+
private loading: Promise<void> | undefined
|
|
62
|
+
private loaded = false
|
|
63
|
+
|
|
64
|
+
constructor(
|
|
65
|
+
private readonly storage: IndexStorage,
|
|
66
|
+
private readonly logger: Logger,
|
|
67
|
+
) {}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 读取收藏表情列表并给每个表情配上编号。
|
|
71
|
+
*
|
|
72
|
+
* 返回的顺序按编号从小到大;`md5` 相同的记录视为同一个表情,只保留一条。
|
|
73
|
+
*/
|
|
74
|
+
async sync(faces: readonly CustomFace[]): Promise<FavoriteRow[]> {
|
|
75
|
+
await this.ensureLoaded()
|
|
76
|
+
const rows: FavoriteRow[] = []
|
|
77
|
+
const seen = new Set<string>()
|
|
78
|
+
let changed = false
|
|
79
|
+
let nextId = this.nextId()
|
|
80
|
+
for (const face of faces) {
|
|
81
|
+
const key = favoriteKey(face)
|
|
82
|
+
if (!key) continue
|
|
83
|
+
if (seen.has(key)) {
|
|
84
|
+
this.logger.warn("收藏表情存在相同 md5 的重复记录,按 md5 去重")
|
|
85
|
+
continue
|
|
86
|
+
}
|
|
87
|
+
seen.add(key)
|
|
88
|
+
let id = this.entries.get(key)
|
|
89
|
+
if (id === undefined) {
|
|
90
|
+
id = nextId
|
|
91
|
+
nextId += 1
|
|
92
|
+
this.entries.set(key, id)
|
|
93
|
+
changed = true
|
|
94
|
+
}
|
|
95
|
+
rows.push({ id, face, tag: faceTag(face) })
|
|
96
|
+
}
|
|
97
|
+
rows.sort((left, right) => left.id - right.id)
|
|
98
|
+
if (changed) await this.persist()
|
|
99
|
+
return rows
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** 按编号找收藏表情;编号不存在时返回 undefined。 */
|
|
103
|
+
async resolve(faces: readonly CustomFace[], id: number): Promise<FavoriteRow | undefined> {
|
|
104
|
+
const rows = await this.sync(faces)
|
|
105
|
+
return rows.find((row) => row.id === id)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 下一个可用的编号。 */
|
|
109
|
+
private nextId(): number {
|
|
110
|
+
let max = 0
|
|
111
|
+
for (const id of this.entries.values()) {
|
|
112
|
+
if (id > max) max = id
|
|
113
|
+
}
|
|
114
|
+
return max + 1
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 从插件存储恢复编号索引;读取失败下次重试,不影响正常使用。 */
|
|
118
|
+
private ensureLoaded(): Promise<void> {
|
|
119
|
+
if (this.loaded) return Promise.resolve()
|
|
120
|
+
this.loading ??= this.read()
|
|
121
|
+
.then(() => {
|
|
122
|
+
this.loaded = true
|
|
123
|
+
})
|
|
124
|
+
.catch((error: unknown) => {
|
|
125
|
+
// 读取失败不缓存结果,下次调用重新读,避免索引长期为空、编号从头分配。
|
|
126
|
+
this.logger.warn("读取收藏表情编号索引失败", error)
|
|
127
|
+
this.loading = undefined
|
|
128
|
+
})
|
|
129
|
+
return this.loading
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
private async read(): Promise<void> {
|
|
133
|
+
const stored = await this.storage.get(FAVORITE_INDEX_KEY)
|
|
134
|
+
for (const entry of parseEntries(stored)) {
|
|
135
|
+
if (!this.entries.has(entry.key)) this.entries.set(entry.key, entry.id)
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** 写回编号索引,串行执行避免互相覆盖。 */
|
|
140
|
+
private async persist(): Promise<void> {
|
|
141
|
+
await this.mutex.runExclusive(async () => {
|
|
142
|
+
try {
|
|
143
|
+
const entries = [...this.entries.entries()].map(([key, id]) => ({ key, id }))
|
|
144
|
+
await this.storage.set(FAVORITE_INDEX_KEY, { version: 1, entries })
|
|
145
|
+
} catch (error) {
|
|
146
|
+
this.logger.error("保存收藏表情编号索引失败", error)
|
|
147
|
+
}
|
|
148
|
+
})
|
|
149
|
+
}
|
|
150
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { Mutex } from "async-mutex"
|
|
2
|
+
import type { Logger } from "../logger"
|
|
3
|
+
import { sanitizeUntrustedText } from "../model-view"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* NapCat 收藏表情(自定义表情)的详情。
|
|
7
|
+
*
|
|
8
|
+
* 只声明插件用到的字段,其余字段保持原样透传。
|
|
9
|
+
*/
|
|
10
|
+
export interface CustomFace {
|
|
11
|
+
/** 表情所属的 QQ 号。 */
|
|
12
|
+
uin?: number | string
|
|
13
|
+
/** 表情编号(账号内唯一),写标签和发送时都用它。 */
|
|
14
|
+
emoId?: number | string
|
|
15
|
+
/** 资源 ID,写标签时用。 */
|
|
16
|
+
resId?: string
|
|
17
|
+
/** CDN 直链,发送收藏表情时用。 */
|
|
18
|
+
url?: string
|
|
19
|
+
/** 图片 md5,写标签时 NapCat 会校验。 */
|
|
20
|
+
md5?: string
|
|
21
|
+
/** 自定义标签;标签只存在 NapCat 的这个字段里。 */
|
|
22
|
+
desc?: string
|
|
23
|
+
[key: string]: unknown
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** OneBot 动作调用器。 */
|
|
27
|
+
export type OneBotCall = (method: string, params?: Record<string, unknown>) => Promise<unknown>
|
|
28
|
+
|
|
29
|
+
/** 收藏表情列表的缓存时长。 */
|
|
30
|
+
export const FAVORITE_CACHE_TTL_MS = 30_000
|
|
31
|
+
/** 一次拉取的收藏表情数量。 */
|
|
32
|
+
export const FAVORITE_FETCH_COUNT = 48
|
|
33
|
+
/** 收藏表情(KCUSTOM)图片段的 sub_type。 */
|
|
34
|
+
export const CUSTOM_FACE_SUB_TYPE = 1
|
|
35
|
+
|
|
36
|
+
/** 读取收藏表情上的标签,没有标签时返回空字符串。 */
|
|
37
|
+
export function faceTag(face: CustomFace): string {
|
|
38
|
+
// desc 由表情主人撰写,属于不受信任文本,进提示词前先净化。
|
|
39
|
+
return typeof face.desc === "string" ? sanitizeUntrustedText(face.desc).trim() : ""
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** 判断一个图片段是不是收藏表情。 */
|
|
43
|
+
export function isCustomFaceImage(data: { sub_type?: unknown }): boolean {
|
|
44
|
+
const subType = data.sub_type
|
|
45
|
+
return subType === CUSTOM_FACE_SUB_TYPE || subType === String(CUSTOM_FACE_SUB_TYPE)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* 收藏表情的编号与数据的对应关系。
|
|
50
|
+
*
|
|
51
|
+
* 编号由插件自己维护(见 `favorite-index.ts`),与 NapCat 的 `emo_id` 无关。
|
|
52
|
+
*/
|
|
53
|
+
export interface FavoriteRow {
|
|
54
|
+
/** 插件维护的稳定编号,从 1 开始。 */
|
|
55
|
+
id: number
|
|
56
|
+
/** 对应的收藏表情。 */
|
|
57
|
+
face: CustomFace
|
|
58
|
+
/** 收藏表情当前的标签。 */
|
|
59
|
+
tag: string
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 列出收藏表情的编号与标签。
|
|
64
|
+
*
|
|
65
|
+
* 编号就是发送收藏表情时用的 id。
|
|
66
|
+
*/
|
|
67
|
+
export function formatFavoriteList(rows: readonly FavoriteRow[]): string {
|
|
68
|
+
if (rows.length === 0) return "没有读取到收藏表情。"
|
|
69
|
+
const lines = rows.map((row) => `${row.id}. ${row.tag || "(未标注)"}`)
|
|
70
|
+
return [`收藏表情(编号即发送用的 id,共 ${rows.length} 个)`, ...lines].join("\n")
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 把收藏表情的编号列成一行,用于报错时提示可用编号。 */
|
|
74
|
+
export function formatFavoriteIds(rows: readonly FavoriteRow[]): string {
|
|
75
|
+
const items = rows.map((row) => (row.tag ? `${row.id}(${row.tag})` : `${row.id}`))
|
|
76
|
+
return items.length > 0 ? items.join(", ") : "(没有收藏表情)"
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 收藏表情的读写入口。
|
|
81
|
+
*
|
|
82
|
+
* 列表带短时缓存,写标签串行执行,避免并发写坏 NapCat 侧的描述。
|
|
83
|
+
*/
|
|
84
|
+
export class FavoriteStore {
|
|
85
|
+
private readonly writeMutex = new Mutex()
|
|
86
|
+
private cache: { faces: CustomFace[]; expires: number } | undefined
|
|
87
|
+
private inflight: Promise<CustomFace[]> | undefined
|
|
88
|
+
|
|
89
|
+
constructor(
|
|
90
|
+
private readonly call: OneBotCall,
|
|
91
|
+
private readonly logger: Logger,
|
|
92
|
+
private readonly ttlMs = FAVORITE_CACHE_TTL_MS,
|
|
93
|
+
) {}
|
|
94
|
+
|
|
95
|
+
/** 读取收藏表情列表;短时间内的重复请求走缓存。 */
|
|
96
|
+
async list(options: { refresh?: boolean } = {}): Promise<CustomFace[]> {
|
|
97
|
+
if (!options.refresh) {
|
|
98
|
+
const cached = this.cache
|
|
99
|
+
if (cached && cached.expires > Date.now()) return cached.faces
|
|
100
|
+
}
|
|
101
|
+
// 先等在途请求结束,避免刷新被它吞掉;非刷新调用直接复用它的结果,
|
|
102
|
+
// 否则在途请求刚填好缓存又会多打一次接口。
|
|
103
|
+
const inflight = this.inflight
|
|
104
|
+
if (inflight) {
|
|
105
|
+
const faces = await inflight.catch(() => undefined)
|
|
106
|
+
if (!options.refresh && faces !== undefined) return faces
|
|
107
|
+
}
|
|
108
|
+
this.inflight ??= this.fetch().finally(() => {
|
|
109
|
+
this.inflight = undefined
|
|
110
|
+
})
|
|
111
|
+
return this.inflight
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
private async fetch(): Promise<CustomFace[]> {
|
|
115
|
+
try {
|
|
116
|
+
const data = await this.call("fetch_custom_face_detail", { count: FAVORITE_FETCH_COUNT })
|
|
117
|
+
const items = Array.isArray(data) ? data : []
|
|
118
|
+
const faces = items.filter(
|
|
119
|
+
(item): item is CustomFace => typeof item === "object" && item !== null,
|
|
120
|
+
)
|
|
121
|
+
this.cache = { faces, expires: Date.now() + this.ttlMs }
|
|
122
|
+
return faces
|
|
123
|
+
} catch (error) {
|
|
124
|
+
this.logger.error("读取收藏表情失败", error)
|
|
125
|
+
return this.cache?.faces ?? []
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* 写入标签。
|
|
131
|
+
*
|
|
132
|
+
* 标签只写在 NapCat 的 `desc` 字段里,插件不保存副本。
|
|
133
|
+
*/
|
|
134
|
+
async setTag(face: CustomFace, tag: string): Promise<boolean> {
|
|
135
|
+
const { emoId, resId, md5 } = face
|
|
136
|
+
if (emoId === undefined || !resId || !md5) {
|
|
137
|
+
this.logger.warn("收藏表情缺少 emoId/res_id/md5,无法写入标签")
|
|
138
|
+
return false
|
|
139
|
+
}
|
|
140
|
+
return this.writeMutex.runExclusive(async () => {
|
|
141
|
+
try {
|
|
142
|
+
await this.call("set_custom_face_desc", {
|
|
143
|
+
emoji_id: emoId,
|
|
144
|
+
res_id: resId,
|
|
145
|
+
md5,
|
|
146
|
+
desc: tag,
|
|
147
|
+
})
|
|
148
|
+
this.invalidate()
|
|
149
|
+
return true
|
|
150
|
+
} catch (error) {
|
|
151
|
+
this.logger.error(`写入收藏表情标签失败 res_id=${resId}`, error)
|
|
152
|
+
return false
|
|
153
|
+
}
|
|
154
|
+
})
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** 让缓存失效,下次读取重新拉取。 */
|
|
158
|
+
invalidate(): void {
|
|
159
|
+
this.cache = undefined
|
|
160
|
+
}
|
|
161
|
+
}
|