dsh-mc-server-ops 0.3.0 → 0.4.1
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/README.md +37 -0
- package/client.js +60 -0
- package/index.js +118 -5
- package/ops/qq-bridge.mjs +408 -0
- package/ops/rcon-probe.mjs +91 -0
- package/package.json +5 -4
package/README.md
CHANGED
|
@@ -63,6 +63,13 @@ dsh plugin add /path/to/dsh-mc-server-ops
|
|
|
63
63
|
| `vote.timeoutMinutes` | `15` | 多久没凑够门槛自动作废 |
|
|
64
64
|
| `vote.vetoEnabled` | `true` | 是否允许一票否决;关掉后反对票只记录、不作废 |
|
|
65
65
|
| `vote.protectedPaths` | `world, ops/data, whitelist` | 改动这些位置需要群友投票放行 |
|
|
66
|
+
| `bridge.enabled` | `false` | 是否启用群服互通(游戏聊天 → QQ 群) |
|
|
67
|
+
| `bridge.mode` | `auto` | `auto` 有玩家在线才转发 / `on` 常开 / `off` 常关 |
|
|
68
|
+
| `bridge.groups` | `[]` | 转发到哪些群(群 openid) |
|
|
69
|
+
| `bridge.events` | `join/leave` 开、`death` 关 | 除聊天外还转发哪些事件 |
|
|
70
|
+
| `bridge.coalesceMs` | `3000` | 多条游戏消息合并成一条 QQ 消息的窗口 |
|
|
71
|
+
| `bridge.maxPerDay` | `900` | 每群每天发送上限(官方上限 1000) |
|
|
72
|
+
| `bridge.appId` / `appSecret` | 空 | 留空自动从本机 qqbot 插件配置读取 |
|
|
66
73
|
|
|
67
74
|
## 目录结构
|
|
68
75
|
|
|
@@ -72,7 +79,9 @@ dsh-mc-server-ops/
|
|
|
72
79
|
├── cordis.patch.yml # 安装时自动插入的加载行
|
|
73
80
|
└── ops/
|
|
74
81
|
├── command-guard.mjs # 静态命令拦截:出网前掐掉“一条命令搞崩整个服”的类型
|
|
82
|
+
├── qq-bridge.mjs # 群服互通:读日志 → 直连 QQ 开放平台(不经过 AI)
|
|
75
83
|
├── rcon.mjs # 跨平台核心:RCON、进程探测、日志、状态汇总
|
|
84
|
+
├── rcon-probe.mjs # 极简 RCON 探测(查在线玩家)
|
|
76
85
|
├── adapters/ # 写操作适配器:local(本机脚本)/ panel(Pterodactyl)
|
|
77
86
|
├── mcadmin.ps1 # 运维入口(status/start/stop/投票/白名单…)
|
|
78
87
|
├── watchdog.ps1 # 看门狗:崩溃自动拉起
|
|
@@ -150,6 +159,32 @@ powershell -File <服务器目录>\ops\mcadmin.ps1 -Action owner-add -Arg <openi
|
|
|
150
159
|
|
|
151
160
|
只读操作(`status` / `players` / `logs` / `crashinfo`)不经过适配器。要接别的面板(Pelican、AMP、PufferPanel)只需再写一个适配器文件,接口就五个方法:`start` / `stop` / `restart` / `sendCommand` / `getStatus`。
|
|
152
161
|
|
|
162
|
+
## 群服互通(游戏聊天 → QQ 群)
|
|
163
|
+
|
|
164
|
+
**不经过 AI,不消耗 token。** 桥直接读服务器日志、直接调 QQ 开放平台接口:群里的人能看到游戏里说了什么,全程不创建 agent 会话、不调模型。
|
|
165
|
+
|
|
166
|
+
| 模式 | 行为 |
|
|
167
|
+
| --- | --- |
|
|
168
|
+
| `auto`(默认) | 有玩家在线才转发;服务器空转时自动静默,不占配额 |
|
|
169
|
+
| `on` | 常开 |
|
|
170
|
+
| `off` | 常关 |
|
|
171
|
+
|
|
172
|
+
转发内容:玩家聊天(始终)、加入 / 离开(默认开)、死亡消息(默认关 —— 文案是本地化的,容易刷屏)。
|
|
173
|
+
|
|
174
|
+
实现要点:
|
|
175
|
+
|
|
176
|
+
- **收** — 增量 tail `logs/latest.log`,**按字节切行**(中文是多字节,先转字符串再切会在块边界切坏字),再识别 `<玩家> 内容`、`joined the game`、`left the game`。
|
|
177
|
+
- **编码** — 服务器的日志是**系统编码**(中文 Windows 上是 GBK),不是 UTF-8。解码器先按 UTF-8 试,出现替换字符 `U+FFFD` 就自动退回 GBK。这一步不做的话,中文在 QQ 里会变成 `��ôţ��`。
|
|
178
|
+
- **发** — 直接 `POST https://api.bot.qq.com/v2/groups/{openid}/messages`,头是 `Authorization: QQBot <access_token>`;token 用 AppID/AppSecret 换,缓存到过期前 1 分钟。
|
|
179
|
+
- **聚合** — `coalesceMs` 窗口内的多条消息合成一条。官方对群主动消息的限制是 **20 条/分钟、每群 1000 条/天**,一条游戏聊天发一条 QQ 会很快撞墙。
|
|
180
|
+
- **限流** — `maxPerDay`(默认 900)本地兜底,超了停发,面板状态行会显示原因。
|
|
181
|
+
- **清洗** — URL 换成 `[链接]`(QQ 会拒收含 URL 的主动消息)、剥掉颜色码 `§x` 和控制字符、单条截断到 900 字。
|
|
182
|
+
- **防环** — 带 `[群]` / `[QQ]` 前缀的消息不再转发,避免 QQ → 游戏 → QQ 打转。
|
|
183
|
+
|
|
184
|
+
配置在设置面板的「群服互通」里,**改完立刻生效**(不用重启),状态行会显示「运行中 / 在线几人 / 今日已发几条 / 错误原因」。
|
|
185
|
+
|
|
186
|
+
群 openid 不知道怎么办:官方没有「列出机器人加入的群」的稳定接口(`/v2/users/@me/groups` 直接 404),只能从一条真实的群消息里抓一次。详细过程写在 [docs/qq-bridge.md](https://github.com/mogutofu/dsh-mc-server-ops/blob/main/docs/qq-bridge.md)。
|
|
187
|
+
|
|
153
188
|
## 安全模型
|
|
154
189
|
|
|
155
190
|
- 仓库和 npm 包里**不含任何口令、QQ 号、记忆数据或整合包**。
|
|
@@ -160,11 +195,13 @@ powershell -File <服务器目录>\ops\mcadmin.ps1 -Action owner-add -Arg <openi
|
|
|
160
195
|
- `export-data` / `import-data` 仅服主可用;导入时会拒绝含 `..` 或绝对路径的压缩包条目(防 zip slip)。
|
|
161
196
|
- `cmd`(op/ban/kick 这类后台指令)在插件层就拦下非服主,不依赖脚本再判一次。
|
|
162
197
|
- `kill @a` / `kick @a` / `whitelist off` 这类“一条命令清场”的指令由静态拦截器直接拒绝,服主也发不出去;拦截在两处生效(插件层 + PowerShell 层)。
|
|
198
|
+
- 群服互通用到的 AppID/AppSecret 只在内存里使用,不写日志;设置里留空时才从本机 qqbot 配置读取。桥不经过 AI,群里刷屏不会消耗 token。
|
|
163
199
|
|
|
164
200
|
## 运行环境
|
|
165
201
|
|
|
166
202
|
- Windows + PowerShell 5.1(脚本用 `powershell.exe -File` 调用)
|
|
167
203
|
- Node.js ≥ 20(DSH 自带)
|
|
204
|
+
- DSH ≥ 0.2.0(`package.json` 里用 `engines.dsh` 声明,安装时会校验)
|
|
168
205
|
|
|
169
206
|
**服务端不限类型**,插件只看端口、RCON 和进程,不假设你跑的是哪一家:
|
|
170
207
|
|
package/client.js
CHANGED
|
@@ -49,6 +49,7 @@ window.__ModuleLoader__.load({
|
|
|
49
49
|
const [status, setStatus] = react.useState({ loading: true, error: "", saved: "", saving: false })
|
|
50
50
|
const [form, setForm] = react.useState(null)
|
|
51
51
|
const [owners, setOwners] = react.useState([])
|
|
52
|
+
const [bridgeState, setBridgeState] = react.useState(null)
|
|
52
53
|
const [newOwner, setNewOwner] = react.useState("")
|
|
53
54
|
|
|
54
55
|
react.useEffect(() => { void load() }, [])
|
|
@@ -73,6 +74,20 @@ window.__ModuleLoader__.load({
|
|
|
73
74
|
serverId: (v.panel || {}).serverId || "",
|
|
74
75
|
clientApiKey: (v.panel || {}).clientApiKey || "",
|
|
75
76
|
},
|
|
77
|
+
bridge: {
|
|
78
|
+
enabled: (v.bridge || {}).enabled === true,
|
|
79
|
+
mode: (v.bridge || {}).mode || "auto",
|
|
80
|
+
groups: Array.isArray((v.bridge || {}).groups) ? (v.bridge || {}).groups.join(", ") : "",
|
|
81
|
+
appId: (v.bridge || {}).appId || "",
|
|
82
|
+
appSecret: (v.bridge || {}).appSecret || "",
|
|
83
|
+
events: {
|
|
84
|
+
join: ((v.bridge || {}).events || {}).join !== false,
|
|
85
|
+
leave: ((v.bridge || {}).events || {}).leave !== false,
|
|
86
|
+
death: ((v.bridge || {}).events || {}).death === true,
|
|
87
|
+
},
|
|
88
|
+
coalesceMs: (v.bridge || {}).coalesceMs ?? 3000,
|
|
89
|
+
maxPerDay: (v.bridge || {}).maxPerDay ?? 900,
|
|
90
|
+
},
|
|
76
91
|
vote: {
|
|
77
92
|
approveNeed: (v.vote || {}).approveNeed ?? 2,
|
|
78
93
|
rejectNeed: (v.vote || {}).rejectNeed ?? 1,
|
|
@@ -95,6 +110,7 @@ window.__ModuleLoader__.load({
|
|
|
95
110
|
},
|
|
96
111
|
})
|
|
97
112
|
setOwners(Array.isArray(data.owners) ? data.owners : [])
|
|
113
|
+
setBridgeState(data.bridgeState || null)
|
|
98
114
|
setStatus({ loading: false, error: "", saved: "", saving: false })
|
|
99
115
|
} catch (err) {
|
|
100
116
|
setStatus({ loading: false, error: String(err && err.message ? err.message : err), saved: "", saving: false })
|
|
@@ -110,6 +126,16 @@ window.__ModuleLoader__.load({
|
|
|
110
126
|
setForm((prev) => (prev ? Object.assign({}, prev, { [key]: value }) : prev))
|
|
111
127
|
}
|
|
112
128
|
|
|
129
|
+
// bridge 里还嵌着 events,单独给两个入口
|
|
130
|
+
function patchBridge(key, value) {
|
|
131
|
+
setForm((prev) => (prev ? Object.assign({}, prev, { bridge: Object.assign({}, prev.bridge, { [key]: value }) }) : prev))
|
|
132
|
+
}
|
|
133
|
+
function patchBridgeEvent(key, value) {
|
|
134
|
+
setForm((prev) => (prev ? Object.assign({}, prev, {
|
|
135
|
+
bridge: Object.assign({}, prev.bridge, { events: Object.assign({}, prev.bridge.events, { [key]: value }) }),
|
|
136
|
+
}) : prev))
|
|
137
|
+
}
|
|
138
|
+
|
|
113
139
|
async function save() {
|
|
114
140
|
if (!form) return
|
|
115
141
|
setStatus(Object.assign({}, status, { saving: true, error: "", saved: "" }))
|
|
@@ -243,6 +269,40 @@ window.__ModuleLoader__.load({
|
|
|
243
269
|
h(Field, { label: "受保护路径", hint: "逗号分隔,改动这些位置要走投票。默认 world, ops/data, whitelist" },
|
|
244
270
|
h(TextInput, { value: form.vote.protectedPaths, placeholder: "world, ops/data, whitelist", onChange: (x) => patch("vote", "protectedPaths", x) })),
|
|
245
271
|
),
|
|
272
|
+
h("div", null,
|
|
273
|
+
h("div", { style: titleStyle }, "群服互通"),
|
|
274
|
+
h("div", { style: hintStyle }, "把游戏内聊天直接转发到 QQ 群。走机器人自己的接口,不经过 AI、不消耗 token。"),
|
|
275
|
+
),
|
|
276
|
+
h("div", { style: groupStyle },
|
|
277
|
+
bridgeState
|
|
278
|
+
? h("div", { style: Object.assign({}, hintStyle, { color: bridgeState.running ? "#3c9a5f" : "#d9534f" }) },
|
|
279
|
+
(bridgeState.running ? "● 运行中" : "○ 未运行")
|
|
280
|
+
+ " · 在线 " + ((bridgeState.online || []).length) + " 人"
|
|
281
|
+
+ " · 今日已发 " + (bridgeState.sentToday || 0) + " 条"
|
|
282
|
+
+ (bridgeState.lastError ? " · ⚠ " + bridgeState.lastError : ""))
|
|
283
|
+
: null,
|
|
284
|
+
h(Toggle, { label: "启用群服互通", value: form.bridge.enabled, onChange: (x) => patchBridge("enabled", x) }),
|
|
285
|
+
h(Field, { label: "运行模式", hint: "auto 只有人玩的时候才转发(推荐);on 一直转发;off 完全关闭" },
|
|
286
|
+
h("select", { style: inputStyle, value: form.bridge.mode, onChange: (e) => patchBridge("mode", e.target.value) },
|
|
287
|
+
h("option", { value: "auto" }, "有玩家时开启(默认)"),
|
|
288
|
+
h("option", { value: "on" }, "常开启"),
|
|
289
|
+
h("option", { value: "off" }, "常关闭"))),
|
|
290
|
+
h(Field, { label: "转发到哪些群", hint: "群 openid,逗号分隔。不知道的话在群里 @ 小铜 问" },
|
|
291
|
+
h(TextInput, { value: form.bridge.groups, placeholder: "FC73DE60… ", onChange: (x) => patchBridge("groups", x) })),
|
|
292
|
+
h(Field, { label: "除聊天外还转发", hint: "聊天内容始终转发" },
|
|
293
|
+
h("div", { style: { display: "flex", gap: 18, flexWrap: "wrap" } },
|
|
294
|
+
h(Toggle, { label: "玩家加入", value: form.bridge.events.join, onChange: (x) => patchBridgeEvent("join", x) }),
|
|
295
|
+
h(Toggle, { label: "玩家离开", value: form.bridge.events.leave, onChange: (x) => patchBridgeEvent("leave", x) }),
|
|
296
|
+
h(Toggle, { label: "死亡消息", value: form.bridge.events.death, onChange: (x) => patchBridgeEvent("death", x) }))),
|
|
297
|
+
h(Field, { label: "合并窗口(毫秒)", hint: "这段时间内的多条游戏消息合成一条 QQ 消息,默认 3000" },
|
|
298
|
+
h(NumberInput, { value: form.bridge.coalesceMs, onChange: (x) => patchBridge("coalesceMs", x) })),
|
|
299
|
+
h(Field, { label: "每群每天发送上限", hint: "官方上限 1000 条/天,默认 900 留余量" },
|
|
300
|
+
h(NumberInput, { value: form.bridge.maxPerDay, onChange: (x) => patchBridge("maxPerDay", x) })),
|
|
301
|
+
h(Field, { label: "AppID", hint: "留空自动从本机 qqbot 配置读取,一般不用填" },
|
|
302
|
+
h(TextInput, { value: form.bridge.appId, placeholder: "留空 = 自动", onChange: (x) => patchBridge("appId", x) })),
|
|
303
|
+
h(Field, { label: "AppSecret", hint: "同上,留空自动读" },
|
|
304
|
+
h(TextInput, { value: form.bridge.appSecret, placeholder: "留空 = 自动", onChange: (x) => patchBridge("appSecret", x) })),
|
|
305
|
+
),
|
|
246
306
|
h("div", null,
|
|
247
307
|
h("div", { style: titleStyle }, "功能开关"),
|
|
248
308
|
h("div", { style: hintStyle }, "逐项决定群友能做什么。关掉的那一项,玩家调用会被直接拒绝(服主不受影响)。"),
|
package/index.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process'
|
|
2
|
-
import { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync } from 'node:fs'
|
|
3
3
|
import { dirname, join } from 'node:path'
|
|
4
4
|
import { fileURLToPath } from 'node:url'
|
|
5
5
|
import Schema from '@deepseek-ai/schemastery'
|
|
6
6
|
import { guardCommand } from './ops/command-guard.mjs'
|
|
7
7
|
import { createAdapter } from './ops/adapters/index.mjs'
|
|
8
|
+
import { createBridge, writeBridgeState, QqApi } from './ops/qq-bridge.mjs'
|
|
8
9
|
|
|
9
10
|
// 运行期路径:apply() 里按配置初始化。服务器目录、脚本位置都可以在设置里改。
|
|
10
11
|
const paths = { serverDir: '', script: '', ownersFile: '', flipLog: '' }
|
|
@@ -88,12 +89,34 @@ function hasToolGrant(agentId) {
|
|
|
88
89
|
return until > Date.now()
|
|
89
90
|
}
|
|
90
91
|
|
|
92
|
+
/**
|
|
93
|
+
* 从本机 DSH profile 的 cordis.patch.yml 里读 qqbot 的 AppID / AppSecret。
|
|
94
|
+
* 只在插件设置里没填的时候用;读不到就返回 null,不抛错。
|
|
95
|
+
*/
|
|
96
|
+
function readQqbotCredentials() {
|
|
97
|
+
try {
|
|
98
|
+
const home = process.env.USERPROFILE || process.env.HOME || ''
|
|
99
|
+
if (!home) return null
|
|
100
|
+
const dir = join(home, '.dsh', 'profiles')
|
|
101
|
+
if (!existsSync(dir)) return null
|
|
102
|
+
for (const name of readdirSync(dir)) {
|
|
103
|
+
const file = join(dir, name, 'cordis.patch.yml')
|
|
104
|
+
if (!existsSync(file)) continue
|
|
105
|
+
const raw = readFileSync(file, 'utf8')
|
|
106
|
+
const id = /appId:\s*'?([0-9]+)'?/.exec(raw)
|
|
107
|
+
const sec = /appSecret:\s*'?([A-Za-z0-9_]+)'?/.exec(raw)
|
|
108
|
+
if (id && sec) return { appId: id[1], appSecret: sec[1] }
|
|
109
|
+
}
|
|
110
|
+
} catch { /* 读不到就算了 */ }
|
|
111
|
+
return null
|
|
112
|
+
}
|
|
113
|
+
|
|
91
114
|
const ACTIONS = [
|
|
92
115
|
'status', 'players', 'say', 'cmd', 'start', 'stop', 'restart',
|
|
93
116
|
'logs', 'crashinfo', 'whoami', 'help', 'gamemode',
|
|
94
117
|
'bind-player', 'unbind-player', 'my-players', 'bindings', 'whitelist-sync',
|
|
95
118
|
'kubejs-backup', 'kubejs-reload', 'vote-start', 'vote-approve', 'vote-reject', 'vote-status',
|
|
96
|
-
'export-data', 'import-data',
|
|
119
|
+
'export-data', 'import-data', 'bridge-groups',
|
|
97
120
|
]
|
|
98
121
|
|
|
99
122
|
function runMcAdmin(args, timeoutMs) {
|
|
@@ -163,6 +186,7 @@ const DESCRIPTION = [
|
|
|
163
186
|
'- vote-status:查看投票进度(可带编号)',
|
|
164
187
|
'- export-data:把 ops\\data(绑定、投票、服主名单、口令)打成 zip,arg 为目标路径,仅服主',
|
|
165
188
|
'- import-data:从 zip 恢复 ops\\data,arg 为 zip 路径,仅服主',
|
|
189
|
+
'- bridge-groups:列出机器人加入的 QQ 群(群名 + 群 openid),配置群服互通时用来填 groups,仅服主',
|
|
166
190
|
'',
|
|
167
191
|
'玩家可以改服务器目录下除敏感区(ops\\data、world、白名单、eula、jar/exe/dll、密钥)之外的文件:kubejs 配方、config/defaultconfigs 配置、server.properties 等,write/edit 直接放行;改之前先备份,改完按需 reload。',
|
|
168
192
|
'玩家不能改 kubejs 目录以外的任何文件。',
|
|
@@ -237,6 +261,24 @@ export const Config = Schema.object({
|
|
|
237
261
|
serverId: Schema.string().default('').description('服务器 ID:面板里该服务器 URL 的最后一段(8 位短 UUID)'),
|
|
238
262
|
clientApiKey: Schema.string().default('').description('客户端 API Key(ptlc_ 开头,面板 → Account → API Credentials 里生成)'),
|
|
239
263
|
}).description('Pterodactyl 面板(adapter 选 panel 时才用)'),
|
|
264
|
+
|
|
265
|
+
bridge: Schema.object({
|
|
266
|
+
enabled: Schema.boolean().default(false)
|
|
267
|
+
.description('群服互通:把游戏内聊天直接转发到 QQ 群。不经过 AI,不消耗 token'),
|
|
268
|
+
mode: Schema.union(['auto', 'on', 'off']).default('auto')
|
|
269
|
+
.description('auto=有玩家在线才转发(默认);on=常开;off=常关'),
|
|
270
|
+
groups: Schema.array(Schema.string()).default([])
|
|
271
|
+
.description('转发到哪些群(群 openid)。用 mc_server 的 bridge-groups 可以查机器人加入的群'),
|
|
272
|
+
appId: Schema.string().default('').description('QQ 机器人 AppID;留空自动从本机 qqbot 插件配置里读'),
|
|
273
|
+
appSecret: Schema.string().default('').description('QQ 机器人 AppSecret;留空自动读'),
|
|
274
|
+
events: Schema.object({
|
|
275
|
+
join: Schema.boolean().default(true).description('转发玩家加入'),
|
|
276
|
+
leave: Schema.boolean().default(true).description('转发玩家离开'),
|
|
277
|
+
death: Schema.boolean().default(false).description('转发死亡消息(本地化文案,容易刷屏,默认关)'),
|
|
278
|
+
}).description('除聊天外还要转发哪些事件'),
|
|
279
|
+
coalesceMs: Schema.number().default(3000).description('多少毫秒内的多条消息合并成一条 QQ 消息'),
|
|
280
|
+
maxPerDay: Schema.number().default(900).description('每个群每天最多发几条(官方上限 1000,留余量)'),
|
|
281
|
+
}).description('群服互通'),
|
|
240
282
|
})
|
|
241
283
|
|
|
242
284
|
export function apply(ctx, config) {
|
|
@@ -297,6 +339,10 @@ export function apply(ctx, config) {
|
|
|
297
339
|
ops: Object.assign({ allowPlayerWrite: true, grantHours: 12, riskApprovalSeconds: 30 }, (config && config.ops) || {}),
|
|
298
340
|
adapter: String((config && config.adapter) || 'local'),
|
|
299
341
|
panel: Object.assign({ url: '', serverId: '', clientApiKey: '' }, (config && config.panel) || {}),
|
|
342
|
+
bridge: Object.assign({
|
|
343
|
+
enabled: false, mode: 'auto', groups: [], appId: '', appSecret: '',
|
|
344
|
+
events: { join: true, leave: true, death: false }, coalesceMs: 3000, maxPerDay: 900,
|
|
345
|
+
}, (config && config.bridge) || {}),
|
|
300
346
|
}
|
|
301
347
|
const memoryConfig = {
|
|
302
348
|
get: () => liveConfig,
|
|
@@ -322,6 +368,36 @@ export function apply(ctx, config) {
|
|
|
322
368
|
panel: (liveConfig && liveConfig.panel) || {},
|
|
323
369
|
})
|
|
324
370
|
|
|
371
|
+
// ── 群服互通:游戏聊天 → QQ 群(不经过 AI,不产生 token)──
|
|
372
|
+
// 常驻创建、常驻运行:是否真的转发由 liveConfig.bridge.enabled 决定,
|
|
373
|
+
// 这样在面板里打开开关立刻生效,不用再重启一次。
|
|
374
|
+
let bridge = null
|
|
375
|
+
{
|
|
376
|
+
const auto = readQqbotCredentials()
|
|
377
|
+
const appId = String(liveConfig.bridge.appId || (auto && auto.appId) || '')
|
|
378
|
+
const appSecret = String(liveConfig.bridge.appSecret || (auto && auto.appSecret) || '')
|
|
379
|
+
bridge = createBridge({
|
|
380
|
+
serverDir,
|
|
381
|
+
appId,
|
|
382
|
+
appSecret,
|
|
383
|
+
readConfig: () => (liveConfig && liveConfig.bridge) || {},
|
|
384
|
+
log: (m) => {
|
|
385
|
+
try { appendFileSync(join(opsDir, 'data', 'bridge.log'), new Date().toISOString() + ' ' + m + '\n') } catch { }
|
|
386
|
+
},
|
|
387
|
+
})
|
|
388
|
+
ctx.effect(() => {
|
|
389
|
+
void bridge.start()
|
|
390
|
+
const tick = setInterval(() => {
|
|
391
|
+
writeBridgeState(serverDir, Object.assign(
|
|
392
|
+
{ appId: appId ? appId.slice(0, 3) + '***' : '', hasSecret: !!appSecret },
|
|
393
|
+
bridge.status(),
|
|
394
|
+
))
|
|
395
|
+
}, 10000)
|
|
396
|
+
if (tick.unref) tick.unref()
|
|
397
|
+
return () => { clearInterval(tick); bridge.stop() }
|
|
398
|
+
})
|
|
399
|
+
}
|
|
400
|
+
|
|
325
401
|
// 依赖可能比本插件晚就绪,用 ctx.inject 等它们可用再挂路由。
|
|
326
402
|
if (typeof ctx.inject === 'function') {
|
|
327
403
|
ctx.inject(['settings', 'webServer'], (scope) => {
|
|
@@ -380,7 +456,7 @@ export function apply(ctx, config) {
|
|
|
380
456
|
}
|
|
381
457
|
if (!isOwner(actor)) {
|
|
382
458
|
if (action === 'cmd') return { ok: false, text: '执行后台命令只有服主能做。' }
|
|
383
|
-
if (action === 'export-data' || action === 'import-data' || action === 'whitelist-sync' || action === 'bindings') {
|
|
459
|
+
if (action === 'export-data' || action === 'import-data' || action === 'whitelist-sync' || action === 'bindings' || action === 'bridge-groups') {
|
|
384
460
|
return { ok: false, text: '这个操作只有服主能做。' }
|
|
385
461
|
}
|
|
386
462
|
const denied = checkActionAllowed(action, currentPerms())
|
|
@@ -407,6 +483,22 @@ export function apply(ctx, config) {
|
|
|
407
483
|
}
|
|
408
484
|
}
|
|
409
485
|
|
|
486
|
+
// 群服互通:列机器人加入的群,供填 bridge.groups
|
|
487
|
+
if (action === 'bridge-groups') {
|
|
488
|
+
const auto = readQqbotCredentials()
|
|
489
|
+
const bCfg = (liveConfig && liveConfig.bridge) || {}
|
|
490
|
+
const appId = String(bCfg.appId || (auto && auto.appId) || '')
|
|
491
|
+
const appSecret = String(bCfg.appSecret || (auto && auto.appSecret) || '')
|
|
492
|
+
try {
|
|
493
|
+
const groups = await new QqApi({ appId, appSecret }).listGroups()
|
|
494
|
+
if (!groups.length) return { ok: true, text: '机器人还没加入任何群(或者没有「群管理」权限,拿不到群列表)。' }
|
|
495
|
+
return { ok: true, text: groups.map((g) => g.name + '\n ' + g.openid).join('\n') }
|
|
496
|
+
} catch (error) {
|
|
497
|
+
const message = error && error.message ? error.message : String(error)
|
|
498
|
+
return { ok: false, text: '查群列表失败:' + message + '\n(需要 AppID/AppSecret,以及开放平台的「群管理」权限)' }
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
410
502
|
const isWindows = process.platform === 'win32'
|
|
411
503
|
if (!isWindows && !NODE_ACTIONS.has(action)) {
|
|
412
504
|
return { ok: false, text: `(${process.platform})${action} 还没跨平台,目前只在 Windows 上可用。跨平台可用的是:${[...NODE_ACTIONS].join(' / ')}` }
|
|
@@ -664,8 +756,8 @@ async function handleConfigRoute(req, res, services, fallbackConfig) {
|
|
|
664
756
|
if (req.method === 'GET') {
|
|
665
757
|
const opsPath = join(paths.serverDir, 'ops')
|
|
666
758
|
const owners = readOwnersList(opsPath)
|
|
667
|
-
if (desc) return send(200, { ns: String(desc.ns), value: desc.value, revision: desc.revision, via: 'settings', owners })
|
|
668
|
-
return send(200, { ns: '', value: fallbackConfig.get(), revision: 0, via: 'memory', owners })
|
|
759
|
+
if (desc) return send(200, { ns: String(desc.ns), value: desc.value, revision: desc.revision, via: 'settings', owners, bridgeState: readBridgeState() })
|
|
760
|
+
return send(200, { ns: '', value: fallbackConfig.get(), revision: 0, via: 'memory', owners, bridgeState: readBridgeState() })
|
|
669
761
|
}
|
|
670
762
|
if (req.method !== 'POST') return send(405, { error: '只支持 GET / POST' })
|
|
671
763
|
|
|
@@ -695,6 +787,10 @@ async function handleConfigRoute(req, res, services, fallbackConfig) {
|
|
|
695
787
|
body.vote.protectedPaths = body.vote.protectedPaths.split(/[,,\s]+/).map((s) => s.trim()).filter(Boolean)
|
|
696
788
|
if (!body.vote.protectedPaths.length) body.vote.protectedPaths = ['world', 'ops/data', 'whitelist']
|
|
697
789
|
}
|
|
790
|
+
// 群列表同理
|
|
791
|
+
if (body && body.bridge && typeof body.bridge.groups === 'string') {
|
|
792
|
+
body.bridge.groups = body.bridge.groups.split(/[,,\s]+/).map((s) => s.trim()).filter(Boolean)
|
|
793
|
+
}
|
|
698
794
|
|
|
699
795
|
if (desc) {
|
|
700
796
|
await settings.update(desc.ns, body, desc.revision)
|
|
@@ -738,6 +834,23 @@ function readOwnersList(opsPath) {
|
|
|
738
834
|
} catch { return [] }
|
|
739
835
|
}
|
|
740
836
|
|
|
837
|
+
/** 读群服互通的运行状态(插件每 10 秒落一次盘),只把面板需要的字段传出去。 */
|
|
838
|
+
function readBridgeState() {
|
|
839
|
+
try {
|
|
840
|
+
const file = join(paths.serverDir, 'ops', 'data', 'bridge-state.json')
|
|
841
|
+
if (!existsSync(file)) return null
|
|
842
|
+
const doc = JSON.parse(readFileSync(file, 'utf8').replace(/^\uFEFF/, ''))
|
|
843
|
+
return {
|
|
844
|
+
running: doc.running === true,
|
|
845
|
+
mode: String(doc.mode || ''),
|
|
846
|
+
online: Array.isArray(doc.online) ? doc.online.map(String) : [],
|
|
847
|
+
sentToday: Number(doc.sentToday) || 0,
|
|
848
|
+
lastError: String(doc.lastError || ''),
|
|
849
|
+
at: String(doc.at || ''),
|
|
850
|
+
}
|
|
851
|
+
} catch { return null }
|
|
852
|
+
}
|
|
853
|
+
|
|
741
854
|
|
|
742
855
|
|
|
743
856
|
/** 把投票门槛写到 ops\data\vote-config.json,脚本每次调用时读它。 */
|
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 群服互通 P0:游戏聊天 → QQ 群(**不经过 AI,不产生 token 消耗**)
|
|
3
|
+
*
|
|
4
|
+
* 链路:
|
|
5
|
+
* logs/latest.log 增量读取 → 解析出聊天/进出事件 → 聚合 → 直连 QQ 开放平台 HTTP API
|
|
6
|
+
*
|
|
7
|
+
* 为什么不走 qqbot 插件:它的入站链路是 中间件 → handleInbound → agent.followup,
|
|
8
|
+
* 出站也只能由模型调用工具触发。这条链路完全绕开它,自己拿 appId/appSecret 发消息。
|
|
9
|
+
*
|
|
10
|
+
* 不依赖任何外部包,只用 Node 内置模块。
|
|
11
|
+
*/
|
|
12
|
+
import { closeSync, existsSync, mkdirSync, openSync, readSync, statSync, writeFileSync } from 'node:fs'
|
|
13
|
+
import { join } from 'node:path'
|
|
14
|
+
|
|
15
|
+
// ─────────────────────────── QQ 开放平台 ───────────────────────────
|
|
16
|
+
|
|
17
|
+
const TOKEN_URL = 'https://bots.qq.com/app/getAppAccessToken'
|
|
18
|
+
const DEFAULT_API = 'https://api.bot.qq.com'
|
|
19
|
+
const TOKEN_SAFETY_MS = 60 * 1000
|
|
20
|
+
|
|
21
|
+
export class QqApi {
|
|
22
|
+
constructor(options = {}) {
|
|
23
|
+
this.appId = String(options.appId || '')
|
|
24
|
+
this.appSecret = String(options.appSecret || '')
|
|
25
|
+
this.apiBase = String(options.apiBase || DEFAULT_API).replace(/\/+$/, '')
|
|
26
|
+
this.tokenUrl = String(options.tokenUrl || TOKEN_URL)
|
|
27
|
+
this.fetchImpl = options.fetchImpl || globalThis.fetch
|
|
28
|
+
this.tokenValue = ''
|
|
29
|
+
this.tokenExpiresAt = 0
|
|
30
|
+
this.tokenPromise = null
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
configProblem() {
|
|
34
|
+
if (!this.appId) return '缺少 AppID'
|
|
35
|
+
if (!this.appSecret) return '缺少 AppSecret'
|
|
36
|
+
if (typeof this.fetchImpl !== 'function') return '当前 Node 没有 fetch(需要 18+)'
|
|
37
|
+
return ''
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 拿 access_token,带缓存;并发时只发一次请求。 */
|
|
41
|
+
async token() {
|
|
42
|
+
const now = Date.now()
|
|
43
|
+
if (this.tokenValue && now < this.tokenExpiresAt) return this.tokenValue
|
|
44
|
+
if (this.tokenPromise) return this.tokenPromise
|
|
45
|
+
const problem = this.configProblem()
|
|
46
|
+
if (problem) throw new Error(problem)
|
|
47
|
+
this.tokenPromise = (async () => {
|
|
48
|
+
const res = await this.fetchImpl(this.tokenUrl, {
|
|
49
|
+
method: 'POST',
|
|
50
|
+
headers: { 'Content-Type': 'application/json' },
|
|
51
|
+
body: JSON.stringify({ appId: this.appId, clientSecret: this.appSecret }),
|
|
52
|
+
signal: AbortSignal.timeout ? AbortSignal.timeout(15000) : undefined,
|
|
53
|
+
})
|
|
54
|
+
const text = await res.text()
|
|
55
|
+
let doc = {}
|
|
56
|
+
try { doc = JSON.parse(text) } catch { /* 原样 */ }
|
|
57
|
+
if (!res.ok || !doc.access_token) {
|
|
58
|
+
throw new Error(`拿 token 失败(HTTP ${res.status}):${String(doc.message || doc.error || text).slice(0, 200)}`)
|
|
59
|
+
}
|
|
60
|
+
const ttl = Math.max(60, Number(doc.expires_in) || 7200)
|
|
61
|
+
this.tokenValue = String(doc.access_token)
|
|
62
|
+
this.tokenExpiresAt = Date.now() + ttl * 1000 - TOKEN_SAFETY_MS
|
|
63
|
+
return this.tokenValue
|
|
64
|
+
})()
|
|
65
|
+
try {
|
|
66
|
+
return await this.tokenPromise
|
|
67
|
+
} finally {
|
|
68
|
+
this.tokenPromise = null
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async request(method, path, body) {
|
|
73
|
+
const token = await this.token()
|
|
74
|
+
const init = {
|
|
75
|
+
method,
|
|
76
|
+
headers: {
|
|
77
|
+
Authorization: 'QQBot ' + token,
|
|
78
|
+
'Content-Type': 'application/json',
|
|
79
|
+
'X-Union-Appid': this.appId,
|
|
80
|
+
},
|
|
81
|
+
signal: AbortSignal.timeout ? AbortSignal.timeout(15000) : undefined,
|
|
82
|
+
}
|
|
83
|
+
if (body !== undefined) init.body = JSON.stringify(body)
|
|
84
|
+
const res = await this.fetchImpl(this.apiBase + path, init)
|
|
85
|
+
const text = await res.text()
|
|
86
|
+
let doc = {}
|
|
87
|
+
try { doc = text ? JSON.parse(text) : {} } catch { /* 非 JSON */ }
|
|
88
|
+
if (!res.ok) {
|
|
89
|
+
const detail = doc.message || doc.msg || text
|
|
90
|
+
const err = new Error(`QQ API ${method} ${path} → HTTP ${res.status}:${String(detail).slice(0, 200)}`)
|
|
91
|
+
err.status = res.status
|
|
92
|
+
err.body = doc
|
|
93
|
+
throw err
|
|
94
|
+
}
|
|
95
|
+
return doc
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** 机器人加入的群列表(需要「群管理」权限)。 */
|
|
99
|
+
async listGroups() {
|
|
100
|
+
const doc = await this.request('GET', '/v2/users/@me/groups')
|
|
101
|
+
const list = Array.isArray(doc) ? doc : (Array.isArray(doc.data) ? doc.data : [])
|
|
102
|
+
return list.map((g) => ({
|
|
103
|
+
openid: String(g.group_openid || g.openid || ''),
|
|
104
|
+
name: String(g.group_name || g.name || ''),
|
|
105
|
+
})).filter((g) => g.openid)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* 往群里发一条纯文本。
|
|
110
|
+
* @param {string} openid 群 openid
|
|
111
|
+
* @param {string} content 文本(已截断、已清洗)
|
|
112
|
+
* @param {object} opts msgId=被动回复;msgSeq 用于区分同一条 msg_id 的多次回复
|
|
113
|
+
*/
|
|
114
|
+
async sendGroupMessage(openid, content, opts = {}) {
|
|
115
|
+
const body = { msg_type: 0, content, msg_seq: Number(opts.msgSeq) || 1 }
|
|
116
|
+
if (opts.msgId) body.msg_id = String(opts.msgId)
|
|
117
|
+
return this.request('POST', `/v2/groups/${encodeURIComponent(openid)}/messages`, body)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// ─────────────────────────── 日志增量读取 ───────────────────────────
|
|
122
|
+
|
|
123
|
+
const COLOR_CODE = /§[0-9a-fk-orx]/gi
|
|
124
|
+
const STRIP_PREFIX = /^\[(Not Secure|Not Secure: )\]\s*/i
|
|
125
|
+
|
|
126
|
+
export function cleanText(text) {
|
|
127
|
+
return String(text || '')
|
|
128
|
+
.replace(COLOR_CODE, '')
|
|
129
|
+
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, '')
|
|
130
|
+
.replace(/\r?\n/g, ' ')
|
|
131
|
+
.trim()
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** 解析一行 MC 日志;不是我们关心的事件就返回 null。 */
|
|
135
|
+
export function parseLogLine(line) {
|
|
136
|
+
if (!line || line[0] !== '[' && !/^\s*\[/.test(line)) return null
|
|
137
|
+
const m = /\[(?:Server thread|Server\/INFO)[^\]]*\/INFO\]\s*\[[^\]]*\]:\s*(.*)$/.exec(line)
|
|
138
|
+
if (!m) return null
|
|
139
|
+
let rest = m[1].trim()
|
|
140
|
+
if (!rest) return null
|
|
141
|
+
rest = rest.replace(STRIP_PREFIX, '')
|
|
142
|
+
|
|
143
|
+
let hit = /^<([A-Za-z0-9_]{1,16})>\s*(.*)$/.exec(rest)
|
|
144
|
+
if (hit) return { type: 'chat', player: hit[1], text: cleanText(hit[2]) }
|
|
145
|
+
|
|
146
|
+
hit = /^([A-Za-z0-9_]{1,16}) joined the game\.?$/.exec(rest)
|
|
147
|
+
if (hit) return { type: 'join', player: hit[1] }
|
|
148
|
+
|
|
149
|
+
hit = /^([A-Za-z0-9_]{1,16}) left the game\.?$/.exec(rest)
|
|
150
|
+
if (hit) return { type: 'leave', player: hit[1] }
|
|
151
|
+
|
|
152
|
+
hit = /^([A-Za-z0-9_]{1,16}) (was |drowned|blew up|hit the ground|fell|burned|died|starved|suffocated|withered|killed|slain|walked into|tried to swim|discovered)/.exec(rest)
|
|
153
|
+
if (hit) return { type: 'death', player: hit[1], text: cleanText(rest) }
|
|
154
|
+
|
|
155
|
+
return null
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* 解码日志字节。
|
|
160
|
+
* 服务器的 latest.log 用的是系统编码:中文 Windows 下是 GBK,不是 UTF-8。
|
|
161
|
+
* 先按 UTF-8 解,出现替换字符(U+FFFD)就退回 GBK。
|
|
162
|
+
*/
|
|
163
|
+
const gbkDecoder = (() => {
|
|
164
|
+
try { return new TextDecoder('gbk') } catch { return null }
|
|
165
|
+
})()
|
|
166
|
+
|
|
167
|
+
export function decodeLogBytes(bytes) {
|
|
168
|
+
const utf8 = Buffer.isBuffer(bytes) ? bytes.toString('utf8') : String(bytes)
|
|
169
|
+
if (!utf8.includes('\uFFFD') || !gbkDecoder) return utf8
|
|
170
|
+
try { return gbkDecoder.decode(bytes) } catch { return utf8 }
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* 增量跟踪 logs/latest.log。
|
|
175
|
+
* 用轮询而不是 fs.watch:Windows 上 watch 在日志轮转(每天 0 点重命名)时会丢事件。
|
|
176
|
+
*/
|
|
177
|
+
export function createLogTail(serverDir, onEvent, opts = {}) {
|
|
178
|
+
const file = join(serverDir, 'logs', 'latest.log')
|
|
179
|
+
const intervalMs = Math.max(200, Number(opts.intervalMs) || 500)
|
|
180
|
+
let offset = 0
|
|
181
|
+
let pending = Buffer.alloc(0)
|
|
182
|
+
let timer = null
|
|
183
|
+
let lastSize = -1
|
|
184
|
+
|
|
185
|
+
function readNew() {
|
|
186
|
+
let st
|
|
187
|
+
try { st = statSync(file) } catch { return } // 还没生成
|
|
188
|
+
if (st.size < offset) { offset = 0; pending = Buffer.alloc(0) } // 轮转了,从头来
|
|
189
|
+
if (st.size === offset) return
|
|
190
|
+
let fd
|
|
191
|
+
try {
|
|
192
|
+
fd = openSync(file, 'r')
|
|
193
|
+
const length = st.size - offset
|
|
194
|
+
const buf = Buffer.alloc(length)
|
|
195
|
+
readSync(fd, buf, 0, length, offset)
|
|
196
|
+
offset = st.size
|
|
197
|
+
// 按字节切行:中文是多字节,先转字符串再切会在块边界切坏字符
|
|
198
|
+
pending = pending.length ? Buffer.concat([pending, buf]) : buf
|
|
199
|
+
let nl = pending.lastIndexOf(0x0a)
|
|
200
|
+
if (nl < 0) return
|
|
201
|
+
const chunk = pending.subarray(0, nl)
|
|
202
|
+
pending = pending.subarray(nl + 1)
|
|
203
|
+
const text = decodeLogBytes(chunk)
|
|
204
|
+
for (const line of text.split('\n')) {
|
|
205
|
+
const evt = parseLogLine(line.trim())
|
|
206
|
+
if (evt) {
|
|
207
|
+
try { onEvent(evt) } catch { /* 单个事件失败不影响后续 */ }
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
} catch { /* 读失败下次再来 */ }
|
|
211
|
+
finally { if (fd !== undefined) { try { closeSync(fd) } catch { } } }
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
return {
|
|
215
|
+
/** 从文件末尾开始(只看新内容) */
|
|
216
|
+
startAtEnd() {
|
|
217
|
+
try { offset = statSync(file).size; lastSize = offset } catch { offset = 0 }
|
|
218
|
+
},
|
|
219
|
+
start({ fromStart = false } = {}) {
|
|
220
|
+
if (fromStart) { offset = 0 } else if (offset === 0) { try { offset = statSync(file).size } catch { } }
|
|
221
|
+
if (timer) return
|
|
222
|
+
timer = setInterval(readNew, intervalMs)
|
|
223
|
+
if (timer.unref) timer.unref()
|
|
224
|
+
},
|
|
225
|
+
stop() { if (timer) { clearInterval(timer); timer = null } },
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// ─────────────────────────── 桥本身 ───────────────────────────
|
|
230
|
+
|
|
231
|
+
const MAX_QQ_CHARS = 900
|
|
232
|
+
const URL_RE = /https?:\/\/\S+/gi
|
|
233
|
+
|
|
234
|
+
/** 把一批游戏消息拼成一条 QQ 消息。 */
|
|
235
|
+
export function formatBatch(events, opts = {}) {
|
|
236
|
+
const gamePrefix = String(opts.gamePrefix || '')
|
|
237
|
+
const lines = []
|
|
238
|
+
for (const e of events) {
|
|
239
|
+
if (e.type === 'chat') lines.push((gamePrefix ? gamePrefix + ' ' : '') + '<' + e.player + '> ' + e.text)
|
|
240
|
+
else if (e.type === 'join') lines.push('· ' + e.player + ' 加入了游戏')
|
|
241
|
+
else if (e.type === 'leave') lines.push('· ' + e.player + ' 离开了游戏')
|
|
242
|
+
else if (e.type === 'death') lines.push('· ' + e.text)
|
|
243
|
+
}
|
|
244
|
+
if (!lines.length) return ''
|
|
245
|
+
let text = lines.join('\n')
|
|
246
|
+
if (opts.stripUrls !== false) text = text.replace(URL_RE, '[链接]')
|
|
247
|
+
if (text.length > MAX_QQ_CHARS) text = text.slice(0, MAX_QQ_CHARS - 1) + '…'
|
|
248
|
+
return text
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* @param {object} deps
|
|
253
|
+
* @param {string} deps.serverDir
|
|
254
|
+
* @param {() => object} deps.readConfig 每次用最新配置
|
|
255
|
+
* @param {(msg: string) => void} [deps.log]
|
|
256
|
+
*/
|
|
257
|
+
export function createBridge(deps) {
|
|
258
|
+
const serverDir = deps.serverDir
|
|
259
|
+
const log = deps.log || (() => { })
|
|
260
|
+
const api = new QqApi({
|
|
261
|
+
appId: deps.appId,
|
|
262
|
+
appSecret: deps.appSecret,
|
|
263
|
+
apiBase: deps.apiBase,
|
|
264
|
+
tokenUrl: deps.tokenUrl,
|
|
265
|
+
fetchImpl: deps.fetchImpl,
|
|
266
|
+
})
|
|
267
|
+
const online = new Set()
|
|
268
|
+
let queue = []
|
|
269
|
+
let flushTimer = null
|
|
270
|
+
let tail = null
|
|
271
|
+
let running = false
|
|
272
|
+
let sentToday = 0
|
|
273
|
+
let dayKey = new Date().toISOString().slice(0, 10)
|
|
274
|
+
let lastError = ''
|
|
275
|
+
let lastSentAt = ''
|
|
276
|
+
const stats = { chats: 0, joins: 0, leaves: 0, deaths: 0, sent: 0, dropped: 0, suppressed: 0 }
|
|
277
|
+
|
|
278
|
+
function cfg() {
|
|
279
|
+
const c = deps.readConfig() || {}
|
|
280
|
+
return {
|
|
281
|
+
enabled: c.enabled === true,
|
|
282
|
+
mode: String(c.mode || 'auto'),
|
|
283
|
+
groups: Array.isArray(c.groups) ? c.groups.map(String).filter(Boolean) : [],
|
|
284
|
+
events: Object.assign({ join: true, leave: true, death: false }, c.events || {}),
|
|
285
|
+
coalesceMs: Math.max(500, Number(c.coalesceMs) || 3000),
|
|
286
|
+
maxPerDay: Math.max(1, Number(c.maxPerDay) || 900),
|
|
287
|
+
gamePrefix: String(c.gamePrefix || ''),
|
|
288
|
+
stripUrls: c.stripUrls !== false,
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** 有玩家时开启:只在 online 非空时转发 */
|
|
293
|
+
function shouldForward(c) {
|
|
294
|
+
if (!c.enabled) return false
|
|
295
|
+
if (c.mode === 'off') return false
|
|
296
|
+
if (c.mode === 'on') return true
|
|
297
|
+
return online.size > 0
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function rollDay() {
|
|
301
|
+
const key = new Date().toISOString().slice(0, 10)
|
|
302
|
+
if (key !== dayKey) { dayKey = key; sentToday = 0 }
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
async function flush() {
|
|
306
|
+
flushTimer = null
|
|
307
|
+
const c = cfg()
|
|
308
|
+
if (!queue.length) return
|
|
309
|
+
const batch = queue
|
|
310
|
+
queue = []
|
|
311
|
+
if (!shouldForward(c)) { stats.suppressed += batch.length; return }
|
|
312
|
+
if (!c.groups.length) { stats.dropped += batch.length; lastError = '还没配置要转发到哪个群'; return }
|
|
313
|
+
const text = formatBatch(batch, { gamePrefix: c.gamePrefix, stripUrls: c.stripUrls })
|
|
314
|
+
if (!text) return
|
|
315
|
+
rollDay()
|
|
316
|
+
if (sentToday >= c.maxPerDay) { stats.dropped += batch.length; lastError = '今日主动消息配额已用完(本地保护上限 ' + c.maxPerDay + ')'; return }
|
|
317
|
+
for (const group of c.groups) {
|
|
318
|
+
try {
|
|
319
|
+
sentToday += 1
|
|
320
|
+
await api.sendGroupMessage(group, text, { msgSeq: sentToday })
|
|
321
|
+
stats.sent += 1
|
|
322
|
+
lastSentAt = new Date().toISOString()
|
|
323
|
+
lastError = ''
|
|
324
|
+
} catch (error) {
|
|
325
|
+
lastError = error && error.message ? error.message : String(error)
|
|
326
|
+
stats.dropped += batch.length
|
|
327
|
+
log('[bridge] 发送失败:' + lastError)
|
|
328
|
+
break
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function onEvent(evt) {
|
|
334
|
+
if (evt.type === 'join') { online.add(evt.player); stats.joins += 1 }
|
|
335
|
+
else if (evt.type === 'leave') { online.delete(evt.player); stats.leaves += 1 }
|
|
336
|
+
else if (evt.type === 'death') stats.deaths += 1
|
|
337
|
+
else if (evt.type === 'chat') stats.chats += 1
|
|
338
|
+
else return
|
|
339
|
+
|
|
340
|
+
const c = cfg()
|
|
341
|
+
if (evt.type === 'join' && !c.events.join) return
|
|
342
|
+
if (evt.type === 'leave' && !c.events.leave) return
|
|
343
|
+
if (evt.type === 'death' && !c.events.death) return
|
|
344
|
+
// 自己发的消息(游戏内回显的 QQ 转发)不该再回环:以 [群] 开头的不转发
|
|
345
|
+
if (evt.type === 'chat' && /^\[(群|QQ)\]/.test(evt.text)) return
|
|
346
|
+
|
|
347
|
+
queue.push(evt)
|
|
348
|
+
if (!flushTimer) {
|
|
349
|
+
flushTimer = setTimeout(() => { void flush() }, c.coalesceMs)
|
|
350
|
+
if (flushTimer.unref) flushTimer.unref()
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
async function seedOnline() {
|
|
355
|
+
// 用 RCON list 补一次,避免 DSH 重启期间漏掉的进出事件
|
|
356
|
+
try {
|
|
357
|
+
const { probePlayers } = await import('./rcon-probe.mjs')
|
|
358
|
+
const names = await probePlayers(serverDir)
|
|
359
|
+
for (const n of names) online.add(n)
|
|
360
|
+
log('[bridge] 启动时在线玩家:' + (names.join(', ') || '无'))
|
|
361
|
+
} catch (error) {
|
|
362
|
+
log('[bridge] 探测在线玩家失败(不影响聊天转发):' + (error && error.message ? error.message : String(error)))
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
return {
|
|
367
|
+
async start() {
|
|
368
|
+
if (running) return
|
|
369
|
+
running = true
|
|
370
|
+
tail = createLogTail(serverDir, onEvent, { intervalMs: 500 })
|
|
371
|
+
tail.startAtEnd()
|
|
372
|
+
tail.start()
|
|
373
|
+
await seedOnline()
|
|
374
|
+
log('[bridge] 已启动,模式=' + cfg().mode)
|
|
375
|
+
},
|
|
376
|
+
stop() {
|
|
377
|
+
running = false
|
|
378
|
+
if (tail) tail.stop()
|
|
379
|
+
if (flushTimer) { clearTimeout(flushTimer); flushTimer = null }
|
|
380
|
+
queue = []
|
|
381
|
+
},
|
|
382
|
+
isRunning: () => running,
|
|
383
|
+
status() {
|
|
384
|
+
return {
|
|
385
|
+
running,
|
|
386
|
+
mode: cfg().mode,
|
|
387
|
+
online: [...online],
|
|
388
|
+
queued: queue.length,
|
|
389
|
+
sentToday,
|
|
390
|
+
stats: Object.assign({}, stats),
|
|
391
|
+
lastError,
|
|
392
|
+
lastSentAt,
|
|
393
|
+
}
|
|
394
|
+
},
|
|
395
|
+
/** 只用于测试/调试:直接喂一条事件 */
|
|
396
|
+
_feed: onEvent,
|
|
397
|
+
api,
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/** 把运行状态落盘,方便面板/排查 */
|
|
402
|
+
export function writeBridgeState(serverDir, state) {
|
|
403
|
+
try {
|
|
404
|
+
const dir = join(serverDir, 'ops', 'data')
|
|
405
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
|
|
406
|
+
writeFileSync(join(dir, 'bridge-state.json'), JSON.stringify(Object.assign({ at: new Date().toISOString() }, state), null, 2), 'utf8')
|
|
407
|
+
} catch { /* 状态文件写不了不影响主流程 */ }
|
|
408
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 极简 RCON 探测:只为了拿「当前在线玩家名单」。
|
|
3
|
+
*
|
|
4
|
+
* 单独一个文件是为了避免 import rcon.mjs —— 那个文件在被 import 时会执行 main()。
|
|
5
|
+
*/
|
|
6
|
+
import { createConnection } from 'node:net'
|
|
7
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
8
|
+
import { join } from 'node:path'
|
|
9
|
+
|
|
10
|
+
function readProperties(dir) {
|
|
11
|
+
const map = {}
|
|
12
|
+
try {
|
|
13
|
+
const file = join(dir, 'server.properties')
|
|
14
|
+
if (!existsSync(file)) return map
|
|
15
|
+
for (const line of readFileSync(file, 'utf8').split(/\r?\n/)) {
|
|
16
|
+
const m = /^([^=#][^=]*)=(.*)$/.exec(line)
|
|
17
|
+
if (m) map[m[1].trim()] = m[2]
|
|
18
|
+
}
|
|
19
|
+
} catch { /* 读不到就当没有 */ }
|
|
20
|
+
return map
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function packet(id, type, body) {
|
|
24
|
+
const payload = Buffer.from(body, 'utf8')
|
|
25
|
+
const buf = Buffer.alloc(14 + payload.length)
|
|
26
|
+
buf.writeInt32LE(10 + payload.length, 0)
|
|
27
|
+
buf.writeInt32LE(id, 4)
|
|
28
|
+
buf.writeInt32LE(type, 8)
|
|
29
|
+
payload.copy(buf, 12)
|
|
30
|
+
buf.writeInt16LE(0, 12 + payload.length)
|
|
31
|
+
return buf
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function rconCommand(port, password, command, timeoutMs = 4000) {
|
|
35
|
+
return new Promise((resolve, reject) => {
|
|
36
|
+
const socket = createConnection({ host: '127.0.0.1', port })
|
|
37
|
+
let buf = Buffer.alloc(0)
|
|
38
|
+
let authed = false
|
|
39
|
+
const timer = setTimeout(() => { socket.destroy(); reject(new Error('RCON 超时')) }, timeoutMs)
|
|
40
|
+
const done = (err, value) => {
|
|
41
|
+
clearTimeout(timer)
|
|
42
|
+
try { socket.destroy() } catch { }
|
|
43
|
+
if (err) reject(err); else resolve(value)
|
|
44
|
+
}
|
|
45
|
+
socket.on('connect', () => socket.write(packet(1, 3, password)))
|
|
46
|
+
socket.on('error', (e) => done(e))
|
|
47
|
+
socket.on('data', (chunk) => {
|
|
48
|
+
buf = Buffer.concat([buf, chunk])
|
|
49
|
+
while (buf.length >= 12) {
|
|
50
|
+
const len = buf.readInt32LE(0)
|
|
51
|
+
if (buf.length < len + 4) break
|
|
52
|
+
const id = buf.readInt32LE(4)
|
|
53
|
+
const type = buf.readInt32LE(8)
|
|
54
|
+
const body = buf.subarray(12, len + 2).toString('utf8')
|
|
55
|
+
buf = buf.subarray(len + 4)
|
|
56
|
+
if (type === 2 && id === -1) return done(new Error('RCON 密码不对'))
|
|
57
|
+
if (!authed) {
|
|
58
|
+
if (type !== 2) continue
|
|
59
|
+
authed = true
|
|
60
|
+
socket.write(packet(2, 2, command))
|
|
61
|
+
continue
|
|
62
|
+
}
|
|
63
|
+
return done(null, body)
|
|
64
|
+
}
|
|
65
|
+
})
|
|
66
|
+
})
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** @returns {Promise<string[]>} 在线玩家名 */
|
|
70
|
+
export async function probePlayers(serverDir) {
|
|
71
|
+
const props = readProperties(serverDir)
|
|
72
|
+
const enabled = String(props['enable-rcon'] || '').toLowerCase() === 'true'
|
|
73
|
+
if (!enabled) return []
|
|
74
|
+
const port = Number(props['rcon.port'] || 25575)
|
|
75
|
+
const password = props['rcon.password'] || ''
|
|
76
|
+
if (!password) return []
|
|
77
|
+
const out = await rconCommand(port, password, 'list', 4000)
|
|
78
|
+
// "There are 1 of a max of 20 players online: Steve, Alex"
|
|
79
|
+
const idx = out.indexOf(':')
|
|
80
|
+
if (idx < 0) return []
|
|
81
|
+
return out.slice(idx + 1).split(',').map((s) => s.trim()).filter(Boolean)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** 直接发一条指令(给 QQ→游戏 的 P1 预留) */
|
|
85
|
+
export async function rconSay(serverDir, command) {
|
|
86
|
+
const props = readProperties(serverDir)
|
|
87
|
+
const port = Number(props['rcon.port'] || 25575)
|
|
88
|
+
const password = props['rcon.password'] || ''
|
|
89
|
+
if (!password) throw new Error('server.properties 里没有 rcon.password')
|
|
90
|
+
return rconCommand(port, password, command, 5000)
|
|
91
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-mc-server-ops",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "在 DeepSeek Harness 里托管 Minecraft
|
|
3
|
+
"version": "0.4.1",
|
|
4
|
+
"description": "在 DeepSeek Harness 里托管 Minecraft 服务器的插件:状态/启停/日志/白名单/投票授权,静态命令拦截,本地/Pterodactyl 可插拔适配器,游戏聊天直通 QQ 群(不经过 AI、不耗 token),并把人设注入 QQ 会话。需要先安装 QQ 机器人插件。",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.js",
|
|
7
7
|
"exports": {
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
],
|
|
24
24
|
"scripts": {
|
|
25
25
|
"build": "npm run check",
|
|
26
|
-
"check": "node --check index.js && node --check client.js && node --check ops/rcon.mjs && node --check ops/command-guard.mjs && node --check ops/adapters/index.mjs && node --check ops/adapters/local.mjs && node --check ops/adapters/pterodactyl.mjs",
|
|
26
|
+
"check": "node --check index.js && node --check client.js && node --check ops/rcon.mjs && node --check ops/command-guard.mjs && node --check ops/adapters/index.mjs && node --check ops/adapters/local.mjs && node --check ops/adapters/pterodactyl.mjs && node --check ops/qq-bridge.mjs && node --check ops/rcon-probe.mjs",
|
|
27
27
|
"prepublishOnly": "npm run check"
|
|
28
28
|
},
|
|
29
29
|
"keywords": [
|
|
@@ -39,7 +39,8 @@
|
|
|
39
39
|
],
|
|
40
40
|
"license": "MIT",
|
|
41
41
|
"engines": {
|
|
42
|
-
"node": ">=20.3.0"
|
|
42
|
+
"node": ">=20.3.0",
|
|
43
|
+
"dsh": ">=0.2.0-0"
|
|
43
44
|
},
|
|
44
45
|
"peerDependencies": {
|
|
45
46
|
"@deepseek-ai/schemastery": ">=3.18.1",
|