koishi-plugin-prism 0.5.2 → 0.5.3

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/lib/index.js CHANGED
@@ -7,8 +7,6 @@ exports.PrismSocket = exports.PrismBotClientError = exports.Config = exports.ver
7
7
  exports.apply = apply;
8
8
  exports.applyPrismKoishiPlugin = applyPrismKoishiPlugin;
9
9
  exports.platformSocketUrl = platformSocketUrl;
10
- exports.humanReadableBotError = humanReadableBotError;
11
- const display_time_js_1 = require("./display-time.js");
12
10
  const ha_watch_js_1 = require("./ha-watch.js");
13
11
  const koishi_1 = require("koishi");
14
12
  const package_json_1 = __importDefault(require("../package.json"));
@@ -16,9 +14,9 @@ var ha_watch_js_2 = require("./ha-watch.js");
16
14
  Object.defineProperty(exports, "HaWatcher", { enumerable: true, get: function () { return ha_watch_js_2.HaWatcher; } });
17
15
  exports.name = "prism";
18
16
  exports.version = package_json_1.default.version;
19
- // Only how to reach the shop is configured here. Everything else (staff, door,
20
- // tables, read-only mode, reminders, watching) is the bot's own settings on its
21
- // resource page in PRiSM, read from the platform when the bot connects.
17
+ // Only how to reach the shop is configured here. What the commands do, who may
18
+ // use them and what the bot says are the platform's: the bot's settings live
19
+ // on its resource page in PRiSM.
22
20
  exports.Config = koishi_1.Schema.object({
23
21
  baseUrl: koishi_1.Schema.string().required().description("PRiSM 后端地址,例如 https://link.neri.moe"),
24
22
  shopCode: koishi_1.Schema.string().description("可选:店铺编号。接入凭据已经指明店铺,无需填写;旧配置仍认。"),
@@ -31,136 +29,101 @@ class PrismBotClientError extends Error {
31
29
  code;
32
30
  status;
33
31
  body;
34
- originalError;
35
- constructor(message, code, status, body, originalError) {
32
+ constructor(message, code, status, body) {
36
33
  super(message);
37
34
  this.code = code;
38
35
  this.status = status;
39
36
  this.body = body;
40
- this.originalError = originalError;
41
37
  this.name = "PrismBotClientError";
42
38
  }
43
39
  }
44
40
  exports.PrismBotClientError = PrismBotClientError;
45
- const USAGE = {
46
- mahjong_join: "/上桌 <桌号>",
47
- mahjong_leave: "/下桌 [桌号]",
48
- mahjong_list: "/麻将列表",
49
- api_benchmark: "/api测速 [次数]",
50
- ws_benchmark: "/ws测速 [次数]",
51
- prism_on: "/prism on <设备名|别名|all>",
52
- prism_off: "/prism off <设备名|别名|all>",
53
- prism_keep: "/keep <设备名或别名>",
54
- prism_coin: "/prism coin <设备名或别名> [数量]",
55
- prism_scan: "/prism scan <设备名或别名>",
56
- prism_redeem: "/prism redeem <兑换码>",
57
- list: "/list [资源或方案]",
58
- show: "/show [设备ID]",
59
- };
60
- /** Where `list` puts players who occupy no resource. */
61
- const OTHER_PLAYERS_LABEL = "其他";
41
+ /**
42
+ * Every command the platform runs, as Koishi registers it. The command's name
43
+ * is its first word; a `target:user` argument names whom it is for and is
44
+ * sent apart from the rest. What each does is `resources/bot-commands.ts` in
45
+ * PRiSM.
46
+ */
47
+ const COMMANDS = [
48
+ ["bind <code:string>", "绑定网页登录账号到当前平台身份"],
49
+ // Instructions already handed to players may still say prism.bind.
50
+ ["prism.bind <code:string>", "绑定网页登录账号到当前平台身份(旧命令,同 bind)"],
51
+ ["login [target:user]", "开启玩家计费场次"],
52
+ ["入场 [target:user]", "入场"],
53
+ ["mahjong <tableId> [target:user]", "加入指定麻将桌"],
54
+ ["上桌 [tableId] [target:user]", "加入指定麻将桌"],
55
+ ["下桌 [tableId] [target:user]", "离开当前所在麻将桌"],
56
+ ["麻将列表", "查看麻将机状态与别名"],
57
+ ["logout [target:user]", "结算玩家计费场次"],
58
+ ["billing [target:user]", "预览玩家结账费用"],
59
+ ["wallet [target:user]", "查看玩家钱包"],
60
+ ["items [target:user]", "查看玩家资产"],
61
+ ["list [name:text]", "查看在店玩家,或某个资源、某个计费方案上的玩家"],
62
+ ["show [deviceId]", "查看设备电源状态"],
63
+ ["history [target:user]", "查看玩家历史"],
64
+ ["lock", "向本店门锁发送开门指令"],
65
+ ["on <deviceRef>", "请求启动指定设备电源"],
66
+ ["off <deviceRef>", "请求关闭指定设备电源"],
67
+ ["keep <deviceRef>", "延迟闲置设备的自动关机"],
68
+ ["coin <deviceRef> [count]", "请求向指定设备投币"],
69
+ ["scan <deviceRef>", "使用当前玩家绑定的 Aime 卡刷卡"],
70
+ ["redeem <code>", "兑换 PRiSM 礼物码"],
71
+ ["add <target:user> <amount:number>", "增加玩家余额"],
72
+ ["del <target:user> <amount:number>", "扣除玩家余额"],
73
+ ["overwrite <target:user> <amount:number> [reason:text]", "覆盖结账金额并立即结账"],
74
+ ];
62
75
  function applyPrismKoishiPlugin(ctx, config) {
63
76
  const service = new PrismKoishiService(ctx, config);
64
- const wrap = (handler, gate = {}) => async (context, ...args) => {
65
- const quoted = (message) => context.session?.messageId ? `${(0, koishi_1.h)("quote", { id: context.session.messageId })}${message}` : message;
66
- try {
67
- if (!gate.offline) {
68
- // A disabled bot, or one that cannot read its settings, answers nothing else.
69
- const bot = await service.config();
70
- if (gate.effect && bot.settings.playerCommands === "readonly" && !service.isStaff(bot, await service.sender(context))) {
71
- return quoted(bot.settings.readOnlyNotice || DEFAULT_READ_ONLY_NOTICE);
72
- }
73
- if (gate.entry && !bot.billingEnabled)
74
- return quoted(RESOURCE_NOT_BILLED_NOTICE);
75
- }
76
- return quoted(await handler(context, ...args));
77
- }
78
- catch (error) {
79
- return quoted(service.handleCommandError(error));
80
- }
81
- };
82
- const effect = (handler, gate = {}) => wrap(handler, { ...gate, effect: true });
83
- const entry = { entry: true };
84
- const bind = wrap(async (context, code) => service.bind(await service.sender(context), code));
85
- ctx.command("bind <code:string>", "绑定网页登录账号到当前平台身份").action(bind);
86
- // Instructions already handed to players may still say prism.bind.
87
- ctx.command("prism.bind <code:string>", "绑定网页登录账号到当前平台身份(旧命令,同 bind)").action(bind);
88
- ctx.command("login [target:user]", "开启玩家计费场次").action(effect(async (context, target) => service.loginForTarget(await service.sender(context), target, context.session?.bot), entry));
89
- ctx.command("入场 [target:user]", "入场").action(effect(async (context, target) => service.loginForTarget(await service.sender(context), target, context.session?.bot), entry));
90
- ctx.command("mahjong <tableId> [target:user]", "加入指定麻将桌").action(effect(async (context, tableId, target) => service.withTarget(await service.sender(context), target, async (sender, targeted) => (targeted ? `玩家 ${formatPlayerReference(sender)}\n` : "") + await service.mahjongJoin(sender, tableId), context.session?.bot)));
91
- ctx.command("上桌 [tableId] [target:user]", "加入指定麻将桌").action(effect(async (context, tableId, target) => service.withTarget(await service.sender(context), target, async (sender, targeted) => (targeted ? `玩家 ${formatPlayerReference(sender)}\n` : "") + await service.mahjongJoin(sender, tableId), context.session?.bot)));
92
- ctx.command("下桌 [tableId] [target:user]", "离开当前所在麻将桌").action(effect(async (context, tableId, target) => service.withTarget(await service.sender(context), target, async (sender, targeted) => (targeted ? `玩家 ${formatPlayerReference(sender)}\n` : "") + await service.mahjongLeave(sender, tableId), context.session?.bot)));
93
- ctx.command("麻将列表", "查看麻将机状态与别名").action(wrap(async () => service.listMahjongTables()));
94
- ctx.command("logout [target:user]", "结算玩家计费场次").action(effect(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.logout(sender, context.session?.bot), context.session?.bot)));
95
- ctx.command("billing [target:user]", "预览玩家结账费用").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.billing(sender), context.session?.bot)));
96
- ctx.command("wallet [target:user]", "查看玩家钱包").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.wallet(sender), context.session?.bot)));
97
- ctx.command("api测速 [count:number]", "测试 Bot 走 HTTP 到 PRiSM 的延迟").action(wrap(async (context, count) => service.benchmarkApi(await service.sender(context), count)));
98
- ctx.command("ws测速 [count:number]", "测试 Bot 走 WebSocket 到 PRiSM 的延迟").action(wrap(async (context, count) => service.benchmarkWs(await service.sender(context), count)));
77
+ const quoted = (context, message) => context.session?.messageId ? `${(0, koishi_1.h)("quote", { id: context.session.messageId })}${message}` : message;
78
+ for (const [declaration, description] of COMMANDS) {
79
+ const [name, ...params] = declaration.split(" ");
80
+ const targetAt = params.findIndex((param) => param.includes(":user"));
81
+ ctx.command(declaration, description).action(async (context, ...args) => quoted(context, await service.run(name, context, args, targetAt)));
82
+ }
83
+ ctx.command("api测速 [count:number]", "测试 Bot 走 HTTP 到 PRiSM 的延迟").action(async (context, count) => quoted(context, await service.benchmarkApi(context, count)));
84
+ ctx.command("ws测速 [count:number]", "测试 Bot 走 WebSocket 到 PRiSM 的延迟").action(async (context, count) => quoted(context, await service.benchmarkWs(context, count)));
99
85
  // The Bot's own version stays visible while the platform is out of reach.
100
- ctx.command("versions", "查看 Bot 与 PRiSM 后端版本").action(wrap(async () => service.versions(), { offline: true }));
101
- ctx.command("items [target:user]", "查看玩家资产").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.items(sender), context.session?.bot)));
102
- ctx.command("list [name:text]", "查看在店玩家,或某个资源、某个计费方案上的玩家").action(wrap(async (context, name) => service.listActiveSessions(await service.sender(context), name)));
103
- ctx.command("show [deviceId]", "查看设备电源状态").action(wrap(async (context, deviceId) => service.listDeviceStates(deviceId)));
104
- ctx.command("history [target:user]", "查看玩家历史").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.history(sender), context.session?.bot)));
105
- ctx.command("lock", "向本店门锁发送开门指令").action(effect(async (context) => service.lock(await service.sender(context))));
106
- ctx.command("on <deviceRef>", "请求启动指定设备电源").action(effect(async (context, deviceRef) => service.powerOn(await service.sender(context), deviceRef)));
107
- ctx.command("off <deviceRef>", "请求关闭指定设备电源").action(effect(async (context, deviceRef) => service.powerOff(await service.sender(context), deviceRef)));
108
- // Not limited by read-only mode: it never switches anything on, and the
109
- // platform only accepts it from an entered player for a device that is on.
110
- ctx.command("keep <deviceRef>", "延迟闲置设备的自动关机").action(wrap(async (context, deviceRef) => service.keep(await service.sender(context), deviceRef)));
111
- ctx.command("coin <deviceRef> [count]", "请求向指定设备投币").action(effect(async (context, deviceRef, count) => service.coin(await service.sender(context), deviceRef, count)));
112
- ctx.command("scan <deviceRef>", "使用当前玩家绑定的 Aime 卡刷卡").action(effect(async (context, deviceRef) => service.scan(await service.sender(context), deviceRef)));
113
- ctx.command("redeem <code>", "兑换 PRiSM 礼物码").action(wrap(async (context, code) => service.redeem(await service.sender(context), code)));
114
- ctx.command("add <target:user> <amount:number>", "增加玩家余额").action(wrap(async (context, target, amount) => service.adjustTargetBalance(await service.sender(context), target, amount, 1, context.session?.bot)));
115
- ctx.command("del <target:user> <amount:number>", "扣除玩家余额").action(wrap(async (context, target, amount) => service.adjustTargetBalance(await service.sender(context), target, amount, -1, context.session?.bot)));
116
- ctx.command("overwrite <target:user> <amount:number> [reason:text]", "覆盖结账金额并立即结账").action(wrap(async (context, target, amount, reason) => service.overwriteTargetCheckout(await service.sender(context), target, amount, reason, context.session?.bot)));
86
+ ctx.command("versions", "查看 Bot 版本与 PRiSM 后端的部署").action(async (context) => quoted(context, await service.versions()));
117
87
  ctx.on?.("dispose", () => service.dispose());
118
88
  }
119
- const DEFAULT_READ_ONLY_NOTICE = "请扫描店内二维码或碰 NFC,在网页或 App Clip 里入场、结账和操作设备。";
120
- /** Platforms before per-resource billing refused billing commands shop-wide. */
121
- const BILLING_DISABLED_NOTICE = "本店未启用计费";
122
- /** The bot's resource has no plan, so there is nothing to enter. */
123
- const RESOURCE_NOT_BILLED_NOTICE = "这里不计费,无需入场";
124
89
  /* --------------------------- platform connection --------------------------- */
125
90
  const SOCKET_OPEN = 1;
126
91
  const REQUEST_TIMEOUT_MS = 30_000;
127
92
  const PING_MS = 30_000;
128
93
  const FIRST_RETRY_MS = 1000;
129
94
  const MAX_RETRY_MS = 30_000;
95
+ const UNREACHABLE = "操作失败,暂时连不上服务器。";
96
+ const TIMED_OUT = "服务器没有及时回应,请稍后确认结果";
130
97
  /**
131
- * The one connection to PRiSM. Requests go out as frames and are matched to
132
- * their replies by id; the platform also pushes events down it. While it is
133
- * down a request fails at once: queueing a checkout or a top-up to run later
134
- * would make players repeat it, and a resend could run it twice.
98
+ * The one connection to PRiSM. Commands go out as `command` frames and the
99
+ * platform answers with `say` frames naming them; the shop's news comes as
100
+ * `say` frames naming none. While it is down a command fails at once:
101
+ * queueing a checkout or a top-up to run later would make players repeat it.
135
102
  */
136
103
  class PrismSocket {
137
104
  open;
138
105
  url;
139
106
  token;
140
107
  hello;
141
- onEvent;
108
+ onNews;
142
109
  logger;
143
110
  hooks;
144
111
  socket = null;
145
112
  pending = new Map();
113
+ /** Commands still being answered, by id. */
114
+ listening = new Map();
146
115
  retryMs = FIRST_RETRY_MS;
147
116
  retryTimer = null;
148
117
  pingTimer = null;
149
118
  lastHeard = 0;
150
119
  stopped = false;
151
120
  sequence = 0;
152
- /** Bumped by every hello being prepared, so only the newest one is sent. */
153
- greeting = 0;
154
121
  pongWaiters = [];
155
- constructor(open,
156
- /** Resolved at each connection: the shop is learned from the credential first. */
157
- url, token,
158
- /**
159
- * What to say in hello, read afresh each time: the bot's settings live on
160
- * the platform, so they are fetched over this connection before it is
161
- * sent. Null when they could not be read.
162
- */
163
- hello, onEvent, logger,
122
+ constructor(open, url, token,
123
+ /** What to say in hello besides that this bot sends commands. */
124
+ hello,
125
+ /** The shop's news: something to say that answers no command. */
126
+ onNews, logger,
164
127
  /**
165
128
  * `onWatch`: the platform asked this bot to watch Home Assistant, or with null to stop.
166
129
  * `onClose`: the connection is gone, and with it the platform's idea of what this bot watches.
@@ -170,7 +133,7 @@ class PrismSocket {
170
133
  this.url = url;
171
134
  this.token = token;
172
135
  this.hello = hello;
173
- this.onEvent = onEvent;
136
+ this.onNews = onNews;
174
137
  this.logger = logger;
175
138
  this.hooks = hooks;
176
139
  }
@@ -190,12 +153,6 @@ class PrismSocket {
190
153
  this.stopped = false;
191
154
  this.connect();
192
155
  }
193
- /** Connect again with what the platform has just told us, such as the shop. */
194
- reconnect() {
195
- this.socket?.close(1000, "shop known");
196
- this.socket = null;
197
- this.connect();
198
- }
199
156
  stop() {
200
157
  this.stopped = true;
201
158
  if (this.retryTimer)
@@ -209,7 +166,7 @@ class PrismSocket {
209
166
  connect() {
210
167
  let socket;
211
168
  try {
212
- socket = this.open(typeof this.url === "function" ? this.url() : this.url, { Authorization: `Bearer ${this.token}` });
169
+ socket = this.open(this.url, { Authorization: `Bearer ${this.token}` });
213
170
  }
214
171
  catch (error) {
215
172
  this.logger?.warn("PRiSM connection failed", error);
@@ -219,7 +176,8 @@ class PrismSocket {
219
176
  this.socket = socket;
220
177
  socket.addEventListener("open", () => {
221
178
  this.lastHeard = Date.now();
222
- void this.greet(socket, true);
179
+ this.retryMs = FIRST_RETRY_MS;
180
+ this.greet();
223
181
  if (this.pingTimer)
224
182
  clearInterval(this.pingTimer);
225
183
  this.pingTimer = setInterval(() => {
@@ -244,32 +202,9 @@ class PrismSocket {
244
202
  });
245
203
  socket.addEventListener("error", (error) => this.logger?.warn("PRiSM connection error", error?.message ?? error));
246
204
  }
247
- /**
248
- * Read the bot's settings and say hello with them: on connecting, and again
249
- * when the platform says they changed. A connection that cannot read them
250
- * at all is closed and tried again later, without resetting the backoff, so
251
- * a platform that keeps failing is not asked every second.
252
- */
253
- async greet(socket, connecting) {
254
- const greeting = ++this.greeting;
255
- let hello = null;
256
- try {
257
- hello = await this.hello();
258
- }
259
- catch (error) {
260
- this.logger?.warn("PRiSM bot settings unavailable", error);
261
- }
262
- // A newer hello is on its way, or this connection is already gone.
263
- if (greeting !== this.greeting || this.socket !== socket)
264
- return;
265
- if (!hello) {
266
- if (connecting)
267
- socket.close(4000, "settings unavailable");
268
- return;
269
- }
270
- if (connecting)
271
- this.retryMs = FIRST_RETRY_MS;
272
- this.send({ type: "hello", ...hello });
205
+ /** Hello: on connecting, and again when the platform says the bot's settings changed, so it rereads them. */
206
+ greet() {
207
+ this.send({ type: "hello", commands: 1, ...this.hello() });
273
208
  }
274
209
  reconnectLater() {
275
210
  if (this.stopped)
@@ -285,6 +220,9 @@ class PrismSocket {
285
220
  waiter.reject(unreachable());
286
221
  }
287
222
  this.pending.clear();
223
+ for (const [, onSay] of this.listening)
224
+ onSay(null);
225
+ this.listening.clear();
288
226
  }
289
227
  receive(raw) {
290
228
  this.lastHeard = Date.now();
@@ -299,7 +237,20 @@ class PrismSocket {
299
237
  catch {
300
238
  return;
301
239
  }
302
- if (frame?.type === "response" && typeof frame.id === "string") {
240
+ if (frame?.type === "say" && Array.isArray(frame.message)) {
241
+ const say = frame;
242
+ if (typeof say.replyTo !== "string") {
243
+ this.onNews(say);
244
+ return;
245
+ }
246
+ const onSay = this.listening.get(say.replyTo);
247
+ if (!onSay)
248
+ return;
249
+ if (say.done)
250
+ this.listening.delete(say.replyTo);
251
+ onSay(say);
252
+ }
253
+ else if (frame?.type === "response" && typeof frame.id === "string") {
303
254
  const waiter = this.pending.get(frame.id);
304
255
  if (!waiter)
305
256
  return;
@@ -307,18 +258,9 @@ class PrismSocket {
307
258
  clearTimeout(waiter.timer);
308
259
  waiter.resolve({ status: Number(frame.status) || 500, body: frame.body, serverMs: typeof frame.serverMs === "number" ? frame.serverMs : null });
309
260
  }
310
- else if (frame?.type === "event" && typeof frame.event === "string") {
311
- try {
312
- this.onEvent({ event: frame.event, data: frame.data });
313
- }
314
- catch (error) {
315
- this.logger?.warn("PRiSM event handling failed", error);
316
- }
317
- }
318
261
  else if (frame?.type === "config.changed") {
319
- // The bot's settings, staff, door or tables changed: read them again and say hello with them.
320
- if (this.socket)
321
- void this.greet(this.socket, false);
262
+ // The bot's settings changed: hello again, so the platform rereads what this bot announces.
263
+ this.greet();
322
264
  }
323
265
  else if (frame?.type === "ha.watch" || frame?.type === "ha.unwatch") {
324
266
  // A watch that cannot be read is as good as none: the platform has nothing for this bot to watch.
@@ -331,6 +273,30 @@ class PrismSocket {
331
273
  }
332
274
  }
333
275
  }
276
+ nextId() {
277
+ return `${Date.now().toString(36)}-${(this.sequence++).toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
278
+ }
279
+ /**
280
+ * Send a command; `onSay` hears each thing the platform says for it, or
281
+ * null once the connection is gone. False while the connection is down.
282
+ */
283
+ command(frame, onSay) {
284
+ const socket = this.socket;
285
+ if (!socket || socket.readyState !== SOCKET_OPEN)
286
+ return false;
287
+ const id = this.nextId();
288
+ this.listening.set(id, onSay);
289
+ try {
290
+ socket.send(JSON.stringify({ type: "command", id, ...frame }));
291
+ }
292
+ catch {
293
+ this.listening.delete(id);
294
+ return false;
295
+ }
296
+ // Words that never come are not waited for forever.
297
+ setTimeout(() => this.listening.delete(id), REQUEST_TIMEOUT_MS * 2);
298
+ return true;
299
+ }
334
300
  /** One heartbeat round trip in milliseconds: the network to the platform and nothing else. */
335
301
  ping() {
336
302
  const socket = this.socket;
@@ -352,15 +318,16 @@ class PrismSocket {
352
318
  socket.send("ping");
353
319
  });
354
320
  }
321
+ /** A platform route over the connection: the version and the speed tests, which measure exactly that. */
355
322
  request(frame) {
356
323
  const socket = this.socket;
357
324
  if (!socket || socket.readyState !== SOCKET_OPEN)
358
325
  return Promise.reject(unreachable());
359
- const id = `${Date.now().toString(36)}-${(this.sequence++).toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
326
+ const id = this.nextId();
360
327
  return new Promise((resolve, reject) => {
361
328
  const timer = setTimeout(() => {
362
329
  this.pending.delete(id);
363
- reject(new PrismBotClientError("服务器没有及时回应,请稍后确认结果", "API_TIMEOUT", 0, {}));
330
+ reject(new PrismBotClientError(TIMED_OUT, "API_TIMEOUT", 0, {}));
364
331
  }, REQUEST_TIMEOUT_MS);
365
332
  this.pending.set(id, { resolve, reject, timer });
366
333
  try {
@@ -382,20 +349,7 @@ function replyError(status, body) {
382
349
  const err = body && typeof body === "object" && typeof body.error === "object" ? body.error : {};
383
350
  return new PrismBotClientError(typeof err.message === "string" ? err.message : `Backend request failed with HTTP ${status}.`, typeof err.code === "string" ? err.code : `HTTP_${status}`, status, body ?? {});
384
351
  }
385
- function benchmarkCount(raw) {
386
- const count = raw == null || raw === "" ? 5 : Number(raw);
387
- return Number.isInteger(count) && count >= 1 && count <= 10 ? count : null;
388
- }
389
- function spread(samples) {
390
- const average = samples.reduce((sum, sample) => sum + sample, 0) / samples.length;
391
- return `最小 ${Math.round(Math.min(...samples))} / 平均 ${Math.round(average)} / 最大 ${Math.round(Math.max(...samples))} ms`;
392
- }
393
- function serverLine(timings) {
394
- const known = timings.map((timing) => timing.serverMs).filter((value) => value !== null);
395
- if (!known.length)
396
- return [];
397
- return [`服务端处理:平均 ${Math.round(known.reduce((sum, value) => sum + value, 0) / known.length)} ms`];
398
- }
352
+ const data = (body) => (body && typeof body === "object" && Object.hasOwn(body, "data") ? body.data : body);
399
353
  /**
400
354
  * The platform connection URL. The credential names the shop, as a device's
401
355
  * token names its machine at `/io/ws`, so nothing identifying is in the path.
@@ -404,213 +358,26 @@ function platformSocketUrl(baseUrl) {
404
358
  const base = baseUrl.trim().replace(/\/+$/, "").replace(/^http/i, "ws");
405
359
  return `${base}/integration/ws`;
406
360
  }
407
- /* ----------------------------- api client ---------------------------------- */
408
- class PrismApiClient {
409
- socket;
410
- http;
411
- constructor(socket, http) {
412
- this.socket = socket;
413
- this.http = http;
414
- }
415
- async request(method, path, options) {
416
- let target = path.replace(/^\/rpc\//, "");
417
- for (const [key, value] of Object.entries(options.params ?? {})) {
418
- target = target.replace(`:${key}`, encodeURIComponent(String(value)));
419
- }
420
- const { status, body } = await this.socket.request({
421
- method,
422
- path: target,
423
- ...(options.query ? { query: options.query } : {}),
424
- ...(method === "GET" ? {} : { body: options.body ?? {} }),
425
- });
426
- if (status >= 400)
427
- throw replyError(status, body);
428
- return body && typeof body === "object" && Object.hasOwn(body, "data") ? body.data : body;
429
- }
430
- confirmPlatformBinding(code, provider, subject) {
431
- return this.request("POST", "/rpc/integration/platform-binding/confirm", { body: { code, provider, subject } });
432
- }
433
- identityBody(identity) {
434
- return {
435
- identity: {
436
- provider: identity.provider,
437
- subject: identity.subject,
438
- },
439
- ...(identity.displayName === undefined ? {} : { displayName: identity.displayName }),
440
- };
441
- }
442
- /** The shop this credential belongs to, read before the shop code is known. */
443
- setShopCode(code) { if (this.http)
444
- this.http.shopCode = code; }
445
- /** The bot's own settings and what it needs to know about the shop. */
446
- async getBotConfig() {
447
- return this.request("GET", "/rpc/integration/bot", {});
448
- }
449
- /** Always the register route: whether a new player is created is the shop's own switch. */
450
- async resolveOrRegisterIdentity(identity) {
451
- const result = await this.request("POST", "/rpc/integration/players/by-identity/register", {
452
- body: this.identityBody(identity),
453
- });
454
- return result.player;
455
- }
456
- async getVersion() {
457
- return this.request("GET", "version", {});
458
- }
459
- /** Admit a player into the shop's default plan; `created` is false when it was already billing. */
460
- async startSessionByIdentity(identity) {
461
- return this.request("POST", "/rpc/integration/players/by-identity/session/start", {
462
- body: { ...this.identityBody(identity), entry: true },
463
- });
464
- }
465
- /** Seat or unseat a player; `table` is a table id, name or alias. */
466
- async mahjongByIdentity(identity, table, action) {
467
- return this.request("POST", "/rpc/integration/players/by-identity/mahjong", {
468
- body: { ...this.identityBody(identity), table, action },
469
- });
470
- }
471
- async listMahjongTables() {
472
- return this.request("GET", "/rpc/integration/mahjong-tables", {});
473
- }
474
- /** Who is in the shop, each once at their place; with a name, one resource or one plan. */
475
- async roster(name) {
476
- return this.request("GET", "/rpc/integration/roster", name ? { query: { name } } : {});
477
- }
478
- async getWalletByIdentity(identity) {
479
- return this.request("POST", "/rpc/integration/players/by-identity/wallet", {
480
- body: this.identityBody(identity),
481
- });
482
- }
483
- /** The wallet query over the platform connection, timed. */
484
- async timeWalletOverSocket(identity) {
485
- const startedAt = performance.now();
486
- const reply = await this.socket.request({ method: "POST", path: "integration/players/by-identity/wallet", body: this.identityBody(identity) });
487
- const ms = performance.now() - startedAt;
488
- if (reply.status >= 400)
489
- throw replyError(reply.status, reply.body);
490
- return { ms, serverMs: reply.serverMs ?? null };
491
- }
492
- /** The same wallet query as a plain HTTP request, the way the Bot used to call, timed. */
493
- async timeWalletOverHttp(identity) {
494
- if (!this.http)
495
- throw new PrismBotClientError("HTTP 测速不可用", "HTTP_UNAVAILABLE", 0, {});
496
- const { post, baseUrl, shopCode, token } = this.http;
497
- if (!shopCode)
498
- throw new PrismBotClientError("店铺尚未读取", "SHOP_UNKNOWN", 0, {});
499
- const url = `${baseUrl.trim().replace(/\/+$/, "")}/api/v1/shops/${encodeURIComponent(shopCode)}/integration/players/by-identity/wallet`;
500
- const startedAt = performance.now();
501
- const response = await post(url, { authorization: `Bearer ${token}`, "content-type": "application/json" }, this.identityBody(identity));
502
- const ms = performance.now() - startedAt;
503
- if (response.status >= 400)
504
- throw replyError(response.status, response.data);
505
- const server = Number.parseFloat(response.headers.get("x-response-time") ?? "");
506
- return { ms, serverMs: Number.isFinite(server) ? server : null, colo: response.headers.get("cf-ray")?.split("-").pop() ?? null };
507
- }
508
- pingSocket() {
509
- return this.socket.ping();
510
- }
511
- async getAssetsByIdentity(identity) {
512
- return this.request("POST", "/rpc/integration/players/by-identity/assets", {
513
- body: this.identityBody(identity),
514
- });
515
- }
516
- async getSessionHistoryByIdentity(identity) {
517
- return this.request("POST", "/rpc/integration/players/by-identity/history", {
518
- body: this.identityBody(identity),
519
- });
520
- }
521
- async previewCheckoutByIdentity(identity) {
522
- return this.request("POST", "/rpc/integration/players/by-identity/checkout/preview", {
523
- body: this.identityBody(identity),
524
- });
525
- }
526
- async confirmCheckoutByIdentity(identity, closeSessionsBeforeBalanceCheck = true) {
527
- return this.request("POST", "/rpc/integration/players/by-identity/checkout/confirm", {
528
- body: { ...this.identityBody(identity), closeSessionsBeforeBalanceCheck },
529
- });
530
- }
531
- async redeemCodeByIdentity(identity, code) {
532
- return this.request("POST", "/rpc/integration/players/by-identity/redeem", {
533
- body: {
534
- ...this.identityBody(identity),
535
- code,
536
- },
537
- });
538
- }
539
- async requestDeviceCommandByIdentity(identity, command, options) {
540
- return this.request("POST", "/rpc/integration/players/by-identity/device-actions", {
541
- body: {
542
- ...this.identityBody(identity),
543
- ...(options?.staffOverride ? { staffOverride: true } : {}),
544
- target: command.target,
545
- action: {
546
- type: command.type,
547
- ...(command.payload === undefined ? {} : { payload: command.payload }),
548
- },
549
- },
550
- });
551
- }
552
- async requestScanByIdentity(identity, scan) {
553
- return this.request("POST", "/rpc/integration/players/by-identity/device-actions", {
554
- body: {
555
- ...this.identityBody(identity),
556
- target: {
557
- kind: "game_machine",
558
- ref: scan.deviceRef,
559
- },
560
- action: {
561
- type: "aime.scan",
562
- payload: {
563
- provider: scan.provider,
564
- },
565
- },
566
- },
567
- });
568
- }
569
- async listActiveSessions() {
570
- return this.request("GET", "/rpc/integration/sessions/active", {});
571
- }
572
- async listDeviceStates() {
573
- return this.request("GET", "/rpc/integration/device-states", {});
574
- }
575
- async adjustWalletByIdentity(identity, amount, reason) {
576
- return this.request("POST", "/rpc/integration/players/by-identity/wallet/adjustment", {
577
- body: { ...this.identityBody(identity), amount, reason },
578
- });
579
- }
580
- async checkoutWithOverrideByIdentity(identity, total, reason) {
581
- return this.request("POST", "/rpc/integration/players/by-identity/checkout/override", {
582
- body: { ...this.identityBody(identity), total, reason },
583
- });
584
- }
585
- }
361
+ /* ------------------------------- service ----------------------------------- */
586
362
  class PrismKoishiService {
587
363
  ctx;
588
364
  options;
589
- logoutInFlight = new Map();
590
- client;
591
365
  logger;
592
- socket = null;
366
+ socket;
593
367
  watcher = null;
594
- /** The bot's settings as last read; null until read, and again once the shop disables the bot. */
595
- bot = null;
596
- /** Announcements still being sent; each waits for the one before. */
368
+ post;
369
+ /** The shop's code, for the HTTP speed test; read from the platform when first needed. */
370
+ shopCode;
371
+ /** News still being said; each waits for the one before, so channels read it in order. */
597
372
  announcing = Promise.resolve();
598
- /** The read in flight, shared by commands arriving together. */
599
- reading = null;
600
- reads = 0;
601
- /** Whether the settings let this bot watch Home Assistant. */
602
- watching = false;
603
373
  constructor(ctx, options) {
604
374
  this.ctx = ctx;
605
375
  this.options = options;
606
376
  this.logger = ctx.logger?.("prism");
607
- if (options.client) {
608
- this.client = options.client;
609
- return;
610
- }
611
377
  if (!options.baseUrl || !options.integrationToken) {
612
378
  throw new Error("PRiSM Koishi plugin requires 'baseUrl' and 'integrationToken'.");
613
379
  }
380
+ this.shopCode = options.shopCode ?? null;
614
381
  const open = options.socket ?? ((url, headers) => {
615
382
  const http = ctx.http;
616
383
  if (!http?.ws)
@@ -621,23 +388,17 @@ class PrismKoishiService {
621
388
  // says nothing about Home Assistant: then there is no watching to offer.
622
389
  const haOpen = options.haSocket ?? (options.socket ? null : open);
623
390
  if (haOpen)
624
- this.watcher = new ha_watch_js_1.HaWatcher(haOpen, (frame) => this.socket?.send(frame), this.logger);
625
- this.socket = new PrismSocket(open, platformSocketUrl(options.baseUrl), options.integrationToken, () => this.hello(), (event) => {
626
- if (event.event === "idle.reminder")
627
- void this.remindIdle(event.data);
628
- // One at a time, so the channels read them in the order they happened.
629
- else if (event.event === "shop.event")
630
- this.announcing = this.announcing
631
- .then(() => this.announce(event.data))
632
- .catch((error) => this.logger?.warn("PRiSM event announcement failed", error));
391
+ this.watcher = new ha_watch_js_1.HaWatcher(haOpen, (frame) => this.socket.send(frame), this.logger);
392
+ this.socket = new PrismSocket(open, platformSocketUrl(options.baseUrl), options.integrationToken,
393
+ // Saying it can watch is what makes the platform consider this bot; the platform decides.
394
+ () => (this.watcher ? { ha: true } : {}), (say) => {
395
+ this.announcing = this.announcing
396
+ .then(() => this.announce(say))
397
+ .catch((error) => this.logger?.warn("PRiSM announcement failed", error));
633
398
  }, this.logger, this.watcher
634
- ? {
635
- // Only a bot whose settings allow it watches, whatever the platform asks.
636
- onWatch: (watch) => (watch && this.watching ? this.watcher.watch(watch) : this.watcher.stop()),
637
- onClose: () => this.watcher.stop(),
638
- }
399
+ ? { onWatch: (watch) => (watch ? this.watcher.watch(watch) : this.watcher.stop()), onClose: () => this.watcher.stop() }
639
400
  : undefined);
640
- const post = options.httpPost ?? (async (url, headers, body) => {
401
+ this.post = options.httpPost ?? (async (url, headers, body) => {
641
402
  const http = ctx.http;
642
403
  if (typeof http !== "function")
643
404
  throw new PrismBotClientError("HTTP 测速需要 Koishi 的 http 服务", "HTTP_UNAVAILABLE", 0, {});
@@ -646,1237 +407,279 @@ class PrismKoishiService {
646
407
  });
647
408
  return { status: response.status, headers: response.headers, data: response.data };
648
409
  });
649
- this.client = new PrismApiClient(this.socket, { post, baseUrl: options.baseUrl, token: options.integrationToken, ...(options.shopCode ? { shopCode: options.shopCode } : {}) });
650
410
  this.socket.start();
651
411
  }
652
412
  dispose() {
653
413
  this.watcher?.stop();
654
- this.socket?.stop();
655
- }
656
- /** The bot's settings, read from the platform the first time they are needed. */
657
- async config() {
658
- return this.bot ?? this.reading ?? this.readConfig();
659
- }
660
- /** Read the settings afresh. A disabled bot forgets the ones it had, so each command asks again. */
661
- readConfig() {
662
- // Only the newest read may settle what the bot knows; an older one answering late is stale.
663
- const read = ++this.reads;
664
- this.reading = (async () => {
665
- try {
666
- const bot = parseBotConfig(await this.client.getBotConfig());
667
- if (read === this.reads) {
668
- this.bot = bot;
669
- if (bot.shop?.code)
670
- this.client.setShopCode(bot.shop.code);
671
- }
672
- return bot;
673
- }
674
- catch (error) {
675
- if (read === this.reads && error instanceof PrismBotClientError && error.code === "BOT_DISABLED")
676
- this.bot = null;
677
- throw error;
678
- }
679
- finally {
680
- if (read === this.reads)
681
- this.reading = null;
682
- }
683
- })();
684
- return this.reading;
414
+ this.socket.stop();
685
415
  }
416
+ /* ----------------------------- commands -------------------------------- */
686
417
  /**
687
- * What this bot says in hello, from settings read just now. A disabled bot
688
- * offers nothing: no watching and no reminders.
418
+ * Hand a command to the platform and answer with the first thing it says
419
+ * back where the command was said; anything else it says for the command
420
+ * (a receipt to staff, a door code) is sent as it comes.
689
421
  */
690
- async hello() {
691
- let bot;
692
- try {
693
- bot = await this.readConfig();
694
- }
695
- catch (error) {
696
- if (!(error instanceof PrismBotClientError && error.code === "BOT_DISABLED"))
697
- throw error;
698
- this.watching = false;
699
- this.watcher?.stop();
700
- return {};
701
- }
702
- const { settings } = bot;
703
- // Watching is the platform's to schedule: every bot that can offers, and the
704
- // hub picks among them. A bot with no Home Assistant connection cannot.
705
- this.watching = this.watcher !== null;
706
- if (!this.watching)
707
- this.watcher?.stop();
708
- return {
709
- name: bot.bot.name,
710
- // Saying so is what makes the platform consider this bot for the watch.
711
- ...(this.watching ? { ha: true } : {}),
712
- // Without anywhere to send it, or with idle news switched off, the
713
- // platform need not plan a reminder.
714
- ...(settings.announceIdle && settings.announceChannelIds.length && settings.idleReminderMinutes > 0
715
- ? { reminderLeadSeconds: settings.idleReminderMinutes * 60 }
716
- : {}),
717
- };
718
- }
719
- /** Whether the sender is one of the shop's staff on this platform. */
720
- isStaff(bot, sender) {
721
- return bot.staff.some((identity) => identity.provider === sender.provider && identity.subject === sender.id);
722
- }
723
- async bind(sender, code) {
724
- try {
725
- await this.client.confirmPlatformBinding(code, sender.provider, sender.id);
726
- return "绑定成功,请返回网页继续操作";
727
- }
728
- catch (error) {
729
- if (error instanceof PrismBotClientError && error.status > 0)
730
- return error.message || "绑定失败,请重新生成验证码";
731
- throw error;
732
- }
733
- }
734
- /**
735
- * Tell the configured channels what happened, if this bot announces that kind
736
- * of thing. A card that put its owner on the cabinet is one message: a start
737
- * when starts are announced, otherwise a card; a coin that did is the same.
738
- * What this bot's own command did is left out: the bot has answered the
739
- * command already.
740
- */
741
- async announce(event) {
742
- const bot = this.bot;
743
- const channels = bot?.settings.announceChannelIds ?? [];
744
- if (!bot || !channels.length)
745
- return;
746
- if (event.botId && event.botId === bot.bot.id)
747
- return;
748
- const message = await this.announcement(event, bot.settings);
749
- if (!message)
750
- return;
751
- await this.broadcast(channels, message);
752
- }
753
- /** Explicit targets need neither Koishi's channel database nor its mutable broadcast list. */
754
- async broadcast(channels, message) {
755
- for (const target of channels) {
756
- try {
757
- const separator = target.indexOf(":");
758
- if (separator < 1 || separator === target.length - 1)
759
- throw new Error(`无效的播报频道:${target}`);
760
- const platform = target.slice(0, separator), channel = target.slice(separator + 1);
761
- if (channel === "private:")
762
- throw new Error(`无效的私聊目标:${target}`);
763
- const bot = this.ctx.bots?.find((bot) => bot.platform === platform && bot.isActive);
764
- if (!bot)
765
- throw new Error(`没有可用的 ${platform} 机器人`);
766
- if (channel.startsWith("private:"))
767
- await bot.sendPrivateMessage(channel.slice(8), message);
768
- else
769
- await bot.sendMessage(channel, message);
770
- }
771
- catch (error) {
772
- this.logger?.warn(`PRiSM announcement to ${target} failed`, error);
773
- }
774
- }
775
- }
776
- async announcement(event, settings) {
777
- const place = event.resourceName || event.resourceId;
778
- const who = async () => {
779
- if (!event.player)
780
- return "未绑定的卡";
781
- // Named as the platform the channels are on would name them, when it can.
782
- const provider = event.player.identities[0]?.provider ?? "";
783
- return this.displayNameForPlayer({
784
- playerId: event.player.playerId,
785
- displayName: event.player.displayName ?? undefined,
786
- sessions: [{ playerDisplayName: event.player.displayName ?? undefined, identities: event.player.identities }],
787
- }, provider);
788
- };
789
- if (event.kind === "power") {
790
- if (!settings.announcePower)
791
- return null;
792
- if (event.by === "system")
793
- return event.state === "off" ? `💤 ${place} 闲置,已自动关机` : `✅ ${place} 已开机`;
794
- const by = event.player ? `(${await who()})` : "";
795
- return event.state === "on" ? `✅ ${place} 已开机${by}` : `🛑 ${place} 已关机${by}`;
796
- }
797
- if (event.kind === "card") {
798
- if (event.started && settings.announceStarts)
799
- return `🎮 ${await who()} 在 ${place} 刷卡上机`;
800
- return settings.announceCards ? `💳 ${await who()} 在 ${place} 刷卡` : null;
801
- }
802
- if (event.kind === "coin") {
803
- if (event.started && settings.announceStarts)
804
- return `🎮 ${await who()} 在 ${place} 投币上机`;
805
- return settings.announceCoins ? `🪙 ${await who()} 在 ${place} 投币` : null;
806
- }
807
- if (event.kind === "occupancy")
808
- return settings.announceStarts ? `🎮 ${await who()} 在 ${place} 上机` : null;
809
- return null;
810
- }
811
- /** Tell the configured channels a power-off is coming, when the shop asks for it. */
812
- async remindIdle(reminder) {
813
- const settings = this.bot?.settings;
814
- const channels = settings?.announceChannelIds ?? [];
815
- if (!settings?.announceIdle || !channels.length)
816
- return;
817
- const now = (this.options.now?.() ?? new Date()).getTime();
818
- const minutes = Math.max(1, Math.round((reminder.at - now) / 60_000));
819
- const names = reminder.devices.map((device) => device.name).join("、");
820
- const message = reminder.reason === "shop_empty"
821
- ? `店里没人,${minutes} 分钟后全部关机`
822
- : `${names} 闲置中,${minutes} 分钟后关机。已入场的玩家发送 keep 设备名 可以延迟`;
823
- await this.broadcast(channels, message);
422
+ async run(name, context, rawArgs, targetAt) {
423
+ const from = await this.sender(context);
424
+ if (!from)
425
+ return "无法获取发送人的平台身份";
426
+ const target = targetAt >= 0 ? await this.target(from, rawArgs[targetAt], context) : null;
427
+ const args = rawArgs.filter((_, index) => index !== targetAt).map((arg) => (arg == null ? "" : String(arg).trim()));
428
+ while (args.length && !args.at(-1))
429
+ args.pop();
430
+ const session = context.session;
431
+ const channel = session.isDirect || !session.channelId ? `private:${from.subject}` : `${from.provider}:${session.channelId}`;
432
+ return new Promise((resolve) => {
433
+ let answered = false;
434
+ let saying = Promise.resolve();
435
+ const answer = (text) => {
436
+ if (answered)
437
+ return;
438
+ answered = true;
439
+ clearTimeout(timer);
440
+ resolve(text);
441
+ };
442
+ const timer = setTimeout(() => answer(TIMED_OUT), REQUEST_TIMEOUT_MS);
443
+ const sent = this.socket.command({ name, args, from, ...(target ? { target } : {}), channel }, (say) => {
444
+ if (!say)
445
+ return answer(UNREACHABLE);
446
+ saying = saying.then(async () => {
447
+ const text = await this.render(say.message, from.provider);
448
+ if (!answered && (!say.to || say.to === channel))
449
+ return answer(text);
450
+ await this.deliver(say.to ?? channel, text, context);
451
+ }).catch((error) => this.logger?.warn("PRiSM reply failed", error));
452
+ });
453
+ if (!sent)
454
+ answer(UNREACHABLE);
455
+ });
824
456
  }
457
+ /** Who sent the command, as the platform knows chat identities. */
825
458
  async sender(context) {
826
- const id = cleanText(context.session?.userId);
827
- const provider = cleanText(context.session?.platform || context.session?.bot?.platform).toLowerCase();
828
- if (!id || !/^[a-z][a-z0-9_-]{0,63}$/.test(provider))
829
- throw new PrismBotClientError("无法获取发送人的平台身份", "INVALID_PLATFORM_IDENTITY", 400, null);
830
- let name = context.session?.username || context.session?.senderName || id;
831
- try {
832
- if (context.session?.bot?.getUser) {
833
- const user = await context.session.bot.getUser(id);
834
- if (user?.name) {
835
- name = user.name;
836
- }
837
- }
838
- }
839
- catch { }
840
- return { id, name, provider };
841
- }
842
- async loginForTarget(actor, targetSubject, bot) {
843
- return this.withTarget(actor, targetSubject, async (sender, isTargeted) => {
844
- const result = (await this.client.startSessionByIdentity(this.identity(sender)));
845
- // Already in: the player had this session before, and the plan says where.
846
- if (result?.created === false) {
847
- const where = typeof result.planName === "string" && result.planName ? `「${result.planName}」` : "场";
848
- return isTargeted ? `用户 ${formatPlayerReference(sender)} 已在${where}中,无需重复入场` : `您已在${where}中,无需重复入场`;
849
- }
850
- // Starting the plan may end one it cannot bill together with.
851
- const stopped = Array.isArray(result?.billing?.stopped) ? result.billing.stopped.filter((name) => typeof name === "string" && name) : [];
852
- const ended = stopped.length ? `\n结束方案:${stopped.join("、")}` : "";
853
- const message = (isTargeted ? `✅ 已为用户 ${formatPlayerReference(sender)} 入场成功` : "✅ 入场成功") + ended;
854
- // Entering and getting the door code as one command, when the shop asks
855
- // for it. A door that fails must not undo an entry that succeeded.
856
- const settings = (await this.config());
857
- return settings.settings.doorPasswordOnEntry && settings.door
858
- ? `${message}\n${await this.doorCode(sender, settings.door, true)}`
859
- : message;
860
- }, bot);
861
- }
862
- async withTarget(actor, targetSubject, action, bot) {
863
- const target = await this.targetSender(actor, targetSubject, bot);
864
- if (typeof target === "string")
865
- return target;
866
- return action(target, target !== actor);
867
- }
868
- async adjustTargetBalance(actor, targetSubject, rawAmount, direction, bot) {
869
- return this.withTarget(actor, targetSubject, async (sender) => {
870
- const amount = Number(rawAmount);
871
- if (!Number.isFinite(amount) || amount <= 0)
872
- return "金额必须大于 0";
873
- const isAddition = direction === 1;
874
- await this.client.adjustWalletByIdentity(this.identity(sender), amount * direction, isAddition ? "Koishi 管理员增加余额" : "Koishi 管理员扣除余额");
875
- return `✅ 已为用户 ${formatPlayerReference(sender)}${isAddition ? "增加" : "扣除"} ${formatNumber(amount)} ${(await this.config()).currencyName}`;
876
- }, bot);
877
- }
878
- async overwriteTargetCheckout(actor, targetSubject, rawAmount, rawReason, bot) {
879
- return this.withTarget(actor, targetSubject, async (sender) => {
880
- const total = Number(rawAmount);
881
- if (!Number.isFinite(total) || total < 0)
882
- return "金额必须为非负数";
883
- const reason = cleanText(rawReason) || "管理员调价";
884
- const result = (await this.client.checkoutWithOverrideByIdentity(this.identity(sender), total, reason));
885
- return this.formatAndNotifyCheckout(result, sender, "✅ 覆盖结账成功 · 结算账单", bot);
886
- }, bot);
887
- }
888
- /**
889
- * Seat the player at a table. The platform opens the table (starting
890
- * everyone's billing) once it fills, so a player need not enter first.
891
- */
892
- async mahjongJoin(sender, rawTableRef) {
893
- const tableRef = cleanText(rawTableRef);
894
- if (!tableRef)
895
- return "请指定麻将桌,例如 /上桌 a;可先使用 /麻将列表 查看可用桌位。";
896
- const table = findMahjongTable((await this.config()).mahjongTables, tableRef);
897
- if (!table)
898
- return `未找到麻将桌「${tableRef}」。可先使用 /麻将列表 查看可用桌位。`;
899
- let state;
900
- try {
901
- state = (await this.client.mahjongByIdentity(this.identity(sender), table.id, "join")).mahjong;
902
- }
903
- catch (error) {
904
- if (!(error instanceof PrismBotClientError))
905
- throw error;
906
- if (error.code === "MAHJONG_TABLE_NOT_FOUND")
907
- return `未找到麻将桌「${tableRef}」。可先使用 /麻将列表 查看可用桌位。`;
908
- if (error.code === "MAHJONG_TABLE_FULL")
909
- return `「${table.name}」已满桌,请等待本局结束后再上桌。`;
910
- const message = platformMessage(error);
911
- if (message)
912
- return `上桌失败,${message}`;
913
- throw error;
914
- }
915
- const seated = state.seats.length;
916
- const mine = state.seats.find((seat) => seat.mine);
917
- if (mine?.playing)
918
- return `已加入 ${table.name},麻将计费已开始。当前 ${seated}/${state.capacity} 人。`;
919
- return `已加入 ${table.name},当前 ${seated}/${state.capacity} 人,满 ${state.capacity} 人开始计费。`;
920
- }
921
- /** Leave the table the player sits at, or the one named. */
922
- async mahjongLeave(sender, rawTableRef) {
923
- const tableRef = cleanText(rawTableRef);
924
- const named = tableRef ? findMahjongTable((await this.config()).mahjongTables, tableRef) : null;
925
- if (tableRef && !named)
926
- return `未找到麻将桌「${tableRef}」。可先使用 /麻将列表 查看可用桌位。`;
927
- const [listing, player] = await Promise.all([this.client.listMahjongTables(), this.resolvePlayer(sender)]);
928
- const playerId = String(player?.id ?? "");
929
- const tables = (listing?.tables ?? []);
930
- const table = tables.find((candidate) => (!named || candidate.id === named.id) && candidate.seats.some((seat) => seat.playerId === playerId));
931
- if (!table?.id)
932
- return named ? `你当前不在 ${named.name}。` : "你当前未在任何麻将桌上。";
933
- const name = table.name || named?.name || table.id;
934
- const wasPlaying = table.seats.some((seat) => seat.playerId === playerId && seat.playing);
935
- let result;
459
+ const subject = String(context.session?.userId ?? "").trim();
460
+ const provider = String(context.session?.platform || context.session?.bot?.platform || "").trim().toLowerCase();
461
+ if (!subject || !/^[a-z][a-z0-9_-]{0,63}$/.test(provider))
462
+ return null;
463
+ let name = context.session?.username || context.session?.senderName || subject;
936
464
  try {
937
- result = (await this.client.mahjongByIdentity(this.identity(sender), table.id, "leave"));
465
+ const user = await context.session?.bot?.getUser?.(subject);
466
+ if (user?.name)
467
+ name = user.name;
938
468
  }
939
- catch (error) {
940
- if (!(error instanceof PrismBotClientError))
941
- throw error;
942
- if (error.code === "MAHJONG_TABLE_NOT_FOUND")
943
- return "你当前未在任何麻将桌上。";
944
- const message = platformMessage(error);
945
- if (message)
946
- return `下桌失败,${message}`;
947
- throw error;
948
- }
949
- const state = result.mahjong;
950
- // Getting up does not check out: what still bills is said, so leaving the shop means /logout.
951
- const remaining = Array.isArray(result.billing?.remaining)
952
- ? result.billing.remaining.filter((plan) => typeof plan === "string" && plan)
953
- : [];
954
- return `已离开 ${name}${wasPlaying ? ",麻将计费已停止" : ""}。当前还剩 ${state.seats.length}/${state.capacity} 人。`
955
- + (remaining.length ? `\n仍在计费:${remaining.join("、")}` : "");
956
- }
957
- async listMahjongTables() {
958
- const result = (await this.client.listMahjongTables());
959
- const tables = (result?.tables ?? []);
960
- if (tables.length === 0)
961
- return "当前没有配置任何麻将机。";
962
- const lines = [`🀄️ 麻将机列表(${tables.length} 台)`];
963
- for (const table of tables) {
964
- const playing = table.seats.filter((seat) => seat.playing).length;
965
- const waiting = table.seats.length - playing;
966
- const statuses = [
967
- ...(playing > 0 ? [`游玩中 ${playing}/${table.capacity}`] : []),
968
- ...(waiting > 0 ? [`等位 ${waiting}/${table.capacity}`] : []),
969
- ];
970
- const aliases = table.aliases ?? [];
971
- lines.push(`- ${table.name}|别名:${aliases.length > 0 ? aliases.join("、") : "无"}|${statuses.join(";") || "空闲"}`);
469
+ catch {
470
+ // The id is enough.
972
471
  }
973
- return lines.join("\n");
472
+ return { provider, subject, name };
974
473
  }
975
- async billing(sender) {
976
- const result = (await this.client.previewCheckoutByIdentity(this.identity(sender)));
977
- return this.formatCheckoutPreview(result, sender, "【结算账单】", true);
978
- }
979
- async logout(sender, bot) {
980
- // A Koishi instance can receive identical userId values from different adapters.
981
- // In-flight settlement coalescing must use the same composite identity as Bot RPC.
982
- const key = `${sender.provider}:${sender.id}`;
983
- const existing = this.logoutInFlight.get(key);
984
- if (existing)
985
- return existing;
986
- const task = this.performLogout(sender, bot);
987
- this.logoutInFlight.set(key, task);
474
+ /** Whom a `target:user` argument names (`platform:id`, or an id on the sender's platform), and what the chat calls them. */
475
+ async target(from, raw, context) {
476
+ const text = String(raw ?? "").trim();
477
+ if (!text)
478
+ return null;
479
+ const separator = text.indexOf(":");
480
+ const provider = separator > 0 ? text.slice(0, separator).toLowerCase() : from.provider;
481
+ const subject = separator > 0 ? text.slice(separator + 1) : text;
482
+ if (!subject)
483
+ return null;
484
+ let name = subject;
988
485
  try {
989
- return await task;
486
+ const user = provider === from.provider ? await context.session?.bot?.getUser?.(subject) : null;
487
+ if (user?.name)
488
+ name = user.name;
990
489
  }
991
- finally {
992
- if (this.logoutInFlight.get(key) === task)
993
- this.logoutInFlight.delete(key);
490
+ catch {
491
+ // The id is enough.
994
492
  }
493
+ return { provider, subject, name };
995
494
  }
996
- async performLogout(sender, bot) {
997
- const result = (await this.client.confirmCheckoutByIdentity(this.identity(sender), false));
998
- return this.formatAndNotifyCheckout(result, sender, "✅ 退场成功 · 结算账单", bot);
999
- }
1000
- async formatAndNotifyCheckout(result, sender, title, bot) {
1001
- const settlement = result.playerSettlement;
1002
- const records = result.settlements;
1003
- const checkoutAdjustments = result.checkoutAdjustments;
1004
- const pricingCapAdjustments = result.pricingCapAdjustments;
1005
- const checkoutAdjustmentKeys = new Set(checkoutAdjustments.map(adjustmentKey));
1006
- const pricingCapAdjustmentKeys = new Set(pricingCapAdjustments.map(adjustmentKey));
1007
- const sessionPreviews = records.map((rec) => {
1008
- const s = rec.settlement;
1009
- const sessionAdjustments = rec.adjustments.filter((adjustment) => {
1010
- const key = adjustmentKey(adjustment);
1011
- return !checkoutAdjustmentKeys.has(key) &&
1012
- !pricingCapAdjustmentKeys.has(key) &&
1013
- !isPricingCapAdjustment(adjustment);
1014
- });
1015
- const sessionSubtotal = toNumber(s.subtotal);
1016
- return {
1017
- sessionId: s.sessionId,
1018
- label: s.label,
1019
- startedAt: s.startedAt,
1020
- endedAt: s.endedAt,
1021
- status: "closed",
1022
- subtotal: sessionSubtotal,
1023
- total: sessionSubtotal + sessionAdjustments.reduce((sum, adjustment) => sum + toNumber(adjustment?.amount ?? 0), 0),
1024
- chargeItems: rec.chargeItems,
1025
- adjustments: sessionAdjustments,
1026
- };
1027
- });
1028
- const synthetic = {
1029
- settlementPreview: {
1030
- playerId: settlement.playerId,
1031
- subtotal: settlement.subtotal,
1032
- total: settlement.total,
1033
- },
1034
- sessionPreviews,
1035
- chargeItems: result.chargeItems,
1036
- checkoutAdjustments,
1037
- pricingCapAdjustments,
1038
- globalCapWindows: result.globalCapWindows,
1039
- wallet: result.wallet,
1040
- };
1041
- const receipt = await this.formatCheckoutPreview(synthetic, sender, title, false);
1042
- // Staff reachable through this adapter get the receipt privately, when the bot's settings say so.
1043
- const config = await this.config();
1044
- const channelIds = config.settings.receiptsToStaff
1045
- ? [...new Set(config.staff.filter((identity) => identity.provider === sender.provider).map((identity) => `private:${identity.subject}`))]
1046
- : [];
1047
- if (channelIds.length > 0 && bot?.broadcast)
1048
- await bot.broadcast(channelIds, receipt);
1049
- return receipt;
1050
- }
1051
- async wallet(sender) {
1052
- const result = (await this.client.getWalletByIdentity(this.identity(sender)));
1053
- return formatWallet(result.wallet, (await this.config()).currencyName);
495
+ /** Somewhere else than where the command was said: a private chat through the same bot, otherwise a channel. */
496
+ async deliver(to, text, context) {
497
+ if (to.startsWith("private:"))
498
+ await context.session?.bot?.broadcast?.([to], text);
499
+ else
500
+ await this.sendTo(to, text);
1054
501
  }
1055
502
  /**
1056
- * The wallet query over plain HTTP. The first request usually has to open a
1057
- * connection (DNS, TCP, TLS), so it is reported apart from the reused ones.
503
+ * `platform:channel` or `platform:private:user`, through that platform's first
504
+ * online bot: this needs neither Koishi's channel database nor its broadcast list.
1058
505
  */
1059
- async benchmarkApi(sender, rawCount) {
1060
- const count = benchmarkCount(rawCount);
1061
- if (count === null)
1062
- return "次数须为 1 到 10 的整数。";
1063
- const timings = [];
1064
- for (let index = 0; index < count; index++)
1065
- timings.push(await this.client.timeWalletOverHttp(this.identity(sender)));
1066
- const [first, ...rest] = timings;
1067
- return [
1068
- `📡 API 测速(HTTP,钱包查询 ${count} 次)`,
1069
- `首次:${Math.round(first.ms)} ms(含建立连接)`,
1070
- ...(rest.length ? [`之后:${spread(rest.map((timing) => timing.ms))}`] : []),
1071
- ...serverLine(timings),
1072
- ...(first.colo ? [`节点:${first.colo}`] : []),
1073
- ].join("\n");
1074
- }
1075
- /** Heartbeats (the network alone) and the same wallet query over the platform connection. */
1076
- async benchmarkWs(sender, rawCount) {
1077
- const count = benchmarkCount(rawCount);
1078
- if (count === null)
1079
- return "次数须为 1 到 10 的整数。";
1080
- const pings = [];
1081
- for (let index = 0; index < count; index++)
1082
- pings.push(await this.client.pingSocket());
1083
- const timings = [];
1084
- for (let index = 0; index < count; index++)
1085
- timings.push(await this.client.timeWalletOverSocket(this.identity(sender)));
1086
- return [
1087
- `📡 WS 测速(${count} 次)`,
1088
- `心跳:${spread(pings)}`,
1089
- `钱包查询:${spread(timings.map((timing) => timing.ms))}`,
1090
- ...serverLine(timings),
1091
- ].join("\n");
1092
- }
1093
- async versions() {
1094
- let backendVersion = "不可用";
506
+ async sendTo(target, text) {
1095
507
  try {
1096
- backendVersion = formatReleaseVersion(await this.client.getVersion());
508
+ const separator = target.indexOf(":");
509
+ if (separator < 1 || separator === target.length - 1)
510
+ throw new Error(`无效的播报频道:${target}`);
511
+ const platform = target.slice(0, separator), channel = target.slice(separator + 1);
512
+ if (channel === "private:")
513
+ throw new Error(`无效的私聊目标:${target}`);
514
+ const bot = this.ctx.bots?.find((candidate) => candidate.platform === platform && candidate.isActive);
515
+ if (!bot)
516
+ throw new Error(`没有可用的 ${platform} 机器人`);
517
+ if (channel.startsWith("private:"))
518
+ await bot.sendPrivateMessage(channel.slice(8), text);
519
+ else
520
+ await bot.sendMessage(channel, text);
1097
521
  }
1098
- catch {
1099
- // The Bot version remains useful when the backend is offline or too old.
522
+ catch (error) {
523
+ this.logger?.warn(`PRiSM announcement to ${target} failed`, error);
1100
524
  }
1101
- return [
1102
- "PRiSM 版本信息",
1103
- `Bot:${exports.version}`,
1104
- `后端:${backendVersion}`,
1105
- ].join("\n");
1106
525
  }
1107
- async items(sender) {
1108
- const result = (await this.client.getAssetsByIdentity(this.identity(sender)));
1109
- const holdings = result.holdings;
1110
- if (holdings.length === 0)
1111
- return "您当前没有任何物品。";
1112
- return ["🎒 --- 您拥有的物品 ---", ...holdings.map(formatInventoryItem)].join("\n");
1113
- }
1114
- async history(sender) {
1115
- const result = (await this.client.getSessionHistoryByIdentity(this.identity(sender)));
1116
- return formatHistory(result.sessions, (await this.config()).currencyName);
1117
- }
1118
- /** Open the door the bot's settings name. */
1119
- async lock(sender) {
1120
- const door = (await this.config()).door;
1121
- if (!door)
1122
- return "🔑 本店还没有设置 Bot 开的门";
1123
- return this.doorCode(sender, door, false);
526
+ /** The shop's news, said where the platform says. */
527
+ async announce(say) {
528
+ if (!say.to)
529
+ return;
530
+ await this.sendTo(say.to, await this.render(say.message));
1124
531
  }
1125
532
  /**
1126
- * The door code, or why there is none. `onEntry` marks the copy that rides
1127
- * along with a successful entry: there the failure is said in one line and
1128
- * never takes the entry down with it.
533
+ * The platform's message as this chat says it: each player by the name the
534
+ * chat knows them by on `provider`, or else on the first platform they are on.
1129
535
  */
1130
- async doorCode(sender, door, onEntry) {
1131
- try {
1132
- const result = await this.client.requestDeviceCommandByIdentity(this.identity(sender), {
1133
- type: "door.open",
1134
- target: { kind: "facility", ref: door.id },
1135
- });
1136
- const failure = this.getCommandFailureMessage(result);
1137
- if (failure) {
1138
- this.logDeviceCommandFailure(result);
1139
- return onEntry ? "🔑 门锁临时密码没有生成,可以在入场后用 lock 再取一次" : `🔑 开门失败,${deviceCommandFailureReason(result)}`;
1140
- }
1141
- if (result?.action?.executorKind && result.action.executorKind !== "ttlock") {
1142
- return "🔑 门锁指令已发送";
536
+ async render(message, provider) {
537
+ const parts = [];
538
+ for (const segment of message) {
539
+ const player = segment?.player;
540
+ if (player && typeof player.playerId === "string")
541
+ parts.push(await this.playerName(player, provider));
542
+ else if (typeof segment?.text === "string")
543
+ parts.push(segment.text);
544
+ }
545
+ return parts.join("");
546
+ }
547
+ async playerName(player, provider) {
548
+ const identities = Array.isArray(player.identities) ? player.identities : [];
549
+ const identity = identities.find((candidate) => candidate.provider === provider) ?? identities[0];
550
+ if (identity && this.options.resolveDisplayName) {
551
+ try {
552
+ const name = await this.options.resolveDisplayName(identity.subject, identity.provider);
553
+ if (name)
554
+ return name;
1143
555
  }
1144
- const password = cleanText(result?.action?.payload?.temporaryPassword);
1145
- if (!password)
1146
- return onEntry ? "🔑 门锁临时密码没有生成,可以在入场后用 lock 再取一次" : "🔑 临时门锁密码生成失败,请稍后再试";
1147
- return `🔑 临时门锁密码:${password}\n有效期:3 分钟`;
1148
- }
1149
- catch (error) {
1150
- this.logCommandError(error);
1151
- return onEntry ? "🔑 门锁临时密码没有生成,可以在入场后用 lock 再取一次" : `🔑 开门失败,${deviceActionFailureReason(error)}`;
1152
- }
1153
- }
1154
- async powerOn(sender, rawDeviceRef) {
1155
- const deviceRef = cleanText(rawDeviceRef);
1156
- if (!deviceRef)
1157
- return commandUsage("prism_on");
1158
- return this.power(sender, deviceRef, "on");
1159
- }
1160
- async powerOff(sender, rawDeviceRef) {
1161
- const deviceRef = cleanText(rawDeviceRef);
1162
- if (!deviceRef)
1163
- return commandUsage("prism_off");
1164
- return this.power(sender, deviceRef, "off");
1165
- }
1166
- async coin(sender, rawDeviceRef, rawCount) {
1167
- const deviceRef = cleanText(rawDeviceRef);
1168
- if (!deviceRef)
1169
- return commandUsage("prism_coin");
1170
- const { value, error } = parsePositiveInt(rawCount, "prism_coin", "数量", 1);
1171
- if (error)
1172
- return error;
1173
- try {
1174
- const result = await this.client.requestDeviceCommandByIdentity(this.identity(sender), {
1175
- type: "coin",
1176
- target: { kind: "game_machine", ref: deviceRef },
1177
- payload: { count: value },
1178
- });
1179
- const failure = deviceCommandFailureReason(result);
1180
- if (failure) {
1181
- this.logDeviceCommandFailure(result);
1182
- return `投币失败,${failure}`;
556
+ catch {
557
+ // The platform's name will do.
1183
558
  }
1184
- const label = deviceCommandLabel(result) || deviceRef;
1185
- return `🪙 ${label} 投币成功(${value} 币)`;
1186
- }
1187
- catch (error) {
1188
- this.logCommandError(error);
1189
- return `投币失败,${deviceActionFailureReason(error)}`;
1190
559
  }
560
+ return player.displayName || identity?.subject || player.playerId || "未知玩家";
1191
561
  }
1192
- async scan(sender, rawDeviceRef) {
1193
- const deviceRef = cleanText(rawDeviceRef);
1194
- if (!deviceRef)
1195
- return commandUsage("prism_scan");
562
+ /* ------------------------- the bot's own commands ------------------------ */
563
+ async versions() {
564
+ let backend = "不可用";
1196
565
  try {
1197
- const result = await this.client.requestScanByIdentity(this.identity(sender), {
1198
- deviceRef,
1199
- provider: "aime",
1200
- });
1201
- const failure = deviceCommandFailureReason(result);
1202
- if (failure) {
1203
- this.logDeviceCommandFailure(result);
1204
- return `刷卡失败,${failure}`;
566
+ const reply = await this.socket.request({ method: "GET", path: "version" });
567
+ if (reply.status < 400) {
568
+ const record = data(reply.body) ?? {};
569
+ // The platform has no release number: it says which Worker answers and the commit it runs.
570
+ const worker = String(record.worker ?? "").trim() || "unknown";
571
+ const revision = String(record.revision ?? "").trim().slice(0, 12);
572
+ backend = revision ? `${worker} (${revision})` : worker;
1205
573
  }
1206
- const label = deviceCommandLabel(result) || deviceRef;
1207
- return `💳 ${label} 刷卡成功`;
1208
574
  }
1209
- catch (error) {
1210
- this.logCommandError(error);
1211
- return `刷卡失败,${deviceActionFailureReason(error)}`;
575
+ catch {
576
+ // The Bot version remains useful when the backend is offline or too old.
1212
577
  }
1213
- }
1214
- async redeem(sender, rawCode) {
1215
- const code = cleanText(rawCode);
1216
- if (!code)
1217
- return commandUsage("prism_redeem");
1218
- const result = (await this.client.redeemCodeByIdentity(this.identity(sender), code));
1219
- const grantedAssets = result.grantedAssets;
1220
- if (grantedAssets.length === 0)
1221
- return "兑换成功,但没有获得任何物品。";
1222
- return ["✅ 兑换成功!您获得了以下物品:", ...grantedAssets.map(formatRedeemedItem)].join("\n");
578
+ return ["PRiSM 版本信息", `Bot:${exports.version}`, `后端:${backend}`].join("\n");
1223
579
  }
1224
580
  /**
1225
- * Who is in the shop, as the platform lists them: every player playing or
1226
- * billing, each once, at the resource they occupy (with its head count and
1227
- * capacity) or their most specific plan. With a name, everyone on that
1228
- * resource or billing that plan.
581
+ * The wallet query over plain HTTP. The first request usually has to open a
582
+ * connection (DNS, TCP, TLS), so it is reported apart from the reused ones.
1229
583
  */
1230
- async listActiveSessions(sender, name) {
1231
- const wanted = cleanText(name);
1232
- let roster;
1233
- try {
1234
- roster = (await this.client.roster(wanted || undefined));
1235
- }
1236
- catch (error) {
1237
- if (wanted && error instanceof PrismBotClientError && error.code === "ROSTER_TARGET_NOT_FOUND")
1238
- return `找不到「${wanted}」`;
1239
- throw error;
1240
- }
1241
- const groups = [];
1242
- for (const group of roster.groups ?? []) {
1243
- const players = [];
1244
- for (const member of group.members ?? []) {
1245
- const player = {
1246
- playerId: member.playerId,
1247
- sessions: [{ playerDisplayName: member.displayName ?? undefined, identities: member.identities ?? [] }],
1248
- };
1249
- player.displayName = await this.displayNameForPlayer(player, sender.provider);
1250
- players.push(player);
1251
- }
1252
- groups.push({ label: group.name, ...(group.kind === "resource" ? { capacity: group.capacity } : {}), players });
1253
- }
1254
- const [only] = groups;
1255
- if (wanted && only && !only.players.length) {
1256
- return only.capacity !== undefined ? `${only.label} ( 0/${only.capacity} )` : `${only.label} ( 0人 )`;
1257
- }
1258
- if (wanted)
1259
- return formatPlayerGroups(groups);
1260
- // The whole shop: players on a resource are listed there, everyone else together,
1261
- // whatever plan they bill. Asking for a plan by name still lists that plan.
1262
- const onResources = groups.filter((group) => group.capacity !== undefined);
1263
- const others = groups.filter((group) => group.capacity === undefined).flatMap((group) => group.players);
1264
- return formatPlayerGroups([...onResources, ...(others.length ? [{ label: OTHER_PLAYERS_LABEL, players: others }] : [])]);
1265
- }
1266
- async listDeviceStates(rawAlias) {
1267
- const alias = cleanText(rawAlias);
1268
- const result = (await this.client.listDeviceStates());
1269
- const states = (result?.deviceStates ?? []);
1270
- if (states.length === 0)
1271
- return "没有找到任何设备状态。";
1272
- if (alias) {
1273
- const matched = states.find((d) => d.deviceId === alias || d.label === alias || d.aliases?.some((value) => value.trim().toLowerCase() === alias.toLowerCase()));
1274
- if (!matched)
1275
- return `找不到设备: ${alias}`;
1276
- const stateVal = normalizeDeviceState(matched.state);
1277
- return `${matched.label || matched.deviceId}: ${stateVal}`;
1278
- }
1279
- return states
1280
- .map((d) => `${d.label || d.deviceId}: ${normalizeDeviceState(d.state)}`)
1281
- .join("\n");
1282
- }
1283
- /** Keep a running device from being switched off as idle; never switches one on. */
1284
- async keep(sender, deviceRef) {
584
+ async benchmarkApi(context, rawCount) {
585
+ const count = benchmarkCount(rawCount);
586
+ if (count === null)
587
+ return "次数须为 1 到 10 的整数。";
588
+ const from = await this.sender(context);
589
+ if (!from)
590
+ return "无法获取发送人的平台身份";
1285
591
  try {
1286
- const result = await this.client.requestDeviceCommandByIdentity(this.identity(sender), {
1287
- type: "power.keep",
1288
- target: { kind: "facility", ref: deviceRef },
1289
- });
1290
- if (this.getCommandFailureMessage(result)) {
1291
- this.logDeviceCommandFailure(result);
1292
- return `延迟失败,${deviceCommandFailureReason(result)}`;
1293
- }
1294
- return `✅ ${result.action.payload.deviceLabel} 已延迟关机`;
592
+ const timings = [];
593
+ for (let index = 0; index < count; index++)
594
+ timings.push(await this.walletOverHttp(from));
595
+ const [first, ...rest] = timings;
596
+ return [
597
+ `📡 API 测速(HTTP,钱包查询 ${count} 次)`,
598
+ `首次:${Math.round(first.ms)} ms(含建立连接)`,
599
+ ...(rest.length ? [`之后:${spread(rest.map((timing) => timing.ms))}`] : []),
600
+ ...serverLine(timings),
601
+ ...(first.colo ? [`节点:${first.colo}`] : []),
602
+ ].join("\n");
1295
603
  }
1296
604
  catch (error) {
1297
- this.logCommandError(error);
1298
- return `延迟失败,${powerFailureReason(error)}`;
605
+ return benchmarkFailure(error);
1299
606
  }
1300
607
  }
1301
- /* ---------------------------- helpers ---------------------------------- */
1302
- async power(sender, deviceRef, state) {
1303
- const operation = state === "on" ? "启动" : "关闭";
1304
- const config = await this.config();
1305
- const staffOverride = state === "off" && config.settings.powerOffStaffOnly;
1306
- if (staffOverride && !this.isStaff(config, sender)) {
1307
- return `${operation}失败,权限不足`;
1308
- }
608
+ /** Heartbeats (the network alone) and the same wallet query over the platform connection. */
609
+ async benchmarkWs(context, rawCount) {
610
+ const count = benchmarkCount(rawCount);
611
+ if (count === null)
612
+ return "次数须为 1 到 10 的整数。";
613
+ const from = await this.sender(context);
614
+ if (!from)
615
+ return "无法获取发送人的平台身份";
1309
616
  try {
1310
- const result = await this.client.requestDeviceCommandByIdentity(this.identity(sender), {
1311
- type: state === "on" ? "power.on" : "power.off",
1312
- target: { kind: "facility", ref: deviceRef },
1313
- payload: { state },
1314
- }, staffOverride ? { staffOverride: true } : undefined);
1315
- const failure = this.getCommandFailureMessage(result);
1316
- if (failure) {
1317
- this.logDeviceCommandFailure(result);
1318
- return `${operation}失败,${deviceCommandFailureReason(result)}`;
617
+ const pings = [];
618
+ for (let index = 0; index < count; index++)
619
+ pings.push(await this.socket.ping());
620
+ const timings = [];
621
+ for (let index = 0; index < count; index++) {
622
+ const startedAt = performance.now();
623
+ const reply = await this.socket.request({ method: "POST", path: "integration/players/by-identity/wallet", body: walletBody(from) });
624
+ if (reply.status >= 400)
625
+ throw replyError(reply.status, reply.body);
626
+ timings.push({ ms: performance.now() - startedAt, serverMs: reply.serverMs ?? null });
1319
627
  }
1320
- const deviceLabel = result.action.payload.deviceLabel;
1321
- return state === "on" ? `✅ ${deviceLabel} 启动成功` : `🛑 ${deviceLabel} 关闭成功`;
628
+ return [
629
+ `📡 WS 测速(${count} 次)`,
630
+ `心跳:${spread(pings)}`,
631
+ `钱包查询:${spread(timings.map((timing) => timing.ms))}`,
632
+ ...serverLine(timings),
633
+ ].join("\n");
1322
634
  }
1323
635
  catch (error) {
1324
- this.logCommandError(error);
1325
- return `${operation}失败,${powerFailureReason(error)}`;
1326
- }
1327
- }
1328
- /** Whether the action failed; the message itself is logged, never shown as it is. */
1329
- getCommandFailureMessage(result) {
1330
- const action = result?.action;
1331
- // `pending` here is an unanswered request (a timeout): it counts as not done.
1332
- if (action?.status === "expired" || action?.status === "rejected" || action?.status === "pending") {
1333
- return action.payload?.executorFailure?.message || "命令执行被拒绝或超时";
1334
- }
1335
- return null;
1336
- }
1337
- async resolvePlatformName(subject, provider) {
1338
- if (!this.options.resolveDisplayName)
1339
- return null;
1340
- try {
1341
- return (await this.options.resolveDisplayName(subject, provider)) ?? null;
1342
- }
1343
- catch {
1344
- return null;
1345
- }
1346
- }
1347
- async displayNameForPlayer(player, provider) {
1348
- let identitySubject;
1349
- for (const session of player.sessions) {
1350
- const subject = findSubjectForSession(session, provider);
1351
- if (!subject)
1352
- continue;
1353
- identitySubject ??= subject;
1354
- const platformName = await this.resolvePlatformName(subject, provider);
1355
- if (platformName)
1356
- return platformName;
636
+ return benchmarkFailure(error);
1357
637
  }
1358
- return player.sessions.find((session) => session.playerDisplayName)?.playerDisplayName
1359
- || identitySubject
1360
- || player.displayName
1361
- || player.playerId
1362
- || "未知玩家";
1363
638
  }
1364
- async resolvePlayerDisplay(sender, playerId) {
1365
- if (!sender)
1366
- return playerId || "未知玩家";
1367
- const platformName = await this.resolvePlatformName(sender.id, sender.provider);
1368
- const name = platformName
1369
- || (sender.name && sender.name !== sender.id ? sender.name : "")
1370
- || "未知昵称";
1371
- return `玩家:${name}(${sender.provider}:${sender.id})`;
1372
- }
1373
- async resolvePlayer(sender) {
1374
- return (await this.client.resolveOrRegisterIdentity(this.identity(sender)));
1375
- }
1376
- identity(sender) {
1377
- return {
1378
- provider: sender.provider,
1379
- subject: sender.id,
1380
- displayName: sender.name || `${sender.provider} ${sender.id}`,
1381
- };
1382
- }
1383
- async targetSender(actor, targetSubject, bot) {
1384
- const raw = cleanText(targetSubject);
1385
- if (!raw)
1386
- return actor;
1387
- const separator = raw.indexOf(":");
1388
- const provider = separator > 0 ? raw.slice(0, separator).toLowerCase() : actor.provider;
1389
- const subject = separator > 0 ? raw.slice(separator + 1) : raw;
1390
- if (provider !== actor.provider)
1391
- return "请在目标平台使用该命令";
1392
- if (!subject)
1393
- return "无法获取目标平台身份";
1394
- // Acting for another player is for staff, and only when the bot's settings allow it.
1395
- const config = await this.config();
1396
- if (!config.settings.staffCommands)
1397
- return "员工命令未启用";
1398
- if (!this.isStaff(config, actor))
1399
- return "权限不足";
1400
- try {
1401
- const user = await bot?.getUser?.(subject);
1402
- return { id: subject, name: user?.name || subject, provider };
1403
- }
1404
- catch {
1405
- return { id: subject, name: subject, provider };
1406
- }
1407
- }
1408
- async formatCheckoutPreview(result, sender, title = "【结算账单】", isPreview) {
1409
- const currency = (await this.config()).currencyName;
1410
- const preview = result.settlementPreview;
1411
- const playerId = preview.playerId;
1412
- const subtotal = preview.subtotal;
1413
- const total = preview.total;
1414
- const previewedAt = (0, display_time_js_1.parseDateTime)(preview.previewedAt);
1415
- const sessionPreviews = result.sessionPreviews;
1416
- const pricingCapAdjustments = result.pricingCapAdjustments;
1417
- const checkoutAdjustments = result.checkoutAdjustments;
1418
- const wallet = result.wallet;
1419
- const balanceBefore = toNumber(wallet?.balanceBefore ?? 0);
1420
- const balanceAfter = toNumber(wallet?.balanceAfter ?? 0);
1421
- const lines = [];
1422
- lines.push(title);
1423
- lines.push(await this.resolvePlayerDisplay(sender, playerId));
1424
- const hasNonZeroSessionTotal = sessionPreviews.some((session) => toNumber(session?.total ?? 0) !== 0);
1425
- const hasNonZeroAdjustment = hasAdjustmentEntries(checkoutAdjustments, sessionPreviews);
1426
- if (!hasNonZeroSessionTotal && !hasNonZeroAdjustment) {
1427
- lines.push("");
1428
- lines.push("本次未产生费用");
1429
- lines.push(`余额:${formatNumber(isPreview ? balanceBefore : balanceAfter)}${currency}`);
1430
- return lines.join("\n");
1431
- }
1432
- const validStarts = sessionPreviews.map(s => s.startedAt).filter(value => (0, display_time_js_1.parseDateTime)(value));
1433
- const validEnds = sessionPreviews.map(s => s.endedAt || (s.status === "active" ? preview.previewedAt : null)).filter(value => (0, display_time_js_1.parseDateTime)(value));
1434
- if (validStarts.length > 0) {
1435
- const overallStart = validStarts.reduce((a, b) => Date.parse(a) < Date.parse(b) ? a : b);
1436
- const overallEnd = validEnds.length > 0 ? validEnds.reduce((a, b) => Date.parse(a) > Date.parse(b) ? a : b) : now(this.options).toISOString();
1437
- const offsets = [...new Set([(0, display_time_js_1.apiOffsetLabel)(overallStart), (0, display_time_js_1.apiOffsetLabel)(overallEnd)])].join(" / ");
1438
- lines.push(`⏰ 游玩时间:${(0, display_time_js_1.formatHM)(overallStart)}–${(0, display_time_js_1.formatHM)(overallEnd)}(${offsets})`);
1439
- }
1440
- for (const sPrev of sessionPreviews) {
1441
- const label = sPrev?.label === "entry" ? DEFAULT_PLAN_LABEL : sPrev?.label || "计时区间";
1442
- const startDt = (0, display_time_js_1.parseDateTime)(sPrev?.startedAt);
1443
- const endDt = sessionDisplayEnd(sPrev, previewedAt);
1444
- const status = sPrev?.status ?? "active";
1445
- const sTotal = toNumber(sPrev?.total ?? 0);
1446
- lines.push("");
1447
- lines.push(label);
1448
- if (startDt && endDt) {
1449
- const minutes = Math.floor((endDt.getTime() - startDt.getTime()) / 60_000);
1450
- lines.push(`游玩时段:${(0, display_time_js_1.formatHM)(sPrev.startedAt)}-${(0, display_time_js_1.formatHM)(sPrev.endedAt || preview.previewedAt || endDt.toISOString())}`);
1451
- lines.push(`游玩时长:${formatDurationValue(minutes)}|计价:${formatNumber(sTotal)}${currency}`);
1452
- }
1453
- else if (startDt) {
1454
- lines.push(`入场:${(0, display_time_js_1.formatHM)(sPrev.startedAt)} (${status === "active" ? "计费中" : "已关闭"})`);
1455
- }
1456
- const sessionAdjustments = (sPrev?.adjustments ?? []);
1457
- for (const adj of sessionAdjustments) {
1458
- const amount = toNumber(adj.amount);
1459
- if (amount === 0)
1460
- continue;
1461
- const adjLabel = adj.label || adj.source || "优惠";
1462
- lines.push(` └ ${adjLabel}:${formatNumber(amount)}${currency}`);
1463
- }
1464
- }
1465
- const cappedWindows = result.globalCapWindows.filter((window) => toNumber(window?.currentAmount) !== toNumber(window?.amountApplied));
1466
- if (cappedWindows.length > 0) {
1467
- lines.push("");
1468
- lines.push("封顶:");
1469
- for (const window of cappedWindows) {
1470
- const label = window.ruleLabel || "封顶时段";
1471
- const startedAt = (0, display_time_js_1.parseDateTime)(window.windowStartedAt);
1472
- const datedLabel = startedAt ? `${(0, display_time_js_1.formatMD)(window.windowStartedAt)} ${label}` : label;
1473
- const currentAmount = toNumber(window.currentAmount);
1474
- const amountApplied = toNumber(window.amountApplied);
1475
- const priceCap = toNumber(window.priceCap);
1476
- const paidBefore = toNumber(window.paidBefore);
1477
- const details = [`上限${formatNumber(priceCap)}`];
1478
- if (paidBefore > 0)
1479
- details.push(`已计${formatNumber(paidBefore)}`);
1480
- lines.push(`- ${datedLabel}:${formatNumber(currentAmount)} → ${formatNumber(amountApplied)}${currency}(${details.join(",")})`);
1481
- }
1482
- }
1483
- const visibleCheckoutAdjustments = checkoutAdjustments.filter((adjustment) => {
1484
- const amount = toNumber(adjustment.amount);
1485
- const isOverride = cleanText(adjustment?.source).startsWith("staff.override:");
1486
- return amount !== 0 && !isOverride;
1487
- });
1488
- lines.push("");
1489
- const cappedTotal = Math.max(0, toNumber(subtotal) + pricingCapAdjustments.reduce((sum, adjustment) => sum + toNumber(adjustment?.amount ?? 0), 0));
1490
- lines.push(`计费总价:${formatNumber(cappedTotal)}${currency}`);
1491
- const hasManualAdjustment = checkoutAdjustments.some((adjustment) => cleanText(adjustment?.source).startsWith("staff.override:"));
1492
- if (visibleCheckoutAdjustments.length > 0) {
1493
- lines.push("");
1494
- for (const adjustment of visibleCheckoutAdjustments) {
1495
- const amount = toNumber(adjustment.amount);
1496
- const label = adjustment.label || adjustment.source || "优惠";
1497
- lines.push(`${label}:${formatNumber(amount)}${currency}`);
1498
- }
1499
- }
1500
- if (hasNonZeroAdjustment) {
1501
- if (visibleCheckoutAdjustments.length > 0)
1502
- lines.push("");
1503
- lines.push(`${hasManualAdjustment ? "调整后价格" : "优惠后价格"}:${formatNumber(total)}${currency}`);
1504
- }
1505
- if (isPreview) {
1506
- lines.push(`当前余额:${formatNumber(balanceBefore)}${currency}`);
1507
- lines.push(balanceAfter >= 0
1508
- ? `预计结账后余额:${formatNumber(balanceAfter)}${currency}`
1509
- : `预计结账后余额:余额不足(还差 ${formatNumber(-balanceAfter)}${currency})`);
1510
- }
1511
- else {
1512
- lines.push(`扣款后余额:${formatNumber(balanceAfter)}${currency}`);
1513
- }
1514
- return lines.join("\n");
1515
- }
1516
- handleCommandError(error) {
1517
- this.logCommandError(error);
1518
- if (error instanceof PrismBotClientError) {
1519
- const shopCode = this.options.shopCode ?? this.bot?.shop?.code;
1520
- if (error.code?.startsWith("LOCATION_") && shopCode && this.options.baseUrl) {
1521
- return `请在网页完成到店校验:${this.options.baseUrl.replace(/\/+$/, "")}/t/${encodeURIComponent(shopCode)}`;
1522
- }
1523
- return humanReadableBotError(error);
1524
- }
1525
- return genericCommandFailure();
1526
- }
1527
- logCommandError(error) {
1528
- this.logger?.warn("PRiSM Bot command failed", error instanceof PrismBotClientError
1529
- ? (error.originalError ?? error)
1530
- : error);
1531
- }
1532
- logDeviceCommandFailure(result) {
1533
- const action = result?.action;
1534
- this.logger?.warn("PRiSM device command failed", action?.payload?.executorFailure ?? action);
1535
- }
1536
- }
1537
- function humanReadableBotError(error) {
1538
- if (error.code === "INVALID_PLATFORM_IDENTITY")
1539
- return error.message;
1540
- if (error.code === "OPERATION_IN_PROGRESS")
1541
- return "其他操作正在处理中,请稍后再试。";
1542
- if (error.code === "REDEEM_CODE_NOT_FOUND")
1543
- return "兑换码无效,请检查后再试。";
1544
- if (error.code === "REDEEM_CODE_NOT_ACTIVE")
1545
- return "兑换码尚未生效。";
1546
- if (error.code === "REDEEM_CODE_EXPIRED" || error.code === "PRESENT_EXPIRED")
1547
- return "兑换码已过期。";
1548
- if (error.code === "PRESENT_NOT_ACTIVE" || error.code === "PRESENT_ARCHIVED")
1549
- return "这份礼物当前无法兑换。";
1550
- if (error.code === "REDEEM_CODE_MAX_USE_REACHED")
1551
- return "兑换码已被领完。";
1552
- if (error.code === "PRESENT_ONCE_PER_PLAYER_REDEEMED")
1553
- return "您已经领取过这份礼物,无需重复兑换。";
1554
- if (error.code === "PRESENT_GRANT_LIMIT_REACHED")
1555
- return "您已达到这份礼物的领取上限。";
1556
- if (error.code === "BOT_DISABLED")
1557
- return "Bot 已被店铺停用";
1558
- if (error.code === "BILLING_DISABLED")
1559
- return BILLING_DISABLED_NOTICE;
1560
- if (error.code === "RESOURCE_NOT_BILLED")
1561
- return RESOURCE_NOT_BILLED_NOTICE;
1562
- if (error.code === "PLAYER_HAS_NO_UNSETTLED_SESSIONS") {
1563
- return "您当前没有未结算的账单,无需结账。";
1564
- }
1565
- if (error.code === "ACTIVE_SESSION_NOT_FOUND") {
1566
- return "您当前没有进行中的计费场次。";
1567
- }
1568
- if (error.code === "DEVICE_COMMAND_REQUIRES_ACTIVE_SESSION") {
1569
- return "操作失败,玩家未入场";
1570
- }
1571
- if (error.code === "PLAYER_IDENTITY_NOT_FOUND") {
1572
- return "未找到您的玩家身份,请先注册或绑定账号。";
1573
- }
1574
- if (error.code === "INSUFFICIENT_BALANCE") {
1575
- return "余额不足,暂时不能结账。请先充值,或由店员在后台改价后再结账。";
1576
- }
1577
- if (error.code === "API_UNREACHABLE")
1578
- return "操作失败,暂时连不上服务器。";
1579
- if (error.code === "NETWORK_ERROR" || error.code === "HTTP_0") {
1580
- return genericCommandFailure();
1581
- }
1582
- if (error.code === "API_TIMEOUT") {
1583
- return genericCommandFailure();
1584
- }
1585
- if (error.code === "INVALID_JSON_RESPONSE") {
1586
- return genericCommandFailure();
1587
- }
1588
- if (error.code === "STAFF_TOKEN_REQUIRED") {
1589
- return genericCommandFailure();
1590
- }
1591
- return genericCommandFailure();
1592
- }
1593
- function powerFailureReason(error) {
1594
- if (error instanceof PrismBotClientError) {
1595
- if (error.code === "DEVICE_COMMAND_REQUIRES_ACTIVE_SESSION")
1596
- return "玩家未入场";
1597
- if (error.code === "PLAYER_IDENTITY_NOT_FOUND")
1598
- return "玩家未注册";
1599
- if (error.code === "BILLING_DISABLED")
1600
- return BILLING_DISABLED_NOTICE;
1601
- if (error.code === "DEVICE_NOT_FOUND")
1602
- return "没有这个设备";
1603
- }
1604
- return "请稍后再试";
1605
- }
1606
- function deviceActionFailureReason(error) {
1607
- if (!(error instanceof PrismBotClientError))
1608
- return "请稍后再试";
1609
- if (error.code === "DEVICE_COMMAND_REQUIRES_ACTIVE_SESSION")
1610
- return "玩家未入场";
1611
- if (error.code === "DEVICE_NOT_FOUND")
1612
- return "设备不存在";
1613
- if (error.code === "SCAN_IDENTITY_NOT_BOUND_TO_PLAYER")
1614
- return "玩家未绑定 Aime 卡";
1615
- if (error.code === "COIN_COMMAND_COOLDOWN_ACTIVE")
1616
- return "投币冷却中,请稍后再试";
1617
- if (error.code === "BILLING_DISABLED")
1618
- return BILLING_DISABLED_NOTICE;
1619
- return "请稍后再试";
1620
- }
1621
- /**
1622
- * What a player may be told about a device that would not act. Only facts about
1623
- * the device itself — whether it exists, is connected, is off, answered — never
1624
- * how the shop configured it or what went wrong inside the platform.
1625
- */
1626
- const DEVICE_REASONS = [
1627
- [/设备不存在|没有找到这个资源/, "没有这个设备"],
1628
- [/机台未在线|没有在线客户端|设备未连接|直连中继尚未配置/, "设备未连接"],
1629
- [/设备已关机/, "设备已关机"],
1630
- [/设备未响应|机台未响应/, "设备没有响应"],
1631
- ];
1632
- function deviceCommandFailureReason(result) {
1633
- const action = result?.action;
1634
- if (!action || (action.status !== "expired" && action.status !== "rejected" && action.status !== "pending"))
1635
- return null;
1636
- const message = cleanText(action.payload?.executorFailure?.message);
1637
- return DEVICE_REASONS.find(([pattern]) => pattern.test(message))?.[1] ?? "操作没有完成,请找店员";
1638
- }
1639
- function deviceCommandLabel(result) {
1640
- return cleanText(result?.action?.payload?.deviceLabel);
1641
- }
1642
- function genericCommandFailure() {
1643
- return "操作失败,请稍后再试。";
1644
- }
1645
- function normalizeDeviceState(value) {
1646
- if (typeof value === "object" && value !== null) {
1647
- return cleanText(value.state) || "unknown";
1648
- }
1649
- const raw = cleanText(value);
1650
- if (!raw)
1651
- return "unknown";
1652
- if (raw.startsWith("{")) {
1653
- try {
1654
- const decoded = JSON.parse(raw);
1655
- return cleanText(decoded?.state) || "unknown";
1656
- }
1657
- catch {
1658
- return raw;
1659
- }
1660
- }
1661
- return raw;
1662
- }
1663
- /** The table a player named, by id, name or alias, as the platform matches it. */
1664
- function findMahjongTable(tables, ref) {
1665
- const target = ref.trim().toLowerCase();
1666
- return tables.find((table) => [table.id, table.name, ...table.aliases].some((value) => cleanText(value).toLowerCase() === target)) ?? null;
1667
- }
1668
- /** The platform's own message for a refusal, when it gave one; never the fallback naming an HTTP status. */
1669
- function platformMessage(error) {
1670
- if (error.status < 400 || error.status >= 500)
1671
- return null;
1672
- const message = error.body?.error?.message;
1673
- return typeof message === "string" && message.trim() ? message.trim() : null;
1674
- }
1675
- /**
1676
- * The bot's settings as the platform sent them. Anything missing takes the
1677
- * platform's own default, so a newer setting an older platform lacks does no harm.
1678
- */
1679
- function parseBotConfig(value) {
1680
- const record = (value && typeof value === "object" ? value : {});
1681
- const settings = (record.settings ?? {});
1682
- const strings = (list) => (Array.isArray(list) ? list : []).map(cleanText).filter(Boolean);
1683
- return {
1684
- bot: { id: cleanText(record.bot?.id), name: cleanText(record.bot?.name) || "Bot" },
1685
- settings: {
1686
- playerCommands: settings.playerCommands === "readonly" ? "readonly" : "all",
1687
- readOnlyNotice: cleanText(settings.readOnlyNotice),
1688
- staffCommands: settings.staffCommands !== false,
1689
- powerOffStaffOnly: settings.powerOffStaffOnly === true,
1690
- receiptsToStaff: settings.receiptsToStaff === true,
1691
- doorPasswordOnEntry: settings.doorPasswordOnEntry === true,
1692
- announceChannelIds: strings(settings.announceChannelIds),
1693
- idleReminderMinutes: Math.max(0, Number(settings.idleReminderMinutes ?? 5) || 0),
1694
- announceIdle: settings.announceIdle === true,
1695
- announcePower: settings.announcePower === true,
1696
- announceStarts: settings.announceStarts === true,
1697
- announceCards: settings.announceCards === true,
1698
- announceCoins: settings.announceCoins === true,
1699
- },
1700
- billingEnabled: record.billingEnabled !== false,
1701
- currencyName: cleanText(record.currencyName) || "余额",
1702
- staff: (Array.isArray(record.staff) ? record.staff : [])
1703
- .map((identity) => ({ provider: cleanText(identity?.provider).toLowerCase(), subject: cleanText(identity?.subject) }))
1704
- .filter((identity) => identity.provider && identity.subject),
1705
- door: record.door?.id ? { id: cleanText(record.door.id), name: cleanText(record.door.name) } : null,
1706
- mahjongTables: (Array.isArray(record.mahjongTables) ? record.mahjongTables : [])
1707
- .filter((table) => cleanText(table?.id))
1708
- .map((table) => ({
1709
- id: cleanText(table.id),
1710
- name: cleanText(table.name) || cleanText(table.id),
1711
- aliases: strings(table.aliases),
1712
- capacity: Number(table.capacity) || 4,
1713
- })),
1714
- };
1715
- }
1716
- /** What the shop's default plan is called when the platform gives no plan name. */
1717
- const DEFAULT_PLAN_LABEL = "入场计费";
1718
- function formatPlayerGroups(groups) {
1719
- const populatedGroups = groups.filter((group) => group.players.length > 0);
1720
- // Each person is in exactly one group.
1721
- const total = populatedGroups.reduce((sum, group) => sum + group.players.length, 0);
1722
- if (total === 0)
1723
- return "🫥 窝里目前没有玩家呢";
1724
- const lines = [`[总计 ${total} 人]`];
1725
- for (const group of populatedGroups) {
1726
- const heading = group.capacity !== undefined
1727
- ? `${group.label} ( ${group.players.length}/${group.capacity} )`
1728
- : `${group.label} ( ${group.players.length}人 )`;
1729
- lines.push(`\n${heading}:\n${formatPlayerNames(group.players)}`);
1730
- }
1731
- return lines.join("\n");
1732
- }
1733
- function formatPlayerNames(players) {
1734
- return players.map((player) => `- ${player.displayName || player.playerId || "未知玩家"}`).join(", ");
1735
- }
1736
- function commandUsage(command) {
1737
- return `用法: ${USAGE[command] ?? command}`;
1738
- }
1739
- function parsePositiveInt(value, command, label, fallback) {
1740
- const text = cleanText(value);
1741
- if (!text) {
1742
- if (fallback !== undefined)
1743
- return { value: fallback, error: null };
1744
- return { value: 0, error: commandUsage(command) };
1745
- }
1746
- const parsed = Number.parseInt(text, 10);
1747
- if (Number.isNaN(parsed) || parsed <= 0) {
1748
- return { value: 0, error: `${label}必须是正整数\n${commandUsage(command)}` };
1749
- }
1750
- return { value: parsed, error: null };
1751
- }
1752
- function cleanText(value) {
1753
- return value == null ? "" : String(value).trim();
1754
- }
1755
- function formatReleaseVersion(value) {
1756
- const record = value && typeof value === "object" ? value : {};
1757
- const release = cleanText(record.version) || "unknown";
1758
- const revision = cleanText(record.revision);
1759
- return !revision || revision === "unknown" ? release : `${release} (${revision})`;
1760
- }
1761
- function formatPlayerReference(sender) {
1762
- const name = sender.name && sender.name !== sender.id ? sender.name : "未知昵称";
1763
- return `${name}(${sender.provider}:${sender.id})`;
1764
- }
1765
- function adjustmentKey(adjustment) {
1766
- const id = cleanText(adjustment?.id);
1767
- if (id)
1768
- return `id:${id}`;
1769
- return JSON.stringify([
1770
- adjustment?.source ?? "",
1771
- adjustment?.label ?? "",
1772
- toNumber(adjustment?.amount ?? 0),
1773
- ]);
1774
- }
1775
- function isPricingCapAdjustment(adjustment) {
1776
- return adjustment?.pricingCapHistory != null ||
1777
- cleanText(adjustment?.source).startsWith("time.cap:") ||
1778
- cleanText(adjustment?.id).startsWith("time-cap:");
1779
- }
1780
- function toNumber(value) {
1781
- if (value == null)
1782
- return 0;
1783
- if (typeof value === "boolean")
1784
- return value ? 1 : 0;
1785
- if (typeof value === "number")
1786
- return value;
1787
- const text = String(value).trim();
1788
- if (!text)
1789
- return 0;
1790
- const asInt = Number.parseInt(text, 10);
1791
- if (!Number.isNaN(asInt))
1792
- return asInt;
1793
- const asFloat = Number.parseFloat(text);
1794
- if (!Number.isNaN(asFloat))
1795
- return asFloat;
1796
- return 0;
1797
- }
1798
- function hasAdjustmentEntries(adjustments, sessionPreviews) {
1799
- return adjustments.some((adjustment) => toNumber(adjustment.amount) !== 0) || sessionPreviews.some((session) => session.adjustments.some((adjustment) => toNumber(adjustment.amount) !== 0));
1800
- }
1801
- function formatNumber(value) {
1802
- if (typeof value === "boolean")
1803
- return value ? "1" : "0";
1804
- if (typeof value === "number") {
1805
- return Number.isInteger(value) ? String(value) : String(value);
1806
- }
1807
- const num = toNumber(value);
1808
- if (num || String(value ?? "").trim() === "0" || String(value ?? "").trim() === "0.0") {
1809
- return Number.isInteger(num) ? String(num) : String(num);
639
+ /** The same wallet query as a plain HTTP request, the way the Bot used to call, timed. */
640
+ async walletOverHttp(from) {
641
+ const code = this.shopCode ?? (this.shopCode = await this.readShopCode());
642
+ const url = `${this.options.baseUrl.trim().replace(/\/+$/, "")}/api/v1/shops/${encodeURIComponent(code)}/integration/players/by-identity/wallet`;
643
+ const startedAt = performance.now();
644
+ const response = await this.post(url, { authorization: `Bearer ${this.options.integrationToken}`, "content-type": "application/json" }, walletBody(from));
645
+ const ms = performance.now() - startedAt;
646
+ if (response.status >= 400)
647
+ throw replyError(response.status, response.data);
648
+ const server = Number.parseFloat(response.headers.get("x-response-time") ?? "");
649
+ return { ms, serverMs: Number.isFinite(server) ? server : null, colo: response.headers.get("cf-ray")?.split("-").pop() ?? null };
1810
650
  }
1811
- return String(value);
1812
- }
1813
- function formatDurationValue(minutes) {
1814
- const total = Math.floor(toNumber(minutes));
1815
- if (total >= 60) {
1816
- const hours = Math.floor(total / 60);
1817
- const mins = total % 60;
1818
- return `${hours}小时${mins}分钟`;
651
+ /** The shop this credential belongs to, as the platform names it. */
652
+ async readShopCode() {
653
+ const reply = await this.socket.request({ method: "GET", path: "integration/bot" });
654
+ if (reply.status >= 400)
655
+ throw replyError(reply.status, reply.body);
656
+ const code = String(data(reply.body)?.shop?.code ?? "").trim();
657
+ if (!code)
658
+ throw new PrismBotClientError("店铺尚未读取", "SHOP_UNKNOWN", 0, {});
659
+ return code;
1819
660
  }
1820
- return `${total}分钟`;
1821
- }
1822
- function sessionDisplayEnd(session, previewedAt) {
1823
- const endedAt = (0, display_time_js_1.parseDateTime)(session?.endedAt);
1824
- if (endedAt)
1825
- return endedAt;
1826
- if (session?.status === "active")
1827
- return previewedAt ?? now(undefined);
1828
- return null;
1829
661
  }
1830
- function now(config) {
1831
- return config?.now ? config.now() : new Date();
662
+ function walletBody(from) {
663
+ return { identity: { provider: from.provider, subject: from.subject } };
1832
664
  }
1833
- function formatInventoryItem(row) {
1834
- let line = `- ${row.assetName || row.assetCode || "资产"} (x${formatNumber(row.quantity)})`;
1835
- if (row.expiresAt)
1836
- line += `\n 到期: ${(0, display_time_js_1.formatDateTime)(row.expiresAt)}`;
1837
- return line;
1838
- }
1839
- function formatRedeemedItem(row) {
1840
- return `- ${row.assetName || row.assetCode || "资产"} x${formatNumber(row.quantity)}`;
665
+ function benchmarkCount(raw) {
666
+ const count = raw == null || raw === "" ? 5 : Number(raw);
667
+ return Number.isInteger(count) && count >= 1 && count <= 10 ? count : null;
1841
668
  }
1842
- function formatWallet(rows, currency) {
1843
- const paid = rows
1844
- .filter((row) => String(row.assetCode).toLowerCase().includes("paid"))
1845
- .reduce((sum, row) => sum + toNumber(row.quantity), 0);
1846
- const free = rows
1847
- .filter((row) => String(row.assetCode).toLowerCase().includes("free"))
1848
- .reduce((sum, row) => sum + toNumber(row.quantity), 0);
1849
- const other = rows
1850
- .filter((row) => {
1851
- const code = String(row.assetCode).toLowerCase();
1852
- return !code.includes("paid") && !code.includes("free");
1853
- })
1854
- .reduce((sum, row) => sum + toNumber(row.quantity), 0);
1855
- const total = paid + free + other;
1856
- return [
1857
- "💰 --- 钱包余额 ---",
1858
- `可用: ${formatNumber(total)} ${currency} (共 ${formatNumber(total)})`,
1859
- ` - 付费: ${formatNumber(paid)}`,
1860
- ` - 免费: ${formatNumber(free)}`,
1861
- ].join("\n");
669
+ function benchmarkFailure(error) {
670
+ if (error instanceof PrismBotClientError && error.status === 0)
671
+ return error.code === "API_TIMEOUT" ? TIMED_OUT : UNREACHABLE;
672
+ return "测速失败,请稍后再试。";
1862
673
  }
1863
- function formatHistory(sessions, currency) {
1864
- if (sessions.length === 0)
1865
- return "暂无历史记录";
1866
- const lines = [`📜 最近 ${sessions.length} 条记录:`];
1867
- for (const session of sessions) {
1868
- const end = session.endedAt ? (0, display_time_js_1.formatDateTime)(session.endedAt) : "进行中";
1869
- const cost = session.total == null ? "未结算" : `${formatNumber(session.total)} ${currency}`;
1870
- lines.push(`- [${session.sessionId}] ${(0, display_time_js_1.formatDateTime)(session.startedAt)} -> ${end} (${cost})`);
1871
- }
1872
- return lines.join("\n");
674
+ function spread(samples) {
675
+ const average = samples.reduce((sum, sample) => sum + sample, 0) / samples.length;
676
+ return `最小 ${Math.round(Math.min(...samples))} / 平均 ${Math.round(average)} / 最大 ${Math.round(Math.max(...samples))} ms`;
1873
677
  }
1874
- function findSubjectForSession(session, provider) {
1875
- const identities = session.identities ?? [];
1876
- if (identities.length === 0)
1877
- return null;
1878
- const identity = provider ? identities.find((id) => id.provider === provider) : identities[0];
1879
- return identity?.subject ?? null;
678
+ function serverLine(timings) {
679
+ const known = timings.map((timing) => timing.serverMs).filter((value) => value !== null);
680
+ if (!known.length)
681
+ return [];
682
+ return [`服务端处理:平均 ${Math.round(known.reduce((sum, value) => sum + value, 0) / known.length)} ms`];
1880
683
  }
1881
684
  exports.default = {
1882
685
  name: exports.name,