luckytri 1.0.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/.github/SECURITY.md +71 -0
- package/LICENSE +21 -0
- package/README.en.md +250 -0
- package/README.md +250 -0
- package/bin/luckytri.js +107 -0
- package/docs/brand/banner.png +0 -0
- package/docs/brand/palette.png +0 -0
- package/docs/brand/portrait.png +0 -0
- package/docs/en/CHANGELOG.md +113 -0
- package/docs/en/architecture.md +152 -0
- package/docs/en/chat-style.md +62 -0
- package/docs/en/connect.md +63 -0
- package/docs/en/guide.md +216 -0
- package/docs/en/her-life.md +189 -0
- package/docs/en/npm-release.md +25 -0
- package/docs/en/plugins.md +82 -0
- package/docs/en/recovery.md +28 -0
- package/docs/en/time.md +71 -0
- package/docs/en/webui.md +73 -0
- package/docs/zh/CHANGELOG.md +113 -0
- package/docs/zh/architecture.md +152 -0
- package/docs/zh/chat-style.md +62 -0
- package/docs/zh/connect.md +63 -0
- package/docs/zh/guide.md +216 -0
- package/docs/zh/her-life.md +189 -0
- package/docs/zh/npm-release.md +33 -0
- package/docs/zh/plugins.md +82 -0
- package/docs/zh/recovery.md +28 -0
- package/docs/zh/time.md +71 -0
- package/docs/zh/webui.md +73 -0
- package/package.json +108 -0
- package/plugins/sdk/index.d.ts +155 -0
- package/plugins/sdk/testing.js +58 -0
- package/plugins/weather/index.js +82 -0
- package/plugins/weather/luckytri-plugin.json +29 -0
- package/public/app/assets/ChatsPage-C-FcRapR.js +3 -0
- package/public/app/assets/ChatsPage-DfyPCS9N.css +1 -0
- package/public/app/assets/Empty-CpP5kQHH.js +2 -0
- package/public/app/assets/Empty-DmUB2-Bk.css +1 -0
- package/public/app/assets/Field-D4gY-INU.js +1 -0
- package/public/app/assets/HeartPage-Bft9wZp5.css +1 -0
- package/public/app/assets/HeartPage-CPy_thQd.js +1 -0
- package/public/app/assets/LifePage-BUi5euBF.css +1 -0
- package/public/app/assets/LifePage-CxWvwmSf.js +1 -0
- package/public/app/assets/MemoryPage-DC4rhQ68.js +1 -0
- package/public/app/assets/MemoryPage-cZvXfkXb.css +1 -0
- package/public/app/assets/NaturePage-CTXHCE2D.css +1 -0
- package/public/app/assets/NaturePage-IvYw04Zq.js +3 -0
- package/public/app/assets/PeoplePage-BmUxkrOU.css +1 -0
- package/public/app/assets/PeoplePage-Cqefm9-q.js +1 -0
- package/public/app/assets/PluginsPage-DKSaKvXb.js +2 -0
- package/public/app/assets/PluginsPage-HyBe5D8w.css +1 -0
- package/public/app/assets/SystemPage-CAMPoYqM.css +1 -0
- package/public/app/assets/SystemPage-CJmtJkrK.js +1 -0
- package/public/app/assets/TimePage-BOms_n4I.css +1 -0
- package/public/app/assets/TimePage-Cw44inM4.js +3 -0
- package/public/app/assets/formatters-ZmW_xFHw.js +1 -0
- package/public/app/assets/index-BheRW-1t.js +4 -0
- package/public/app/assets/index-YDz1ree1.css +1 -0
- package/public/app/assets/knowledge-DG0e0uKw.js +1 -0
- package/public/app/assets/liquid-garden-IMoHBwzc.png +0 -0
- package/public/app/assets/luckytri-home-95QKeMtc.png +0 -0
- package/public/app/assets/media-BzPDBm7e.js +1 -0
- package/public/app/index.html +27 -0
- package/public/guide.en.html +1053 -0
- package/public/guide.html +893 -0
- package/public/plugin-kit/v1/bridge.js +30 -0
- package/public/plugin-kit/v1/kit.css +14 -0
- package/public/tutorial.en.md +214 -0
- package/public/tutorial.md +214 -0
- package/scripts/backup.js +311 -0
- package/scripts/browser.js +41 -0
- package/scripts/launch.js +94 -0
- package/scripts/plugin.js +150 -0
- package/scripts/proxy-config.js +167 -0
- package/scripts/recover.js +26 -0
- package/scripts/runtime.js +25 -0
- package/scripts/service.js +47 -0
- package/scripts/setup.js +50 -0
- package/scripts/start-server.js +41 -0
- package/scripts/stop.js +36 -0
- package/server/app.js +96 -0
- package/server/channels/adapters.js +27 -0
- package/server/channels/contract.js +57 -0
- package/server/channels/hub.js +165 -0
- package/server/channels/index.js +25 -0
- package/server/channels/onebot/adapter.js +288 -0
- package/server/channels/onebot/index.js +336 -0
- package/server/channels/onebot/token.js +3 -0
- package/server/channels/qqbot/adapter.js +253 -0
- package/server/channels/qqbot/api.js +199 -0
- package/server/channels/qqbot/credentials.js +11 -0
- package/server/channels/qqbot/gateway.js +274 -0
- package/server/channels/qqbot/index.js +389 -0
- package/server/channels/segments.js +40 -0
- package/server/channels/session-key.js +153 -0
- package/server/channels/state.js +42 -0
- package/server/core/api.js +564 -0
- package/server/core/capabilities.js +208 -0
- package/server/core/context-builder.js +288 -0
- package/server/core/context-compactor.js +454 -0
- package/server/core/conversation-cues.js +325 -0
- package/server/core/conversation-manager.js +87 -0
- package/server/core/events.js +60 -0
- package/server/core/feedback.js +8 -0
- package/server/core/group-style.js +72 -0
- package/server/core/image-preprocessor.js +208 -0
- package/server/core/initiative-context.js +66 -0
- package/server/core/input-budget.js +32 -0
- package/server/core/local-demo.js +98 -0
- package/server/core/message-manager.js +118 -0
- package/server/core/message-scheduler.js +78 -0
- package/server/core/model-json.js +190 -0
- package/server/core/model-manager.js +1213 -0
- package/server/core/model-presets.js +900 -0
- package/server/core/name-call.js +29 -0
- package/server/core/net-guard.js +49 -0
- package/server/core/network.js +157 -0
- package/server/core/orchestrator.js +569 -0
- package/server/core/perceivers.js +91 -0
- package/server/core/person-name.js +22 -0
- package/server/core/persona-manager.js +243 -0
- package/server/core/reply-delivery.js +393 -0
- package/server/core/reply-target-resolver.js +50 -0
- package/server/core/repository.js +293 -0
- package/server/core/response-generator.js +50 -0
- package/server/core/response-validator.js +508 -0
- package/server/core/retired-prompts.js +51 -0
- package/server/core/sessions.js +109 -0
- package/server/core/speaker-names.js +92 -0
- package/server/core/topic-tracker.js +65 -0
- package/server/core/turn-processor.js +630 -0
- package/server/core/turn.js +236 -0
- package/server/core/vision-manager.js +633 -0
- package/server/http.js +18 -0
- package/server/i18n/decisions.js +206 -0
- package/server/i18n/errors.js +497 -0
- package/server/i18n/index.js +144 -0
- package/server/i18n/labels.js +653 -0
- package/server/i18n/models.js +111 -0
- package/server/index.js +102 -0
- package/server/knowledge/api.js +342 -0
- package/server/knowledge/embedding-profile.js +114 -0
- package/server/knowledge/index.js +13 -0
- package/server/knowledge/manager.js +386 -0
- package/server/knowledge/retrieval.js +93 -0
- package/server/knowledge/schema.js +154 -0
- package/server/knowledge/vector-index.js +90 -0
- package/server/mind/affect.js +265 -0
- package/server/mind/anticipations.js +507 -0
- package/server/mind/api.js +703 -0
- package/server/mind/attention.js +200 -0
- package/server/mind/bonds.js +558 -0
- package/server/mind/budget.js +152 -0
- package/server/mind/clock.js +83 -0
- package/server/mind/context-selection.js +61 -0
- package/server/mind/continuity.js +562 -0
- package/server/mind/conversation-origin.js +175 -0
- package/server/mind/day-planner.js +324 -0
- package/server/mind/days.js +210 -0
- package/server/mind/evidence-read.js +45 -0
- package/server/mind/evidence.js +148 -0
- package/server/mind/faces.js +138 -0
- package/server/mind/guard.js +60 -0
- package/server/mind/index.js +445 -0
- package/server/mind/initiative.js +333 -0
- package/server/mind/life/activities.js +21 -0
- package/server/mind/life/context.js +309 -0
- package/server/mind/life/diary.js +786 -0
- package/server/mind/life/growth.js +252 -0
- package/server/mind/life/index.js +1049 -0
- package/server/mind/life/presence.js +305 -0
- package/server/mind/meetings.js +1069 -0
- package/server/mind/memory-policy.js +48 -0
- package/server/mind/memory.js +888 -0
- package/server/mind/nature.js +262 -0
- package/server/mind/novelty.js +19 -0
- package/server/mind/observations.js +84 -0
- package/server/mind/own-day.js +324 -0
- package/server/mind/own-voice.js +318 -0
- package/server/mind/periods.js +118 -0
- package/server/mind/reading.js +120 -0
- package/server/mind/salience.js +201 -0
- package/server/mind/schema.js +562 -0
- package/server/mind/self.js +484 -0
- package/server/mind/senses.js +53 -0
- package/server/mind/thoughts.js +274 -0
- package/server/mind/time/activity-clock.js +196 -0
- package/server/mind/time/agenda.js +242 -0
- package/server/mind/time/api.js +200 -0
- package/server/mind/time/attention.js +34 -0
- package/server/mind/time/availability.js +69 -0
- package/server/mind/time/commitment-review.js +198 -0
- package/server/mind/time/delivery-links.js +130 -0
- package/server/mind/time/executor.js +512 -0
- package/server/mind/time/experiences.js +128 -0
- package/server/mind/time/games.js +562 -0
- package/server/mind/time/index.js +739 -0
- package/server/mind/time/intent.js +166 -0
- package/server/mind/time/kinds.js +171 -0
- package/server/mind/time/model-material.js +77 -0
- package/server/mind/time/plugin-activity.js +207 -0
- package/server/mind/time/presentation.js +51 -0
- package/server/mind/time/schedule.js +83 -0
- package/server/mind/time/schema.js +84 -0
- package/server/mind/time/search.js +383 -0
- package/server/mind/time/sharing.js +472 -0
- package/server/mind/time/task-links.js +311 -0
- package/server/mind/time/tasks.js +587 -0
- package/server/mind/time/works.js +432 -0
- package/server/mind/traits.js +191 -0
- package/server/mind/util.js +110 -0
- package/server/mind/view.js +273 -0
- package/server/paths.js +102 -0
- package/server/plugins/api.js +204 -0
- package/server/plugins/host.js +967 -0
- package/server/plugins/install.js +295 -0
- package/server/plugins/manifest.js +201 -0
- package/server/plugins/permissions.js +42 -0
- package/server/plugins/runner/guard.mjs +36 -0
- package/server/plugins/runner/worker.mjs +250 -0
- package/server/plugins/schema.js +91 -0
- package/server/plugins/zip.js +112 -0
- package/server/startup-lock.js +118 -0
- package/server/storage/archive.js +241 -0
- package/server/storage/backup-cleanup-worker.js +8 -0
- package/server/storage/backup-cleanup.js +414 -0
- package/server/storage/backup-lock.js +76 -0
- package/server/storage/backup-scheduler.js +131 -0
- package/server/storage/store.js +199 -0
- package/server/studio/display-names.js +138 -0
- package/server/studio/management.js +102 -0
- package/server/studio/readiness.js +190 -0
- package/server/studio/settings.js +236 -0
- package/server/version.js +10 -0
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
import { WebSocketServer, WebSocket } from "ws";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { tokenEqual } from "../../http.js";
|
|
4
|
+
import { effectiveOneBotToken } from "./token.js";
|
|
5
|
+
import { onebot, normalize } from "./adapter.js";
|
|
6
|
+
import { defineChannel } from "../contract.js";
|
|
7
|
+
import { parseSessionKey } from "../session-key.js";
|
|
8
|
+
import { applyDirectoryNames } from "../../core/sessions.js";
|
|
9
|
+
import { saveAccountNames } from "../../studio/display-names.js";
|
|
10
|
+
import { visionImageLimits } from "../../core/image-preprocessor.js";
|
|
11
|
+
|
|
12
|
+
const EVENT_MAX_BYTES = 1024 * 1024;
|
|
13
|
+
const IMAGE_TIMEOUT_MS = 30000;
|
|
14
|
+
|
|
15
|
+
// OneBot 11 over a reverse WebSocket: a client she does not manage (any
|
|
16
|
+
// OneBot 11 implementation) connects to /onebot/v11/ws with the shared token.
|
|
17
|
+
export function createOneBotChannel(store) {
|
|
18
|
+
const pending = new Map();
|
|
19
|
+
const botMessageIds = new Set();
|
|
20
|
+
let running = false;
|
|
21
|
+
let socket = null;
|
|
22
|
+
let connectedAt = null;
|
|
23
|
+
let lastEventAt = null;
|
|
24
|
+
let lastDisconnectAt = null;
|
|
25
|
+
let heartbeat = null;
|
|
26
|
+
let wss = null;
|
|
27
|
+
let directoryAt = 0;
|
|
28
|
+
const checkedNames = new Map();
|
|
29
|
+
|
|
30
|
+
function asList(data) {
|
|
31
|
+
if (Array.isArray(data)) return data;
|
|
32
|
+
if (Array.isArray(data?.data)) return data.data;
|
|
33
|
+
if (Array.isArray(data?.groups)) return data.groups;
|
|
34
|
+
return [];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function refreshDirectory() {
|
|
38
|
+
if (!socket || socket.readyState !== WebSocket.OPEN) return 0;
|
|
39
|
+
if (Date.now() - directoryAt < 15000) return 0;
|
|
40
|
+
directoryAt = Date.now();
|
|
41
|
+
const listed = async (action, params = {}) => {
|
|
42
|
+
try {
|
|
43
|
+
return asList(await rpc(action, params, 8000));
|
|
44
|
+
} catch (error) {
|
|
45
|
+
console.error(`读取 QQ ${action} 失败:${error.message}`);
|
|
46
|
+
return [];
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
const [groups, friends] = await Promise.all([
|
|
50
|
+
listed("get_group_list"),
|
|
51
|
+
listed("get_friend_list"),
|
|
52
|
+
]);
|
|
53
|
+
const known = store.db.prepare("SELECT id,kind FROM sessions").all();
|
|
54
|
+
for (const row of known) {
|
|
55
|
+
const native = String(row.id).split(":").pop();
|
|
56
|
+
const isGroup =
|
|
57
|
+
row.kind === "group" || String(row.id).includes(":group:");
|
|
58
|
+
if (!isGroup || !/^\d+$/.test(native)) continue;
|
|
59
|
+
if (groups.some((group) => String(group.group_id) === native)) continue;
|
|
60
|
+
try {
|
|
61
|
+
const info = await rpc(
|
|
62
|
+
"get_group_info",
|
|
63
|
+
{ group_id: Number(native) },
|
|
64
|
+
8000,
|
|
65
|
+
);
|
|
66
|
+
if (info && typeof info === "object") groups.push(info);
|
|
67
|
+
} catch (error) {
|
|
68
|
+
console.error(`读取群 ${native} 的名字失败:${error.message}`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
let changed = applyDirectoryNames(store.db, { groups, friends });
|
|
72
|
+
changed += saveAccountNames(store.db, friends);
|
|
73
|
+
const ids = store.db
|
|
74
|
+
.prepare(
|
|
75
|
+
"SELECT user_id FROM mind_people ORDER BY last_seen DESC LIMIT 200",
|
|
76
|
+
)
|
|
77
|
+
.all()
|
|
78
|
+
.map((row) => row.user_id)
|
|
79
|
+
.filter(
|
|
80
|
+
(id) =>
|
|
81
|
+
/^\d{4,20}$/.test(id) &&
|
|
82
|
+
!friends.some((friend) => String(friend.user_id) === id) &&
|
|
83
|
+
Date.now() - (checkedNames.get(id) || 0) > 3600000,
|
|
84
|
+
);
|
|
85
|
+
const accounts = [];
|
|
86
|
+
for (let start = 0; start < ids.length; start += 4) {
|
|
87
|
+
await Promise.all(
|
|
88
|
+
ids.slice(start, start + 4).map(async (id) => {
|
|
89
|
+
checkedNames.set(id, Date.now());
|
|
90
|
+
try {
|
|
91
|
+
const person = await rpc(
|
|
92
|
+
"get_stranger_info",
|
|
93
|
+
{ user_id: Number(id) },
|
|
94
|
+
2500,
|
|
95
|
+
);
|
|
96
|
+
if (person?.nickname) accounts.push({ ...person, user_id: id });
|
|
97
|
+
} catch {
|
|
98
|
+
/* The message nickname remains usable if QQ cannot look it up. */
|
|
99
|
+
}
|
|
100
|
+
}),
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
changed += saveAccountNames(store.db, accounts);
|
|
104
|
+
if (changed) store.revision++;
|
|
105
|
+
return changed;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const rpc = (action, params, timeoutMs) => {
|
|
109
|
+
if (!socket || socket.readyState !== WebSocket.OPEN)
|
|
110
|
+
throw new Error("QQ 尚未连接");
|
|
111
|
+
const echo = randomUUID();
|
|
112
|
+
return new Promise((resolve, reject) => {
|
|
113
|
+
const timer = setTimeout(() => {
|
|
114
|
+
pending.delete(echo);
|
|
115
|
+
reject(
|
|
116
|
+
new Error(
|
|
117
|
+
action === "get_msg"
|
|
118
|
+
? "引用恢复超时"
|
|
119
|
+
: action === "get_image"
|
|
120
|
+
? "QQ 图片读取超时"
|
|
121
|
+
: "QQ 发送确认超时,不自动重发",
|
|
122
|
+
),
|
|
123
|
+
);
|
|
124
|
+
}, timeoutMs);
|
|
125
|
+
pending.set(echo, { action, resolve, reject, timer });
|
|
126
|
+
socket.send(JSON.stringify({ action, params, echo }));
|
|
127
|
+
});
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
const send = async (m, text) => {
|
|
131
|
+
if (m.simulated) return { message_id: "sim" };
|
|
132
|
+
const result = await rpc(
|
|
133
|
+
onebot.sendAction(m),
|
|
134
|
+
onebot.sendParams(m, text),
|
|
135
|
+
10000,
|
|
136
|
+
);
|
|
137
|
+
if (result?.message_id != null) {
|
|
138
|
+
botMessageIds.add(String(result.message_id));
|
|
139
|
+
while (botMessageIds.size > 2000)
|
|
140
|
+
botMessageIds.delete(botMessageIds.values().next().value);
|
|
141
|
+
}
|
|
142
|
+
return result;
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
async function fetchQuoted(message) {
|
|
146
|
+
const data = await rpc("get_msg", { message_id: message.replyId }, 4000);
|
|
147
|
+
return onebot.quotedMessage(data, message);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async function fetchImage(file) {
|
|
151
|
+
const data = await rpc(
|
|
152
|
+
"get_image",
|
|
153
|
+
{ file: String(file) },
|
|
154
|
+
IMAGE_TIMEOUT_MS,
|
|
155
|
+
);
|
|
156
|
+
return data && typeof data === "object" ? data : null;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function fetchMedia(file, type) {
|
|
160
|
+
const action = type === "record" ? "get_record" : "get_file";
|
|
161
|
+
const data = await rpc(action, { file: String(file) }, 8000);
|
|
162
|
+
return data && typeof data === "object" ? data : null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function attach(httpServer, chatSystem) {
|
|
166
|
+
// Only authenticated OneBot clients reach this server. get_image may carry
|
|
167
|
+
// base64 rather than a URL, so its frame must fit the source-image budget.
|
|
168
|
+
// Ordinary events still have the smaller independent limit below.
|
|
169
|
+
const imageBytes = visionImageLimits().maxSourceBytes;
|
|
170
|
+
wss = new WebSocketServer({
|
|
171
|
+
noServer: true,
|
|
172
|
+
maxPayload: Math.ceil(imageBytes / 3) * 4 + EVENT_MAX_BYTES,
|
|
173
|
+
});
|
|
174
|
+
httpServer.on("upgrade", (req, sock, head) => {
|
|
175
|
+
if (
|
|
176
|
+
!running ||
|
|
177
|
+
req.url !== "/onebot/v11/ws" ||
|
|
178
|
+
!effectiveOneBotToken(store) ||
|
|
179
|
+
!tokenEqual(
|
|
180
|
+
req.headers.authorization,
|
|
181
|
+
`Bearer ${effectiveOneBotToken(store)}`,
|
|
182
|
+
) ||
|
|
183
|
+
socket
|
|
184
|
+
) {
|
|
185
|
+
sock.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
|
|
186
|
+
sock.destroy();
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
wss.handleUpgrade(req, sock, head, (ws) => wss.emit("connection", ws));
|
|
190
|
+
});
|
|
191
|
+
wss.on("connection", (ws) => {
|
|
192
|
+
socket = ws;
|
|
193
|
+
connectedAt = Date.now();
|
|
194
|
+
directoryAt = 0;
|
|
195
|
+
const pullNames = (attempt = 0) => {
|
|
196
|
+
if (!running || socket !== ws) return;
|
|
197
|
+
directoryAt = 0;
|
|
198
|
+
refreshDirectory()
|
|
199
|
+
.then((changed) => {
|
|
200
|
+
if (changed || attempt >= 4) return;
|
|
201
|
+
setTimeout(() => pullNames(attempt + 1), 4000).unref?.();
|
|
202
|
+
})
|
|
203
|
+
.catch(() => {});
|
|
204
|
+
};
|
|
205
|
+
pullNames();
|
|
206
|
+
ws.isAlive = true;
|
|
207
|
+
ws.on("pong", () => (ws.isAlive = true));
|
|
208
|
+
ws.on("message", async (raw) => {
|
|
209
|
+
try {
|
|
210
|
+
const event = JSON.parse(raw.toString());
|
|
211
|
+
if (!event || typeof event !== "object" || Array.isArray(event))
|
|
212
|
+
return;
|
|
213
|
+
const reply =
|
|
214
|
+
typeof event.echo === "string" && pending.get(event.echo);
|
|
215
|
+
const imageReply =
|
|
216
|
+
reply?.action === "get_image" &&
|
|
217
|
+
!event.post_type &&
|
|
218
|
+
((["number", "string"].includes(typeof event.retcode) &&
|
|
219
|
+
String(event.retcode).trim() !== "" &&
|
|
220
|
+
Number.isFinite(Number(event.retcode))) ||
|
|
221
|
+
["ok", "success", "failed"].includes(event.status));
|
|
222
|
+
if (raw.byteLength > EVENT_MAX_BYTES && !imageReply) {
|
|
223
|
+
console.error("OneBot: 超过普通消息大小限制,已忽略");
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
lastEventAt = Date.now();
|
|
227
|
+
if (reply) {
|
|
228
|
+
const p = reply;
|
|
229
|
+
clearTimeout(p.timer);
|
|
230
|
+
pending.delete(event.echo);
|
|
231
|
+
Number(event.retcode) === 0 ||
|
|
232
|
+
event.status === "ok" ||
|
|
233
|
+
event.status === "success"
|
|
234
|
+
? p.resolve(event.data ?? {})
|
|
235
|
+
: p.reject(
|
|
236
|
+
new Error(
|
|
237
|
+
event.message ||
|
|
238
|
+
event.wording ||
|
|
239
|
+
event.msg ||
|
|
240
|
+
"QQ 没有完成这个请求",
|
|
241
|
+
),
|
|
242
|
+
);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
const m = normalize(event, { botMessageIds });
|
|
246
|
+
if (m) chatSystem.receive(m);
|
|
247
|
+
} catch (err) {
|
|
248
|
+
console.error("OneBot:", err.message);
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
ws.on("error", () => {});
|
|
252
|
+
ws.on("close", () => {
|
|
253
|
+
if (socket === ws) socket = null;
|
|
254
|
+
lastDisconnectAt = Date.now();
|
|
255
|
+
for (const p of pending.values()) {
|
|
256
|
+
clearTimeout(p.timer);
|
|
257
|
+
p.reject(new Error("QQ 连接已断开"));
|
|
258
|
+
}
|
|
259
|
+
pending.clear();
|
|
260
|
+
});
|
|
261
|
+
});
|
|
262
|
+
heartbeat = setInterval(() => {
|
|
263
|
+
for (const ws of wss.clients) {
|
|
264
|
+
if (!ws.isAlive) {
|
|
265
|
+
ws.terminate();
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
ws.isAlive = false;
|
|
269
|
+
ws.ping();
|
|
270
|
+
}
|
|
271
|
+
}, 30000);
|
|
272
|
+
heartbeat.unref();
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// Whether a client may connect at all. Stopping also drops the one that is
|
|
276
|
+
// connected, so switching to another channel never leaves a stale line open.
|
|
277
|
+
function start() {
|
|
278
|
+
running = true;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function stop() {
|
|
282
|
+
running = false;
|
|
283
|
+
if (wss) for (const ws of wss.clients) ws.terminate();
|
|
284
|
+
for (const p of pending.values()) {
|
|
285
|
+
clearTimeout(p.timer);
|
|
286
|
+
p.reject(new Error("QQ 连接已断开"));
|
|
287
|
+
}
|
|
288
|
+
pending.clear();
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function close() {
|
|
292
|
+
if (heartbeat) clearInterval(heartbeat);
|
|
293
|
+
stop();
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// A connected client can reach every room it knows; there is no window and
|
|
297
|
+
// no per-room permission to respect.
|
|
298
|
+
function canReach(sessionId) {
|
|
299
|
+
if (!socket) return false;
|
|
300
|
+
try {
|
|
301
|
+
return parseSessionKey(sessionId).channel === "onebot";
|
|
302
|
+
} catch {
|
|
303
|
+
return false;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function status() {
|
|
308
|
+
return {
|
|
309
|
+
type: "onebot",
|
|
310
|
+
online: !!socket,
|
|
311
|
+
connectedAt,
|
|
312
|
+
lastEventAt,
|
|
313
|
+
lastDisconnectAt,
|
|
314
|
+
tokenConfigured: !!effectiveOneBotToken(store),
|
|
315
|
+
adminProtected: !!process.env.ADMIN_TOKEN,
|
|
316
|
+
wsPath: "/onebot/v11/ws",
|
|
317
|
+
port: Number(process.env.PORT || 3210),
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
return defineChannel({
|
|
322
|
+
type: "onebot",
|
|
323
|
+
capabilities: onebot.capabilities,
|
|
324
|
+
attach,
|
|
325
|
+
start,
|
|
326
|
+
stop,
|
|
327
|
+
send,
|
|
328
|
+
fetchQuoted,
|
|
329
|
+
fetchImage,
|
|
330
|
+
fetchMedia,
|
|
331
|
+
refreshDirectory,
|
|
332
|
+
canReach,
|
|
333
|
+
status,
|
|
334
|
+
close,
|
|
335
|
+
});
|
|
336
|
+
}
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { formatSessionKey, parseSessionKey } from "../session-key.js";
|
|
2
|
+
|
|
3
|
+
// Turns events of the QQ 开放平台 into the neutral message the core reads, and
|
|
4
|
+
// knows how the platform addresses a room. No network and no state here.
|
|
5
|
+
|
|
6
|
+
const text = (value) => (value == null ? "" : String(value));
|
|
7
|
+
|
|
8
|
+
// `message_scene.ext` is a list of "key=value" strings.
|
|
9
|
+
export function sceneExt(scene) {
|
|
10
|
+
const out = {};
|
|
11
|
+
for (const item of Array.isArray(scene?.ext) ? scene.ext : []) {
|
|
12
|
+
const at = String(item).indexOf("=");
|
|
13
|
+
if (at > 0) out[String(item).slice(0, at)] = String(item).slice(at + 1);
|
|
14
|
+
}
|
|
15
|
+
return out;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const placeholderName = (id) =>
|
|
19
|
+
`QQ 用户·${text(id).slice(-4).toUpperCase()}`;
|
|
20
|
+
export const isPlaceholderName = (name) => /^QQ 用户·/.test(text(name));
|
|
21
|
+
|
|
22
|
+
function mediaUrl(value) {
|
|
23
|
+
const raw = text(value).trim();
|
|
24
|
+
if (!raw) return "";
|
|
25
|
+
if (raw.startsWith("//")) return `https:${raw}`;
|
|
26
|
+
if (/^https?:\/\//i.test(raw)) return raw;
|
|
27
|
+
return `https://${raw}`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function attachmentOf(item) {
|
|
31
|
+
const type = text(item?.content_type).toLowerCase();
|
|
32
|
+
const url = mediaUrl(item?.url);
|
|
33
|
+
const kind = type.startsWith("image/")
|
|
34
|
+
? "image"
|
|
35
|
+
: type.startsWith("voice") || type.startsWith("audio")
|
|
36
|
+
? "record"
|
|
37
|
+
: type.startsWith("video")
|
|
38
|
+
? "video"
|
|
39
|
+
: "file";
|
|
40
|
+
return {
|
|
41
|
+
type: kind,
|
|
42
|
+
url,
|
|
43
|
+
file: "",
|
|
44
|
+
filename: text(item?.filename).slice(0, 120),
|
|
45
|
+
contentType: type,
|
|
46
|
+
width: Number(item?.width) || undefined,
|
|
47
|
+
height: Number(item?.height) || undefined,
|
|
48
|
+
size: Number(item?.size) || undefined,
|
|
49
|
+
summary: "",
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const MENTION = /<@!?([^>\s]+)>/g;
|
|
54
|
+
|
|
55
|
+
// The quoted message carried inside a message_type 103 event, if any.
|
|
56
|
+
export function quotedElement(d, replyId) {
|
|
57
|
+
const elements = Array.isArray(d?.msg_elements) ? d.msg_elements : [];
|
|
58
|
+
return (
|
|
59
|
+
elements.find((item) => replyId && text(item?.msg_idx) === replyId) ||
|
|
60
|
+
elements.find((item) => item && typeof item === "object") ||
|
|
61
|
+
null
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export const qqbot = {
|
|
66
|
+
type: "qqbot",
|
|
67
|
+
capabilities: {
|
|
68
|
+
mention: true,
|
|
69
|
+
quote: true,
|
|
70
|
+
image: true,
|
|
71
|
+
thread: false,
|
|
72
|
+
sticker: false,
|
|
73
|
+
},
|
|
74
|
+
mediaHosts: /(^|\.)(qpic\.cn|gtimg\.cn|qq\.com\.cn|qq\.com|myqcloud\.com)$/i,
|
|
75
|
+
usableMediaUrl(url) {
|
|
76
|
+
try {
|
|
77
|
+
const u = new URL(url);
|
|
78
|
+
return (
|
|
79
|
+
u.protocol === "https:" &&
|
|
80
|
+
!u.username &&
|
|
81
|
+
!u.password &&
|
|
82
|
+
this.mediaHosts.test(u.hostname)
|
|
83
|
+
);
|
|
84
|
+
} catch {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
},
|
|
88
|
+
nativeChatId(sessionId) {
|
|
89
|
+
return parseSessionKey(sessionId).nativeId;
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
// `type` is the event name (`t`), `d` its data. `context` supplies what only
|
|
94
|
+
// the channel knows: the AppID, the references of messages she sent herself,
|
|
95
|
+
// and a name remembered for a person.
|
|
96
|
+
export function normalize(type, d, context = {}) {
|
|
97
|
+
const group =
|
|
98
|
+
type === "GROUP_AT_MESSAGE_CREATE" || type === "GROUP_MESSAGE_CREATE";
|
|
99
|
+
if (!group && type !== "C2C_MESSAGE_CREATE") return null;
|
|
100
|
+
if (!d || typeof d !== "object" || d.id == null) return null;
|
|
101
|
+
const appId = text(context.appId);
|
|
102
|
+
const author = d.author && typeof d.author === "object" ? d.author : {};
|
|
103
|
+
if (author.bot === true) return null;
|
|
104
|
+
const openid = text(
|
|
105
|
+
group ? author.member_openid || author.id : author.user_openid || author.id,
|
|
106
|
+
);
|
|
107
|
+
// Someone seen in several rooms is only recognised as one person when the
|
|
108
|
+
// platform hands out a unified identity; otherwise each room's openid is a
|
|
109
|
+
// separate person, as it would be for anyone met in different places.
|
|
110
|
+
const person = text(author.union_openid) || openid;
|
|
111
|
+
const kind = group ? "group" : "private";
|
|
112
|
+
const nativeId = group ? text(d.group_openid ?? d.group_id) : person;
|
|
113
|
+
if (!appId || !openid || !nativeId) return null;
|
|
114
|
+
|
|
115
|
+
const ext = sceneExt(d.message_scene);
|
|
116
|
+
const platformId = ext.msg_idx || text(d.id);
|
|
117
|
+
const replyId = ext.ref_msg_idx || "";
|
|
118
|
+
const quoted = replyId ? quotedElement(d, replyId) : null;
|
|
119
|
+
const botRefs = context.botRefs;
|
|
120
|
+
const replyToBot =
|
|
121
|
+
!!replyId &&
|
|
122
|
+
(!!botRefs?.has?.(replyId) ||
|
|
123
|
+
quoted?.author?.bot === true ||
|
|
124
|
+
(!!quoted?.author?.id && text(quoted.author.id) === text(context.botId)));
|
|
125
|
+
|
|
126
|
+
const mentionList = Array.isArray(d.mentions) ? d.mentions : [];
|
|
127
|
+
const self = new Set(
|
|
128
|
+
mentionList
|
|
129
|
+
.filter((user) => user?.is_you === true)
|
|
130
|
+
.flatMap((user) => [user.id, user.member_openid, user.user_openid])
|
|
131
|
+
.filter(Boolean)
|
|
132
|
+
.map(text),
|
|
133
|
+
);
|
|
134
|
+
const atSelf =
|
|
135
|
+
type === "GROUP_AT_MESSAGE_CREATE" ||
|
|
136
|
+
mentionList.some((user) => user?.is_you === true);
|
|
137
|
+
const mentions = [
|
|
138
|
+
...(atSelf ? [appId] : []),
|
|
139
|
+
...mentionList
|
|
140
|
+
.filter((user) => user?.is_you !== true)
|
|
141
|
+
.map((user) => text(user.union_openid || user.member_openid || user.id))
|
|
142
|
+
.filter(Boolean),
|
|
143
|
+
];
|
|
144
|
+
|
|
145
|
+
const attachments = (Array.isArray(d.attachments) ? d.attachments : [])
|
|
146
|
+
.filter((item) => item && typeof item === "object")
|
|
147
|
+
.map(attachmentOf);
|
|
148
|
+
const media = {
|
|
149
|
+
images: attachments.filter((item) => item.type === "image").length,
|
|
150
|
+
stickers: 0,
|
|
151
|
+
other: attachments.filter((item) => item.type !== "image").length,
|
|
152
|
+
};
|
|
153
|
+
const body = text(d.content)
|
|
154
|
+
.replace(MENTION, (_, id) => (self.has(id) ? "@我" : "[提及成员]"))
|
|
155
|
+
.replace(/\u00a0/g, " ");
|
|
156
|
+
const plain = body.replace(/\[提及成员\]|@我/g, "").trim();
|
|
157
|
+
const marks = attachments
|
|
158
|
+
.map((item) => (item.type === "image" ? "[图片]" : "[媒体]"))
|
|
159
|
+
.join("");
|
|
160
|
+
const addressed = atSelf && !/@我/.test(body) ? "@我 " : "";
|
|
161
|
+
const visible = (addressed + body.trim() + marks).trim();
|
|
162
|
+
const out =
|
|
163
|
+
visible ||
|
|
164
|
+
(atSelf || replyToBot ? (replyToBot ? "[回复你]" : "[叫了你一声]") : "");
|
|
165
|
+
if (!out) return null;
|
|
166
|
+
const mediaCount = media.images + media.other;
|
|
167
|
+
|
|
168
|
+
const name =
|
|
169
|
+
text(author.username).trim() ||
|
|
170
|
+
text(context.knownName?.(person)).trim() ||
|
|
171
|
+
placeholderName(person);
|
|
172
|
+
const time = Date.parse(text(d.timestamp));
|
|
173
|
+
return {
|
|
174
|
+
sessionId: formatSessionKey({
|
|
175
|
+
channel: "qqbot",
|
|
176
|
+
accountId: appId,
|
|
177
|
+
kind,
|
|
178
|
+
nativeId,
|
|
179
|
+
}),
|
|
180
|
+
channel: "qqbot",
|
|
181
|
+
accountId: appId,
|
|
182
|
+
nativeId,
|
|
183
|
+
kind,
|
|
184
|
+
userId: person,
|
|
185
|
+
name: name.slice(0, 100),
|
|
186
|
+
accountName: name.slice(0, 100),
|
|
187
|
+
text: out.slice(0, 4000),
|
|
188
|
+
mentioned: atSelf || replyToBot,
|
|
189
|
+
replyToBot,
|
|
190
|
+
platformId,
|
|
191
|
+
replyId,
|
|
192
|
+
time: Number.isFinite(time) ? time : Date.now(),
|
|
193
|
+
mentions,
|
|
194
|
+
attachments,
|
|
195
|
+
segments: [],
|
|
196
|
+
media: {
|
|
197
|
+
...media,
|
|
198
|
+
count: mediaCount,
|
|
199
|
+
only: mediaCount > 0 && !plain && !atSelf && !replyToBot,
|
|
200
|
+
imageOnly:
|
|
201
|
+
media.images > 0 &&
|
|
202
|
+
mediaCount === media.images &&
|
|
203
|
+
!plain &&
|
|
204
|
+
!atSelf &&
|
|
205
|
+
!replyToBot,
|
|
206
|
+
stickerOnly: false,
|
|
207
|
+
},
|
|
208
|
+
eventId: `${appId}:${kind}:${nativeId}:${text(d.id)}`,
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// The openid the platform wants when it is sent something for this event.
|
|
213
|
+
export function openidOf(type, d) {
|
|
214
|
+
const author = d?.author || {};
|
|
215
|
+
return text(
|
|
216
|
+
type === "C2C_MESSAGE_CREATE"
|
|
217
|
+
? author.user_openid || author.id
|
|
218
|
+
: author.member_openid || author.id,
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// The message `replyId` pointed to, rebuilt from the event that quoted it.
|
|
223
|
+
export function quotedMessage(current, element, context = {}) {
|
|
224
|
+
if (!element || typeof element !== "object") return null;
|
|
225
|
+
const author = element.author || {};
|
|
226
|
+
const bot =
|
|
227
|
+
author.bot === true ||
|
|
228
|
+
(!!author.id && text(author.id) === text(context.botId)) ||
|
|
229
|
+
!!context.botRefs?.has?.(text(current.replyId));
|
|
230
|
+
const id = text(
|
|
231
|
+
author.union_openid ||
|
|
232
|
+
author.member_openid ||
|
|
233
|
+
author.user_openid ||
|
|
234
|
+
author.id,
|
|
235
|
+
);
|
|
236
|
+
const content = text(element.content).replace(MENTION, "[提及成员]").trim();
|
|
237
|
+
const marks = (Array.isArray(element.attachments) ? element.attachments : [])
|
|
238
|
+
.map((item) => (attachmentOf(item).type === "image" ? "[图片]" : "[媒体]"))
|
|
239
|
+
.join("");
|
|
240
|
+
return {
|
|
241
|
+
sessionId: current.sessionId,
|
|
242
|
+
kind: current.kind,
|
|
243
|
+
userId: bot ? "bot" : id || "unknown",
|
|
244
|
+
name: bot
|
|
245
|
+
? ""
|
|
246
|
+
: text(author.username).trim() || (id ? placeholderName(id) : ""),
|
|
247
|
+
text: (content + marks).trim(),
|
|
248
|
+
role: bot ? "assistant" : "user",
|
|
249
|
+
platformId: text(current.replyId),
|
|
250
|
+
accountId: current.accountId,
|
|
251
|
+
time: Date.now(),
|
|
252
|
+
};
|
|
253
|
+
}
|