dsh-mc-server-ops 0.6.0 → 0.6.2

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 CHANGED
@@ -96,7 +96,7 @@ dsh plugin add /path/to/dsh-mc-server-ops
96
96
  | `vote.protectedPaths` | `world, ops/data, whitelist` | 改动这些位置需要群友投票放行 |
97
97
  | `bridge.enabled` | `true` | 是否启用群服互通(游戏聊天 → QQ 群) |
98
98
  | `bridge.mode` | `auto` | `auto` 有玩家在线才转发 / `on` 常开 / `off` 常关 |
99
- | `bridge.groups` | `[]` | 转发到哪些群(群 openid) |
99
+ | `bridge.groups` | `[]` | 转发到哪些群(群 openid);留空 = 自动用上次记住/最近捕获的群,重装插件不会哑 |
100
100
  | `bridge.events` | 三项都关 | 除聊天外还转发哪些事件(进出服和死亡默认不转,防刷屏) |
101
101
  | `bridge.coalesceMs` | `3000` | 固定合并窗口(`coalesce.mode=fixed` 时用) |
102
102
  | `bridge.coalesce.mode` | `auto` | 合并窗口:`auto` 按最近发言节奏 + 在线人数自动调整 / `fixed` 固定 |
@@ -240,7 +240,11 @@ powershell -File <服务器目录>\ops\mcadmin.ps1 -Action owner-add -Arg <openi
240
240
 
241
241
  配置在设置面板的「群服互通」里,**改完立刻生效**(不用重启),状态行会显示「运行中 / 在线几人 / 今日已发几条 / 错误原因」。
242
242
 
243
- 群 openid 不知道怎么办:官方没有「列出机器人加入的群」的稳定接口(`/v2/users/@me/groups` 直接 404),只能从一条真实的群消息里抓一次。详细过程写在 [docs/qq-bridge.md](https://github.com/mogutofu/dsh-mc-server-ops/blob/main/docs/qq-bridge.md)。
243
+ 群 openid 不知道怎么办:**第一次不用填**。插件加载时会自动给本机 qqbot 的 `inbound.js` 打一个幂等抓取钩子(带标记、先备份、失败不影响 qqbot),机器人收到群消息时会把群 openid 写进 `ops/data/qq-keys.txt`;群友在群里 **@ 一次机器人**,群服互通就会自动用上这个群,不需要手填。详细说明见 [docs/qq-bridge.md](https://github.com/mogutofu/dsh-mc-server-ops/blob/main/docs/qq-bridge.md)。
244
+
245
+ 如果 qqbot 升级把钩子冲掉了:插件下次加载会自动重打;实在不行也可以手动填 `bridge.groups`(`mc_server bridge-groups` 会给出本地记录过的群 openid)。
246
+
247
+ 插件会自动记住用过的群:正常转发过一次后,群 openid 会存到 `ops/data/bridge-groups.json`;`bridge.groups` 留空或因为重装插件被重置时,自动用上次记住的群,再退回最近捕获的群(`ops/data/qq-keys.txt`),所以**重装/升级插件不会再让群服互通断掉**。状态和日志里会标出来源(`config` / `remembered` / `captured`)。
244
248
 
245
249
  ## 游戏内 AI 对话(/ai)
246
250
 
package/client.js CHANGED
@@ -415,8 +415,8 @@ window.__ModuleLoader__.load({
415
415
  h("option", { value: "auto" }, "有玩家时开启(默认)"),
416
416
  h("option", { value: "on" }, "常开启"),
417
417
  h("option", { value: "off" }, "常关闭"))),
418
- h(Field, { label: "转发到哪些群", hint: "群 openid,逗号分隔。不知道的话在群里 @ 小铜 问" },
419
- h(TextInput, { value: form.bridge.groups, placeholder: "FC73DE60… ", onChange: (x) => patchBridge("groups", x) })),
418
+ h(Field, { label: "转发到哪些群", hint: "首次不用填:在群里 @ 一次小铜,插件会自动发现;留空 = 自动(上次记住 → 最近捕获),重装插件不会丢" },
419
+ h(TextInput, { value: form.bridge.groups, placeholder: "留空 = 自动(上次记住的群)", onChange: (x) => patchBridge("groups", x) })),
420
420
  h(Field, { label: "除聊天外还转发", hint: "聊天始终转发。进服/退服默认关(会刷屏),死亡消息默认开" },
421
421
  h("div", { style: { display: "flex", gap: 18, flexWrap: "wrap" } },
422
422
  h(Toggle, { label: "玩家加入(默认关)", value: form.bridge.events.join, onChange: (x) => patchBridgeEvent("join", x) }),
package/index.js CHANGED
@@ -8,6 +8,7 @@ import Schema from '@deepseek-ai/schemastery'
8
8
  import { guardCommand } from './ops/command-guard.mjs'
9
9
  import { createAdapter } from './ops/adapters/index.mjs'
10
10
  import { createBridge, writeBridgeState, QqApi } from './ops/qq-bridge.mjs'
11
+ import { ensureQqbotInboundHook } from './ops/qqbot-hook.mjs'
11
12
 
12
13
  // 运行期路径:apply() 里按配置初始化。服务器目录、脚本位置都可以在设置里改。
13
14
  const paths = { serverDir: '', script: '', ownersFile: '', flipLog: '' }
@@ -188,7 +189,7 @@ const DESCRIPTION = [
188
189
  '- vote-status:查看投票进度(可带编号)',
189
190
  '- export-data:把 ops\\data(绑定、投票、服主名单、口令)打成 zip,arg 为目标路径,仅服主',
190
191
  '- import-data:从 zip 恢复 ops\\data,arg 为 zip 路径,仅服主',
191
- '- bridge-groups:列出机器人加入的 QQ 群(群名 + 群 openid),配置群服互通时用来填 groups,仅服主',
192
+ '- bridge-groups:列出机器人加入的 QQ 群(群名 + 群 openid),配置群服互通时用来填 groups;QQ 接口列不出来时回退到本地记录/最近捕获的群,仅服主',
192
193
  '',
193
194
  '玩家可以改服务器目录下除敏感区(ops\\data、world、白名单、eula、jar/exe/dll、密钥)之外的文件:kubejs 配方、config/defaultconfigs 配置、server.properties 等,write/edit 直接放行;改之前先备份,改完按需 reload。',
194
195
  '玩家不能改 kubejs 目录以外的任何文件。',
@@ -654,6 +655,23 @@ export function apply(ctx, config) {
654
655
  paths.ownersFile = join(opsDir, 'data', 'owners.json')
655
656
  paths.flipLog = join(opsDir, 'data', 'preset-flip.log')
656
657
 
658
+ // ── QQ 群 openid 自动发现 ──
659
+ // 给 qqbot 的 inbound.js 打幂等钩子:它收到群消息时把群 openid 追加到下面的文件,
660
+ // bridge 发现配置里没有群时会自动采用(来源:captured)。首次装插件不需要手填 openid,
661
+ // 群友在群里 @ 一次机器人即可。钩子写失败不影响任何功能,退回手动配置。
662
+ process.env.MC_OPS_QQ_KEYS_FILE = join(opsDir, 'data', 'qq-keys.txt')
663
+ try {
664
+ mkdirSync(join(opsDir, 'data'), { recursive: true })
665
+ ensureQqbotInboundHook({
666
+ log: (m) => {
667
+ try {
668
+ appendFileSync(join(opsDir, 'data', 'bridge.log'), new Date().toISOString() + ' [bridge] ' + m + '\n')
669
+ } catch (error) { }
670
+ },
671
+ })
672
+ } catch (error) { }
673
+
674
+
657
675
  // 设置页:插件详情里渲染自己的表单(client.js),表单通过下面这两个 HTTP 路由读写配置。
658
676
  const settingsService = ctx.get('settings')
659
677
  if (settingsService && typeof settingsService.configure === 'function') {
@@ -722,6 +740,76 @@ export function apply(ctx, config) {
722
740
  panel: (liveConfig && liveConfig.panel) || {},
723
741
  })
724
742
 
743
+ // ── 群服互通的目标群:配置 → 上次记住 → 本地捕获(qq-keys.txt)三层兜底 ──
744
+ // 插件配置存在 profile 的 cordis.patch.yml 里;重装/升级插件时 DSH 会重建这条配置行,
745
+ // 用户填的 bridge.groups 会丢。群 openid 本身可以本地记住,所以这里做持久化 + 自动恢复,
746
+ // 避免「重装一次插件,群服互通就哑了」。
747
+ const BRIDGE_GROUPS_FILE = join(opsDir, 'data', 'bridge-groups.json')
748
+ function readBridgeGroupList(list) {
749
+ return Array.isArray(list) ? list.map((x) => String(x || '').trim()).filter(Boolean) : []
750
+ }
751
+ function rememberBridgeGroups(groups) {
752
+ const list = [...new Set(readBridgeGroupList(groups))]
753
+ if (!list.length) return
754
+ try {
755
+ mkdirSync(join(opsDir, 'data'), { recursive: true })
756
+ writeFileSync(BRIDGE_GROUPS_FILE, JSON.stringify({ at: new Date().toISOString(), groups: list }, null, 2) + '\n', 'utf8')
757
+ } catch (error) { }
758
+ }
759
+ function loadRememberedBridgeGroups() {
760
+ try {
761
+ const doc = JSON.parse(readFileSync(BRIDGE_GROUPS_FILE, 'utf8'))
762
+ return readBridgeGroupList(Array.isArray(doc) ? doc : doc && doc.groups)
763
+ } catch (error) { return [] }
764
+ }
765
+ function loadCapturedBridgeGroups(limit = 3) {
766
+ // qqbot 的 inbound.js 抓到群消息时会把 openid 记进 ops/data/qq-keys.txt(每行「时间 group OPENID」)
767
+ try {
768
+ const text = readFileSync(join(opsDir, 'data', 'qq-keys.txt'), 'utf8')
769
+ const seen = []
770
+ for (const line of text.split(/\r?\n/)) {
771
+ const match = /\bgroup\s+([0-9A-Za-z]{16,64})\b/.exec(line)
772
+ if (!match) continue
773
+ const openid = match[1]
774
+ const index = seen.indexOf(openid)
775
+ if (index !== -1) seen.splice(index, 1)
776
+ seen.push(openid)
777
+ }
778
+ return seen.slice(-limit).reverse()
779
+ } catch (error) { return [] }
780
+ }
781
+ let bridgeGroupsState = { groups: [], source: 'none' }
782
+ let lastBridgeGroupsLog = ''
783
+ function resolveBridgeGroups(rawBridge) {
784
+ const configured = readBridgeGroupList(rawBridge && rawBridge.groups)
785
+ if (configured.length) {
786
+ rememberBridgeGroups(configured)
787
+ bridgeGroupsState = { groups: configured, source: 'config' }
788
+ } else {
789
+ const remembered = loadRememberedBridgeGroups()
790
+ if (remembered.length) {
791
+ bridgeGroupsState = { groups: remembered, source: 'remembered' }
792
+ } else {
793
+ const captured = loadCapturedBridgeGroups()
794
+ if (captured.length) {
795
+ rememberBridgeGroups(captured)
796
+ bridgeGroupsState = { groups: captured, source: 'captured' }
797
+ } else {
798
+ bridgeGroupsState = { groups: [], source: 'none' }
799
+ }
800
+ }
801
+ }
802
+ const key = bridgeGroupsState.source + ':' + bridgeGroupsState.groups.join(',')
803
+ if (key !== lastBridgeGroupsLog) {
804
+ lastBridgeGroupsLog = key
805
+ try {
806
+ const hint = bridgeGroupsState.source === 'none' ? ';未发现目标群:在 QQ 群里 @ 一次机器人即可自动发现,也可在设置里手填' : ''
807
+ appendFileSync(join(opsDir, 'data', 'bridge.log'), new Date().toISOString() + ' [bridge] 群目标:' + (bridgeGroupsState.groups.join(', ') || '(空)') + '(来源:' + bridgeGroupsState.source + ')' + hint + '\n')
808
+ } catch (error) { }
809
+ }
810
+ return bridgeGroupsState
811
+ }
812
+
725
813
  // ── 群服互通:游戏聊天 → QQ 群(不经过 AI,不产生 token)──
726
814
  // 常驻创建、常驻运行:是否真的转发由 liveConfig.bridge.enabled 决定,
727
815
  // 这样在面板里打开开关立刻生效,不用再重启一次。
@@ -734,17 +822,24 @@ export function apply(ctx, config) {
734
822
  serverDir,
735
823
  appId,
736
824
  appSecret,
737
- readConfig: () => (liveConfig && liveConfig.bridge) || {},
825
+ readConfig: () => {
826
+ const raw = (liveConfig && liveConfig.bridge) || {}
827
+ const resolved = resolveBridgeGroups(raw)
828
+ return Object.assign({}, raw, { groups: resolved.groups, groupsSource: resolved.source })
829
+ },
738
830
  log: (m) => {
739
831
  try { appendFileSync(join(opsDir, 'data', 'bridge.log'), new Date().toISOString() + ' ' + m + '\n') } catch { }
740
832
  },
741
833
  })
742
834
  ctx.effect(() => {
835
+ resolveBridgeGroups((liveConfig && liveConfig.bridge) || {})
743
836
  void bridge.start()
744
837
  const tick = setInterval(() => {
838
+ resolveBridgeGroups((liveConfig && liveConfig.bridge) || {})
745
839
  writeBridgeState(serverDir, Object.assign(
746
840
  { appId: appId ? appId.slice(0, 3) + '***' : '', hasSecret: !!appSecret },
747
841
  bridge.status(),
842
+ { groups: bridgeGroupsState.groups, groupsSource: bridgeGroupsState.source },
748
843
  ))
749
844
  }, 10000)
750
845
  if (tick.unref) tick.unref()
@@ -1065,10 +1160,20 @@ export function apply(ctx, config) {
1065
1160
  try {
1066
1161
  const groups = await new QqApi({ appId, appSecret }).listGroups()
1067
1162
  if (!groups.length) return { ok: true, text: '机器人还没加入任何群(或者没有「群管理」权限,拿不到群列表)。' }
1163
+ rememberBridgeGroups(groups.map((g) => g.openid))
1068
1164
  return { ok: true, text: groups.map((g) => g.name + '\n ' + g.openid).join('\n') }
1069
1165
  } catch (error) {
1070
1166
  const message = error && error.message ? error.message : String(error)
1071
- return { ok: false, text: '查群列表失败:' + message + '\n(需要 AppID/AppSecret,以及开放平台的「群管理」权限)' }
1167
+ const local = [...new Set([...loadRememberedBridgeGroups(), ...loadCapturedBridgeGroups()])]
1168
+ if (local.length) {
1169
+ return {
1170
+ ok: true,
1171
+ text: 'QQ 接口不支持直接列群(' + message + '),改用本地记录到的群 openid:\n'
1172
+ + local.join('\n')
1173
+ + '\n\n填到「群服互通 → 转发到哪些群」即可;留空也会自动用这些群。',
1174
+ }
1175
+ }
1176
+ return { ok: false, text: '查群列表失败:' + message + '\n(需要 AppID/AppSecret,以及开放平台的「群管理」权限;也可以让群友在群里 @ 一次机器人来捕获群 openid)' }
1072
1177
  }
1073
1178
  }
1074
1179
 
package/ops/qq-bridge.mjs CHANGED
@@ -339,7 +339,7 @@ export function createBridge(deps) {
339
339
  const batch = queue
340
340
  queue = []
341
341
  if (!shouldForward(c)) { stats.suppressed += batch.length; return }
342
- if (!c.groups.length) { stats.dropped += batch.length; lastError = '还没配置要转发到哪个群'; return }
342
+ if (!c.groups.length) { stats.dropped += batch.length; lastError = '还没发现目标群:在 QQ 群里 @ 一次机器人即可自动发现(或设置里手填群 openid)'; return }
343
343
  const text = formatBatch(batch, { gamePrefix: c.gamePrefix, stripUrls: c.stripUrls })
344
344
  if (!text) return
345
345
  rollDay()
@@ -0,0 +1,113 @@
1
+ /**
2
+ * 给 @tencent-connect/dsh-qqbot 的 inbound.js 打一个幂等抓取钩子:
3
+ * 机器人收到 QQ 群/私聊消息时,把 scope + peerId(群 openid / 用户 openid)
4
+ * 追加到 process.env.MC_OPS_QQ_KEYS_FILE 指向的文件里。
5
+ *
6
+ * 这样群服互通不需要用户手填群 openid:装好插件后在群里 @ 一次机器人,
7
+ * 群 openid 就会被抓到,bridge 会自动采用(来源:captured)。
8
+ *
9
+ * 设计要点:
10
+ * - 幂等:文件里已有 MARKER 就不再写;插件每次加载都会检查,qqbot 升级冲掉了会自动重打。
11
+ * - 失败安全:任何异常都只返回结果,不抛错、不影响 qqbot 运行。
12
+ * - 留备份:首次写前保存 inbound.js.mc-ops.bak。
13
+ */
14
+ import { existsSync, readdirSync, readFileSync, writeFileSync, copyFileSync } from 'node:fs'
15
+ import { homedir } from 'node:os'
16
+ import { join } from 'node:path'
17
+
18
+ const MARKER = '[mc-ops capture hook]'
19
+
20
+ function listProfileDirs() {
21
+ const dirs = []
22
+ const home = process.env.DSH_HOME || join(homedir(), '.dsh')
23
+ const profiles = join(home, 'profiles')
24
+ try {
25
+ for (const name of readdirSync(profiles)) dirs.push(join(profiles, name))
26
+ } catch (error) {
27
+ // ignore
28
+ }
29
+ const fromEnv = process.env.DSH_PROFILE_DIR
30
+ if (fromEnv) dirs.push(fromEnv)
31
+ return dirs
32
+ }
33
+
34
+ function findQqbotInboundFiles() {
35
+ const files = []
36
+ for (const dir of listProfileDirs()) {
37
+ const candidate = join(dir, 'node_modules', '@tencent-connect', 'dsh-qqbot', 'dist', 'transport', 'inbound.js')
38
+ if (existsSync(candidate)) files.push(candidate)
39
+ }
40
+ return files
41
+ }
42
+
43
+ function ensureAppendFileSyncImport(source) {
44
+ const m = /import\s*\{([^}]*)\}\s*from\s*'node:fs'/m.exec(source)
45
+ if (m) {
46
+ if (/\bappendFileSync\b/.test(m[1])) return source
47
+ const names = m[1].trimEnd()
48
+ return source.replace(m[0], 'import {' + names + ', appendFileSync } from \'node:fs\'')
49
+ }
50
+ // 没有 node:fs 具名导入:在第一条 import 后补一行
51
+ const first = /^import[^\n]*\n/m.exec(source)
52
+ if (!first) return source
53
+ return source.slice(0, first.index + first[0].length) + 'import { appendFileSync } from \'node:fs\'\n' + source.slice(first.index + first[0].length)
54
+ }
55
+
56
+ function patchSource(source) {
57
+ if (source.includes(MARKER)) return { changed: false, source, reason: 'already-patched' }
58
+ const anchor = source.indexOf('const replyTarget = {')
59
+ if (anchor === -1) return { changed: false, source, reason: 'anchor-not-found' }
60
+ const end = source.indexOf('};', anchor)
61
+ if (end === -1) return { changed: false, source, reason: 'anchor-end-not-found' }
62
+ let next = ensureAppendFileSyncImport(source)
63
+ const insertAt = next.indexOf('};', next.indexOf('const replyTarget = {')) + 2
64
+ const block = [
65
+ '',
66
+ ' // ' + MARKER + ' 记录群/用户 openid,供群服互通自动发现目标群(dsh-mc-server-ops 写入,可删)',
67
+ ' try {',
68
+ ' const hookFile = process.env.MC_OPS_QQ_KEYS_FILE;',
69
+ ' if (hookFile) appendFileSync(hookFile, new Date().toISOString() + \' \' + scope + \' \' + peerId + \'\\n\');',
70
+ ' } catch { }',
71
+ '',
72
+ ].join('\n')
73
+ next = next.slice(0, insertAt) + block + next.slice(insertAt)
74
+ return { changed: true, source: next, reason: 'patched' }
75
+ }
76
+
77
+ /**
78
+ * @param {{ log?: (message: string) => void }} [options]
79
+ * @returns {{ ok: boolean, patched: number, failed: number, files: string[], reason?: string }}
80
+ */
81
+ export function ensureQqbotInboundHook(options = {}) {
82
+ const log = typeof options.log === 'function' ? options.log : () => {}
83
+ const files = findQqbotInboundFiles()
84
+ const result = { ok: files.length > 0, patched: 0, failed: 0, files, reason: '' }
85
+ if (!files.length) {
86
+ result.reason = '没有找到 @tencent-connect/dsh-qqbot(未安装 QQ 机器人插件?)'
87
+ return result
88
+ }
89
+ for (const file of files) {
90
+ try {
91
+ const source = readFileSync(file, 'utf8')
92
+ const patched = patchSource(source)
93
+ if (!patched.changed) {
94
+ log('qqbot 抓取钩子已存在:' + file)
95
+ continue
96
+ }
97
+ if (patched.reason !== 'patched') {
98
+ result.failed += 1
99
+ log('qqbot 抓取钩子打不上(' + patched.reason + '):' + file)
100
+ continue
101
+ }
102
+ const backup = file + '.mc-ops.bak'
103
+ if (!existsSync(backup)) copyFileSync(file, backup)
104
+ writeFileSync(file, patched.source, 'utf8')
105
+ result.patched += 1
106
+ log('qqbot 抓取钩子已写入:' + file + '(重启 DSH / 重载 qqbot 后生效)')
107
+ } catch (error) {
108
+ result.failed += 1
109
+ log('qqbot 抓取钩子写入失败:' + file + ':' + (error && error.message ? error.message : String(error)))
110
+ }
111
+ }
112
+ return result
113
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mc-server-ops",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "description": "在 DeepSeek Harness 里托管 Minecraft 服务器的插件:状态/启停/日志/白名单/投票授权,静态命令拦截,本地/Pterodactyl 可插拔适配器,游戏聊天直通 QQ 群(不经过 AI、不耗 token),把人设注入 QQ 会话,并让游戏内玩家用 /ai 和「小铜」对话(配套 Forge mod)。需要先安装 QQ 机器人插件。",
5
5
  "type": "module",
6
6
  "main": "./index.js",