koishi-plugin-prism 0.5.1 → 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/README.md +24 -7
- package/lib/ha-watch.d.ts +1 -1
- package/lib/ha-watch.js +3 -1
- package/lib/index.d.ts +80 -118
- package/lib/index.js +346 -1532
- package/package.json +1 -1
- package/lib/display-time.d.ts +0 -10
- package/lib/display-time.js +0 -36
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.
|
|
20
|
-
//
|
|
21
|
-
// resource page in PRiSM
|
|
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
|
-
|
|
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
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
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
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
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>", "加入指定麻将桌").action(effect(async (context, tableId) => service.mahjongJoin(await service.sender(context), tableId)));
|
|
91
|
-
ctx.command("上桌 [tableId]", "加入指定麻将桌").action(effect(async (context, tableId) => service.mahjongJoin(await service.sender(context), tableId)));
|
|
92
|
-
ctx.command("下桌 [tableId]", "离开当前所在麻将桌").action(effect(async (context, tableId) => service.mahjongLeave(await service.sender(context), tableId)));
|
|
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
|
|
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.
|
|
132
|
-
*
|
|
133
|
-
*
|
|
134
|
-
*
|
|
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
|
-
|
|
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
|
-
/**
|
|
157
|
-
|
|
158
|
-
/**
|
|
159
|
-
|
|
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.
|
|
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(
|
|
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
|
-
|
|
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
|
-
|
|
249
|
-
|
|
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 === "
|
|
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
|
|
320
|
-
|
|
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 =
|
|
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(
|
|
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
|
-
|
|
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
|
-
/*
|
|
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
|
|
366
|
+
socket;
|
|
593
367
|
watcher = null;
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
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
|
|
625
|
-
this.socket = new PrismSocket(open, platformSocketUrl(options.baseUrl), options.integrationToken,
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
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
|
-
|
|
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,1226 +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
|
|
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
|
-
*
|
|
688
|
-
*
|
|
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
|
|
691
|
-
|
|
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
|
+
});
|
|
456
|
+
}
|
|
457
|
+
/** Who sent the command, as the platform knows chat identities. */
|
|
458
|
+
async sender(context) {
|
|
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;
|
|
692
464
|
try {
|
|
693
|
-
|
|
465
|
+
const user = await context.session?.bot?.getUser?.(subject);
|
|
466
|
+
if (user?.name)
|
|
467
|
+
name = user.name;
|
|
694
468
|
}
|
|
695
|
-
catch
|
|
696
|
-
|
|
697
|
-
throw error;
|
|
698
|
-
this.watching = false;
|
|
699
|
-
this.watcher?.stop();
|
|
700
|
-
return {};
|
|
469
|
+
catch {
|
|
470
|
+
// The id is enough.
|
|
701
471
|
}
|
|
702
|
-
|
|
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
|
-
};
|
|
472
|
+
return { provider, subject, name };
|
|
718
473
|
}
|
|
719
|
-
/**
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
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;
|
|
724
485
|
try {
|
|
725
|
-
|
|
726
|
-
|
|
486
|
+
const user = provider === from.provider ? await context.session?.bot?.getUser?.(subject) : null;
|
|
487
|
+
if (user?.name)
|
|
488
|
+
name = user.name;
|
|
727
489
|
}
|
|
728
|
-
catch
|
|
729
|
-
|
|
730
|
-
return error.message || "绑定失败,请重新生成验证码";
|
|
731
|
-
throw error;
|
|
490
|
+
catch {
|
|
491
|
+
// The id is enough.
|
|
732
492
|
}
|
|
493
|
+
return { provider, subject, name };
|
|
494
|
+
}
|
|
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);
|
|
733
501
|
}
|
|
734
502
|
/**
|
|
735
|
-
*
|
|
736
|
-
*
|
|
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.
|
|
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.
|
|
740
505
|
*/
|
|
741
|
-
async
|
|
742
|
-
const bot = this.bot;
|
|
743
|
-
const channels = bot?.settings.announceChannelIds ?? [];
|
|
744
|
-
if (!bot || !channels.length || typeof this.ctx.broadcast !== "function")
|
|
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;
|
|
506
|
+
async sendTo(target, text) {
|
|
751
507
|
try {
|
|
752
|
-
|
|
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);
|
|
753
521
|
}
|
|
754
522
|
catch (error) {
|
|
755
|
-
this.logger?.warn(
|
|
523
|
+
this.logger?.warn(`PRiSM announcement to ${target} failed`, error);
|
|
756
524
|
}
|
|
757
525
|
}
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
if (!event.player)
|
|
762
|
-
return "未绑定的卡";
|
|
763
|
-
// Named as the platform the channels are on would name them, when it can.
|
|
764
|
-
const provider = event.player.identities[0]?.provider ?? "";
|
|
765
|
-
return this.displayNameForPlayer({
|
|
766
|
-
playerId: event.player.playerId,
|
|
767
|
-
displayName: event.player.displayName ?? undefined,
|
|
768
|
-
sessions: [{ playerDisplayName: event.player.displayName ?? undefined, identities: event.player.identities }],
|
|
769
|
-
}, provider);
|
|
770
|
-
};
|
|
771
|
-
if (event.kind === "power") {
|
|
772
|
-
if (!settings.announcePower)
|
|
773
|
-
return null;
|
|
774
|
-
if (event.by === "system")
|
|
775
|
-
return event.state === "off" ? `💤 ${place} 闲置,已自动关机` : `✅ ${place} 已开机`;
|
|
776
|
-
const by = event.player ? `(${await who()})` : "";
|
|
777
|
-
return event.state === "on" ? `✅ ${place} 已开机${by}` : `🛑 ${place} 已关机${by}`;
|
|
778
|
-
}
|
|
779
|
-
if (event.kind === "card") {
|
|
780
|
-
if (event.started && settings.announceStarts)
|
|
781
|
-
return `🎮 ${await who()} 在 ${place} 刷卡上机`;
|
|
782
|
-
return settings.announceCards ? `💳 ${await who()} 在 ${place} 刷卡` : null;
|
|
783
|
-
}
|
|
784
|
-
if (event.kind === "coin") {
|
|
785
|
-
if (event.started && settings.announceStarts)
|
|
786
|
-
return `🎮 ${await who()} 在 ${place} 投币上机`;
|
|
787
|
-
return settings.announceCoins ? `🪙 ${await who()} 在 ${place} 投币` : null;
|
|
788
|
-
}
|
|
789
|
-
if (event.kind === "occupancy")
|
|
790
|
-
return settings.announceStarts ? `🎮 ${await who()} 在 ${place} 上机` : null;
|
|
791
|
-
return null;
|
|
792
|
-
}
|
|
793
|
-
/** Tell the configured channels a power-off is coming, when the shop asks for it. */
|
|
794
|
-
async remindIdle(reminder) {
|
|
795
|
-
const settings = this.bot?.settings;
|
|
796
|
-
const channels = settings?.announceChannelIds ?? [];
|
|
797
|
-
if (!settings?.announceIdle || !channels.length || typeof this.ctx.broadcast !== "function")
|
|
526
|
+
/** The shop's news, said where the platform says. */
|
|
527
|
+
async announce(say) {
|
|
528
|
+
if (!say.to)
|
|
798
529
|
return;
|
|
799
|
-
|
|
800
|
-
const minutes = Math.max(1, Math.round((reminder.at - now) / 60_000));
|
|
801
|
-
const names = reminder.devices.map((device) => device.name).join("、");
|
|
802
|
-
const message = reminder.reason === "shop_empty"
|
|
803
|
-
? `店里没人,${minutes} 分钟后全部关机`
|
|
804
|
-
: `${names} 闲置中,${minutes} 分钟后关机。已入场的玩家发送 keep 设备名 可以延迟`;
|
|
805
|
-
try {
|
|
806
|
-
await this.ctx.broadcast(channels, message);
|
|
807
|
-
}
|
|
808
|
-
catch (error) {
|
|
809
|
-
this.logger?.warn("PRiSM idle reminder failed", error);
|
|
810
|
-
}
|
|
811
|
-
}
|
|
812
|
-
async sender(context) {
|
|
813
|
-
const id = cleanText(context.session?.userId);
|
|
814
|
-
const provider = cleanText(context.session?.platform || context.session?.bot?.platform).toLowerCase();
|
|
815
|
-
if (!id || !/^[a-z][a-z0-9_-]{0,63}$/.test(provider))
|
|
816
|
-
throw new PrismBotClientError("无法获取发送人的平台身份", "INVALID_PLATFORM_IDENTITY", 400, null);
|
|
817
|
-
let name = context.session?.username || context.session?.senderName || id;
|
|
818
|
-
try {
|
|
819
|
-
if (context.session?.bot?.getUser) {
|
|
820
|
-
const user = await context.session.bot.getUser(id);
|
|
821
|
-
if (user?.name) {
|
|
822
|
-
name = user.name;
|
|
823
|
-
}
|
|
824
|
-
}
|
|
825
|
-
}
|
|
826
|
-
catch { }
|
|
827
|
-
return { id, name, provider };
|
|
828
|
-
}
|
|
829
|
-
async loginForTarget(actor, targetSubject, bot) {
|
|
830
|
-
return this.withTarget(actor, targetSubject, async (sender, isTargeted) => {
|
|
831
|
-
const result = (await this.client.startSessionByIdentity(this.identity(sender)));
|
|
832
|
-
// Already in: the player had this session before, and the plan says where.
|
|
833
|
-
if (result?.created === false) {
|
|
834
|
-
const where = typeof result.planName === "string" && result.planName ? `「${result.planName}」` : "场";
|
|
835
|
-
return isTargeted ? `用户 ${formatPlayerReference(sender)} 已在${where}中,无需重复入场` : `您已在${where}中,无需重复入场`;
|
|
836
|
-
}
|
|
837
|
-
// Starting the plan may end one it cannot bill together with.
|
|
838
|
-
const stopped = Array.isArray(result?.billing?.stopped) ? result.billing.stopped.filter((name) => typeof name === "string" && name) : [];
|
|
839
|
-
const ended = stopped.length ? `\n结束方案:${stopped.join("、")}` : "";
|
|
840
|
-
const message = (isTargeted ? `✅ 已为用户 ${formatPlayerReference(sender)} 入场成功` : "✅ 入场成功") + ended;
|
|
841
|
-
// Entering and getting the door code as one command, when the shop asks
|
|
842
|
-
// for it. A door that fails must not undo an entry that succeeded.
|
|
843
|
-
const settings = (await this.config());
|
|
844
|
-
return settings.settings.doorPasswordOnEntry && settings.door
|
|
845
|
-
? `${message}\n${await this.doorCode(sender, settings.door, true)}`
|
|
846
|
-
: message;
|
|
847
|
-
}, bot);
|
|
848
|
-
}
|
|
849
|
-
async withTarget(actor, targetSubject, action, bot) {
|
|
850
|
-
const target = await this.targetSender(actor, targetSubject, bot);
|
|
851
|
-
if (typeof target === "string")
|
|
852
|
-
return target;
|
|
853
|
-
return action(target, target !== actor);
|
|
854
|
-
}
|
|
855
|
-
async adjustTargetBalance(actor, targetSubject, rawAmount, direction, bot) {
|
|
856
|
-
return this.withTarget(actor, targetSubject, async (sender) => {
|
|
857
|
-
const amount = Number(rawAmount);
|
|
858
|
-
if (!Number.isFinite(amount) || amount <= 0)
|
|
859
|
-
return "金额必须大于 0";
|
|
860
|
-
const isAddition = direction === 1;
|
|
861
|
-
await this.client.adjustWalletByIdentity(this.identity(sender), amount * direction, isAddition ? "Koishi 管理员增加余额" : "Koishi 管理员扣除余额");
|
|
862
|
-
return `✅ 已为用户 ${formatPlayerReference(sender)}${isAddition ? "增加" : "扣除"} ${formatNumber(amount)} ${(await this.config()).currencyName}`;
|
|
863
|
-
}, bot);
|
|
864
|
-
}
|
|
865
|
-
async overwriteTargetCheckout(actor, targetSubject, rawAmount, rawReason, bot) {
|
|
866
|
-
return this.withTarget(actor, targetSubject, async (sender) => {
|
|
867
|
-
const total = Number(rawAmount);
|
|
868
|
-
if (!Number.isFinite(total) || total < 0)
|
|
869
|
-
return "金额必须为非负数";
|
|
870
|
-
const reason = cleanText(rawReason) || "管理员调价";
|
|
871
|
-
const result = (await this.client.checkoutWithOverrideByIdentity(this.identity(sender), total, reason));
|
|
872
|
-
return this.formatAndNotifyCheckout(result, sender, "✅ 覆盖结账成功 · 结算账单", bot);
|
|
873
|
-
}, bot);
|
|
530
|
+
await this.sendTo(say.to, await this.render(say.message));
|
|
874
531
|
}
|
|
875
532
|
/**
|
|
876
|
-
*
|
|
877
|
-
*
|
|
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.
|
|
878
535
|
*/
|
|
879
|
-
async
|
|
880
|
-
const
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
throw error;
|
|
903
|
-
}
|
|
904
|
-
const seated = state.seats.length;
|
|
905
|
-
const mine = state.seats.find((seat) => seat.mine);
|
|
906
|
-
if (mine?.playing)
|
|
907
|
-
return `已加入 ${table.name},麻将计费已开始。当前 ${seated}/${state.capacity} 人。`;
|
|
908
|
-
return `已加入 ${table.name},当前 ${seated}/${state.capacity} 人,满 ${state.capacity} 人开始计费。`;
|
|
909
|
-
}
|
|
910
|
-
/** Leave the table the player sits at, or the one named. */
|
|
911
|
-
async mahjongLeave(sender, rawTableRef) {
|
|
912
|
-
const tableRef = cleanText(rawTableRef);
|
|
913
|
-
const named = tableRef ? findMahjongTable((await this.config()).mahjongTables, tableRef) : null;
|
|
914
|
-
if (tableRef && !named)
|
|
915
|
-
return `未找到麻将桌「${tableRef}」。可先使用 /麻将列表 查看可用桌位。`;
|
|
916
|
-
const [listing, player] = await Promise.all([this.client.listMahjongTables(), this.resolvePlayer(sender)]);
|
|
917
|
-
const playerId = String(player?.id ?? "");
|
|
918
|
-
const tables = (listing?.tables ?? []);
|
|
919
|
-
const table = tables.find((candidate) => (!named || candidate.id === named.id) && candidate.seats.some((seat) => seat.playerId === playerId));
|
|
920
|
-
if (!table?.id)
|
|
921
|
-
return named ? `你当前不在 ${named.name}。` : "你当前未在任何麻将桌上。";
|
|
922
|
-
const name = table.name || named?.name || table.id;
|
|
923
|
-
const wasPlaying = table.seats.some((seat) => seat.playerId === playerId && seat.playing);
|
|
924
|
-
let result;
|
|
925
|
-
try {
|
|
926
|
-
result = (await this.client.mahjongByIdentity(this.identity(sender), table.id, "leave"));
|
|
927
|
-
}
|
|
928
|
-
catch (error) {
|
|
929
|
-
if (!(error instanceof PrismBotClientError))
|
|
930
|
-
throw error;
|
|
931
|
-
if (error.code === "MAHJONG_TABLE_NOT_FOUND")
|
|
932
|
-
return "你当前未在任何麻将桌上。";
|
|
933
|
-
const message = platformMessage(error);
|
|
934
|
-
if (message)
|
|
935
|
-
return `下桌失败,${message}`;
|
|
936
|
-
throw error;
|
|
937
|
-
}
|
|
938
|
-
const state = result.mahjong;
|
|
939
|
-
// Getting up does not check out: what still bills is said, so leaving the shop means /logout.
|
|
940
|
-
const remaining = Array.isArray(result.billing?.remaining)
|
|
941
|
-
? result.billing.remaining.filter((plan) => typeof plan === "string" && plan)
|
|
942
|
-
: [];
|
|
943
|
-
return `已离开 ${name}${wasPlaying ? ",麻将计费已停止" : ""}。当前还剩 ${state.seats.length}/${state.capacity} 人。`
|
|
944
|
-
+ (remaining.length ? `\n仍在计费:${remaining.join("、")}` : "");
|
|
945
|
-
}
|
|
946
|
-
async listMahjongTables() {
|
|
947
|
-
const result = (await this.client.listMahjongTables());
|
|
948
|
-
const tables = (result?.tables ?? []);
|
|
949
|
-
if (tables.length === 0)
|
|
950
|
-
return "当前没有配置任何麻将机。";
|
|
951
|
-
const lines = [`🀄️ 麻将机列表(${tables.length} 台)`];
|
|
952
|
-
for (const table of tables) {
|
|
953
|
-
const playing = table.seats.filter((seat) => seat.playing).length;
|
|
954
|
-
const waiting = table.seats.length - playing;
|
|
955
|
-
const statuses = [
|
|
956
|
-
...(playing > 0 ? [`游玩中 ${playing}/${table.capacity}`] : []),
|
|
957
|
-
...(waiting > 0 ? [`等位 ${waiting}/${table.capacity}`] : []),
|
|
958
|
-
];
|
|
959
|
-
const aliases = table.aliases ?? [];
|
|
960
|
-
lines.push(`- ${table.name}|别名:${aliases.length > 0 ? aliases.join("、") : "无"}|${statuses.join(";") || "空闲"}`);
|
|
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;
|
|
555
|
+
}
|
|
556
|
+
catch {
|
|
557
|
+
// The platform's name will do.
|
|
558
|
+
}
|
|
961
559
|
}
|
|
962
|
-
return
|
|
963
|
-
}
|
|
964
|
-
async billing(sender) {
|
|
965
|
-
const result = (await this.client.previewCheckoutByIdentity(this.identity(sender)));
|
|
966
|
-
return this.formatCheckoutPreview(result, sender, "【结算账单】", true);
|
|
560
|
+
return player.displayName || identity?.subject || player.playerId || "未知玩家";
|
|
967
561
|
}
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
const key = `${sender.provider}:${sender.id}`;
|
|
972
|
-
const existing = this.logoutInFlight.get(key);
|
|
973
|
-
if (existing)
|
|
974
|
-
return existing;
|
|
975
|
-
const task = this.performLogout(sender, bot);
|
|
976
|
-
this.logoutInFlight.set(key, task);
|
|
562
|
+
/* ------------------------- the bot's own commands ------------------------ */
|
|
563
|
+
async versions() {
|
|
564
|
+
let backend = "不可用";
|
|
977
565
|
try {
|
|
978
|
-
|
|
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;
|
|
573
|
+
}
|
|
979
574
|
}
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
this.logoutInFlight.delete(key);
|
|
575
|
+
catch {
|
|
576
|
+
// The Bot version remains useful when the backend is offline or too old.
|
|
983
577
|
}
|
|
984
|
-
|
|
985
|
-
async performLogout(sender, bot) {
|
|
986
|
-
const result = (await this.client.confirmCheckoutByIdentity(this.identity(sender), false));
|
|
987
|
-
return this.formatAndNotifyCheckout(result, sender, "✅ 退场成功 · 结算账单", bot);
|
|
988
|
-
}
|
|
989
|
-
async formatAndNotifyCheckout(result, sender, title, bot) {
|
|
990
|
-
const settlement = result.playerSettlement;
|
|
991
|
-
const records = result.settlements;
|
|
992
|
-
const checkoutAdjustments = result.checkoutAdjustments;
|
|
993
|
-
const pricingCapAdjustments = result.pricingCapAdjustments;
|
|
994
|
-
const checkoutAdjustmentKeys = new Set(checkoutAdjustments.map(adjustmentKey));
|
|
995
|
-
const pricingCapAdjustmentKeys = new Set(pricingCapAdjustments.map(adjustmentKey));
|
|
996
|
-
const sessionPreviews = records.map((rec) => {
|
|
997
|
-
const s = rec.settlement;
|
|
998
|
-
const sessionAdjustments = rec.adjustments.filter((adjustment) => {
|
|
999
|
-
const key = adjustmentKey(adjustment);
|
|
1000
|
-
return !checkoutAdjustmentKeys.has(key) &&
|
|
1001
|
-
!pricingCapAdjustmentKeys.has(key) &&
|
|
1002
|
-
!isPricingCapAdjustment(adjustment);
|
|
1003
|
-
});
|
|
1004
|
-
const sessionSubtotal = toNumber(s.subtotal);
|
|
1005
|
-
return {
|
|
1006
|
-
sessionId: s.sessionId,
|
|
1007
|
-
label: s.label,
|
|
1008
|
-
startedAt: s.startedAt,
|
|
1009
|
-
endedAt: s.endedAt,
|
|
1010
|
-
status: "closed",
|
|
1011
|
-
subtotal: sessionSubtotal,
|
|
1012
|
-
total: sessionSubtotal + sessionAdjustments.reduce((sum, adjustment) => sum + toNumber(adjustment?.amount ?? 0), 0),
|
|
1013
|
-
chargeItems: rec.chargeItems,
|
|
1014
|
-
adjustments: sessionAdjustments,
|
|
1015
|
-
};
|
|
1016
|
-
});
|
|
1017
|
-
const synthetic = {
|
|
1018
|
-
settlementPreview: {
|
|
1019
|
-
playerId: settlement.playerId,
|
|
1020
|
-
subtotal: settlement.subtotal,
|
|
1021
|
-
total: settlement.total,
|
|
1022
|
-
},
|
|
1023
|
-
sessionPreviews,
|
|
1024
|
-
chargeItems: result.chargeItems,
|
|
1025
|
-
checkoutAdjustments,
|
|
1026
|
-
pricingCapAdjustments,
|
|
1027
|
-
globalCapWindows: result.globalCapWindows,
|
|
1028
|
-
wallet: result.wallet,
|
|
1029
|
-
};
|
|
1030
|
-
const receipt = await this.formatCheckoutPreview(synthetic, sender, title, false);
|
|
1031
|
-
// Staff reachable through this adapter get the receipt privately, when the bot's settings say so.
|
|
1032
|
-
const config = await this.config();
|
|
1033
|
-
const channelIds = config.settings.receiptsToStaff
|
|
1034
|
-
? [...new Set(config.staff.filter((identity) => identity.provider === sender.provider).map((identity) => `private:${identity.subject}`))]
|
|
1035
|
-
: [];
|
|
1036
|
-
if (channelIds.length > 0 && bot?.broadcast)
|
|
1037
|
-
await bot.broadcast(channelIds, receipt);
|
|
1038
|
-
return receipt;
|
|
1039
|
-
}
|
|
1040
|
-
async wallet(sender) {
|
|
1041
|
-
const result = (await this.client.getWalletByIdentity(this.identity(sender)));
|
|
1042
|
-
return formatWallet(result.wallet, (await this.config()).currencyName);
|
|
578
|
+
return ["PRiSM 版本信息", `Bot:${exports.version}`, `后端:${backend}`].join("\n");
|
|
1043
579
|
}
|
|
1044
580
|
/**
|
|
1045
581
|
* The wallet query over plain HTTP. The first request usually has to open a
|
|
1046
582
|
* connection (DNS, TCP, TLS), so it is reported apart from the reused ones.
|
|
1047
583
|
*/
|
|
1048
|
-
async benchmarkApi(
|
|
584
|
+
async benchmarkApi(context, rawCount) {
|
|
1049
585
|
const count = benchmarkCount(rawCount);
|
|
1050
586
|
if (count === null)
|
|
1051
587
|
return "次数须为 1 到 10 的整数。";
|
|
1052
|
-
const
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
const [first, ...rest] = timings;
|
|
1056
|
-
return [
|
|
1057
|
-
`📡 API 测速(HTTP,钱包查询 ${count} 次)`,
|
|
1058
|
-
`首次:${Math.round(first.ms)} ms(含建立连接)`,
|
|
1059
|
-
...(rest.length ? [`之后:${spread(rest.map((timing) => timing.ms))}`] : []),
|
|
1060
|
-
...serverLine(timings),
|
|
1061
|
-
...(first.colo ? [`节点:${first.colo}`] : []),
|
|
1062
|
-
].join("\n");
|
|
1063
|
-
}
|
|
1064
|
-
/** Heartbeats (the network alone) and the same wallet query over the platform connection. */
|
|
1065
|
-
async benchmarkWs(sender, rawCount) {
|
|
1066
|
-
const count = benchmarkCount(rawCount);
|
|
1067
|
-
if (count === null)
|
|
1068
|
-
return "次数须为 1 到 10 的整数。";
|
|
1069
|
-
const pings = [];
|
|
1070
|
-
for (let index = 0; index < count; index++)
|
|
1071
|
-
pings.push(await this.client.pingSocket());
|
|
1072
|
-
const timings = [];
|
|
1073
|
-
for (let index = 0; index < count; index++)
|
|
1074
|
-
timings.push(await this.client.timeWalletOverSocket(this.identity(sender)));
|
|
1075
|
-
return [
|
|
1076
|
-
`📡 WS 测速(${count} 次)`,
|
|
1077
|
-
`心跳:${spread(pings)}`,
|
|
1078
|
-
`钱包查询:${spread(timings.map((timing) => timing.ms))}`,
|
|
1079
|
-
...serverLine(timings),
|
|
1080
|
-
].join("\n");
|
|
1081
|
-
}
|
|
1082
|
-
async versions() {
|
|
1083
|
-
let backendVersion = "不可用";
|
|
1084
|
-
try {
|
|
1085
|
-
backendVersion = formatReleaseVersion(await this.client.getVersion());
|
|
1086
|
-
}
|
|
1087
|
-
catch {
|
|
1088
|
-
// The Bot version remains useful when the backend is offline or too old.
|
|
1089
|
-
}
|
|
1090
|
-
return [
|
|
1091
|
-
"PRiSM 版本信息",
|
|
1092
|
-
`Bot:${exports.version}`,
|
|
1093
|
-
`后端:${backendVersion}`,
|
|
1094
|
-
].join("\n");
|
|
1095
|
-
}
|
|
1096
|
-
async items(sender) {
|
|
1097
|
-
const result = (await this.client.getAssetsByIdentity(this.identity(sender)));
|
|
1098
|
-
const holdings = result.holdings;
|
|
1099
|
-
if (holdings.length === 0)
|
|
1100
|
-
return "您当前没有任何物品。";
|
|
1101
|
-
return ["🎒 --- 您拥有的物品 ---", ...holdings.map(formatInventoryItem)].join("\n");
|
|
1102
|
-
}
|
|
1103
|
-
async history(sender) {
|
|
1104
|
-
const result = (await this.client.getSessionHistoryByIdentity(this.identity(sender)));
|
|
1105
|
-
return formatHistory(result.sessions, (await this.config()).currencyName);
|
|
1106
|
-
}
|
|
1107
|
-
/** Open the door the bot's settings name. */
|
|
1108
|
-
async lock(sender) {
|
|
1109
|
-
const door = (await this.config()).door;
|
|
1110
|
-
if (!door)
|
|
1111
|
-
return "🔑 本店还没有设置 Bot 开的门";
|
|
1112
|
-
return this.doorCode(sender, door, false);
|
|
1113
|
-
}
|
|
1114
|
-
/**
|
|
1115
|
-
* The door code, or why there is none. `onEntry` marks the copy that rides
|
|
1116
|
-
* along with a successful entry: there the failure is said in one line and
|
|
1117
|
-
* never takes the entry down with it.
|
|
1118
|
-
*/
|
|
1119
|
-
async doorCode(sender, door, onEntry) {
|
|
588
|
+
const from = await this.sender(context);
|
|
589
|
+
if (!from)
|
|
590
|
+
return "无法获取发送人的平台身份";
|
|
1120
591
|
try {
|
|
1121
|
-
const
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
}
|
|
1133
|
-
const password = cleanText(result?.action?.payload?.temporaryPassword);
|
|
1134
|
-
if (!password)
|
|
1135
|
-
return onEntry ? "🔑 门锁临时密码没有生成,可以在入场后用 lock 再取一次" : "🔑 临时门锁密码生成失败,请稍后再试";
|
|
1136
|
-
return `🔑 临时门锁密码:${password}\n有效期:3 分钟`;
|
|
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");
|
|
1137
603
|
}
|
|
1138
604
|
catch (error) {
|
|
1139
|
-
|
|
1140
|
-
return onEntry ? "🔑 门锁临时密码没有生成,可以在入场后用 lock 再取一次" : `🔑 开门失败,${deviceActionFailureReason(error)}`;
|
|
605
|
+
return benchmarkFailure(error);
|
|
1141
606
|
}
|
|
1142
607
|
}
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
if (!deviceRef)
|
|
1152
|
-
return commandUsage("prism_off");
|
|
1153
|
-
return this.power(sender, deviceRef, "off");
|
|
1154
|
-
}
|
|
1155
|
-
async coin(sender, rawDeviceRef, rawCount) {
|
|
1156
|
-
const deviceRef = cleanText(rawDeviceRef);
|
|
1157
|
-
if (!deviceRef)
|
|
1158
|
-
return commandUsage("prism_coin");
|
|
1159
|
-
const { value, error } = parsePositiveInt(rawCount, "prism_coin", "数量", 1);
|
|
1160
|
-
if (error)
|
|
1161
|
-
return error;
|
|
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 "无法获取发送人的平台身份";
|
|
1162
616
|
try {
|
|
1163
|
-
const
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
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 });
|
|
1172
627
|
}
|
|
1173
|
-
|
|
1174
|
-
|
|
628
|
+
return [
|
|
629
|
+
`📡 WS 测速(${count} 次)`,
|
|
630
|
+
`心跳:${spread(pings)}`,
|
|
631
|
+
`钱包查询:${spread(timings.map((timing) => timing.ms))}`,
|
|
632
|
+
...serverLine(timings),
|
|
633
|
+
].join("\n");
|
|
1175
634
|
}
|
|
1176
635
|
catch (error) {
|
|
1177
|
-
|
|
1178
|
-
return `投币失败,${deviceActionFailureReason(error)}`;
|
|
636
|
+
return benchmarkFailure(error);
|
|
1179
637
|
}
|
|
1180
638
|
}
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
this.logDeviceCommandFailure(result);
|
|
1193
|
-
return `刷卡失败,${failure}`;
|
|
1194
|
-
}
|
|
1195
|
-
const label = deviceCommandLabel(result) || deviceRef;
|
|
1196
|
-
return `💳 ${label} 刷卡成功`;
|
|
1197
|
-
}
|
|
1198
|
-
catch (error) {
|
|
1199
|
-
this.logCommandError(error);
|
|
1200
|
-
return `刷卡失败,${deviceActionFailureReason(error)}`;
|
|
1201
|
-
}
|
|
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 };
|
|
1202
650
|
}
|
|
1203
|
-
|
|
1204
|
-
|
|
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();
|
|
1205
657
|
if (!code)
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
const grantedAssets = result.grantedAssets;
|
|
1209
|
-
if (grantedAssets.length === 0)
|
|
1210
|
-
return "兑换成功,但没有获得任何物品。";
|
|
1211
|
-
return ["✅ 兑换成功!您获得了以下物品:", ...grantedAssets.map(formatRedeemedItem)].join("\n");
|
|
1212
|
-
}
|
|
1213
|
-
/**
|
|
1214
|
-
* Who is in the shop, as the platform lists them: every player playing or
|
|
1215
|
-
* billing, each once, at the resource they occupy (with its head count and
|
|
1216
|
-
* capacity) or their most specific plan. With a name, everyone on that
|
|
1217
|
-
* resource or billing that plan.
|
|
1218
|
-
*/
|
|
1219
|
-
async listActiveSessions(sender, name) {
|
|
1220
|
-
const wanted = cleanText(name);
|
|
1221
|
-
let roster;
|
|
1222
|
-
try {
|
|
1223
|
-
roster = (await this.client.roster(wanted || undefined));
|
|
1224
|
-
}
|
|
1225
|
-
catch (error) {
|
|
1226
|
-
if (wanted && error instanceof PrismBotClientError && error.code === "ROSTER_TARGET_NOT_FOUND")
|
|
1227
|
-
return `找不到「${wanted}」`;
|
|
1228
|
-
throw error;
|
|
1229
|
-
}
|
|
1230
|
-
const groups = [];
|
|
1231
|
-
for (const group of roster.groups ?? []) {
|
|
1232
|
-
const players = [];
|
|
1233
|
-
for (const member of group.members ?? []) {
|
|
1234
|
-
const player = {
|
|
1235
|
-
playerId: member.playerId,
|
|
1236
|
-
sessions: [{ playerDisplayName: member.displayName ?? undefined, identities: member.identities ?? [] }],
|
|
1237
|
-
};
|
|
1238
|
-
player.displayName = await this.displayNameForPlayer(player, sender.provider);
|
|
1239
|
-
players.push(player);
|
|
1240
|
-
}
|
|
1241
|
-
groups.push({ label: group.name, ...(group.kind === "resource" ? { capacity: group.capacity } : {}), players });
|
|
1242
|
-
}
|
|
1243
|
-
const [only] = groups;
|
|
1244
|
-
if (wanted && only && !only.players.length) {
|
|
1245
|
-
return only.capacity !== undefined ? `${only.label} ( 0/${only.capacity} )` : `${only.label} ( 0人 )`;
|
|
1246
|
-
}
|
|
1247
|
-
if (wanted)
|
|
1248
|
-
return formatPlayerGroups(groups);
|
|
1249
|
-
// The whole shop: players on a resource are listed there, everyone else together,
|
|
1250
|
-
// whatever plan they bill. Asking for a plan by name still lists that plan.
|
|
1251
|
-
const onResources = groups.filter((group) => group.capacity !== undefined);
|
|
1252
|
-
const others = groups.filter((group) => group.capacity === undefined).flatMap((group) => group.players);
|
|
1253
|
-
return formatPlayerGroups([...onResources, ...(others.length ? [{ label: OTHER_PLAYERS_LABEL, players: others }] : [])]);
|
|
1254
|
-
}
|
|
1255
|
-
async listDeviceStates(rawAlias) {
|
|
1256
|
-
const alias = cleanText(rawAlias);
|
|
1257
|
-
const result = (await this.client.listDeviceStates());
|
|
1258
|
-
const states = (result?.deviceStates ?? []);
|
|
1259
|
-
if (states.length === 0)
|
|
1260
|
-
return "没有找到任何设备状态。";
|
|
1261
|
-
if (alias) {
|
|
1262
|
-
const matched = states.find((d) => d.deviceId === alias || d.label === alias || d.aliases?.some((value) => value.trim().toLowerCase() === alias.toLowerCase()));
|
|
1263
|
-
if (!matched)
|
|
1264
|
-
return `找不到设备: ${alias}`;
|
|
1265
|
-
const stateVal = normalizeDeviceState(matched.state);
|
|
1266
|
-
return `${matched.label || matched.deviceId}: ${stateVal}`;
|
|
1267
|
-
}
|
|
1268
|
-
return states
|
|
1269
|
-
.map((d) => `${d.label || d.deviceId}: ${normalizeDeviceState(d.state)}`)
|
|
1270
|
-
.join("\n");
|
|
1271
|
-
}
|
|
1272
|
-
/** Keep a running device from being switched off as idle; never switches one on. */
|
|
1273
|
-
async keep(sender, deviceRef) {
|
|
1274
|
-
try {
|
|
1275
|
-
const result = await this.client.requestDeviceCommandByIdentity(this.identity(sender), {
|
|
1276
|
-
type: "power.keep",
|
|
1277
|
-
target: { kind: "facility", ref: deviceRef },
|
|
1278
|
-
});
|
|
1279
|
-
if (this.getCommandFailureMessage(result)) {
|
|
1280
|
-
this.logDeviceCommandFailure(result);
|
|
1281
|
-
return `延迟失败,${deviceCommandFailureReason(result)}`;
|
|
1282
|
-
}
|
|
1283
|
-
return `✅ ${result.action.payload.deviceLabel} 已延迟关机`;
|
|
1284
|
-
}
|
|
1285
|
-
catch (error) {
|
|
1286
|
-
this.logCommandError(error);
|
|
1287
|
-
return `延迟失败,${powerFailureReason(error)}`;
|
|
1288
|
-
}
|
|
1289
|
-
}
|
|
1290
|
-
/* ---------------------------- helpers ---------------------------------- */
|
|
1291
|
-
async power(sender, deviceRef, state) {
|
|
1292
|
-
const operation = state === "on" ? "启动" : "关闭";
|
|
1293
|
-
const config = await this.config();
|
|
1294
|
-
const staffOverride = state === "off" && config.settings.powerOffStaffOnly;
|
|
1295
|
-
if (staffOverride && !this.isStaff(config, sender)) {
|
|
1296
|
-
return `${operation}失败,权限不足`;
|
|
1297
|
-
}
|
|
1298
|
-
try {
|
|
1299
|
-
const result = await this.client.requestDeviceCommandByIdentity(this.identity(sender), {
|
|
1300
|
-
type: state === "on" ? "power.on" : "power.off",
|
|
1301
|
-
target: { kind: "facility", ref: deviceRef },
|
|
1302
|
-
payload: { state },
|
|
1303
|
-
}, staffOverride ? { staffOverride: true } : undefined);
|
|
1304
|
-
const failure = this.getCommandFailureMessage(result);
|
|
1305
|
-
if (failure) {
|
|
1306
|
-
this.logDeviceCommandFailure(result);
|
|
1307
|
-
return `${operation}失败,${deviceCommandFailureReason(result)}`;
|
|
1308
|
-
}
|
|
1309
|
-
const deviceLabel = result.action.payload.deviceLabel;
|
|
1310
|
-
return state === "on" ? `✅ ${deviceLabel} 启动成功` : `🛑 ${deviceLabel} 关闭成功`;
|
|
1311
|
-
}
|
|
1312
|
-
catch (error) {
|
|
1313
|
-
this.logCommandError(error);
|
|
1314
|
-
return `${operation}失败,${powerFailureReason(error)}`;
|
|
1315
|
-
}
|
|
1316
|
-
}
|
|
1317
|
-
/** Whether the action failed; the message itself is logged, never shown as it is. */
|
|
1318
|
-
getCommandFailureMessage(result) {
|
|
1319
|
-
const action = result?.action;
|
|
1320
|
-
// `pending` here is an unanswered request (a timeout): it counts as not done.
|
|
1321
|
-
if (action?.status === "expired" || action?.status === "rejected" || action?.status === "pending") {
|
|
1322
|
-
return action.payload?.executorFailure?.message || "命令执行被拒绝或超时";
|
|
1323
|
-
}
|
|
1324
|
-
return null;
|
|
1325
|
-
}
|
|
1326
|
-
async resolvePlatformName(subject, provider) {
|
|
1327
|
-
if (!this.options.resolveDisplayName)
|
|
1328
|
-
return null;
|
|
1329
|
-
try {
|
|
1330
|
-
return (await this.options.resolveDisplayName(subject, provider)) ?? null;
|
|
1331
|
-
}
|
|
1332
|
-
catch {
|
|
1333
|
-
return null;
|
|
1334
|
-
}
|
|
1335
|
-
}
|
|
1336
|
-
async displayNameForPlayer(player, provider) {
|
|
1337
|
-
let identitySubject;
|
|
1338
|
-
for (const session of player.sessions) {
|
|
1339
|
-
const subject = findSubjectForSession(session, provider);
|
|
1340
|
-
if (!subject)
|
|
1341
|
-
continue;
|
|
1342
|
-
identitySubject ??= subject;
|
|
1343
|
-
const platformName = await this.resolvePlatformName(subject, provider);
|
|
1344
|
-
if (platformName)
|
|
1345
|
-
return platformName;
|
|
1346
|
-
}
|
|
1347
|
-
return player.sessions.find((session) => session.playerDisplayName)?.playerDisplayName
|
|
1348
|
-
|| identitySubject
|
|
1349
|
-
|| player.displayName
|
|
1350
|
-
|| player.playerId
|
|
1351
|
-
|| "未知玩家";
|
|
1352
|
-
}
|
|
1353
|
-
async resolvePlayerDisplay(sender, playerId) {
|
|
1354
|
-
if (!sender)
|
|
1355
|
-
return playerId || "未知玩家";
|
|
1356
|
-
const platformName = await this.resolvePlatformName(sender.id, sender.provider);
|
|
1357
|
-
const name = platformName
|
|
1358
|
-
|| (sender.name && sender.name !== sender.id ? sender.name : "")
|
|
1359
|
-
|| "未知昵称";
|
|
1360
|
-
return `玩家:${name}(${sender.provider}:${sender.id})`;
|
|
1361
|
-
}
|
|
1362
|
-
async resolvePlayer(sender) {
|
|
1363
|
-
return (await this.client.resolveOrRegisterIdentity(this.identity(sender)));
|
|
1364
|
-
}
|
|
1365
|
-
identity(sender) {
|
|
1366
|
-
return {
|
|
1367
|
-
provider: sender.provider,
|
|
1368
|
-
subject: sender.id,
|
|
1369
|
-
displayName: sender.name || `${sender.provider} ${sender.id}`,
|
|
1370
|
-
};
|
|
1371
|
-
}
|
|
1372
|
-
async targetSender(actor, targetSubject, bot) {
|
|
1373
|
-
const raw = cleanText(targetSubject);
|
|
1374
|
-
if (!raw)
|
|
1375
|
-
return actor;
|
|
1376
|
-
const separator = raw.indexOf(":");
|
|
1377
|
-
const provider = separator > 0 ? raw.slice(0, separator).toLowerCase() : actor.provider;
|
|
1378
|
-
const subject = separator > 0 ? raw.slice(separator + 1) : raw;
|
|
1379
|
-
if (provider !== actor.provider)
|
|
1380
|
-
return "请在目标平台使用该命令";
|
|
1381
|
-
if (!subject)
|
|
1382
|
-
return "无法获取目标平台身份";
|
|
1383
|
-
// Acting for another player is for staff, and only when the bot's settings allow it.
|
|
1384
|
-
const config = await this.config();
|
|
1385
|
-
if (!config.settings.staffCommands)
|
|
1386
|
-
return "员工命令未启用";
|
|
1387
|
-
if (!this.isStaff(config, actor))
|
|
1388
|
-
return "权限不足";
|
|
1389
|
-
try {
|
|
1390
|
-
const user = await bot?.getUser?.(subject);
|
|
1391
|
-
return { id: subject, name: user?.name || subject, provider };
|
|
1392
|
-
}
|
|
1393
|
-
catch {
|
|
1394
|
-
return { id: subject, name: subject, provider };
|
|
1395
|
-
}
|
|
1396
|
-
}
|
|
1397
|
-
async formatCheckoutPreview(result, sender, title = "【结算账单】", isPreview) {
|
|
1398
|
-
const currency = (await this.config()).currencyName;
|
|
1399
|
-
const preview = result.settlementPreview;
|
|
1400
|
-
const playerId = preview.playerId;
|
|
1401
|
-
const subtotal = preview.subtotal;
|
|
1402
|
-
const total = preview.total;
|
|
1403
|
-
const previewedAt = (0, display_time_js_1.parseDateTime)(preview.previewedAt);
|
|
1404
|
-
const sessionPreviews = result.sessionPreviews;
|
|
1405
|
-
const pricingCapAdjustments = result.pricingCapAdjustments;
|
|
1406
|
-
const checkoutAdjustments = result.checkoutAdjustments;
|
|
1407
|
-
const wallet = result.wallet;
|
|
1408
|
-
const balanceBefore = toNumber(wallet?.balanceBefore ?? 0);
|
|
1409
|
-
const balanceAfter = toNumber(wallet?.balanceAfter ?? 0);
|
|
1410
|
-
const lines = [];
|
|
1411
|
-
lines.push(title);
|
|
1412
|
-
lines.push(await this.resolvePlayerDisplay(sender, playerId));
|
|
1413
|
-
const hasNonZeroSessionTotal = sessionPreviews.some((session) => toNumber(session?.total ?? 0) !== 0);
|
|
1414
|
-
const hasNonZeroAdjustment = hasAdjustmentEntries(checkoutAdjustments, sessionPreviews);
|
|
1415
|
-
if (!hasNonZeroSessionTotal && !hasNonZeroAdjustment) {
|
|
1416
|
-
lines.push("");
|
|
1417
|
-
lines.push("本次未产生费用");
|
|
1418
|
-
lines.push(`余额:${formatNumber(isPreview ? balanceBefore : balanceAfter)}${currency}`);
|
|
1419
|
-
return lines.join("\n");
|
|
1420
|
-
}
|
|
1421
|
-
const validStarts = sessionPreviews.map(s => s.startedAt).filter(value => (0, display_time_js_1.parseDateTime)(value));
|
|
1422
|
-
const validEnds = sessionPreviews.map(s => s.endedAt || (s.status === "active" ? preview.previewedAt : null)).filter(value => (0, display_time_js_1.parseDateTime)(value));
|
|
1423
|
-
if (validStarts.length > 0) {
|
|
1424
|
-
const overallStart = validStarts.reduce((a, b) => Date.parse(a) < Date.parse(b) ? a : b);
|
|
1425
|
-
const overallEnd = validEnds.length > 0 ? validEnds.reduce((a, b) => Date.parse(a) > Date.parse(b) ? a : b) : now(this.options).toISOString();
|
|
1426
|
-
const offsets = [...new Set([(0, display_time_js_1.apiOffsetLabel)(overallStart), (0, display_time_js_1.apiOffsetLabel)(overallEnd)])].join(" / ");
|
|
1427
|
-
lines.push(`⏰ 游玩时间:${(0, display_time_js_1.formatHM)(overallStart)}–${(0, display_time_js_1.formatHM)(overallEnd)}(${offsets})`);
|
|
1428
|
-
}
|
|
1429
|
-
for (const sPrev of sessionPreviews) {
|
|
1430
|
-
const label = sPrev?.label === "entry" ? DEFAULT_PLAN_LABEL : sPrev?.label || "计时区间";
|
|
1431
|
-
const startDt = (0, display_time_js_1.parseDateTime)(sPrev?.startedAt);
|
|
1432
|
-
const endDt = sessionDisplayEnd(sPrev, previewedAt);
|
|
1433
|
-
const status = sPrev?.status ?? "active";
|
|
1434
|
-
const sTotal = toNumber(sPrev?.total ?? 0);
|
|
1435
|
-
lines.push("");
|
|
1436
|
-
lines.push(label);
|
|
1437
|
-
if (startDt && endDt) {
|
|
1438
|
-
const minutes = Math.floor((endDt.getTime() - startDt.getTime()) / 60_000);
|
|
1439
|
-
lines.push(`游玩时段:${(0, display_time_js_1.formatHM)(sPrev.startedAt)}-${(0, display_time_js_1.formatHM)(sPrev.endedAt || preview.previewedAt || endDt.toISOString())}`);
|
|
1440
|
-
lines.push(`游玩时长:${formatDurationValue(minutes)}|计价:${formatNumber(sTotal)}${currency}`);
|
|
1441
|
-
}
|
|
1442
|
-
else if (startDt) {
|
|
1443
|
-
lines.push(`入场:${(0, display_time_js_1.formatHM)(sPrev.startedAt)} (${status === "active" ? "计费中" : "已关闭"})`);
|
|
1444
|
-
}
|
|
1445
|
-
const sessionAdjustments = (sPrev?.adjustments ?? []);
|
|
1446
|
-
for (const adj of sessionAdjustments) {
|
|
1447
|
-
const amount = toNumber(adj.amount);
|
|
1448
|
-
if (amount === 0)
|
|
1449
|
-
continue;
|
|
1450
|
-
const adjLabel = adj.label || adj.source || "优惠";
|
|
1451
|
-
lines.push(` └ ${adjLabel}:${formatNumber(amount)}${currency}`);
|
|
1452
|
-
}
|
|
1453
|
-
}
|
|
1454
|
-
const cappedWindows = result.globalCapWindows.filter((window) => toNumber(window?.currentAmount) !== toNumber(window?.amountApplied));
|
|
1455
|
-
if (cappedWindows.length > 0) {
|
|
1456
|
-
lines.push("");
|
|
1457
|
-
lines.push("封顶:");
|
|
1458
|
-
for (const window of cappedWindows) {
|
|
1459
|
-
const label = window.ruleLabel || "封顶时段";
|
|
1460
|
-
const startedAt = (0, display_time_js_1.parseDateTime)(window.windowStartedAt);
|
|
1461
|
-
const datedLabel = startedAt ? `${(0, display_time_js_1.formatMD)(window.windowStartedAt)} ${label}` : label;
|
|
1462
|
-
const currentAmount = toNumber(window.currentAmount);
|
|
1463
|
-
const amountApplied = toNumber(window.amountApplied);
|
|
1464
|
-
const priceCap = toNumber(window.priceCap);
|
|
1465
|
-
const paidBefore = toNumber(window.paidBefore);
|
|
1466
|
-
const details = [`上限${formatNumber(priceCap)}`];
|
|
1467
|
-
if (paidBefore > 0)
|
|
1468
|
-
details.push(`已计${formatNumber(paidBefore)}`);
|
|
1469
|
-
lines.push(`- ${datedLabel}:${formatNumber(currentAmount)} → ${formatNumber(amountApplied)}${currency}(${details.join(",")})`);
|
|
1470
|
-
}
|
|
1471
|
-
}
|
|
1472
|
-
const visibleCheckoutAdjustments = checkoutAdjustments.filter((adjustment) => {
|
|
1473
|
-
const amount = toNumber(adjustment.amount);
|
|
1474
|
-
const isOverride = cleanText(adjustment?.source).startsWith("staff.override:");
|
|
1475
|
-
return amount !== 0 && !isOverride;
|
|
1476
|
-
});
|
|
1477
|
-
lines.push("");
|
|
1478
|
-
const cappedTotal = Math.max(0, toNumber(subtotal) + pricingCapAdjustments.reduce((sum, adjustment) => sum + toNumber(adjustment?.amount ?? 0), 0));
|
|
1479
|
-
lines.push(`计费总价:${formatNumber(cappedTotal)}${currency}`);
|
|
1480
|
-
const hasManualAdjustment = checkoutAdjustments.some((adjustment) => cleanText(adjustment?.source).startsWith("staff.override:"));
|
|
1481
|
-
if (visibleCheckoutAdjustments.length > 0) {
|
|
1482
|
-
lines.push("");
|
|
1483
|
-
for (const adjustment of visibleCheckoutAdjustments) {
|
|
1484
|
-
const amount = toNumber(adjustment.amount);
|
|
1485
|
-
const label = adjustment.label || adjustment.source || "优惠";
|
|
1486
|
-
lines.push(`${label}:${formatNumber(amount)}${currency}`);
|
|
1487
|
-
}
|
|
1488
|
-
}
|
|
1489
|
-
if (hasNonZeroAdjustment) {
|
|
1490
|
-
if (visibleCheckoutAdjustments.length > 0)
|
|
1491
|
-
lines.push("");
|
|
1492
|
-
lines.push(`${hasManualAdjustment ? "调整后价格" : "优惠后价格"}:${formatNumber(total)}${currency}`);
|
|
1493
|
-
}
|
|
1494
|
-
if (isPreview) {
|
|
1495
|
-
lines.push(`当前余额:${formatNumber(balanceBefore)}${currency}`);
|
|
1496
|
-
lines.push(balanceAfter >= 0
|
|
1497
|
-
? `预计结账后余额:${formatNumber(balanceAfter)}${currency}`
|
|
1498
|
-
: `预计结账后余额:余额不足(还差 ${formatNumber(-balanceAfter)}${currency})`);
|
|
1499
|
-
}
|
|
1500
|
-
else {
|
|
1501
|
-
lines.push(`扣款后余额:${formatNumber(balanceAfter)}${currency}`);
|
|
1502
|
-
}
|
|
1503
|
-
return lines.join("\n");
|
|
1504
|
-
}
|
|
1505
|
-
handleCommandError(error) {
|
|
1506
|
-
this.logCommandError(error);
|
|
1507
|
-
if (error instanceof PrismBotClientError) {
|
|
1508
|
-
const shopCode = this.options.shopCode ?? this.bot?.shop?.code;
|
|
1509
|
-
if (error.code?.startsWith("LOCATION_") && shopCode && this.options.baseUrl) {
|
|
1510
|
-
return `请在网页完成到店校验:${this.options.baseUrl.replace(/\/+$/, "")}/t/${encodeURIComponent(shopCode)}`;
|
|
1511
|
-
}
|
|
1512
|
-
return humanReadableBotError(error);
|
|
1513
|
-
}
|
|
1514
|
-
return genericCommandFailure();
|
|
1515
|
-
}
|
|
1516
|
-
logCommandError(error) {
|
|
1517
|
-
this.logger?.warn("PRiSM Bot command failed", error instanceof PrismBotClientError
|
|
1518
|
-
? (error.originalError ?? error)
|
|
1519
|
-
: error);
|
|
1520
|
-
}
|
|
1521
|
-
logDeviceCommandFailure(result) {
|
|
1522
|
-
const action = result?.action;
|
|
1523
|
-
this.logger?.warn("PRiSM device command failed", action?.payload?.executorFailure ?? action);
|
|
1524
|
-
}
|
|
1525
|
-
}
|
|
1526
|
-
function humanReadableBotError(error) {
|
|
1527
|
-
if (error.code === "INVALID_PLATFORM_IDENTITY")
|
|
1528
|
-
return error.message;
|
|
1529
|
-
if (error.code === "OPERATION_IN_PROGRESS")
|
|
1530
|
-
return "其他操作正在处理中,请稍后再试。";
|
|
1531
|
-
if (error.code === "REDEEM_CODE_NOT_FOUND")
|
|
1532
|
-
return "兑换码无效,请检查后再试。";
|
|
1533
|
-
if (error.code === "REDEEM_CODE_NOT_ACTIVE")
|
|
1534
|
-
return "兑换码尚未生效。";
|
|
1535
|
-
if (error.code === "REDEEM_CODE_EXPIRED" || error.code === "PRESENT_EXPIRED")
|
|
1536
|
-
return "兑换码已过期。";
|
|
1537
|
-
if (error.code === "PRESENT_NOT_ACTIVE" || error.code === "PRESENT_ARCHIVED")
|
|
1538
|
-
return "这份礼物当前无法兑换。";
|
|
1539
|
-
if (error.code === "REDEEM_CODE_MAX_USE_REACHED")
|
|
1540
|
-
return "兑换码已被领完。";
|
|
1541
|
-
if (error.code === "PRESENT_ONCE_PER_PLAYER_REDEEMED")
|
|
1542
|
-
return "您已经领取过这份礼物,无需重复兑换。";
|
|
1543
|
-
if (error.code === "PRESENT_GRANT_LIMIT_REACHED")
|
|
1544
|
-
return "您已达到这份礼物的领取上限。";
|
|
1545
|
-
if (error.code === "BOT_DISABLED")
|
|
1546
|
-
return "Bot 已被店铺停用";
|
|
1547
|
-
if (error.code === "BILLING_DISABLED")
|
|
1548
|
-
return BILLING_DISABLED_NOTICE;
|
|
1549
|
-
if (error.code === "RESOURCE_NOT_BILLED")
|
|
1550
|
-
return RESOURCE_NOT_BILLED_NOTICE;
|
|
1551
|
-
if (error.code === "PLAYER_HAS_NO_UNSETTLED_SESSIONS") {
|
|
1552
|
-
return "您当前没有未结算的账单,无需结账。";
|
|
1553
|
-
}
|
|
1554
|
-
if (error.code === "ACTIVE_SESSION_NOT_FOUND") {
|
|
1555
|
-
return "您当前没有进行中的计费场次。";
|
|
1556
|
-
}
|
|
1557
|
-
if (error.code === "DEVICE_COMMAND_REQUIRES_ACTIVE_SESSION") {
|
|
1558
|
-
return "操作失败,玩家未入场";
|
|
1559
|
-
}
|
|
1560
|
-
if (error.code === "PLAYER_IDENTITY_NOT_FOUND") {
|
|
1561
|
-
return "未找到您的玩家身份,请先注册或绑定账号。";
|
|
1562
|
-
}
|
|
1563
|
-
if (error.code === "INSUFFICIENT_BALANCE") {
|
|
1564
|
-
return "余额不足,暂时不能结账。请先充值,或由店员在后台改价后再结账。";
|
|
1565
|
-
}
|
|
1566
|
-
if (error.code === "API_UNREACHABLE")
|
|
1567
|
-
return "操作失败,暂时连不上服务器。";
|
|
1568
|
-
if (error.code === "NETWORK_ERROR" || error.code === "HTTP_0") {
|
|
1569
|
-
return genericCommandFailure();
|
|
1570
|
-
}
|
|
1571
|
-
if (error.code === "API_TIMEOUT") {
|
|
1572
|
-
return genericCommandFailure();
|
|
1573
|
-
}
|
|
1574
|
-
if (error.code === "INVALID_JSON_RESPONSE") {
|
|
1575
|
-
return genericCommandFailure();
|
|
1576
|
-
}
|
|
1577
|
-
if (error.code === "STAFF_TOKEN_REQUIRED") {
|
|
1578
|
-
return genericCommandFailure();
|
|
1579
|
-
}
|
|
1580
|
-
return genericCommandFailure();
|
|
1581
|
-
}
|
|
1582
|
-
function powerFailureReason(error) {
|
|
1583
|
-
if (error instanceof PrismBotClientError) {
|
|
1584
|
-
if (error.code === "DEVICE_COMMAND_REQUIRES_ACTIVE_SESSION")
|
|
1585
|
-
return "玩家未入场";
|
|
1586
|
-
if (error.code === "PLAYER_IDENTITY_NOT_FOUND")
|
|
1587
|
-
return "玩家未注册";
|
|
1588
|
-
if (error.code === "BILLING_DISABLED")
|
|
1589
|
-
return BILLING_DISABLED_NOTICE;
|
|
1590
|
-
if (error.code === "DEVICE_NOT_FOUND")
|
|
1591
|
-
return "没有这个设备";
|
|
1592
|
-
}
|
|
1593
|
-
return "请稍后再试";
|
|
1594
|
-
}
|
|
1595
|
-
function deviceActionFailureReason(error) {
|
|
1596
|
-
if (!(error instanceof PrismBotClientError))
|
|
1597
|
-
return "请稍后再试";
|
|
1598
|
-
if (error.code === "DEVICE_COMMAND_REQUIRES_ACTIVE_SESSION")
|
|
1599
|
-
return "玩家未入场";
|
|
1600
|
-
if (error.code === "DEVICE_NOT_FOUND")
|
|
1601
|
-
return "设备不存在";
|
|
1602
|
-
if (error.code === "SCAN_IDENTITY_NOT_BOUND_TO_PLAYER")
|
|
1603
|
-
return "玩家未绑定 Aime 卡";
|
|
1604
|
-
if (error.code === "COIN_COMMAND_COOLDOWN_ACTIVE")
|
|
1605
|
-
return "投币冷却中,请稍后再试";
|
|
1606
|
-
if (error.code === "BILLING_DISABLED")
|
|
1607
|
-
return BILLING_DISABLED_NOTICE;
|
|
1608
|
-
return "请稍后再试";
|
|
1609
|
-
}
|
|
1610
|
-
/**
|
|
1611
|
-
* What a player may be told about a device that would not act. Only facts about
|
|
1612
|
-
* the device itself — whether it exists, is connected, is off, answered — never
|
|
1613
|
-
* how the shop configured it or what went wrong inside the platform.
|
|
1614
|
-
*/
|
|
1615
|
-
const DEVICE_REASONS = [
|
|
1616
|
-
[/设备不存在|没有找到这个资源/, "没有这个设备"],
|
|
1617
|
-
[/机台未在线|没有在线客户端|设备未连接|直连中继尚未配置/, "设备未连接"],
|
|
1618
|
-
[/设备已关机/, "设备已关机"],
|
|
1619
|
-
[/设备未响应|机台未响应/, "设备没有响应"],
|
|
1620
|
-
];
|
|
1621
|
-
function deviceCommandFailureReason(result) {
|
|
1622
|
-
const action = result?.action;
|
|
1623
|
-
if (!action || (action.status !== "expired" && action.status !== "rejected" && action.status !== "pending"))
|
|
1624
|
-
return null;
|
|
1625
|
-
const message = cleanText(action.payload?.executorFailure?.message);
|
|
1626
|
-
return DEVICE_REASONS.find(([pattern]) => pattern.test(message))?.[1] ?? "操作没有完成,请找店员";
|
|
1627
|
-
}
|
|
1628
|
-
function deviceCommandLabel(result) {
|
|
1629
|
-
return cleanText(result?.action?.payload?.deviceLabel);
|
|
1630
|
-
}
|
|
1631
|
-
function genericCommandFailure() {
|
|
1632
|
-
return "操作失败,请稍后再试。";
|
|
1633
|
-
}
|
|
1634
|
-
function normalizeDeviceState(value) {
|
|
1635
|
-
if (typeof value === "object" && value !== null) {
|
|
1636
|
-
return cleanText(value.state) || "unknown";
|
|
1637
|
-
}
|
|
1638
|
-
const raw = cleanText(value);
|
|
1639
|
-
if (!raw)
|
|
1640
|
-
return "unknown";
|
|
1641
|
-
if (raw.startsWith("{")) {
|
|
1642
|
-
try {
|
|
1643
|
-
const decoded = JSON.parse(raw);
|
|
1644
|
-
return cleanText(decoded?.state) || "unknown";
|
|
1645
|
-
}
|
|
1646
|
-
catch {
|
|
1647
|
-
return raw;
|
|
1648
|
-
}
|
|
1649
|
-
}
|
|
1650
|
-
return raw;
|
|
1651
|
-
}
|
|
1652
|
-
/** The table a player named, by id, name or alias, as the platform matches it. */
|
|
1653
|
-
function findMahjongTable(tables, ref) {
|
|
1654
|
-
const target = ref.trim().toLowerCase();
|
|
1655
|
-
return tables.find((table) => [table.id, table.name, ...table.aliases].some((value) => cleanText(value).toLowerCase() === target)) ?? null;
|
|
1656
|
-
}
|
|
1657
|
-
/** The platform's own message for a refusal, when it gave one; never the fallback naming an HTTP status. */
|
|
1658
|
-
function platformMessage(error) {
|
|
1659
|
-
if (error.status < 400 || error.status >= 500)
|
|
1660
|
-
return null;
|
|
1661
|
-
const message = error.body?.error?.message;
|
|
1662
|
-
return typeof message === "string" && message.trim() ? message.trim() : null;
|
|
1663
|
-
}
|
|
1664
|
-
/**
|
|
1665
|
-
* The bot's settings as the platform sent them. Anything missing takes the
|
|
1666
|
-
* platform's own default, so a newer setting an older platform lacks does no harm.
|
|
1667
|
-
*/
|
|
1668
|
-
function parseBotConfig(value) {
|
|
1669
|
-
const record = (value && typeof value === "object" ? value : {});
|
|
1670
|
-
const settings = (record.settings ?? {});
|
|
1671
|
-
const strings = (list) => (Array.isArray(list) ? list : []).map(cleanText).filter(Boolean);
|
|
1672
|
-
return {
|
|
1673
|
-
bot: { id: cleanText(record.bot?.id), name: cleanText(record.bot?.name) || "Bot" },
|
|
1674
|
-
settings: {
|
|
1675
|
-
playerCommands: settings.playerCommands === "readonly" ? "readonly" : "all",
|
|
1676
|
-
readOnlyNotice: cleanText(settings.readOnlyNotice),
|
|
1677
|
-
staffCommands: settings.staffCommands !== false,
|
|
1678
|
-
powerOffStaffOnly: settings.powerOffStaffOnly === true,
|
|
1679
|
-
receiptsToStaff: settings.receiptsToStaff === true,
|
|
1680
|
-
doorPasswordOnEntry: settings.doorPasswordOnEntry === true,
|
|
1681
|
-
announceChannelIds: strings(settings.announceChannelIds),
|
|
1682
|
-
idleReminderMinutes: Math.max(0, Number(settings.idleReminderMinutes ?? 5) || 0),
|
|
1683
|
-
announceIdle: settings.announceIdle === true,
|
|
1684
|
-
announcePower: settings.announcePower === true,
|
|
1685
|
-
announceStarts: settings.announceStarts === true,
|
|
1686
|
-
announceCards: settings.announceCards === true,
|
|
1687
|
-
announceCoins: settings.announceCoins === true,
|
|
1688
|
-
},
|
|
1689
|
-
billingEnabled: record.billingEnabled !== false,
|
|
1690
|
-
currencyName: cleanText(record.currencyName) || "余额",
|
|
1691
|
-
staff: (Array.isArray(record.staff) ? record.staff : [])
|
|
1692
|
-
.map((identity) => ({ provider: cleanText(identity?.provider).toLowerCase(), subject: cleanText(identity?.subject) }))
|
|
1693
|
-
.filter((identity) => identity.provider && identity.subject),
|
|
1694
|
-
door: record.door?.id ? { id: cleanText(record.door.id), name: cleanText(record.door.name) } : null,
|
|
1695
|
-
mahjongTables: (Array.isArray(record.mahjongTables) ? record.mahjongTables : [])
|
|
1696
|
-
.filter((table) => cleanText(table?.id))
|
|
1697
|
-
.map((table) => ({
|
|
1698
|
-
id: cleanText(table.id),
|
|
1699
|
-
name: cleanText(table.name) || cleanText(table.id),
|
|
1700
|
-
aliases: strings(table.aliases),
|
|
1701
|
-
capacity: Number(table.capacity) || 4,
|
|
1702
|
-
})),
|
|
1703
|
-
};
|
|
1704
|
-
}
|
|
1705
|
-
/** What the shop's default plan is called when the platform gives no plan name. */
|
|
1706
|
-
const DEFAULT_PLAN_LABEL = "入场计费";
|
|
1707
|
-
function formatPlayerGroups(groups) {
|
|
1708
|
-
const populatedGroups = groups.filter((group) => group.players.length > 0);
|
|
1709
|
-
// Each person is in exactly one group.
|
|
1710
|
-
const total = populatedGroups.reduce((sum, group) => sum + group.players.length, 0);
|
|
1711
|
-
if (total === 0)
|
|
1712
|
-
return "🫥 窝里目前没有玩家呢";
|
|
1713
|
-
const lines = [`[总计 ${total} 人]`];
|
|
1714
|
-
for (const group of populatedGroups) {
|
|
1715
|
-
const heading = group.capacity !== undefined
|
|
1716
|
-
? `${group.label} ( ${group.players.length}/${group.capacity} )`
|
|
1717
|
-
: `${group.label} ( ${group.players.length}人 )`;
|
|
1718
|
-
lines.push(`\n${heading}:\n${formatPlayerNames(group.players)}`);
|
|
1719
|
-
}
|
|
1720
|
-
return lines.join("\n");
|
|
1721
|
-
}
|
|
1722
|
-
function formatPlayerNames(players) {
|
|
1723
|
-
return players.map((player) => `- ${player.displayName || player.playerId || "未知玩家"}`).join(", ");
|
|
1724
|
-
}
|
|
1725
|
-
function commandUsage(command) {
|
|
1726
|
-
return `用法: ${USAGE[command] ?? command}`;
|
|
1727
|
-
}
|
|
1728
|
-
function parsePositiveInt(value, command, label, fallback) {
|
|
1729
|
-
const text = cleanText(value);
|
|
1730
|
-
if (!text) {
|
|
1731
|
-
if (fallback !== undefined)
|
|
1732
|
-
return { value: fallback, error: null };
|
|
1733
|
-
return { value: 0, error: commandUsage(command) };
|
|
1734
|
-
}
|
|
1735
|
-
const parsed = Number.parseInt(text, 10);
|
|
1736
|
-
if (Number.isNaN(parsed) || parsed <= 0) {
|
|
1737
|
-
return { value: 0, error: `${label}必须是正整数\n${commandUsage(command)}` };
|
|
1738
|
-
}
|
|
1739
|
-
return { value: parsed, error: null };
|
|
1740
|
-
}
|
|
1741
|
-
function cleanText(value) {
|
|
1742
|
-
return value == null ? "" : String(value).trim();
|
|
1743
|
-
}
|
|
1744
|
-
function formatReleaseVersion(value) {
|
|
1745
|
-
const record = value && typeof value === "object" ? value : {};
|
|
1746
|
-
const release = cleanText(record.version) || "unknown";
|
|
1747
|
-
const revision = cleanText(record.revision);
|
|
1748
|
-
return !revision || revision === "unknown" ? release : `${release} (${revision})`;
|
|
1749
|
-
}
|
|
1750
|
-
function formatPlayerReference(sender) {
|
|
1751
|
-
const name = sender.name && sender.name !== sender.id ? sender.name : "未知昵称";
|
|
1752
|
-
return `${name}(${sender.provider}:${sender.id})`;
|
|
1753
|
-
}
|
|
1754
|
-
function adjustmentKey(adjustment) {
|
|
1755
|
-
const id = cleanText(adjustment?.id);
|
|
1756
|
-
if (id)
|
|
1757
|
-
return `id:${id}`;
|
|
1758
|
-
return JSON.stringify([
|
|
1759
|
-
adjustment?.source ?? "",
|
|
1760
|
-
adjustment?.label ?? "",
|
|
1761
|
-
toNumber(adjustment?.amount ?? 0),
|
|
1762
|
-
]);
|
|
1763
|
-
}
|
|
1764
|
-
function isPricingCapAdjustment(adjustment) {
|
|
1765
|
-
return adjustment?.pricingCapHistory != null ||
|
|
1766
|
-
cleanText(adjustment?.source).startsWith("time.cap:") ||
|
|
1767
|
-
cleanText(adjustment?.id).startsWith("time-cap:");
|
|
1768
|
-
}
|
|
1769
|
-
function toNumber(value) {
|
|
1770
|
-
if (value == null)
|
|
1771
|
-
return 0;
|
|
1772
|
-
if (typeof value === "boolean")
|
|
1773
|
-
return value ? 1 : 0;
|
|
1774
|
-
if (typeof value === "number")
|
|
1775
|
-
return value;
|
|
1776
|
-
const text = String(value).trim();
|
|
1777
|
-
if (!text)
|
|
1778
|
-
return 0;
|
|
1779
|
-
const asInt = Number.parseInt(text, 10);
|
|
1780
|
-
if (!Number.isNaN(asInt))
|
|
1781
|
-
return asInt;
|
|
1782
|
-
const asFloat = Number.parseFloat(text);
|
|
1783
|
-
if (!Number.isNaN(asFloat))
|
|
1784
|
-
return asFloat;
|
|
1785
|
-
return 0;
|
|
1786
|
-
}
|
|
1787
|
-
function hasAdjustmentEntries(adjustments, sessionPreviews) {
|
|
1788
|
-
return adjustments.some((adjustment) => toNumber(adjustment.amount) !== 0) || sessionPreviews.some((session) => session.adjustments.some((adjustment) => toNumber(adjustment.amount) !== 0));
|
|
1789
|
-
}
|
|
1790
|
-
function formatNumber(value) {
|
|
1791
|
-
if (typeof value === "boolean")
|
|
1792
|
-
return value ? "1" : "0";
|
|
1793
|
-
if (typeof value === "number") {
|
|
1794
|
-
return Number.isInteger(value) ? String(value) : String(value);
|
|
1795
|
-
}
|
|
1796
|
-
const num = toNumber(value);
|
|
1797
|
-
if (num || String(value ?? "").trim() === "0" || String(value ?? "").trim() === "0.0") {
|
|
1798
|
-
return Number.isInteger(num) ? String(num) : String(num);
|
|
1799
|
-
}
|
|
1800
|
-
return String(value);
|
|
1801
|
-
}
|
|
1802
|
-
function formatDurationValue(minutes) {
|
|
1803
|
-
const total = Math.floor(toNumber(minutes));
|
|
1804
|
-
if (total >= 60) {
|
|
1805
|
-
const hours = Math.floor(total / 60);
|
|
1806
|
-
const mins = total % 60;
|
|
1807
|
-
return `${hours}小时${mins}分钟`;
|
|
658
|
+
throw new PrismBotClientError("店铺尚未读取", "SHOP_UNKNOWN", 0, {});
|
|
659
|
+
return code;
|
|
1808
660
|
}
|
|
1809
|
-
return `${total}分钟`;
|
|
1810
|
-
}
|
|
1811
|
-
function sessionDisplayEnd(session, previewedAt) {
|
|
1812
|
-
const endedAt = (0, display_time_js_1.parseDateTime)(session?.endedAt);
|
|
1813
|
-
if (endedAt)
|
|
1814
|
-
return endedAt;
|
|
1815
|
-
if (session?.status === "active")
|
|
1816
|
-
return previewedAt ?? now(undefined);
|
|
1817
|
-
return null;
|
|
1818
661
|
}
|
|
1819
|
-
function
|
|
1820
|
-
return
|
|
662
|
+
function walletBody(from) {
|
|
663
|
+
return { identity: { provider: from.provider, subject: from.subject } };
|
|
1821
664
|
}
|
|
1822
|
-
function
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
line += `\n 到期: ${(0, display_time_js_1.formatDateTime)(row.expiresAt)}`;
|
|
1826
|
-
return line;
|
|
1827
|
-
}
|
|
1828
|
-
function formatRedeemedItem(row) {
|
|
1829
|
-
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;
|
|
1830
668
|
}
|
|
1831
|
-
function
|
|
1832
|
-
|
|
1833
|
-
.
|
|
1834
|
-
|
|
1835
|
-
const free = rows
|
|
1836
|
-
.filter((row) => String(row.assetCode).toLowerCase().includes("free"))
|
|
1837
|
-
.reduce((sum, row) => sum + toNumber(row.quantity), 0);
|
|
1838
|
-
const other = rows
|
|
1839
|
-
.filter((row) => {
|
|
1840
|
-
const code = String(row.assetCode).toLowerCase();
|
|
1841
|
-
return !code.includes("paid") && !code.includes("free");
|
|
1842
|
-
})
|
|
1843
|
-
.reduce((sum, row) => sum + toNumber(row.quantity), 0);
|
|
1844
|
-
const total = paid + free + other;
|
|
1845
|
-
return [
|
|
1846
|
-
"💰 --- 钱包余额 ---",
|
|
1847
|
-
`可用: ${formatNumber(total)} ${currency} (共 ${formatNumber(total)})`,
|
|
1848
|
-
` - 付费: ${formatNumber(paid)}`,
|
|
1849
|
-
` - 免费: ${formatNumber(free)}`,
|
|
1850
|
-
].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 "测速失败,请稍后再试。";
|
|
1851
673
|
}
|
|
1852
|
-
function
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
const lines = [`📜 最近 ${sessions.length} 条记录:`];
|
|
1856
|
-
for (const session of sessions) {
|
|
1857
|
-
const end = session.endedAt ? (0, display_time_js_1.formatDateTime)(session.endedAt) : "进行中";
|
|
1858
|
-
const cost = session.total == null ? "未结算" : `${formatNumber(session.total)} ${currency}`;
|
|
1859
|
-
lines.push(`- [${session.sessionId}] ${(0, display_time_js_1.formatDateTime)(session.startedAt)} -> ${end} (${cost})`);
|
|
1860
|
-
}
|
|
1861
|
-
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`;
|
|
1862
677
|
}
|
|
1863
|
-
function
|
|
1864
|
-
const
|
|
1865
|
-
if (
|
|
1866
|
-
return
|
|
1867
|
-
|
|
1868
|
-
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`];
|
|
1869
683
|
}
|
|
1870
684
|
exports.default = {
|
|
1871
685
|
name: exports.name,
|