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