koishi-plugin-prism 0.2.0 → 0.3.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 +55 -51
- package/lib/ha-watch.d.ts +111 -0
- package/lib/ha-watch.js +349 -0
- package/lib/index.d.ts +82 -27
- package/lib/index.js +445 -445
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -3,44 +3,26 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.PrismSocket = exports.PrismBotClientError = exports.Config = exports.version = exports.name = void 0;
|
|
6
|
+
exports.PrismSocket = exports.PrismBotClientError = exports.Config = exports.version = exports.name = exports.HaWatcher = void 0;
|
|
7
7
|
exports.apply = apply;
|
|
8
8
|
exports.applyPrismKoishiPlugin = applyPrismKoishiPlugin;
|
|
9
9
|
exports.platformSocketUrl = platformSocketUrl;
|
|
10
10
|
exports.humanReadableBotError = humanReadableBotError;
|
|
11
|
-
exports.resolveMahjongTableConfigs = resolveMahjongTableConfigs;
|
|
12
11
|
const display_time_js_1 = require("./display-time.js");
|
|
12
|
+
const ha_watch_js_1 = require("./ha-watch.js");
|
|
13
13
|
const koishi_1 = require("koishi");
|
|
14
14
|
const package_json_1 = __importDefault(require("../package.json"));
|
|
15
|
+
var ha_watch_js_2 = require("./ha-watch.js");
|
|
16
|
+
Object.defineProperty(exports, "HaWatcher", { enumerable: true, get: function () { return ha_watch_js_2.HaWatcher; } });
|
|
15
17
|
exports.name = "prism";
|
|
16
18
|
exports.version = package_json_1.default.version;
|
|
19
|
+
// Only how to reach the shop is configured here. Everything else (staff, door,
|
|
20
|
+
// tables, read-only mode, reminders, watching) is the bot's own settings on its
|
|
21
|
+
// resource page in PRiSM, read from the platform when the bot connects.
|
|
17
22
|
exports.Config = koishi_1.Schema.object({
|
|
18
|
-
autoRegister: koishi_1.Schema.boolean().default(true).description("是否自动注册"),
|
|
19
|
-
shopCode: koishi_1.Schema.string().required().description("统一平台店铺编号"),
|
|
20
23
|
baseUrl: koishi_1.Schema.string().required().description("PRiSM 后端地址,例如 https://link.neri.moe"),
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
defaultDoorDeviceId: koishi_1.Schema.string().default("front-door").description("默认开门设备名或别名"),
|
|
24
|
-
defaultScanProvider: koishi_1.Schema.string().default("aime").description("默认刷卡提供商"),
|
|
25
|
-
loginPricingConfigIds: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("默认入场绑定的计费策略ID"),
|
|
26
|
-
loginSessionLabel: koishi_1.Schema.string().default("音游区间").description("默认入场场次标签 (防重复入场)"),
|
|
27
|
-
enableStaffCommands: koishi_1.Schema.boolean().default(false).description("是否启用管理员指令"),
|
|
28
|
-
staffUserIds: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("允许执行管理员指令的平台身份列表(如 onebot:123456、telegram:123456)"),
|
|
29
|
-
powerCommandsAdminOnly: koishi_1.Schema.boolean().default(false).description("关机是否仅允许管理员使用;开机始终仅已入场玩家可用"),
|
|
30
|
-
playerCommands: koishi_1.Schema.union([
|
|
31
|
-
koishi_1.Schema.const("all").description("全部:玩家可以在 Bot 里入场、结账、上下桌和操作设备"),
|
|
32
|
-
koishi_1.Schema.const("readonly").description("只读:玩家只能绑定身份、查询和兑换;入场、结账、上下桌和设备操作仅管理员可用"),
|
|
33
|
-
]).default("all").description("玩家可用的命令"),
|
|
34
|
-
readOnlyNotice: koishi_1.Schema.string().default("请扫描设备上的二维码或碰 NFC,在网页或 App Clip 里操作").description("只读模式下玩家使用受限命令时的回复"),
|
|
35
|
-
logoutNotifyUserIds: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("结账账单私聊通知的平台身份列表(如 onebot:123456)"),
|
|
36
|
-
idleNotifyChannelIds: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("闲置自动关机的提醒发到哪里:群写 onebot:群号,私聊写 onebot:private:QQ号"),
|
|
37
|
-
idleReminderMinutes: koishi_1.Schema.number().min(0).max(120).default(5).description("自动关机前几分钟提醒(0 为不提醒)"),
|
|
38
|
-
mahjongTableConfigs: koishi_1.Schema.array(koishi_1.Schema.object({
|
|
39
|
-
displayName: koishi_1.Schema.string().required().description("桌位显示名称和 session 标签"),
|
|
40
|
-
aliases: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("命令别名(至少一个),例如 a、四麻A"),
|
|
41
|
-
pricingConfigIds: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("开局时绑定的计费方案 ID"),
|
|
42
|
-
})).default([]).description("麻将桌配置"),
|
|
43
|
-
mahjongTableSize: koishi_1.Schema.number().default(4).description("麻将桌人数限制"),
|
|
24
|
+
shopCode: koishi_1.Schema.string().required().description("统一平台店铺编号"),
|
|
25
|
+
integrationToken: koishi_1.Schema.string().role("secret").required().description("集成 API Token;其余设置在 PRiSM 商户工作台 → 资源 → 这个 Bot → Bot 设置"),
|
|
44
26
|
});
|
|
45
27
|
function apply(ctx, config) {
|
|
46
28
|
applyPrismKoishiPlugin(ctx, config);
|
|
@@ -62,7 +44,7 @@ class PrismBotClientError extends Error {
|
|
|
62
44
|
exports.PrismBotClientError = PrismBotClientError;
|
|
63
45
|
const USAGE = {
|
|
64
46
|
mahjong_join: "/上桌 <桌号>",
|
|
65
|
-
mahjong_leave: "/下桌",
|
|
47
|
+
mahjong_leave: "/下桌 [桌号]",
|
|
66
48
|
mahjong_list: "/麻将列表",
|
|
67
49
|
api_benchmark: "/api测速 [次数]",
|
|
68
50
|
ws_benchmark: "/ws测速 [次数]",
|
|
@@ -72,50 +54,53 @@ const USAGE = {
|
|
|
72
54
|
prism_coin: "/prism coin <设备名或别名> [数量]",
|
|
73
55
|
prism_scan: "/prism scan <设备名或别名>",
|
|
74
56
|
prism_redeem: "/prism redeem <兑换码>",
|
|
75
|
-
list: "/list",
|
|
57
|
+
list: "/list [资源或方案]",
|
|
76
58
|
show: "/show [设备ID]",
|
|
77
59
|
};
|
|
78
60
|
function applyPrismKoishiPlugin(ctx, config) {
|
|
79
61
|
const service = new PrismKoishiService(ctx, config);
|
|
80
|
-
const wrap = (handler) => async (context, ...args) => {
|
|
62
|
+
const wrap = (handler, gate = {}) => async (context, ...args) => {
|
|
63
|
+
const quoted = (message) => context.session?.messageId ? `${(0, koishi_1.h)("quote", { id: context.session.messageId })}${message}` : message;
|
|
81
64
|
try {
|
|
82
|
-
|
|
83
|
-
|
|
65
|
+
if (!gate.offline) {
|
|
66
|
+
// A disabled bot, or one that cannot read its settings, answers nothing else.
|
|
67
|
+
const bot = await service.config();
|
|
68
|
+
if (gate.effect && bot.settings.playerCommands === "readonly" && !service.isStaff(bot, await service.sender(context))) {
|
|
69
|
+
return quoted(bot.settings.readOnlyNotice || DEFAULT_READ_ONLY_NOTICE);
|
|
70
|
+
}
|
|
71
|
+
if (gate.billed && !bot.billingEnabled)
|
|
72
|
+
return quoted(BILLING_DISABLED_NOTICE);
|
|
73
|
+
}
|
|
74
|
+
return quoted(await handler(context, ...args));
|
|
84
75
|
}
|
|
85
76
|
catch (error) {
|
|
86
|
-
|
|
87
|
-
return context.session?.messageId ? `${(0, koishi_1.h)("quote", { id: context.session.messageId })}${message}` : message;
|
|
77
|
+
return quoted(service.handleCommandError(error));
|
|
88
78
|
}
|
|
89
79
|
};
|
|
80
|
+
const effect = (handler, gate = {}) => wrap(handler, { ...gate, effect: true });
|
|
81
|
+
const billed = { billed: true };
|
|
90
82
|
const bind = wrap(async (context, code) => service.bind(await service.sender(context), code));
|
|
91
83
|
ctx.command("bind <code:string>", "绑定网页登录账号到当前平台身份").action(bind);
|
|
92
84
|
// Instructions already handed to players may still say prism.bind.
|
|
93
85
|
ctx.command("prism.bind <code:string>", "绑定网页登录账号到当前平台身份(旧命令,同 bind)").action(bind);
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
ctx.command("
|
|
103
|
-
ctx.command("入场 [target:user]", "入场").action(effect(async (context, target) => service.loginForTarget(await service.sender(context), target, context.session?.bot)));
|
|
104
|
-
ctx.command("mahjong <tableId>", "加入指定麻将桌").action(effect(async (context, tableId) => service.mahjongJoin(await service.sender(context), tableId)));
|
|
105
|
-
ctx.command("上桌 [tableId]", "加入指定麻将桌").action(effect(async (context, tableId) => service.mahjongJoin(await service.sender(context), tableId)));
|
|
106
|
-
ctx.command("下桌", "离开当前所在麻将桌").action(effect(async (context) => service.mahjongLeave(await service.sender(context))));
|
|
107
|
-
ctx.command("麻将列表", "查看麻将机状态与别名").action(wrap(async () => service.listMahjongTables()));
|
|
108
|
-
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)));
|
|
109
|
-
ctx.command("billing [target:user]", "预览玩家结账费用").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.billing(sender), context.session?.bot)));
|
|
110
|
-
ctx.command("wallet [target:user]", "查看玩家钱包").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.wallet(sender), context.session?.bot)));
|
|
86
|
+
ctx.command("login [target:user]", "开启玩家计费场次").action(effect(async (context, target) => service.loginForTarget(await service.sender(context), target, context.session?.bot), billed));
|
|
87
|
+
ctx.command("入场 [target:user]", "入场").action(effect(async (context, target) => service.loginForTarget(await service.sender(context), target, context.session?.bot), billed));
|
|
88
|
+
ctx.command("mahjong <tableId>", "加入指定麻将桌").action(effect(async (context, tableId) => service.mahjongJoin(await service.sender(context), tableId), billed));
|
|
89
|
+
ctx.command("上桌 [tableId]", "加入指定麻将桌").action(effect(async (context, tableId) => service.mahjongJoin(await service.sender(context), tableId), billed));
|
|
90
|
+
ctx.command("下桌 [tableId]", "离开当前所在麻将桌").action(effect(async (context, tableId) => service.mahjongLeave(await service.sender(context), tableId), billed));
|
|
91
|
+
ctx.command("麻将列表", "查看麻将机状态与别名").action(wrap(async () => service.listMahjongTables(), billed));
|
|
92
|
+
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), billed));
|
|
93
|
+
ctx.command("billing [target:user]", "预览玩家结账费用").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.billing(sender), context.session?.bot), billed));
|
|
94
|
+
ctx.command("wallet [target:user]", "查看玩家钱包").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.wallet(sender), context.session?.bot), billed));
|
|
111
95
|
ctx.command("api测速 [count:number]", "测试 Bot 走 HTTP 到 PRiSM 的延迟").action(wrap(async (context, count) => service.benchmarkApi(await service.sender(context), count)));
|
|
112
96
|
ctx.command("ws测速 [count:number]", "测试 Bot 走 WebSocket 到 PRiSM 的延迟").action(wrap(async (context, count) => service.benchmarkWs(await service.sender(context), count)));
|
|
113
|
-
|
|
114
|
-
ctx.command("
|
|
115
|
-
ctx.command("
|
|
97
|
+
// The Bot's own version stays visible while the platform is out of reach.
|
|
98
|
+
ctx.command("versions", "查看 Bot 与 PRiSM 后端版本").action(wrap(async () => service.versions(), { offline: true }));
|
|
99
|
+
ctx.command("items [target:user]", "查看玩家资产").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.items(sender), context.session?.bot), billed));
|
|
100
|
+
ctx.command("list [name:text]", "查看在店玩家,或某个资源、某个计费方案上的玩家").action(wrap(async (context, name) => service.listActiveSessions(await service.sender(context), name), billed));
|
|
116
101
|
ctx.command("show [deviceId]", "查看设备电源状态").action(wrap(async (context, deviceId) => service.listDeviceStates(deviceId)));
|
|
117
|
-
ctx.command("history [target:user]", "查看玩家历史").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.history(sender), context.session?.bot)));
|
|
118
|
-
ctx.command("lock", "
|
|
102
|
+
ctx.command("history [target:user]", "查看玩家历史").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.history(sender), context.session?.bot), billed));
|
|
103
|
+
ctx.command("lock", "向本店门锁发送开门指令").action(effect(async (context) => service.lock(await service.sender(context))));
|
|
119
104
|
ctx.command("on <deviceRef>", "请求启动指定设备电源").action(effect(async (context, deviceRef) => service.powerOn(await service.sender(context), deviceRef)));
|
|
120
105
|
ctx.command("off <deviceRef>", "请求关闭指定设备电源").action(effect(async (context, deviceRef) => service.powerOff(await service.sender(context), deviceRef)));
|
|
121
106
|
// Not limited by read-only mode: it never switches anything on, and the
|
|
@@ -123,12 +108,14 @@ function applyPrismKoishiPlugin(ctx, config) {
|
|
|
123
108
|
ctx.command("keep <deviceRef>", "延迟闲置设备的自动关机").action(wrap(async (context, deviceRef) => service.keep(await service.sender(context), deviceRef)));
|
|
124
109
|
ctx.command("coin <deviceRef> [count]", "请求向指定设备投币").action(effect(async (context, deviceRef, count) => service.coin(await service.sender(context), deviceRef, count)));
|
|
125
110
|
ctx.command("scan <deviceRef>", "使用当前玩家绑定的 Aime 卡刷卡").action(effect(async (context, deviceRef) => service.scan(await service.sender(context), deviceRef)));
|
|
126
|
-
ctx.command("redeem <code>", "兑换 PRiSM 礼物码").action(wrap(async (context, code) => service.redeem(await service.sender(context), code)));
|
|
127
|
-
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)));
|
|
128
|
-
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)));
|
|
129
|
-
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)));
|
|
111
|
+
ctx.command("redeem <code>", "兑换 PRiSM 礼物码").action(wrap(async (context, code) => service.redeem(await service.sender(context), code), billed));
|
|
112
|
+
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), billed));
|
|
113
|
+
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), billed));
|
|
114
|
+
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), billed));
|
|
130
115
|
ctx.on?.("dispose", () => service.dispose());
|
|
131
116
|
}
|
|
117
|
+
const DEFAULT_READ_ONLY_NOTICE = "请扫描店内二维码或碰 NFC,在网页或 App Clip 里入场、结账和操作设备。";
|
|
118
|
+
const BILLING_DISABLED_NOTICE = "本店未启用计费";
|
|
132
119
|
/* --------------------------- platform connection --------------------------- */
|
|
133
120
|
const SOCKET_OPEN = 1;
|
|
134
121
|
const REQUEST_TIMEOUT_MS = 30_000;
|
|
@@ -148,6 +135,7 @@ class PrismSocket {
|
|
|
148
135
|
hello;
|
|
149
136
|
onEvent;
|
|
150
137
|
logger;
|
|
138
|
+
hooks;
|
|
151
139
|
socket = null;
|
|
152
140
|
pending = new Map();
|
|
153
141
|
retryMs = FIRST_RETRY_MS;
|
|
@@ -156,14 +144,40 @@ class PrismSocket {
|
|
|
156
144
|
lastHeard = 0;
|
|
157
145
|
stopped = false;
|
|
158
146
|
sequence = 0;
|
|
147
|
+
/** Bumped by every hello being prepared, so only the newest one is sent. */
|
|
148
|
+
greeting = 0;
|
|
159
149
|
pongWaiters = [];
|
|
160
|
-
constructor(open, url, token,
|
|
150
|
+
constructor(open, url, token,
|
|
151
|
+
/**
|
|
152
|
+
* What to say in hello, read afresh each time: the bot's settings live on
|
|
153
|
+
* the platform, so they are fetched over this connection before it is
|
|
154
|
+
* sent. Null when they could not be read.
|
|
155
|
+
*/
|
|
156
|
+
hello, onEvent, logger,
|
|
157
|
+
/**
|
|
158
|
+
* `onWatch`: the platform asked this bot to watch Home Assistant, or with null to stop.
|
|
159
|
+
* `onClose`: the connection is gone, and with it the platform's idea of what this bot watches.
|
|
160
|
+
*/
|
|
161
|
+
hooks) {
|
|
161
162
|
this.open = open;
|
|
162
163
|
this.url = url;
|
|
163
164
|
this.token = token;
|
|
164
165
|
this.hello = hello;
|
|
165
166
|
this.onEvent = onEvent;
|
|
166
167
|
this.logger = logger;
|
|
168
|
+
this.hooks = hooks;
|
|
169
|
+
}
|
|
170
|
+
/** Send a frame if the connection is up; a report made while it is down is dropped, as the platform has forgotten the watch by then. */
|
|
171
|
+
send(frame) {
|
|
172
|
+
const socket = this.socket;
|
|
173
|
+
if (!socket || socket.readyState !== SOCKET_OPEN)
|
|
174
|
+
return;
|
|
175
|
+
try {
|
|
176
|
+
socket.send(JSON.stringify(frame));
|
|
177
|
+
}
|
|
178
|
+
catch {
|
|
179
|
+
// The connection went between the check and the send.
|
|
180
|
+
}
|
|
167
181
|
}
|
|
168
182
|
start() {
|
|
169
183
|
this.stopped = false;
|
|
@@ -191,9 +205,8 @@ class PrismSocket {
|
|
|
191
205
|
}
|
|
192
206
|
this.socket = socket;
|
|
193
207
|
socket.addEventListener("open", () => {
|
|
194
|
-
this.retryMs = FIRST_RETRY_MS;
|
|
195
208
|
this.lastHeard = Date.now();
|
|
196
|
-
|
|
209
|
+
void this.greet(socket, true);
|
|
197
210
|
if (this.pingTimer)
|
|
198
211
|
clearInterval(this.pingTimer);
|
|
199
212
|
this.pingTimer = setInterval(() => {
|
|
@@ -212,10 +225,39 @@ class PrismSocket {
|
|
|
212
225
|
if (this.pingTimer)
|
|
213
226
|
clearInterval(this.pingTimer);
|
|
214
227
|
this.failPending();
|
|
228
|
+
// The platform forgets what this bot watches with the connection; it is asked again after hello.
|
|
229
|
+
this.hooks?.onClose();
|
|
215
230
|
this.reconnectLater();
|
|
216
231
|
});
|
|
217
232
|
socket.addEventListener("error", (error) => this.logger?.warn("PRiSM connection error", error?.message ?? error));
|
|
218
233
|
}
|
|
234
|
+
/**
|
|
235
|
+
* Read the bot's settings and say hello with them: on connecting, and again
|
|
236
|
+
* when the platform says they changed. A connection that cannot read them
|
|
237
|
+
* at all is closed and tried again later, without resetting the backoff, so
|
|
238
|
+
* a platform that keeps failing is not asked every second.
|
|
239
|
+
*/
|
|
240
|
+
async greet(socket, connecting) {
|
|
241
|
+
const greeting = ++this.greeting;
|
|
242
|
+
let hello = null;
|
|
243
|
+
try {
|
|
244
|
+
hello = await this.hello();
|
|
245
|
+
}
|
|
246
|
+
catch (error) {
|
|
247
|
+
this.logger?.warn("PRiSM bot settings unavailable", error);
|
|
248
|
+
}
|
|
249
|
+
// A newer hello is on its way, or this connection is already gone.
|
|
250
|
+
if (greeting !== this.greeting || this.socket !== socket)
|
|
251
|
+
return;
|
|
252
|
+
if (!hello) {
|
|
253
|
+
if (connecting)
|
|
254
|
+
socket.close(4000, "settings unavailable");
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
if (connecting)
|
|
258
|
+
this.retryMs = FIRST_RETRY_MS;
|
|
259
|
+
this.send({ type: "hello", ...hello });
|
|
260
|
+
}
|
|
219
261
|
reconnectLater() {
|
|
220
262
|
if (this.stopped)
|
|
221
263
|
return;
|
|
@@ -260,6 +302,21 @@ class PrismSocket {
|
|
|
260
302
|
this.logger?.warn("PRiSM event handling failed", error);
|
|
261
303
|
}
|
|
262
304
|
}
|
|
305
|
+
else if (frame?.type === "config.changed") {
|
|
306
|
+
// The bot's settings, staff, door or tables changed: read them again and say hello with them.
|
|
307
|
+
if (this.socket)
|
|
308
|
+
void this.greet(this.socket, false);
|
|
309
|
+
}
|
|
310
|
+
else if (frame?.type === "ha.watch" || frame?.type === "ha.unwatch") {
|
|
311
|
+
// A watch that cannot be read is as good as none: the platform has nothing for this bot to watch.
|
|
312
|
+
const watch = frame.type === "ha.watch" ? (0, ha_watch_js_1.parseWatch)(frame.watch) : null;
|
|
313
|
+
try {
|
|
314
|
+
this.hooks?.onWatch(watch);
|
|
315
|
+
}
|
|
316
|
+
catch (error) {
|
|
317
|
+
this.logger?.warn("PRiSM Home Assistant watch failed", error);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
263
320
|
}
|
|
264
321
|
/** One heartbeat round trip in milliseconds: the network to the platform and nothing else. */
|
|
265
322
|
ping() {
|
|
@@ -363,15 +420,16 @@ class PrismApiClient {
|
|
|
363
420
|
provider: identity.provider,
|
|
364
421
|
subject: identity.subject,
|
|
365
422
|
},
|
|
366
|
-
...(identity.autoRegister === undefined ? {} : { autoRegister: identity.autoRegister }),
|
|
367
423
|
...(identity.displayName === undefined ? {} : { displayName: identity.displayName }),
|
|
368
424
|
};
|
|
369
425
|
}
|
|
426
|
+
/** The bot's own settings and what it needs to know about the shop. */
|
|
427
|
+
async getBotConfig() {
|
|
428
|
+
return this.request("GET", "/rpc/integration/bot", {});
|
|
429
|
+
}
|
|
430
|
+
/** Always the register route: whether a new player is created is the shop's own switch. */
|
|
370
431
|
async resolveOrRegisterIdentity(identity) {
|
|
371
|
-
const
|
|
372
|
-
? "/rpc/integration/players/by-identity/register"
|
|
373
|
-
: "/rpc/integration/players/by-identity/resolve";
|
|
374
|
-
const result = await this.request("POST", endpoint, {
|
|
432
|
+
const result = await this.request("POST", "/rpc/integration/players/by-identity/register", {
|
|
375
433
|
body: this.identityBody(identity),
|
|
376
434
|
});
|
|
377
435
|
return result.player;
|
|
@@ -379,20 +437,25 @@ class PrismApiClient {
|
|
|
379
437
|
async getVersion() {
|
|
380
438
|
return this.request("GET", "version", {});
|
|
381
439
|
}
|
|
382
|
-
|
|
440
|
+
/** Admit a player into the shop's default plan; `created` is false when it was already billing. */
|
|
441
|
+
async startSessionByIdentity(identity) {
|
|
383
442
|
return this.request("POST", "/rpc/integration/players/by-identity/session/start", {
|
|
384
|
-
body: {
|
|
385
|
-
...this.identityBody(identity),
|
|
386
|
-
...(body ?? {}),
|
|
387
|
-
},
|
|
443
|
+
body: { ...this.identityBody(identity), entry: true },
|
|
388
444
|
});
|
|
389
445
|
}
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
body: this.identityBody(identity),
|
|
446
|
+
/** Seat or unseat a player; `table` is a table id, name or alias. */
|
|
447
|
+
async mahjongByIdentity(identity, table, action) {
|
|
448
|
+
return this.request("POST", "/rpc/integration/players/by-identity/mahjong", {
|
|
449
|
+
body: { ...this.identityBody(identity), table, action },
|
|
394
450
|
});
|
|
395
451
|
}
|
|
452
|
+
async listMahjongTables() {
|
|
453
|
+
return this.request("GET", "/rpc/integration/mahjong-tables", {});
|
|
454
|
+
}
|
|
455
|
+
/** Who is in the shop, each once at their place; with a name, one resource or one plan. */
|
|
456
|
+
async roster(name) {
|
|
457
|
+
return this.request("GET", "/rpc/integration/roster", name ? { query: { name } } : {});
|
|
458
|
+
}
|
|
396
459
|
async getWalletByIdentity(identity) {
|
|
397
460
|
return this.request("POST", "/rpc/integration/players/by-identity/wallet", {
|
|
398
461
|
body: this.identityBody(identity),
|
|
@@ -488,11 +551,6 @@ class PrismApiClient {
|
|
|
488
551
|
async listDeviceStates() {
|
|
489
552
|
return this.request("GET", "/rpc/integration/device-states", {});
|
|
490
553
|
}
|
|
491
|
-
async adjustAssetsByIdentity(identity, adjustments) {
|
|
492
|
-
return this.request("POST", "/rpc/integration/players/by-identity/assets/adjustments", {
|
|
493
|
-
body: { ...this.identityBody(identity), adjustments },
|
|
494
|
-
});
|
|
495
|
-
}
|
|
496
554
|
async adjustWalletByIdentity(identity, amount, reason) {
|
|
497
555
|
return this.request("POST", "/rpc/integration/players/by-identity/wallet/adjustment", {
|
|
498
556
|
body: { ...this.identityBody(identity), amount, reason },
|
|
@@ -506,37 +564,52 @@ class PrismApiClient {
|
|
|
506
564
|
}
|
|
507
565
|
class PrismKoishiService {
|
|
508
566
|
ctx;
|
|
509
|
-
|
|
510
|
-
mahjongTables = new Map();
|
|
567
|
+
options;
|
|
511
568
|
logoutInFlight = new Map();
|
|
512
569
|
client;
|
|
513
570
|
logger;
|
|
514
571
|
socket = null;
|
|
515
|
-
|
|
572
|
+
watcher = null;
|
|
573
|
+
/** The bot's settings as last read; null until read, and again once the shop disables the bot. */
|
|
574
|
+
bot = null;
|
|
575
|
+
/** The read in flight, shared by commands arriving together. */
|
|
576
|
+
reading = null;
|
|
577
|
+
reads = 0;
|
|
578
|
+
/** Whether the settings let this bot watch Home Assistant. */
|
|
579
|
+
watching = false;
|
|
580
|
+
constructor(ctx, options) {
|
|
516
581
|
this.ctx = ctx;
|
|
517
|
-
this.
|
|
582
|
+
this.options = options;
|
|
518
583
|
this.logger = ctx.logger?.("prism");
|
|
519
|
-
if (
|
|
520
|
-
this.client =
|
|
584
|
+
if (options.client) {
|
|
585
|
+
this.client = options.client;
|
|
521
586
|
return;
|
|
522
587
|
}
|
|
523
|
-
if (!
|
|
588
|
+
if (!options.shopCode || !options.baseUrl || !options.integrationToken) {
|
|
524
589
|
throw new Error("PRiSM Koishi plugin requires 'shopCode', 'baseUrl' and 'integrationToken'.");
|
|
525
590
|
}
|
|
526
|
-
const open =
|
|
591
|
+
const open = options.socket ?? ((url, headers) => {
|
|
527
592
|
const http = ctx.http;
|
|
528
593
|
if (!http?.ws)
|
|
529
594
|
throw new Error("Koishi http service with WebSocket support is required.");
|
|
530
595
|
return http.ws(url, { headers });
|
|
531
596
|
});
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
597
|
+
// Home Assistant is reached the way the platform is, unless a test stands in for the platform and
|
|
598
|
+
// says nothing about Home Assistant: then there is no watching to offer.
|
|
599
|
+
const haOpen = options.haSocket ?? (options.socket ? null : open);
|
|
600
|
+
if (haOpen)
|
|
601
|
+
this.watcher = new ha_watch_js_1.HaWatcher(haOpen, (frame) => this.socket?.send(frame), this.logger);
|
|
602
|
+
this.socket = new PrismSocket(open, platformSocketUrl(options.baseUrl, options.shopCode), options.integrationToken, () => this.hello(), (event) => {
|
|
536
603
|
if (event.event === "idle.reminder")
|
|
537
604
|
void this.remindIdle(event.data);
|
|
538
|
-
}, this.logger
|
|
539
|
-
|
|
605
|
+
}, this.logger, this.watcher
|
|
606
|
+
? {
|
|
607
|
+
// Only a bot whose settings allow it watches, whatever the platform asks.
|
|
608
|
+
onWatch: (watch) => (watch && this.watching ? this.watcher.watch(watch) : this.watcher.stop()),
|
|
609
|
+
onClose: () => this.watcher.stop(),
|
|
610
|
+
}
|
|
611
|
+
: undefined);
|
|
612
|
+
const post = options.httpPost ?? (async (url, headers, body) => {
|
|
540
613
|
const http = ctx.http;
|
|
541
614
|
if (typeof http !== "function")
|
|
542
615
|
throw new PrismBotClientError("HTTP 测速需要 Koishi 的 http 服务", "HTTP_UNAVAILABLE", 0, {});
|
|
@@ -545,12 +618,73 @@ class PrismKoishiService {
|
|
|
545
618
|
});
|
|
546
619
|
return { status: response.status, headers: response.headers, data: response.data };
|
|
547
620
|
});
|
|
548
|
-
this.client = new PrismApiClient(this.socket, { post, baseUrl:
|
|
621
|
+
this.client = new PrismApiClient(this.socket, { post, baseUrl: options.baseUrl, shopCode: options.shopCode, token: options.integrationToken });
|
|
549
622
|
this.socket.start();
|
|
550
623
|
}
|
|
551
624
|
dispose() {
|
|
625
|
+
this.watcher?.stop();
|
|
552
626
|
this.socket?.stop();
|
|
553
627
|
}
|
|
628
|
+
/** The bot's settings, read from the platform the first time they are needed. */
|
|
629
|
+
async config() {
|
|
630
|
+
return this.bot ?? this.reading ?? this.readConfig();
|
|
631
|
+
}
|
|
632
|
+
/** Read the settings afresh. A disabled bot forgets the ones it had, so each command asks again. */
|
|
633
|
+
readConfig() {
|
|
634
|
+
// Only the newest read may settle what the bot knows; an older one answering late is stale.
|
|
635
|
+
const read = ++this.reads;
|
|
636
|
+
this.reading = (async () => {
|
|
637
|
+
try {
|
|
638
|
+
const bot = parseBotConfig(await this.client.getBotConfig());
|
|
639
|
+
if (read === this.reads)
|
|
640
|
+
this.bot = bot;
|
|
641
|
+
return bot;
|
|
642
|
+
}
|
|
643
|
+
catch (error) {
|
|
644
|
+
if (read === this.reads && error instanceof PrismBotClientError && error.code === "BOT_DISABLED")
|
|
645
|
+
this.bot = null;
|
|
646
|
+
throw error;
|
|
647
|
+
}
|
|
648
|
+
finally {
|
|
649
|
+
if (read === this.reads)
|
|
650
|
+
this.reading = null;
|
|
651
|
+
}
|
|
652
|
+
})();
|
|
653
|
+
return this.reading;
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* What this bot says in hello, from settings read just now. A disabled bot
|
|
657
|
+
* offers nothing: no watching and no reminders.
|
|
658
|
+
*/
|
|
659
|
+
async hello() {
|
|
660
|
+
let bot;
|
|
661
|
+
try {
|
|
662
|
+
bot = await this.readConfig();
|
|
663
|
+
}
|
|
664
|
+
catch (error) {
|
|
665
|
+
if (!(error instanceof PrismBotClientError && error.code === "BOT_DISABLED"))
|
|
666
|
+
throw error;
|
|
667
|
+
this.watching = false;
|
|
668
|
+
this.watcher?.stop();
|
|
669
|
+
return {};
|
|
670
|
+
}
|
|
671
|
+
const { settings } = bot;
|
|
672
|
+
this.watching = settings.watchHomeAssistant && this.watcher !== null;
|
|
673
|
+
// Turned off: the platform hands the watch on when it hears the hello.
|
|
674
|
+
if (!this.watching)
|
|
675
|
+
this.watcher?.stop();
|
|
676
|
+
return {
|
|
677
|
+
name: bot.bot.name,
|
|
678
|
+
// Saying so is what makes the platform consider this bot for the watch.
|
|
679
|
+
...(this.watching ? { ha: true } : {}),
|
|
680
|
+
// Without anywhere to send it, the platform need not plan a reminder.
|
|
681
|
+
...(settings.idleChannelIds.length && settings.idleReminderMinutes > 0 ? { reminderLeadSeconds: settings.idleReminderMinutes * 60 } : {}),
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
/** Whether the sender is one of the shop's staff on this platform. */
|
|
685
|
+
isStaff(bot, sender) {
|
|
686
|
+
return bot.staff.some((identity) => identity.provider === sender.provider && identity.subject === sender.id);
|
|
687
|
+
}
|
|
554
688
|
async bind(sender, code) {
|
|
555
689
|
try {
|
|
556
690
|
await this.client.confirmPlatformBinding(code, sender.provider, sender.id);
|
|
@@ -564,10 +698,10 @@ class PrismKoishiService {
|
|
|
564
698
|
}
|
|
565
699
|
/** Tell the configured channels a power-off is coming. Short: they can read a device name. */
|
|
566
700
|
async remindIdle(reminder) {
|
|
567
|
-
const channels = this.
|
|
701
|
+
const channels = this.bot?.settings.idleChannelIds ?? [];
|
|
568
702
|
if (!channels.length || typeof this.ctx.broadcast !== "function")
|
|
569
703
|
return;
|
|
570
|
-
const now = (this.
|
|
704
|
+
const now = (this.options.now?.() ?? new Date()).getTime();
|
|
571
705
|
const minutes = Math.max(1, Math.round((reminder.at - now) / 60_000));
|
|
572
706
|
const names = reminder.devices.map((device) => device.name).join("、");
|
|
573
707
|
const message = reminder.reason === "shop_empty"
|
|
@@ -597,20 +731,20 @@ class PrismKoishiService {
|
|
|
597
731
|
catch { }
|
|
598
732
|
return { id, name, provider };
|
|
599
733
|
}
|
|
600
|
-
async register(sender) {
|
|
601
|
-
await this.client.resolveOrRegisterIdentity(this.identity(sender));
|
|
602
|
-
return "注册成功";
|
|
603
|
-
}
|
|
604
734
|
async loginForTarget(actor, targetSubject, bot) {
|
|
605
735
|
return this.withTarget(actor, targetSubject, async (sender, isTargeted) => {
|
|
606
|
-
await this.client.startSessionByIdentity(this.identity(sender)
|
|
607
|
-
|
|
736
|
+
const result = (await this.client.startSessionByIdentity(this.identity(sender)));
|
|
737
|
+
// Already in: the player had this session before, and the plan says where.
|
|
738
|
+
if (result?.created === false) {
|
|
739
|
+
const where = typeof result.planName === "string" && result.planName ? `「${result.planName}」` : "场";
|
|
740
|
+
return isTargeted ? `用户 ${formatPlayerReference(sender)} 已在${where}中,无需重复入场` : `您已在${where}中,无需重复入场`;
|
|
741
|
+
}
|
|
742
|
+
// Starting the plan may end one it cannot bill together with.
|
|
743
|
+
const stopped = Array.isArray(result?.billing?.stopped) ? result.billing.stopped.filter((name) => typeof name === "string" && name) : [];
|
|
744
|
+
const ended = stopped.length ? `\n结束方案:${stopped.join("、")}` : "";
|
|
745
|
+
return (isTargeted ? `✅ 已为用户 ${formatPlayerReference(sender)} 入场成功` : "✅ 入场成功") + ended;
|
|
608
746
|
}, bot);
|
|
609
747
|
}
|
|
610
|
-
async login(sender) {
|
|
611
|
-
await this.client.startSessionByIdentity(this.identity(sender), this.loginSessionBody());
|
|
612
|
-
return "✅ 入场成功";
|
|
613
|
-
}
|
|
614
748
|
async withTarget(actor, targetSubject, action, bot) {
|
|
615
749
|
const target = await this.targetSender(actor, targetSubject, bot);
|
|
616
750
|
if (typeof target === "string")
|
|
@@ -624,7 +758,7 @@ class PrismKoishiService {
|
|
|
624
758
|
return "金额必须大于 0";
|
|
625
759
|
const isAddition = direction === 1;
|
|
626
760
|
await this.client.adjustWalletByIdentity(this.identity(sender), amount * direction, isAddition ? "Koishi 管理员增加余额" : "Koishi 管理员扣除余额");
|
|
627
|
-
return `✅ 已为用户 ${formatPlayerReference(sender)}${isAddition ? "增加" : "扣除"} ${formatNumber(amount)} ${this.config.currencyName}`;
|
|
761
|
+
return `✅ 已为用户 ${formatPlayerReference(sender)}${isAddition ? "增加" : "扣除"} ${formatNumber(amount)} ${(await this.config()).currencyName}`;
|
|
628
762
|
}, bot);
|
|
629
763
|
}
|
|
630
764
|
async overwriteTargetCheckout(actor, targetSubject, rawAmount, rawReason, bot) {
|
|
@@ -634,124 +768,95 @@ class PrismKoishiService {
|
|
|
634
768
|
return "金额必须为非负数";
|
|
635
769
|
const reason = cleanText(rawReason) || "管理员调价";
|
|
636
770
|
const result = (await this.client.checkoutWithOverrideByIdentity(this.identity(sender), total, reason));
|
|
637
|
-
const playerId = String(result.playerSettlement.playerId);
|
|
638
|
-
if (playerId)
|
|
639
|
-
this.removeMahjongPlayer(playerId);
|
|
640
771
|
return this.formatAndNotifyCheckout(result, sender, "✅ 覆盖结账成功 · 结算账单", bot);
|
|
641
772
|
}, bot);
|
|
642
773
|
}
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
774
|
+
/**
|
|
775
|
+
* Seat the player at a table. The platform opens the table (starting
|
|
776
|
+
* everyone's billing) once it fills, so a player need not enter first.
|
|
777
|
+
*/
|
|
778
|
+
async mahjongJoin(sender, rawTableRef) {
|
|
779
|
+
const tableRef = cleanText(rawTableRef);
|
|
780
|
+
if (!tableRef)
|
|
646
781
|
return "请指定麻将桌,例如 /上桌 a;可先使用 /麻将列表 查看可用桌位。";
|
|
647
|
-
const
|
|
648
|
-
if (!
|
|
649
|
-
return `未找到麻将桌「${
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
const playerId = String(player.id ?? "");
|
|
654
|
-
const activeResult = (await this.client.listActiveSessions());
|
|
655
|
-
const activeSessions = (activeResult.sessions ?? []);
|
|
656
|
-
this.syncMahjongTableStates(activeSessions);
|
|
657
|
-
if (!this.hasEntrySession(playerId, activeSessions)) {
|
|
658
|
-
return "请先入场后再上桌。";
|
|
659
|
-
}
|
|
660
|
-
const existing = this.mahjongTableForPlayer(playerId);
|
|
661
|
-
if (existing)
|
|
662
|
-
return `你已经在 ${existing},无需重复上桌。`;
|
|
663
|
-
const state = this.mahjongTables.get(tableKey) ?? { waiting: [], activeSessions: {} };
|
|
664
|
-
this.mahjongTables.set(tableKey, state);
|
|
665
|
-
const activeCount = Object.keys(state.activeSessions).length;
|
|
666
|
-
const tableSize = this.config.mahjongTableSize ?? 4;
|
|
667
|
-
if (activeCount >= tableSize) {
|
|
668
|
-
return `「${tableSubject}」正在游玩中(${activeCount}/${tableSize}),请等待本局结束后再上桌。`;
|
|
669
|
-
}
|
|
670
|
-
if (activeCount > 0) {
|
|
671
|
-
const label = tableConfig.displayName;
|
|
672
|
-
const result = (await this.client.startSessionByIdentity(this.identity(sender), {
|
|
673
|
-
pricingConfigIds: tableConfig.pricingConfigIds,
|
|
674
|
-
label,
|
|
675
|
-
entry: false,
|
|
676
|
-
}));
|
|
677
|
-
const session = (result?.session ?? {});
|
|
678
|
-
const sessionId = String(session.id ?? "");
|
|
679
|
-
if (sessionId) {
|
|
680
|
-
state.activeSessions[playerId] = sessionId;
|
|
681
|
-
}
|
|
682
|
-
return `已加入 ${tableSubject},补位成功,麻将计费已开始。当前 ${activeCount + 1}/${tableSize} 人。`;
|
|
782
|
+
const table = findMahjongTable((await this.config()).mahjongTables, tableRef);
|
|
783
|
+
if (!table)
|
|
784
|
+
return `未找到麻将桌「${tableRef}」。可先使用 /麻将列表 查看可用桌位。`;
|
|
785
|
+
let state;
|
|
786
|
+
try {
|
|
787
|
+
state = (await this.client.mahjongByIdentity(this.identity(sender), table.id, "join")).mahjong;
|
|
683
788
|
}
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
}
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
const
|
|
711
|
-
|
|
712
|
-
const
|
|
713
|
-
const
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
const
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
const
|
|
735
|
-
|
|
736
|
-
|
|
789
|
+
catch (error) {
|
|
790
|
+
if (!(error instanceof PrismBotClientError))
|
|
791
|
+
throw error;
|
|
792
|
+
if (error.code === "MAHJONG_TABLE_NOT_FOUND")
|
|
793
|
+
return `未找到麻将桌「${tableRef}」。可先使用 /麻将列表 查看可用桌位。`;
|
|
794
|
+
if (error.code === "MAHJONG_TABLE_FULL")
|
|
795
|
+
return `「${table.name}」已满桌,请等待本局结束后再上桌。`;
|
|
796
|
+
if (error.code === "MAHJONG_ALREADY_SEATED")
|
|
797
|
+
return "你已经在另一张麻将桌上,请先 /下桌。";
|
|
798
|
+
const message = platformMessage(error);
|
|
799
|
+
if (message)
|
|
800
|
+
return `上桌失败,${message}`;
|
|
801
|
+
throw error;
|
|
802
|
+
}
|
|
803
|
+
const seated = state.seats.length;
|
|
804
|
+
const mine = state.seats.find((seat) => seat.mine);
|
|
805
|
+
if (mine?.playing)
|
|
806
|
+
return `已加入 ${table.name},麻将计费已开始。当前 ${seated}/${state.capacity} 人。`;
|
|
807
|
+
return `已加入 ${table.name},当前 ${seated}/${state.capacity} 人,满 ${state.capacity} 人开始计费。`;
|
|
808
|
+
}
|
|
809
|
+
/** Leave the table the player sits at, or the one named. */
|
|
810
|
+
async mahjongLeave(sender, rawTableRef) {
|
|
811
|
+
const tableRef = cleanText(rawTableRef);
|
|
812
|
+
const named = tableRef ? findMahjongTable((await this.config()).mahjongTables, tableRef) : null;
|
|
813
|
+
if (tableRef && !named)
|
|
814
|
+
return `未找到麻将桌「${tableRef}」。可先使用 /麻将列表 查看可用桌位。`;
|
|
815
|
+
const [listing, player] = await Promise.all([this.client.listMahjongTables(), this.resolvePlayer(sender)]);
|
|
816
|
+
const playerId = String(player?.id ?? "");
|
|
817
|
+
const tables = (listing?.tables ?? []);
|
|
818
|
+
const table = tables.find((candidate) => (!named || candidate.id === named.id) && candidate.seats.some((seat) => seat.playerId === playerId));
|
|
819
|
+
if (!table?.id)
|
|
820
|
+
return named ? `你当前不在 ${named.name}。` : "你当前未在任何麻将桌上。";
|
|
821
|
+
const name = table.name || named?.name || table.id;
|
|
822
|
+
const wasPlaying = table.seats.some((seat) => seat.playerId === playerId && seat.playing);
|
|
823
|
+
let result;
|
|
824
|
+
try {
|
|
825
|
+
result = (await this.client.mahjongByIdentity(this.identity(sender), table.id, "leave"));
|
|
826
|
+
}
|
|
827
|
+
catch (error) {
|
|
828
|
+
if (!(error instanceof PrismBotClientError))
|
|
829
|
+
throw error;
|
|
830
|
+
if (error.code === "MAHJONG_TABLE_NOT_FOUND")
|
|
831
|
+
return "你当前未在任何麻将桌上。";
|
|
832
|
+
const message = platformMessage(error);
|
|
833
|
+
if (message)
|
|
834
|
+
return `下桌失败,${message}`;
|
|
835
|
+
throw error;
|
|
836
|
+
}
|
|
837
|
+
const state = result.mahjong;
|
|
838
|
+
// Getting up does not check out: what still bills is said, so leaving the shop means /logout.
|
|
839
|
+
const remaining = Array.isArray(result.billing?.remaining)
|
|
840
|
+
? result.billing.remaining.filter((plan) => typeof plan === "string" && plan)
|
|
841
|
+
: [];
|
|
842
|
+
return `已离开 ${name}${wasPlaying ? ",麻将计费已停止" : ""}。当前还剩 ${state.seats.length}/${state.capacity} 人。`
|
|
843
|
+
+ (remaining.length ? `\n仍在计费:${remaining.join("、")}` : "");
|
|
737
844
|
}
|
|
738
845
|
async listMahjongTables() {
|
|
739
|
-
const
|
|
740
|
-
|
|
741
|
-
const tableSize = this.config.mahjongTableSize ?? 4;
|
|
742
|
-
const tables = uniqueMahjongConfigs(this.mahjongTableConfigs());
|
|
846
|
+
const result = (await this.client.listMahjongTables());
|
|
847
|
+
const tables = (result?.tables ?? []);
|
|
743
848
|
if (tables.length === 0)
|
|
744
849
|
return "当前没有配置任何麻将机。";
|
|
745
850
|
const lines = [`🀄️ 麻将机列表(${tables.length} 台)`];
|
|
746
851
|
for (const table of tables) {
|
|
747
|
-
const
|
|
748
|
-
const
|
|
749
|
-
const waitingCount = state.waiting.length;
|
|
852
|
+
const playing = table.seats.filter((seat) => seat.playing).length;
|
|
853
|
+
const waiting = table.seats.length - playing;
|
|
750
854
|
const statuses = [
|
|
751
|
-
...(
|
|
752
|
-
...(
|
|
855
|
+
...(playing > 0 ? [`游玩中 ${playing}/${table.capacity}`] : []),
|
|
856
|
+
...(waiting > 0 ? [`等位 ${waiting}/${table.capacity}`] : []),
|
|
753
857
|
];
|
|
754
|
-
|
|
858
|
+
const aliases = table.aliases ?? [];
|
|
859
|
+
lines.push(`- ${table.name}|别名:${aliases.length > 0 ? aliases.join("、") : "无"}|${statuses.join(";") || "空闲"}`);
|
|
755
860
|
}
|
|
756
861
|
return lines.join("\n");
|
|
757
862
|
}
|
|
@@ -778,9 +883,6 @@ class PrismKoishiService {
|
|
|
778
883
|
}
|
|
779
884
|
async performLogout(sender, bot) {
|
|
780
885
|
const result = (await this.client.confirmCheckoutByIdentity(this.identity(sender), false));
|
|
781
|
-
const playerId = String(result.playerSettlement.playerId);
|
|
782
|
-
if (playerId)
|
|
783
|
-
this.removeMahjongPlayer(playerId);
|
|
784
886
|
return this.formatAndNotifyCheckout(result, sender, "✅ 退场成功 · 结算账单", bot);
|
|
785
887
|
}
|
|
786
888
|
async formatAndNotifyCheckout(result, sender, title, bot) {
|
|
@@ -825,21 +927,18 @@ class PrismKoishiService {
|
|
|
825
927
|
wallet: result.wallet,
|
|
826
928
|
};
|
|
827
929
|
const receipt = await this.formatCheckoutPreview(synthetic, sender, title, false);
|
|
828
|
-
|
|
829
|
-
const
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
return [identity.startsWith("private:") ? identity : `private:${identity}`];
|
|
834
|
-
return [];
|
|
835
|
-
});
|
|
930
|
+
// Staff reachable through this adapter get the receipt privately, when the bot's settings say so.
|
|
931
|
+
const config = await this.config();
|
|
932
|
+
const channelIds = config.settings.receiptsToStaff
|
|
933
|
+
? [...new Set(config.staff.filter((identity) => identity.provider === sender.provider).map((identity) => `private:${identity.subject}`))]
|
|
934
|
+
: [];
|
|
836
935
|
if (channelIds.length > 0 && bot?.broadcast)
|
|
837
936
|
await bot.broadcast(channelIds, receipt);
|
|
838
937
|
return receipt;
|
|
839
938
|
}
|
|
840
939
|
async wallet(sender) {
|
|
841
940
|
const result = (await this.client.getWalletByIdentity(this.identity(sender)));
|
|
842
|
-
return formatWallet(result.wallet, this.config.currencyName);
|
|
941
|
+
return formatWallet(result.wallet, (await this.config()).currencyName);
|
|
843
942
|
}
|
|
844
943
|
/**
|
|
845
944
|
* The wallet query over plain HTTP. The first request usually has to open a
|
|
@@ -902,13 +1001,17 @@ class PrismKoishiService {
|
|
|
902
1001
|
}
|
|
903
1002
|
async history(sender) {
|
|
904
1003
|
const result = (await this.client.getSessionHistoryByIdentity(this.identity(sender)));
|
|
905
|
-
return formatHistory(result.sessions, this.config.currencyName);
|
|
1004
|
+
return formatHistory(result.sessions, (await this.config()).currencyName);
|
|
906
1005
|
}
|
|
1006
|
+
/** Open the door the bot's settings name. */
|
|
907
1007
|
async lock(sender) {
|
|
1008
|
+
const door = (await this.config()).door;
|
|
1009
|
+
if (!door)
|
|
1010
|
+
return "🔑 本店还没有设置 Bot 开的门";
|
|
908
1011
|
try {
|
|
909
1012
|
const result = await this.client.requestDeviceCommandByIdentity(this.identity(sender), {
|
|
910
1013
|
type: "door.open",
|
|
911
|
-
target: { kind: "facility", ref:
|
|
1014
|
+
target: { kind: "facility", ref: door.id },
|
|
912
1015
|
});
|
|
913
1016
|
const failure = this.getCommandFailureMessage(result);
|
|
914
1017
|
if (failure) {
|
|
@@ -973,7 +1076,7 @@ class PrismKoishiService {
|
|
|
973
1076
|
try {
|
|
974
1077
|
const result = await this.client.requestScanByIdentity(this.identity(sender), {
|
|
975
1078
|
deviceRef,
|
|
976
|
-
provider:
|
|
1079
|
+
provider: "aime",
|
|
977
1080
|
});
|
|
978
1081
|
const failure = deviceCommandFailureReason(result);
|
|
979
1082
|
if (failure) {
|
|
@@ -998,31 +1101,41 @@ class PrismKoishiService {
|
|
|
998
1101
|
return "兑换成功,但没有获得任何物品。";
|
|
999
1102
|
return ["✅ 兑换成功!您获得了以下物品:", ...grantedAssets.map(formatRedeemedItem)].join("\n");
|
|
1000
1103
|
}
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
])
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1104
|
+
/**
|
|
1105
|
+
* Who is in the shop, as the platform lists them: every player playing or
|
|
1106
|
+
* billing, each once, at the resource they occupy (with its head count and
|
|
1107
|
+
* capacity) or their most specific plan. With a name, everyone on that
|
|
1108
|
+
* resource or billing that plan.
|
|
1109
|
+
*/
|
|
1110
|
+
async listActiveSessions(sender, name) {
|
|
1111
|
+
const wanted = cleanText(name);
|
|
1112
|
+
let roster;
|
|
1113
|
+
try {
|
|
1114
|
+
roster = (await this.client.roster(wanted || undefined));
|
|
1115
|
+
}
|
|
1116
|
+
catch (error) {
|
|
1117
|
+
if (wanted && error instanceof PrismBotClientError && error.code === "ROSTER_TARGET_NOT_FOUND")
|
|
1118
|
+
return `找不到「${wanted}」`;
|
|
1119
|
+
throw error;
|
|
1120
|
+
}
|
|
1121
|
+
const groups = [];
|
|
1122
|
+
for (const group of roster.groups ?? []) {
|
|
1123
|
+
const players = [];
|
|
1124
|
+
for (const member of group.members ?? []) {
|
|
1125
|
+
const player = {
|
|
1126
|
+
playerId: member.playerId,
|
|
1127
|
+
sessions: [{ playerDisplayName: member.displayName ?? undefined, identities: member.identities ?? [] }],
|
|
1128
|
+
};
|
|
1129
|
+
player.displayName = await this.displayNameForPlayer(player, sender.provider);
|
|
1130
|
+
players.push(player);
|
|
1131
|
+
}
|
|
1132
|
+
groups.push({ label: group.name, ...(group.kind === "resource" ? { capacity: group.capacity } : {}), players });
|
|
1133
|
+
}
|
|
1134
|
+
const [only] = groups;
|
|
1135
|
+
if (wanted && only && !only.players.length) {
|
|
1136
|
+
return only.capacity !== undefined ? `${only.label} ( 0/${only.capacity} )` : `${only.label} ( 0人 )`;
|
|
1137
|
+
}
|
|
1138
|
+
return formatPlayerGroups(groups);
|
|
1026
1139
|
}
|
|
1027
1140
|
async listDeviceStates(rawAlias) {
|
|
1028
1141
|
const alias = cleanText(rawAlias);
|
|
@@ -1062,8 +1175,9 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
1062
1175
|
/* ---------------------------- helpers ---------------------------------- */
|
|
1063
1176
|
async power(sender, deviceRef, state) {
|
|
1064
1177
|
const operation = state === "on" ? "启动" : "关闭";
|
|
1065
|
-
const
|
|
1066
|
-
|
|
1178
|
+
const config = await this.config();
|
|
1179
|
+
const staffOverride = state === "off" && config.settings.powerOffStaffOnly;
|
|
1180
|
+
if (staffOverride && !this.isStaff(config, sender)) {
|
|
1067
1181
|
return `${operation}失败,权限不足`;
|
|
1068
1182
|
}
|
|
1069
1183
|
try {
|
|
@@ -1093,10 +1207,10 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
1093
1207
|
return null;
|
|
1094
1208
|
}
|
|
1095
1209
|
async resolvePlatformName(subject, provider) {
|
|
1096
|
-
if (!this.
|
|
1210
|
+
if (!this.options.resolveDisplayName)
|
|
1097
1211
|
return null;
|
|
1098
1212
|
try {
|
|
1099
|
-
return (await this.
|
|
1213
|
+
return (await this.options.resolveDisplayName(subject, provider)) ?? null;
|
|
1100
1214
|
}
|
|
1101
1215
|
catch {
|
|
1102
1216
|
return null;
|
|
@@ -1119,50 +1233,6 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
1119
1233
|
|| player.playerId
|
|
1120
1234
|
|| "未知玩家";
|
|
1121
1235
|
}
|
|
1122
|
-
async buildPlayerGroups(players, tableByLabel, provider) {
|
|
1123
|
-
const groups = { groups: [] };
|
|
1124
|
-
const groupByLabel = new Map();
|
|
1125
|
-
const musicLabel = this.config.loginSessionLabel?.trim() || "音游区间";
|
|
1126
|
-
for (const player of players.values()) {
|
|
1127
|
-
player.displayName = await this.displayNameForPlayer(player, provider);
|
|
1128
|
-
const nonMusic = player.sessions.filter((session) => Boolean(session.label) && session.label !== "entry" && session.label !== musicLabel);
|
|
1129
|
-
const source = nonMusic.length > 0 ? nonMusic : player.sessions;
|
|
1130
|
-
const selected = source.reduce((latest, session) => !latest || sessionStartedAt(session) > sessionStartedAt(latest) ? session : latest, undefined);
|
|
1131
|
-
const label = selected?.label === "entry" ? musicLabel : selected?.label || musicLabel;
|
|
1132
|
-
let group = groupByLabel.get(label);
|
|
1133
|
-
if (!group) {
|
|
1134
|
-
group = { label, table: tableByLabel.get(label), players: [] };
|
|
1135
|
-
groupByLabel.set(label, group);
|
|
1136
|
-
groups.groups.push(group);
|
|
1137
|
-
}
|
|
1138
|
-
group.players.push(player);
|
|
1139
|
-
}
|
|
1140
|
-
return groups;
|
|
1141
|
-
}
|
|
1142
|
-
mergeWaitingSeats(groups) {
|
|
1143
|
-
for (const [tableId, state] of this.mahjongTables) {
|
|
1144
|
-
const table = uniqueMahjongConfigs(this.mahjongTableConfigs()).find((candidate) => candidate.tableId === tableId);
|
|
1145
|
-
if (!table)
|
|
1146
|
-
continue;
|
|
1147
|
-
const label = mahjongSessionLabel(table);
|
|
1148
|
-
let group = groups.groups.find((candidate) => candidate.label === label);
|
|
1149
|
-
if (!group) {
|
|
1150
|
-
group = { label, table, players: [] };
|
|
1151
|
-
groups.groups.push(group);
|
|
1152
|
-
}
|
|
1153
|
-
for (const seat of state.waiting) {
|
|
1154
|
-
if (group.players.some((player) => player.playerId === seat.playerId))
|
|
1155
|
-
continue;
|
|
1156
|
-
const existing = groups.groups.flatMap((candidate) => candidate.players)
|
|
1157
|
-
.find((player) => player.playerId === seat.playerId);
|
|
1158
|
-
for (const candidate of groups.groups) {
|
|
1159
|
-
if (candidate !== group)
|
|
1160
|
-
candidate.players = candidate.players.filter((player) => player.playerId !== seat.playerId);
|
|
1161
|
-
}
|
|
1162
|
-
group.players.push(existing ?? { playerId: seat.playerId, sessions: [], displayName: seat.displayName });
|
|
1163
|
-
}
|
|
1164
|
-
}
|
|
1165
|
-
}
|
|
1166
1236
|
async resolvePlayerDisplay(sender, playerId) {
|
|
1167
1237
|
if (!sender)
|
|
1168
1238
|
return playerId || "未知玩家";
|
|
@@ -1172,67 +1242,13 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
1172
1242
|
|| "未知昵称";
|
|
1173
1243
|
return `玩家:${name}(${sender.provider}:${sender.id})`;
|
|
1174
1244
|
}
|
|
1175
|
-
mahjongTableForPlayer(playerId) {
|
|
1176
|
-
for (const [tableId, state] of this.mahjongTables) {
|
|
1177
|
-
if (state.activeSessions[playerId])
|
|
1178
|
-
return tableId;
|
|
1179
|
-
if (state.waiting.some((seat) => seat.playerId === playerId))
|
|
1180
|
-
return tableId;
|
|
1181
|
-
}
|
|
1182
|
-
return null;
|
|
1183
|
-
}
|
|
1184
|
-
removeMahjongPlayer(playerId) {
|
|
1185
|
-
for (const state of this.mahjongTables.values()) {
|
|
1186
|
-
delete state.activeSessions[playerId];
|
|
1187
|
-
state.waiting = state.waiting.filter((seat) => seat.playerId !== playerId);
|
|
1188
|
-
}
|
|
1189
|
-
}
|
|
1190
|
-
mahjongTableConfigs() {
|
|
1191
|
-
return resolveMahjongTableConfigs(this.config.mahjongTableConfigs ?? []);
|
|
1192
|
-
}
|
|
1193
|
-
syncMahjongTableStates(sessions) {
|
|
1194
|
-
const tables = uniqueMahjongConfigs(this.mahjongTableConfigs());
|
|
1195
|
-
const tableByLabel = new Map(tables.map((table) => [
|
|
1196
|
-
mahjongSessionLabel(table),
|
|
1197
|
-
table,
|
|
1198
|
-
]));
|
|
1199
|
-
// All playerIds that still have at least one active session in the backend.
|
|
1200
|
-
// Used to evict waiting seats for players who have fully checked out externally.
|
|
1201
|
-
const allActivePlayerIds = new Set(sessions.map((s) => String(s.playerId ?? "")).filter(Boolean));
|
|
1202
|
-
const activeByTable = new Map();
|
|
1203
|
-
for (const session of sessions) {
|
|
1204
|
-
const table = tableByLabel.get(session.label ?? "");
|
|
1205
|
-
const playerId = String(session.playerId ?? "");
|
|
1206
|
-
const sessionId = String(session.id ?? "");
|
|
1207
|
-
if (!table || !playerId || !sessionId)
|
|
1208
|
-
continue;
|
|
1209
|
-
const active = activeByTable.get(table.tableId) ?? {};
|
|
1210
|
-
active[playerId] = sessionId;
|
|
1211
|
-
activeByTable.set(table.tableId, active);
|
|
1212
|
-
}
|
|
1213
|
-
for (const table of tables) {
|
|
1214
|
-
const state = this.mahjongTables.get(table.tableId) ?? { waiting: [], activeSessions: {} };
|
|
1215
|
-
state.activeSessions = activeByTable.get(table.tableId) ?? {};
|
|
1216
|
-
// Remove seats that have been promoted to active, or whose players have
|
|
1217
|
-
// fully left the backend (no entry session remaining — orphan eviction).
|
|
1218
|
-
state.waiting = state.waiting.filter((seat) => !state.activeSessions[seat.playerId] && allActivePlayerIds.has(seat.playerId));
|
|
1219
|
-
if (state.waiting.length > 0 || Object.keys(state.activeSessions).length > 0 || this.mahjongTables.has(table.tableId)) {
|
|
1220
|
-
this.mahjongTables.set(table.tableId, state);
|
|
1221
|
-
}
|
|
1222
|
-
}
|
|
1223
|
-
}
|
|
1224
1245
|
async resolvePlayer(sender) {
|
|
1225
1246
|
return (await this.client.resolveOrRegisterIdentity(this.identity(sender)));
|
|
1226
1247
|
}
|
|
1227
|
-
hasEntrySession(playerId, sessions) {
|
|
1228
|
-
const label = this.config.loginSessionLabel?.trim();
|
|
1229
|
-
return sessions.some((session) => session.playerId === playerId && (session.label === "entry" || (label ? session.label === label : true)));
|
|
1230
|
-
}
|
|
1231
1248
|
identity(sender) {
|
|
1232
1249
|
return {
|
|
1233
1250
|
provider: sender.provider,
|
|
1234
1251
|
subject: sender.id,
|
|
1235
|
-
autoRegister: this.config.autoRegister,
|
|
1236
1252
|
displayName: sender.name || `${sender.provider} ${sender.id}`,
|
|
1237
1253
|
};
|
|
1238
1254
|
}
|
|
@@ -1247,9 +1263,12 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
1247
1263
|
return "请在目标平台使用该命令";
|
|
1248
1264
|
if (!subject)
|
|
1249
1265
|
return "无法获取目标平台身份";
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1266
|
+
// Acting for another player is for staff, and only when the bot's settings allow it.
|
|
1267
|
+
const config = await this.config();
|
|
1268
|
+
if (!config.settings.staffCommands)
|
|
1269
|
+
return "员工命令未启用";
|
|
1270
|
+
if (!this.isStaff(config, actor))
|
|
1271
|
+
return "权限不足";
|
|
1253
1272
|
try {
|
|
1254
1273
|
const user = await bot?.getUser?.(subject);
|
|
1255
1274
|
return { id: subject, name: user?.name || subject, provider };
|
|
@@ -1258,35 +1277,8 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
1258
1277
|
return { id: subject, name: subject, provider };
|
|
1259
1278
|
}
|
|
1260
1279
|
}
|
|
1261
|
-
loginSessionBody() {
|
|
1262
|
-
const pricingConfigIds = (this.config.loginPricingConfigIds ?? [])
|
|
1263
|
-
.map((id) => id.trim())
|
|
1264
|
-
.filter(Boolean);
|
|
1265
|
-
const label = this.config.loginSessionLabel?.trim();
|
|
1266
|
-
return {
|
|
1267
|
-
entry: true,
|
|
1268
|
-
...(pricingConfigIds.length === 0 ? {} : { pricingConfigIds }),
|
|
1269
|
-
...(label ? { label } : {}),
|
|
1270
|
-
};
|
|
1271
|
-
}
|
|
1272
|
-
staffDenied(sender) {
|
|
1273
|
-
if (!this.config.enableStaffCommands)
|
|
1274
|
-
return "员工命令未启用";
|
|
1275
|
-
const allowed = this.config.staffUserIds ?? [];
|
|
1276
|
-
if (allowed.length > 0 && !matchesPlatformIdentity(allowed, sender))
|
|
1277
|
-
return "权限不足";
|
|
1278
|
-
return null;
|
|
1279
|
-
}
|
|
1280
|
-
targetStaffDenied(sender) {
|
|
1281
|
-
if (!this.config.enableStaffCommands)
|
|
1282
|
-
return "员工命令未启用";
|
|
1283
|
-
const allowed = this.config.staffUserIds ?? [];
|
|
1284
|
-
if (!matchesPlatformIdentity(allowed, sender))
|
|
1285
|
-
return "权限不足";
|
|
1286
|
-
return null;
|
|
1287
|
-
}
|
|
1288
1280
|
async formatCheckoutPreview(result, sender, title = "【结算账单】", isPreview) {
|
|
1289
|
-
const currency = this.config.currencyName;
|
|
1281
|
+
const currency = (await this.config()).currencyName;
|
|
1290
1282
|
const preview = result.settlementPreview;
|
|
1291
1283
|
const playerId = preview.playerId;
|
|
1292
1284
|
const subtotal = preview.subtotal;
|
|
@@ -1313,12 +1305,12 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
1313
1305
|
const validEnds = sessionPreviews.map(s => s.endedAt || (s.status === "active" ? preview.previewedAt : null)).filter(value => (0, display_time_js_1.parseDateTime)(value));
|
|
1314
1306
|
if (validStarts.length > 0) {
|
|
1315
1307
|
const overallStart = validStarts.reduce((a, b) => Date.parse(a) < Date.parse(b) ? a : b);
|
|
1316
|
-
const overallEnd = validEnds.length > 0 ? validEnds.reduce((a, b) => Date.parse(a) > Date.parse(b) ? a : b) : now(this.
|
|
1308
|
+
const overallEnd = validEnds.length > 0 ? validEnds.reduce((a, b) => Date.parse(a) > Date.parse(b) ? a : b) : now(this.options).toISOString();
|
|
1317
1309
|
const offsets = [...new Set([(0, display_time_js_1.apiOffsetLabel)(overallStart), (0, display_time_js_1.apiOffsetLabel)(overallEnd)])].join(" / ");
|
|
1318
1310
|
lines.push(`⏰ 游玩时间:${(0, display_time_js_1.formatHM)(overallStart)}–${(0, display_time_js_1.formatHM)(overallEnd)}(${offsets})`);
|
|
1319
1311
|
}
|
|
1320
1312
|
for (const sPrev of sessionPreviews) {
|
|
1321
|
-
const label = sPrev?.label === "entry" ?
|
|
1313
|
+
const label = sPrev?.label === "entry" ? DEFAULT_PLAN_LABEL : sPrev?.label || "计时区间";
|
|
1322
1314
|
const startDt = (0, display_time_js_1.parseDateTime)(sPrev?.startedAt);
|
|
1323
1315
|
const endDt = sessionDisplayEnd(sPrev, previewedAt);
|
|
1324
1316
|
const status = sPrev?.status ?? "active";
|
|
@@ -1396,8 +1388,8 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
1396
1388
|
handleCommandError(error) {
|
|
1397
1389
|
this.logCommandError(error);
|
|
1398
1390
|
if (error instanceof PrismBotClientError) {
|
|
1399
|
-
if (error.code?.startsWith("LOCATION_") && this.
|
|
1400
|
-
return `请在网页完成到店校验:${this.
|
|
1391
|
+
if (error.code?.startsWith("LOCATION_") && this.options.shopCode && this.options.baseUrl) {
|
|
1392
|
+
return `请在网页完成到店校验:${this.options.baseUrl.replace(/\/+$/, "")}/t/${encodeURIComponent(this.options.shopCode)}`;
|
|
1401
1393
|
}
|
|
1402
1394
|
return humanReadableBotError(error);
|
|
1403
1395
|
}
|
|
@@ -1416,9 +1408,10 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
1416
1408
|
function humanReadableBotError(error) {
|
|
1417
1409
|
if (error.code === "INVALID_PLATFORM_IDENTITY")
|
|
1418
1410
|
return error.message;
|
|
1419
|
-
if (error.code === "
|
|
1420
|
-
return "
|
|
1421
|
-
|
|
1411
|
+
if (error.code === "BOT_DISABLED")
|
|
1412
|
+
return "Bot 已被店铺停用";
|
|
1413
|
+
if (error.code === "BILLING_DISABLED")
|
|
1414
|
+
return BILLING_DISABLED_NOTICE;
|
|
1422
1415
|
if (error.code === "PLAYER_HAS_NO_UNSETTLED_SESSIONS") {
|
|
1423
1416
|
return "您当前没有未结算的账单,无需结账。";
|
|
1424
1417
|
}
|
|
@@ -1456,6 +1449,8 @@ function powerFailureReason(error) {
|
|
|
1456
1449
|
return "玩家未入场";
|
|
1457
1450
|
if (error.code === "PLAYER_IDENTITY_NOT_FOUND")
|
|
1458
1451
|
return "玩家未注册";
|
|
1452
|
+
if (error.code === "BILLING_DISABLED")
|
|
1453
|
+
return BILLING_DISABLED_NOTICE;
|
|
1459
1454
|
return "请稍后再试";
|
|
1460
1455
|
}
|
|
1461
1456
|
return "请稍后再试";
|
|
@@ -1471,6 +1466,8 @@ function deviceActionFailureReason(error) {
|
|
|
1471
1466
|
return "玩家未绑定 Aime 卡";
|
|
1472
1467
|
if (error.code === "COIN_COMMAND_COOLDOWN_ACTIVE")
|
|
1473
1468
|
return "投币冷却中,请稍后再试";
|
|
1469
|
+
if (error.code === "BILLING_DISABLED")
|
|
1470
|
+
return BILLING_DISABLED_NOTICE;
|
|
1474
1471
|
return "请稍后再试";
|
|
1475
1472
|
}
|
|
1476
1473
|
function deviceCommandFailureReason(result) {
|
|
@@ -1508,52 +1505,66 @@ function normalizeDeviceState(value) {
|
|
|
1508
1505
|
}
|
|
1509
1506
|
return raw;
|
|
1510
1507
|
}
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
const tableId = displayName;
|
|
1516
|
-
const aliases = [...new Set((input.aliases ?? []).map(cleanText).filter(Boolean))];
|
|
1517
|
-
const pricingConfigIds = (input.pricingConfigIds ?? []).map(cleanText).filter(Boolean);
|
|
1518
|
-
if (!tableId || !displayName || pricingConfigIds.length === 0)
|
|
1519
|
-
continue;
|
|
1520
|
-
const table = { tableId, displayName, aliases, pricingConfigIds };
|
|
1521
|
-
for (const alias of aliases)
|
|
1522
|
-
tables.set(alias, table);
|
|
1523
|
-
}
|
|
1524
|
-
return tables;
|
|
1525
|
-
}
|
|
1526
|
-
function uniqueMahjongConfigs(tables) {
|
|
1527
|
-
return [...new Map([...tables.values()].map((table) => [table.tableId, table])).values()];
|
|
1528
|
-
}
|
|
1529
|
-
function mahjongSessionLabel(table) {
|
|
1530
|
-
return table.displayName;
|
|
1508
|
+
/** The table a player named, by id, name or alias, as the platform matches it. */
|
|
1509
|
+
function findMahjongTable(tables, ref) {
|
|
1510
|
+
const target = ref.trim().toLowerCase();
|
|
1511
|
+
return tables.find((table) => [table.id, table.name, ...table.aliases].some((value) => cleanText(value).toLowerCase() === target)) ?? null;
|
|
1531
1512
|
}
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
const player = players.get(playerId) ?? { playerId, sessions: [] };
|
|
1539
|
-
player.sessions.push(session);
|
|
1540
|
-
players.set(playerId, player);
|
|
1541
|
-
}
|
|
1542
|
-
return players;
|
|
1513
|
+
/** The platform's own message for a refusal, when it gave one; never the fallback naming an HTTP status. */
|
|
1514
|
+
function platformMessage(error) {
|
|
1515
|
+
if (error.status < 400 || error.status >= 500)
|
|
1516
|
+
return null;
|
|
1517
|
+
const message = error.body?.error?.message;
|
|
1518
|
+
return typeof message === "string" && message.trim() ? message.trim() : null;
|
|
1543
1519
|
}
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1520
|
+
/**
|
|
1521
|
+
* The bot's settings as the platform sent them. Anything missing takes the
|
|
1522
|
+
* platform's own default, so a newer setting an older platform lacks does no harm.
|
|
1523
|
+
*/
|
|
1524
|
+
function parseBotConfig(value) {
|
|
1525
|
+
const record = (value && typeof value === "object" ? value : {});
|
|
1526
|
+
const settings = (record.settings ?? {});
|
|
1527
|
+
const strings = (list) => (Array.isArray(list) ? list : []).map(cleanText).filter(Boolean);
|
|
1528
|
+
return {
|
|
1529
|
+
bot: { id: cleanText(record.bot?.id), name: cleanText(record.bot?.name) || "Bot" },
|
|
1530
|
+
settings: {
|
|
1531
|
+
playerCommands: settings.playerCommands === "readonly" ? "readonly" : "all",
|
|
1532
|
+
readOnlyNotice: cleanText(settings.readOnlyNotice),
|
|
1533
|
+
staffCommands: settings.staffCommands !== false,
|
|
1534
|
+
powerOffStaffOnly: settings.powerOffStaffOnly === true,
|
|
1535
|
+
receiptsToStaff: settings.receiptsToStaff === true,
|
|
1536
|
+
idleChannelIds: strings(settings.idleChannelIds),
|
|
1537
|
+
idleReminderMinutes: Math.max(0, Number(settings.idleReminderMinutes ?? 5) || 0),
|
|
1538
|
+
watchHomeAssistant: settings.watchHomeAssistant !== false,
|
|
1539
|
+
},
|
|
1540
|
+
billingEnabled: record.billingEnabled !== false,
|
|
1541
|
+
currencyName: cleanText(record.currencyName) || "余额",
|
|
1542
|
+
staff: (Array.isArray(record.staff) ? record.staff : [])
|
|
1543
|
+
.map((identity) => ({ provider: cleanText(identity?.provider).toLowerCase(), subject: cleanText(identity?.subject) }))
|
|
1544
|
+
.filter((identity) => identity.provider && identity.subject),
|
|
1545
|
+
door: record.door?.id ? { id: cleanText(record.door.id), name: cleanText(record.door.name) } : null,
|
|
1546
|
+
mahjongTables: (Array.isArray(record.mahjongTables) ? record.mahjongTables : [])
|
|
1547
|
+
.filter((table) => cleanText(table?.id))
|
|
1548
|
+
.map((table) => ({
|
|
1549
|
+
id: cleanText(table.id),
|
|
1550
|
+
name: cleanText(table.name) || cleanText(table.id),
|
|
1551
|
+
aliases: strings(table.aliases),
|
|
1552
|
+
capacity: Number(table.capacity) || 4,
|
|
1553
|
+
})),
|
|
1554
|
+
};
|
|
1547
1555
|
}
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1556
|
+
/** What the shop's default plan is called when the platform gives no plan name. */
|
|
1557
|
+
const DEFAULT_PLAN_LABEL = "入场计费";
|
|
1558
|
+
function formatPlayerGroups(groups) {
|
|
1559
|
+
const populatedGroups = groups.filter((group) => group.players.length > 0);
|
|
1560
|
+
// Each person is in exactly one group.
|
|
1561
|
+
const total = populatedGroups.reduce((sum, group) => sum + group.players.length, 0);
|
|
1551
1562
|
if (total === 0)
|
|
1552
1563
|
return "🫥 窝里目前没有玩家呢";
|
|
1553
1564
|
const lines = [`[总计 ${total} 人]`];
|
|
1554
1565
|
for (const group of populatedGroups) {
|
|
1555
|
-
const heading = group.
|
|
1556
|
-
? `${group.
|
|
1566
|
+
const heading = group.capacity !== undefined
|
|
1567
|
+
? `${group.label} ( ${group.players.length}/${group.capacity} )`
|
|
1557
1568
|
: `${group.label} ( ${group.players.length}人 )`;
|
|
1558
1569
|
lines.push(`\n${heading}:\n${formatPlayerNames(group.players)}`);
|
|
1559
1570
|
}
|
|
@@ -1587,11 +1598,6 @@ function formatReleaseVersion(value) {
|
|
|
1587
1598
|
const revision = cleanText(record.revision);
|
|
1588
1599
|
return !revision || revision === "unknown" ? release : `${release} (${revision})`;
|
|
1589
1600
|
}
|
|
1590
|
-
function matchesPlatformIdentity(identities, sender) {
|
|
1591
|
-
return identities.includes(`${sender.provider}:${sender.id}`)
|
|
1592
|
-
// Legacy unqualified staff lists belong to the original adapter only.
|
|
1593
|
-
|| (sender.provider === "onebot" && identities.includes(sender.id));
|
|
1594
|
-
}
|
|
1595
1601
|
function formatPlayerReference(sender) {
|
|
1596
1602
|
const name = sender.name && sender.name !== sender.id ? sender.name : "未知昵称";
|
|
1597
1603
|
return `${name}(${sender.provider}:${sender.id})`;
|
|
@@ -1664,12 +1670,6 @@ function sessionDisplayEnd(session, previewedAt) {
|
|
|
1664
1670
|
function now(config) {
|
|
1665
1671
|
return config?.now ? config.now() : new Date();
|
|
1666
1672
|
}
|
|
1667
|
-
function minDate(dates) {
|
|
1668
|
-
return dates.reduce((acc, d) => (d.getTime() < acc.getTime() ? d : acc), dates[0]);
|
|
1669
|
-
}
|
|
1670
|
-
function maxDate(dates) {
|
|
1671
|
-
return dates.reduce((acc, d) => (d.getTime() > acc.getTime() ? d : acc), dates[0]);
|
|
1672
|
-
}
|
|
1673
1673
|
function formatInventoryItem(row) {
|
|
1674
1674
|
let line = `- ${row.assetName || row.assetCode || "资产"} (x${formatNumber(row.quantity)})`;
|
|
1675
1675
|
if (row.expiresAt)
|