@nestim/koishi-plugin-qq-group-manager 1.1.3 → 1.2.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/CHANGELOG.md +299 -0
- package/lib/ai/engine.d.ts +74 -0
- package/lib/ai/engine.js +525 -0
- package/lib/ai/memory.d.ts +30 -0
- package/lib/ai/memory.js +89 -0
- package/lib/ai/prompt.d.ts +36 -0
- package/lib/ai/prompt.js +125 -0
- package/lib/ai/provider.d.ts +48 -0
- package/lib/ai/provider.js +194 -0
- package/lib/ai/state.d.ts +53 -0
- package/lib/ai/state.js +62 -0
- package/lib/ai/trigger.d.ts +28 -0
- package/lib/ai/trigger.js +41 -0
- package/lib/ai/vision.d.ts +15 -0
- package/lib/ai/vision.js +64 -0
- package/lib/core/names.d.ts +48 -0
- package/lib/core/names.js +144 -0
- package/lib/core/text.d.ts +47 -0
- package/lib/core/text.js +284 -0
- package/lib/index.d.ts +263 -54
- package/lib/index.js +19 -13
- package/lib/service.d.ts +574 -153
- package/lib/service.js +56 -1221
- package/package.json +20 -7
- package/readme.md +149 -11
- package/src/ai/engine.ts +568 -0
- package/src/ai/memory.ts +104 -0
- package/src/ai/prompt.ts +142 -0
- package/src/ai/provider.ts +221 -0
- package/src/ai/state.ts +91 -0
- package/src/ai/trigger.ts +60 -0
- package/src/ai/vision.ts +81 -0
- package/src/core/names.ts +158 -0
- package/src/core/text.ts +332 -0
- package/src/index.ts +186 -0
- package/src/service.js +3327 -0
- package/tsconfig.json +24 -0
- package/lib/commands.d.ts +0 -4
- package/lib/commands.js +0 -18
- package/lib/types.d.ts +0 -23
- package/lib/types.js +0 -2
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 群名片解析。
|
|
3
|
+
*
|
|
4
|
+
* 旧实现只读 `session.username`,拿不到时直接退化成 QQ 昵称或 QQ 号,
|
|
5
|
+
* 而且从不调用 getGroupMemberInfo 兜底。这里统一成一条链路:
|
|
6
|
+
*
|
|
7
|
+
* sender.card(群名片) → getGroupMemberInfo().card → sender.nickname → QQ 号
|
|
8
|
+
*
|
|
9
|
+
* 结果按「群 + QQ」缓存,避免每条消息都打 API。
|
|
10
|
+
*/
|
|
11
|
+
export type MemberRole = 'owner' | 'admin' | 'member' | 'unknown';
|
|
12
|
+
export interface MemberIdentity {
|
|
13
|
+
qq: string;
|
|
14
|
+
name: string;
|
|
15
|
+
role: MemberRole;
|
|
16
|
+
/** 群名片是否为空(为空说明群成员没设名片) */
|
|
17
|
+
cardEmpty: boolean;
|
|
18
|
+
}
|
|
19
|
+
export interface NameHost {
|
|
20
|
+
getOneBotApi(session: any): any;
|
|
21
|
+
toGroupId(session: any): number | null;
|
|
22
|
+
logger: any;
|
|
23
|
+
}
|
|
24
|
+
export declare function roleLabel(role: MemberRole): string;
|
|
25
|
+
export declare function normalizeRole(raw: unknown): MemberRole;
|
|
26
|
+
export declare class NameResolver {
|
|
27
|
+
private host;
|
|
28
|
+
private cache;
|
|
29
|
+
constructor(host: NameHost);
|
|
30
|
+
/** 从消息事件本身取身份(最快,零 API) */
|
|
31
|
+
fromSession(session: any): MemberIdentity;
|
|
32
|
+
private key;
|
|
33
|
+
/** 查群成员资料(带缓存)。失败返回 null,绝不抛错。 */
|
|
34
|
+
lookup(session: any, qq: string): Promise<{
|
|
35
|
+
name: string;
|
|
36
|
+
role: MemberRole;
|
|
37
|
+
} | null>;
|
|
38
|
+
/** 给某个 session 生成同步用的「QQ → 名字」解析函数(renderMessage 用) */
|
|
39
|
+
resolverFor(session: any): (qq: string) => Promise<string>;
|
|
40
|
+
/**
|
|
41
|
+
* 解析发言人身份:事件自带的群名片优先;为空才查 API。
|
|
42
|
+
* 返回值里 role 尽量给出,供提示词标注「群主/管理员/成员」。
|
|
43
|
+
*/
|
|
44
|
+
identify(session: any): Promise<MemberIdentity>;
|
|
45
|
+
/** 指令回显用:尽量给出「群名片(QQ)」 */
|
|
46
|
+
display(session: any, qq: string): Promise<string>;
|
|
47
|
+
clear(): void;
|
|
48
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* 群名片解析。
|
|
4
|
+
*
|
|
5
|
+
* 旧实现只读 `session.username`,拿不到时直接退化成 QQ 昵称或 QQ 号,
|
|
6
|
+
* 而且从不调用 getGroupMemberInfo 兜底。这里统一成一条链路:
|
|
7
|
+
*
|
|
8
|
+
* sender.card(群名片) → getGroupMemberInfo().card → sender.nickname → QQ 号
|
|
9
|
+
*
|
|
10
|
+
* 结果按「群 + QQ」缓存,避免每条消息都打 API。
|
|
11
|
+
*/
|
|
12
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
+
exports.NameResolver = void 0;
|
|
14
|
+
exports.roleLabel = roleLabel;
|
|
15
|
+
exports.normalizeRole = normalizeRole;
|
|
16
|
+
const ROLE_LABELS = {
|
|
17
|
+
owner: '群主',
|
|
18
|
+
admin: '管理员',
|
|
19
|
+
member: '成员',
|
|
20
|
+
unknown: '',
|
|
21
|
+
};
|
|
22
|
+
const CACHE_TTL_MS = 10 * 60 * 1000;
|
|
23
|
+
const NEGATIVE_TTL_MS = 60 * 1000;
|
|
24
|
+
function roleLabel(role) {
|
|
25
|
+
return ROLE_LABELS[role] ?? '';
|
|
26
|
+
}
|
|
27
|
+
function normalizeRole(raw) {
|
|
28
|
+
const value = String(raw ?? '').toLowerCase();
|
|
29
|
+
if (value === 'owner' || value === 'admin' || value === 'member')
|
|
30
|
+
return value;
|
|
31
|
+
return 'unknown';
|
|
32
|
+
}
|
|
33
|
+
class NameResolver {
|
|
34
|
+
host;
|
|
35
|
+
cache = new Map();
|
|
36
|
+
constructor(host) {
|
|
37
|
+
this.host = host;
|
|
38
|
+
}
|
|
39
|
+
/** 从消息事件本身取身份(最快,零 API) */
|
|
40
|
+
fromSession(session) {
|
|
41
|
+
const qq = String(session?.userId ?? '').trim();
|
|
42
|
+
const card = String(session?.author?.nick ?? '').trim();
|
|
43
|
+
const nickname = String(session?.author?.name ?? '').trim();
|
|
44
|
+
const role = normalizeRole(session?.author?.roles?.[0]?.id ?? session?.sender?.role);
|
|
45
|
+
return {
|
|
46
|
+
qq,
|
|
47
|
+
name: card || nickname || qq,
|
|
48
|
+
role,
|
|
49
|
+
cardEmpty: !card,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
key(guildId, qq) {
|
|
53
|
+
return `${guildId}:${qq}`;
|
|
54
|
+
}
|
|
55
|
+
/** 查群成员资料(带缓存)。失败返回 null,绝不抛错。 */
|
|
56
|
+
async lookup(session, qq) {
|
|
57
|
+
const id = String(qq ?? '').trim();
|
|
58
|
+
if (!id)
|
|
59
|
+
return null;
|
|
60
|
+
const guildId = String(session?.guildId ?? '');
|
|
61
|
+
const key = this.key(guildId, id);
|
|
62
|
+
const cached = this.cache.get(key);
|
|
63
|
+
if (cached && cached.exp > Date.now()) {
|
|
64
|
+
return { name: cached.name, role: cached.role };
|
|
65
|
+
}
|
|
66
|
+
const onebot = this.host.getOneBotApi(session);
|
|
67
|
+
const groupId = this.host.toGroupId(session);
|
|
68
|
+
if (!onebot?.getGroupMemberInfo || groupId == null)
|
|
69
|
+
return null;
|
|
70
|
+
try {
|
|
71
|
+
// OneBot 的 getGroupMemberInfo 没有超时保证,这里兜一个 3 秒上限,
|
|
72
|
+
// 避免偶发的接口卡住把消息处理链路拖死(拿不到就退回昵称/QQ 号)。
|
|
73
|
+
const info = await Promise.race([
|
|
74
|
+
onebot.getGroupMemberInfo(groupId, Number(id), true),
|
|
75
|
+
new Promise((resolve) => setTimeout(() => resolve(null), 3000)),
|
|
76
|
+
]);
|
|
77
|
+
if (!info) {
|
|
78
|
+
this.cache.set(key, { name: '', role: 'unknown', cardEmpty: true, exp: Date.now() + NEGATIVE_TTL_MS });
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
const card = String(info.card ?? '').trim();
|
|
82
|
+
const nickname = String(info.nickname ?? info.nick ?? '').trim();
|
|
83
|
+
const name = card || nickname;
|
|
84
|
+
const role = normalizeRole(info.role);
|
|
85
|
+
this.cache.set(key, {
|
|
86
|
+
name,
|
|
87
|
+
role,
|
|
88
|
+
cardEmpty: !card,
|
|
89
|
+
exp: Date.now() + CACHE_TTL_MS,
|
|
90
|
+
});
|
|
91
|
+
return { name, role };
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
this.cache.set(key, { name: '', role: 'unknown', cardEmpty: true, exp: Date.now() + NEGATIVE_TTL_MS });
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/** 给某个 session 生成同步用的「QQ → 名字」解析函数(renderMessage 用) */
|
|
99
|
+
resolverFor(session) {
|
|
100
|
+
return async (qq) => {
|
|
101
|
+
const id = String(qq ?? '').trim();
|
|
102
|
+
if (!id)
|
|
103
|
+
return '';
|
|
104
|
+
const cached = this.cache.get(this.key(String(session?.guildId ?? ''), id));
|
|
105
|
+
if (cached?.name)
|
|
106
|
+
return cached.name;
|
|
107
|
+
const found = await this.lookup(session, id);
|
|
108
|
+
return found?.name || id;
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* 解析发言人身份:事件自带的群名片优先;为空才查 API。
|
|
113
|
+
* 返回值里 role 尽量给出,供提示词标注「群主/管理员/成员」。
|
|
114
|
+
*/
|
|
115
|
+
async identify(session) {
|
|
116
|
+
const base = this.fromSession(session);
|
|
117
|
+
if (!base.qq)
|
|
118
|
+
return base;
|
|
119
|
+
const role = base.role;
|
|
120
|
+
if (!base.cardEmpty && role !== 'unknown')
|
|
121
|
+
return base;
|
|
122
|
+
const found = await this.lookup(session, base.qq);
|
|
123
|
+
if (!found)
|
|
124
|
+
return { ...base, role };
|
|
125
|
+
return {
|
|
126
|
+
qq: base.qq,
|
|
127
|
+
name: found.name || base.name,
|
|
128
|
+
role: role !== 'unknown' ? role : found.role,
|
|
129
|
+
cardEmpty: base.cardEmpty,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
/** 指令回显用:尽量给出「群名片(QQ)」 */
|
|
133
|
+
async display(session, qq) {
|
|
134
|
+
const id = String(qq ?? '').trim();
|
|
135
|
+
if (!id)
|
|
136
|
+
return '';
|
|
137
|
+
const found = await this.lookup(session, id);
|
|
138
|
+
return found?.name ? `${found.name}(${id})` : id;
|
|
139
|
+
}
|
|
140
|
+
clear() {
|
|
141
|
+
this.cache.clear();
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
exports.NameResolver = NameResolver;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 消息渲染:把 Koishi/OneBot 的 session 变成"人或模型都能读懂"的一行文本。
|
|
3
|
+
*
|
|
4
|
+
* 旧实现直接用 `content.replace(/<[^>]+>/g, ' ')`,等于把 @、图片、表情、卡片、
|
|
5
|
+
* 引用全部抹掉——模型因此不知道"谁在叫谁",也看不到被回复的原文。
|
|
6
|
+
* 这里按元素逐项渲染,并单独抽出图片引用供视觉模型使用。
|
|
7
|
+
*/
|
|
8
|
+
export type NameResolver = (qq: string) => Promise<string>;
|
|
9
|
+
export interface RenderedImage {
|
|
10
|
+
url: string;
|
|
11
|
+
ref: string;
|
|
12
|
+
sticker: boolean;
|
|
13
|
+
}
|
|
14
|
+
export interface RenderedQuote {
|
|
15
|
+
userId: string;
|
|
16
|
+
name: string;
|
|
17
|
+
text: string;
|
|
18
|
+
}
|
|
19
|
+
export interface RenderedMessage {
|
|
20
|
+
/** 已渲染的正文(含 @名字 / [图片] 等占位) */
|
|
21
|
+
text: string;
|
|
22
|
+
/** 本条消息自带的图片(不含引用里的) */
|
|
23
|
+
images: RenderedImage[];
|
|
24
|
+
/** 引用(被回复)的那条消息 */
|
|
25
|
+
quote?: RenderedQuote;
|
|
26
|
+
/** 正文里点名到的 QQ 号(不含 bot 自己) */
|
|
27
|
+
mentions: string[];
|
|
28
|
+
/** 本条消息是否 @ 了 bot(与 session.content 的格式无关) */
|
|
29
|
+
atBot: boolean;
|
|
30
|
+
/** 纯文本,用于关键词/记忆匹配 */
|
|
31
|
+
plain: string;
|
|
32
|
+
/** 是否是纯图片/表情消息 */
|
|
33
|
+
visualOnly: boolean;
|
|
34
|
+
}
|
|
35
|
+
declare function truncate(value: string, max: number): string;
|
|
36
|
+
declare function stripTags(content: string): string;
|
|
37
|
+
/**
|
|
38
|
+
* 渲染一条消息。
|
|
39
|
+
* - @ 会解析成群名片(`@你` 表示 @bot)
|
|
40
|
+
* - 图片/表情/卡片/转发/语音都有占位
|
|
41
|
+
* - 引用消息(被回复的那条)单独返回,由提示词层决定怎么用
|
|
42
|
+
*/
|
|
43
|
+
export declare function renderMessage(session: any, resolveName: NameResolver, options?: {
|
|
44
|
+
selfId?: string;
|
|
45
|
+
quoteMaxChars?: number;
|
|
46
|
+
}): Promise<RenderedMessage>;
|
|
47
|
+
export { truncate, stripTags };
|
package/lib/core/text.js
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* 消息渲染:把 Koishi/OneBot 的 session 变成"人或模型都能读懂"的一行文本。
|
|
4
|
+
*
|
|
5
|
+
* 旧实现直接用 `content.replace(/<[^>]+>/g, ' ')`,等于把 @、图片、表情、卡片、
|
|
6
|
+
* 引用全部抹掉——模型因此不知道"谁在叫谁",也看不到被回复的原文。
|
|
7
|
+
* 这里按元素逐项渲染,并单独抽出图片引用供视觉模型使用。
|
|
8
|
+
*/
|
|
9
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
+
exports.renderMessage = renderMessage;
|
|
11
|
+
exports.truncate = truncate;
|
|
12
|
+
exports.stripTags = stripTags;
|
|
13
|
+
const CARD_TYPES = new Set(['card', 'json', 'xml', 'share', 'music', 'location']);
|
|
14
|
+
const FORWARD_TYPES = new Set(['forward', 'node', 'nodes']);
|
|
15
|
+
function decodeEntities(value) {
|
|
16
|
+
return String(value || '')
|
|
17
|
+
.replace(/&/gi, '&')
|
|
18
|
+
.replace(/</gi, '<')
|
|
19
|
+
.replace(/>/gi, '>')
|
|
20
|
+
.replace(/"/gi, '"')
|
|
21
|
+
.replace(/�?39;/g, "'")
|
|
22
|
+
.replace(/'/gi, "'")
|
|
23
|
+
.replace(///gi, '/');
|
|
24
|
+
}
|
|
25
|
+
function parseAttrs(tag) {
|
|
26
|
+
const out = {};
|
|
27
|
+
const body = tag.replace(/^<\w+\b/i, '').replace(/\/?>$/g, '');
|
|
28
|
+
const re = /([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
|
|
29
|
+
let m;
|
|
30
|
+
while ((m = re.exec(body))) {
|
|
31
|
+
out[m[1].toLowerCase()] = decodeEntities(m[2] ?? m[3] ?? '');
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
function cqAttrs(chunk) {
|
|
36
|
+
const out = {};
|
|
37
|
+
const body = chunk.replace(/^\[CQ:[^,]+,?/i, '').replace(/\]$/, '');
|
|
38
|
+
for (const part of body.split(',')) {
|
|
39
|
+
const idx = part.indexOf('=');
|
|
40
|
+
if (idx <= 0)
|
|
41
|
+
continue;
|
|
42
|
+
const key = part.slice(0, idx).trim().toLowerCase();
|
|
43
|
+
try {
|
|
44
|
+
out[key] = decodeURIComponent(part.slice(idx + 1));
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
out[key] = part.slice(idx + 1);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
/** 从元素里尽力取出图片 URL / 文件引用 */
|
|
53
|
+
function imageFromElement(el) {
|
|
54
|
+
const attrs = el?.attrs ?? {};
|
|
55
|
+
const url = String(el?.url || el?.src || attrs.url || attrs.src || attrs.image || attrs.href || '').trim();
|
|
56
|
+
const ref = String(el?.file || el?.fileId || el?.file_id || attrs.file || attrs.fileid || attrs.file_id || attrs.id || '').trim();
|
|
57
|
+
if (!url && !ref)
|
|
58
|
+
return null;
|
|
59
|
+
const type = String(el?.type ?? '').toLowerCase();
|
|
60
|
+
const subtype = String(attrs.subType ?? attrs.subtype ?? attrs['sub-type'] ?? '');
|
|
61
|
+
const summary = String(attrs.summary ?? '');
|
|
62
|
+
const sticker = type === 'face' || type === 'sticker' || type === 'mface'
|
|
63
|
+
|| subtype === '1' || /动画表情|表情|贴纸|sticker|mface/i.test(summary);
|
|
64
|
+
return { url: decodeEntities(url), ref, sticker };
|
|
65
|
+
}
|
|
66
|
+
function imageFromTag(tag) {
|
|
67
|
+
const attrs = parseAttrs(tag);
|
|
68
|
+
const url = String(attrs.src || attrs.url || attrs.file || '').trim();
|
|
69
|
+
const ref = String(attrs.file || attrs.fileid || attrs.file_id || attrs.id || '').trim();
|
|
70
|
+
if (!url && !ref)
|
|
71
|
+
return null;
|
|
72
|
+
const subtype = String(attrs.subtype ?? attrs['sub-type'] ?? '');
|
|
73
|
+
const sticker = subtype === '1' || /动画表情|表情|贴纸|sticker|mface/i.test(String(attrs.summary ?? ''));
|
|
74
|
+
return { url, ref, sticker };
|
|
75
|
+
}
|
|
76
|
+
function imageFromCq(chunk) {
|
|
77
|
+
const attrs = cqAttrs(chunk);
|
|
78
|
+
const url = String(attrs.url || attrs.file || '').trim();
|
|
79
|
+
const ref = String(attrs.file_id || attrs.file || attrs.id || '').trim();
|
|
80
|
+
if (!url && !ref)
|
|
81
|
+
return null;
|
|
82
|
+
const sticker = String(attrs.sub_type ?? attrs.subtype ?? '') === '1'
|
|
83
|
+
|| /动画表情|表情|贴纸|sticker|mface/i.test(String(attrs.summary ?? ''));
|
|
84
|
+
return { url, ref, sticker };
|
|
85
|
+
}
|
|
86
|
+
function truncate(value, max) {
|
|
87
|
+
const text = String(value || '').replace(/\s+/g, ' ').trim();
|
|
88
|
+
if (text.length <= max)
|
|
89
|
+
return text;
|
|
90
|
+
return `${text.slice(0, max)}…`;
|
|
91
|
+
}
|
|
92
|
+
function stripTags(content) {
|
|
93
|
+
return String(content || '')
|
|
94
|
+
.replace(/\[CQ:[^\]]+\]/gi, ' ')
|
|
95
|
+
.replace(/<[^>]+>/g, ' ')
|
|
96
|
+
.replace(/\s+/g, ' ')
|
|
97
|
+
.trim();
|
|
98
|
+
}
|
|
99
|
+
/** 没有 elements 时的兜底:从 content 里解析 CQ 码 / HTML 标签 */
|
|
100
|
+
function renderFromContent(content, selfId, resolveName) {
|
|
101
|
+
const images = [];
|
|
102
|
+
const mentions = [];
|
|
103
|
+
let text = String(content || '');
|
|
104
|
+
// 图片 / 表情
|
|
105
|
+
text = text.replace(/\[CQ:image,([^\]]*)\]/gi, (_all, body) => {
|
|
106
|
+
const img = imageFromCq(`[CQ:image,${body}]`);
|
|
107
|
+
if (img)
|
|
108
|
+
images.push(img);
|
|
109
|
+
return ' [图片] ';
|
|
110
|
+
});
|
|
111
|
+
text = text.replace(/\[CQ:(face|mface|sticker),([^\]]*)\]/gi, () => ' [表情] ');
|
|
112
|
+
text = text.replace(/<img\b[^>]*\/?>/gi, (tag) => {
|
|
113
|
+
const img = imageFromTag(tag);
|
|
114
|
+
if (img)
|
|
115
|
+
images.push(img);
|
|
116
|
+
return ' [图片] ';
|
|
117
|
+
});
|
|
118
|
+
text = text.replace(/<face\b[^>]*\/?>/gi, ' [表情] ');
|
|
119
|
+
// @
|
|
120
|
+
text = text.replace(/\[CQ:at,([^\]]*)\]/gi, (_all, body) => {
|
|
121
|
+
const attrs = cqAttrs(`[CQ:at,${body}]`);
|
|
122
|
+
const qq = String(attrs.qq || attrs.id || '').trim();
|
|
123
|
+
if (!qq || qq === 'all')
|
|
124
|
+
return ' @全体成员 ';
|
|
125
|
+
if (qq !== selfId)
|
|
126
|
+
mentions.push(qq);
|
|
127
|
+
return ` @${qq === selfId ? '你' : qq} `;
|
|
128
|
+
});
|
|
129
|
+
text = text.replace(/<at\b[^>]*\/?>/gi, (tag) => {
|
|
130
|
+
const attrs = parseAttrs(tag);
|
|
131
|
+
const qq = String(attrs.qq || attrs.id || '').trim();
|
|
132
|
+
if (!qq || qq === 'all')
|
|
133
|
+
return ' @全体成员 ';
|
|
134
|
+
if (qq !== selfId)
|
|
135
|
+
mentions.push(qq);
|
|
136
|
+
return ` @${qq === selfId ? '你' : (attrs.name || qq)} `;
|
|
137
|
+
});
|
|
138
|
+
// 卡片 / 转发 / 其它
|
|
139
|
+
text = text.replace(/\[CQ:(json|xml),([^\]]*)\]/gi, ' [卡片消息] ');
|
|
140
|
+
text = text.replace(/\[CQ:(forward|node),([^\]]*)\]/gi, ' [合并转发] ');
|
|
141
|
+
text = text.replace(/\[CQ:(record|audio),([^\]]*)\]/gi, ' [语音] ');
|
|
142
|
+
text = text.replace(/\[CQ:video,([^\]]*)\]/gi, ' [视频] ');
|
|
143
|
+
text = text.replace(/\[CQ:file,([^\]]*)\]/gi, ' [文件] ');
|
|
144
|
+
return { text: stripTags(text), images, mentions };
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* 渲染一条消息。
|
|
148
|
+
* - @ 会解析成群名片(`@你` 表示 @bot)
|
|
149
|
+
* - 图片/表情/卡片/转发/语音都有占位
|
|
150
|
+
* - 引用消息(被回复的那条)单独返回,由提示词层决定怎么用
|
|
151
|
+
*/
|
|
152
|
+
async function renderMessage(session, resolveName, options = {}) {
|
|
153
|
+
const selfId = String(options.selfId ?? session?.bot?.selfId ?? session?.selfId ?? '');
|
|
154
|
+
const quoteMax = options.quoteMaxChars ?? 60;
|
|
155
|
+
const elements = Array.isArray(session?.elements) ? session.elements : [];
|
|
156
|
+
const images = [];
|
|
157
|
+
const mentions = [];
|
|
158
|
+
const parts = [];
|
|
159
|
+
let atBot = false;
|
|
160
|
+
if (!elements.length) {
|
|
161
|
+
const fallback = renderFromContent(String(session?.content ?? ''), selfId, resolveName);
|
|
162
|
+
// 兜底路径无法异步解析 @ 名字,尽力把 html 里的 name 用上
|
|
163
|
+
const withNames = await replaceMentionsWithNames(fallback.text, resolveName, selfId);
|
|
164
|
+
return {
|
|
165
|
+
text: withNames.text,
|
|
166
|
+
images: fallback.images,
|
|
167
|
+
mentions: [...new Set([...fallback.mentions, ...withNames.mentions])],
|
|
168
|
+
atBot: !!selfId && (fallback.text.includes('@你')
|
|
169
|
+
|| fallback.text.includes(`<at id="${selfId}"`)
|
|
170
|
+
|| fallback.text.includes(`qq=${selfId}`)),
|
|
171
|
+
quote: await renderQuote(session?.quote, resolveName, quoteMax),
|
|
172
|
+
plain: withNames.text,
|
|
173
|
+
visualOnly: !withNames.text.replace(/\[[^\]]+\]/g, '').trim(),
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
for (const el of elements) {
|
|
177
|
+
const type = String(el?.type ?? '').toLowerCase();
|
|
178
|
+
const attrs = el?.attrs ?? {};
|
|
179
|
+
if (!type)
|
|
180
|
+
continue;
|
|
181
|
+
if (type === 'text') {
|
|
182
|
+
parts.push(String(attrs.content ?? ''));
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
if (type === 'at' || type === 'mention') {
|
|
186
|
+
const qq = String(attrs.id ?? attrs.qq ?? el?.id ?? '').trim();
|
|
187
|
+
if (!qq || qq === 'all') {
|
|
188
|
+
parts.push(' @全体成员 ');
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
if (qq === selfId) {
|
|
192
|
+
atBot = true;
|
|
193
|
+
parts.push(' @你 ');
|
|
194
|
+
}
|
|
195
|
+
else {
|
|
196
|
+
mentions.push(qq);
|
|
197
|
+
const name = attrs.name || (await resolveName(qq)) || qq;
|
|
198
|
+
parts.push(` @${name} `);
|
|
199
|
+
}
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
if (type === 'image' || type === 'img' || type === 'sticker' || type === 'mface') {
|
|
203
|
+
const img = imageFromElement(el);
|
|
204
|
+
if (img)
|
|
205
|
+
images.push(img);
|
|
206
|
+
parts.push(img?.sticker ? ' [表情] ' : ' [图片] ');
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
if (type === 'face') {
|
|
210
|
+
// QFace 只是表情 id,不是可识别的图片内容,不要送进视觉模型
|
|
211
|
+
parts.push(' [表情] ');
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
if (type === 'quote' || type === 'reply') {
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
if (CARD_TYPES.has(type)) {
|
|
218
|
+
parts.push(' [卡片消息] ');
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
if (FORWARD_TYPES.has(type)) {
|
|
222
|
+
parts.push(' [合并转发] ');
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
if (type === 'record' || type === 'audio' || type === 'voice') {
|
|
226
|
+
parts.push(' [语音] ');
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
if (type === 'video') {
|
|
230
|
+
parts.push(' [视频] ');
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
if (type === 'file') {
|
|
234
|
+
parts.push(' [文件] ');
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
// 未知元素:把 attrs.content 或原文本带上,别丢信息
|
|
238
|
+
if (attrs.content)
|
|
239
|
+
parts.push(String(attrs.content));
|
|
240
|
+
}
|
|
241
|
+
let text = parts.join('').replace(/[ \t]+/g, ' ').replace(/\s*\n\s*/g, '\n').trim();
|
|
242
|
+
if (!text && images.length)
|
|
243
|
+
text = images.some((item) => !item.sticker) ? '[图片]' : '[表情]';
|
|
244
|
+
const quote = await renderQuote(session?.quote, resolveName, quoteMax);
|
|
245
|
+
return {
|
|
246
|
+
text,
|
|
247
|
+
images,
|
|
248
|
+
quote,
|
|
249
|
+
mentions: [...new Set(mentions)],
|
|
250
|
+
atBot,
|
|
251
|
+
plain: text,
|
|
252
|
+
visualOnly: !text.replace(/\[[^\]]+\]/g, '').trim(),
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
async function replaceMentionsWithNames(text, resolveName, selfId) {
|
|
256
|
+
const mentions = [];
|
|
257
|
+
const re = /@(\d{5,12})\b/g;
|
|
258
|
+
const ids = [...new Set([...text.matchAll(re)].map((m) => m[1]))];
|
|
259
|
+
let out = text;
|
|
260
|
+
for (const id of ids) {
|
|
261
|
+
if (id === selfId) {
|
|
262
|
+
out = out.split(`@${id}`).join('@你');
|
|
263
|
+
continue;
|
|
264
|
+
}
|
|
265
|
+
mentions.push(id);
|
|
266
|
+
const name = await resolveName(id);
|
|
267
|
+
if (name)
|
|
268
|
+
out = out.split(`@${id}`).join(`@${name}`);
|
|
269
|
+
}
|
|
270
|
+
return { text: out, mentions };
|
|
271
|
+
}
|
|
272
|
+
async function renderQuote(quote, resolveName, maxChars) {
|
|
273
|
+
if (!quote)
|
|
274
|
+
return undefined;
|
|
275
|
+
const content = String(quote.content ?? '').trim()
|
|
276
|
+
|| (Array.isArray(quote.elements) ? quote.elements.map((el) => el?.attrs?.content ?? '').join('') : '');
|
|
277
|
+
const text = truncate(stripTags(content), maxChars);
|
|
278
|
+
if (!text)
|
|
279
|
+
return undefined;
|
|
280
|
+
const userId = String(quote.user?.id ?? quote.userId ?? quote.author?.id ?? '');
|
|
281
|
+
const rawName = quote.user?.name ?? quote.author?.nick ?? quote.author?.name ?? '';
|
|
282
|
+
const name = String(rawName || (userId ? await resolveName(userId) : '') || '某人');
|
|
283
|
+
return { userId, name, text };
|
|
284
|
+
}
|