koishi-plugin-prism 0.1.41 → 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 +67 -54
- package/lib/ha-watch.d.ts +111 -0
- package/lib/ha-watch.js +349 -0
- package/lib/index.d.ts +159 -24
- package/lib/index.js +800 -578
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -3,42 +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.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
|
+
exports.platformSocketUrl = platformSocketUrl;
|
|
9
10
|
exports.humanReadableBotError = humanReadableBotError;
|
|
10
|
-
exports.resolveMahjongTableConfigs = resolveMahjongTableConfigs;
|
|
11
11
|
const display_time_js_1 = require("./display-time.js");
|
|
12
|
+
const ha_watch_js_1 = require("./ha-watch.js");
|
|
12
13
|
const koishi_1 = require("koishi");
|
|
13
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; } });
|
|
14
17
|
exports.name = "prism";
|
|
15
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.
|
|
16
22
|
exports.Config = koishi_1.Schema.object({
|
|
17
|
-
|
|
18
|
-
shopCode: koishi_1.Schema.string().description("
|
|
19
|
-
|
|
20
|
-
integrationToken: koishi_1.Schema.string().role("secret").description("集成 API Token"),
|
|
21
|
-
currencyName: koishi_1.Schema.string().default("猫粮").description("代币名称"),
|
|
22
|
-
defaultDoorDeviceId: koishi_1.Schema.string().default("front-door").description("默认开门设备名或别名"),
|
|
23
|
-
defaultScanProvider: koishi_1.Schema.string().default("aime").description("默认刷卡提供商"),
|
|
24
|
-
loginPricingConfigIds: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("默认入场绑定的计费策略ID"),
|
|
25
|
-
loginSessionLabel: koishi_1.Schema.string().default("音游区间").description("默认入场场次标签 (防重复入场)"),
|
|
26
|
-
enableStaffCommands: koishi_1.Schema.boolean().default(false).description("是否启用管理员指令"),
|
|
27
|
-
staffUserIds: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("允许执行管理员指令的平台身份列表(如 onebot:123456、telegram:123456)"),
|
|
28
|
-
powerCommandsAdminOnly: koishi_1.Schema.boolean().default(false).description("关机是否仅允许管理员使用;开机始终仅已入场玩家可用"),
|
|
29
|
-
playerCommands: koishi_1.Schema.union([
|
|
30
|
-
koishi_1.Schema.const("all").description("全部:玩家可以在 Bot 里入场、结账、上下桌和操作设备"),
|
|
31
|
-
koishi_1.Schema.const("readonly").description("只读:玩家只能绑定身份、查询和兑换;入场、结账、上下桌和设备操作仅管理员可用"),
|
|
32
|
-
]).default("all").description("玩家可用的命令"),
|
|
33
|
-
readOnlyNotice: koishi_1.Schema.string().default("请扫描设备上的二维码或碰 NFC,在网页或 App Clip 里操作").description("只读模式下玩家使用受限命令时的回复"),
|
|
34
|
-
logoutNotifyUserIds: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("结账账单私聊通知的平台身份列表(如 onebot:123456)"),
|
|
35
|
-
powerOffInterval: koishi_1.Schema.number().default(0).description("无人自动关机等待秒数 (0为禁用)"),
|
|
36
|
-
mahjongTableConfigs: koishi_1.Schema.array(koishi_1.Schema.object({
|
|
37
|
-
displayName: koishi_1.Schema.string().required().description("桌位显示名称和 session 标签"),
|
|
38
|
-
aliases: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("命令别名(至少一个),例如 a、四麻A"),
|
|
39
|
-
pricingConfigIds: koishi_1.Schema.array(koishi_1.Schema.string()).default([]).description("开局时绑定的计费方案 ID"),
|
|
40
|
-
})).default([]).description("麻将桌配置"),
|
|
41
|
-
mahjongTableSize: koishi_1.Schema.number().default(4).description("麻将桌人数限制"),
|
|
23
|
+
baseUrl: koishi_1.Schema.string().required().description("PRiSM 后端地址,例如 https://link.neri.moe"),
|
|
24
|
+
shopCode: koishi_1.Schema.string().required().description("统一平台店铺编号"),
|
|
25
|
+
integrationToken: koishi_1.Schema.string().role("secret").required().description("集成 API Token;其余设置在 PRiSM 商户工作台 → 资源 → 这个 Bot → Bot 设置"),
|
|
42
26
|
});
|
|
43
27
|
function apply(ctx, config) {
|
|
44
28
|
applyPrismKoishiPlugin(ctx, config);
|
|
@@ -60,139 +44,375 @@ class PrismBotClientError extends Error {
|
|
|
60
44
|
exports.PrismBotClientError = PrismBotClientError;
|
|
61
45
|
const USAGE = {
|
|
62
46
|
mahjong_join: "/上桌 <桌号>",
|
|
63
|
-
mahjong_leave: "/下桌",
|
|
47
|
+
mahjong_leave: "/下桌 [桌号]",
|
|
64
48
|
mahjong_list: "/麻将列表",
|
|
65
49
|
api_benchmark: "/api测速 [次数]",
|
|
50
|
+
ws_benchmark: "/ws测速 [次数]",
|
|
66
51
|
prism_on: "/prism on <设备名|别名|all>",
|
|
67
52
|
prism_off: "/prism off <设备名|别名|all>",
|
|
53
|
+
prism_keep: "/keep <设备名或别名>",
|
|
68
54
|
prism_coin: "/prism coin <设备名或别名> [数量]",
|
|
69
55
|
prism_scan: "/prism scan <设备名或别名>",
|
|
70
56
|
prism_redeem: "/prism redeem <兑换码>",
|
|
71
|
-
list: "/list",
|
|
57
|
+
list: "/list [资源或方案]",
|
|
72
58
|
show: "/show [设备ID]",
|
|
73
59
|
};
|
|
74
60
|
function applyPrismKoishiPlugin(ctx, config) {
|
|
75
61
|
const service = new PrismKoishiService(ctx, config);
|
|
76
|
-
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;
|
|
77
64
|
try {
|
|
78
|
-
|
|
79
|
-
|
|
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));
|
|
80
75
|
}
|
|
81
76
|
catch (error) {
|
|
82
|
-
|
|
83
|
-
return context.session?.messageId ? `${(0, koishi_1.h)("quote", { id: context.session.messageId })}${message}` : message;
|
|
77
|
+
return quoted(service.handleCommandError(error));
|
|
84
78
|
}
|
|
85
79
|
};
|
|
86
|
-
const
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
return "请店家配置统一平台店铺编号与 Bot 凭据";
|
|
90
|
-
const response = await fetch(`${config.baseUrl.replace(/\/+$/, "")}/api/v1/shops/${encodeURIComponent(config.shopCode)}/integration/platform-binding/confirm`, {
|
|
91
|
-
method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${config.integrationToken}` },
|
|
92
|
-
body: JSON.stringify({ code, provider: sender.provider, subject: sender.id }),
|
|
93
|
-
});
|
|
94
|
-
const body = await response.json();
|
|
95
|
-
return response.ok ? "绑定成功,请返回网页继续操作" : body.error?.message ?? "绑定失败,请重新生成验证码";
|
|
96
|
-
});
|
|
80
|
+
const effect = (handler, gate = {}) => wrap(handler, { ...gate, effect: true });
|
|
81
|
+
const billed = { billed: true };
|
|
82
|
+
const bind = wrap(async (context, code) => service.bind(await service.sender(context), code));
|
|
97
83
|
ctx.command("bind <code:string>", "绑定网页登录账号到当前平台身份").action(bind);
|
|
98
84
|
// Instructions already handed to players may still say prism.bind.
|
|
99
85
|
ctx.command("prism.bind <code:string>", "绑定网页登录账号到当前平台身份(旧命令,同 bind)").action(bind);
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
ctx.command("
|
|
109
|
-
ctx.command("
|
|
110
|
-
ctx.command("
|
|
111
|
-
|
|
112
|
-
ctx.command("
|
|
113
|
-
ctx.command("
|
|
114
|
-
ctx.command("
|
|
115
|
-
ctx.command("billing [target:user]", "预览玩家结账费用").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.billing(sender), context.session?.bot)));
|
|
116
|
-
ctx.command("wallet [target:user]", "查看玩家钱包").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.wallet(sender), context.session?.bot)));
|
|
117
|
-
ctx.command("api测速 [count:number]", "测试 Bot 到 PRiSM API 的钱包查询延迟").action(wrap(async (context, count) => service.benchmarkApi(await service.sender(context), count)));
|
|
118
|
-
ctx.command("versions", "查看 Bot 与 PRiSM 后端版本").action(wrap(async () => service.versions()));
|
|
119
|
-
ctx.command("items [target:user]", "查看玩家资产").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.items(sender), context.session?.bot)));
|
|
120
|
-
ctx.command("list", "查看当前在线玩家列表").action(wrap(async (context) => service.listActiveSessions(await service.sender(context))));
|
|
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));
|
|
95
|
+
ctx.command("api测速 [count:number]", "测试 Bot 走 HTTP 到 PRiSM 的延迟").action(wrap(async (context, count) => service.benchmarkApi(await service.sender(context), count)));
|
|
96
|
+
ctx.command("ws测速 [count:number]", "测试 Bot 走 WebSocket 到 PRiSM 的延迟").action(wrap(async (context, count) => service.benchmarkWs(await service.sender(context), count)));
|
|
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));
|
|
121
101
|
ctx.command("show [deviceId]", "查看设备电源状态").action(wrap(async (context, deviceId) => service.listDeviceStates(deviceId)));
|
|
122
|
-
ctx.command("history [target:user]", "查看玩家历史").action(wrap(async (context, target) => service.withTarget(await service.sender(context), target, (sender) => service.history(sender), context.session?.bot)));
|
|
123
|
-
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))));
|
|
124
104
|
ctx.command("on <deviceRef>", "请求启动指定设备电源").action(effect(async (context, deviceRef) => service.powerOn(await service.sender(context), deviceRef)));
|
|
125
105
|
ctx.command("off <deviceRef>", "请求关闭指定设备电源").action(effect(async (context, deviceRef) => service.powerOff(await service.sender(context), deviceRef)));
|
|
106
|
+
// Not limited by read-only mode: it never switches anything on, and the
|
|
107
|
+
// platform only accepts it from an entered player for a device that is on.
|
|
108
|
+
ctx.command("keep <deviceRef>", "延迟闲置设备的自动关机").action(wrap(async (context, deviceRef) => service.keep(await service.sender(context), deviceRef)));
|
|
126
109
|
ctx.command("coin <deviceRef> [count]", "请求向指定设备投币").action(effect(async (context, deviceRef, count) => service.coin(await service.sender(context), deviceRef, count)));
|
|
127
110
|
ctx.command("scan <deviceRef>", "使用当前玩家绑定的 Aime 卡刷卡").action(effect(async (context, deviceRef) => service.scan(await service.sender(context), deviceRef)));
|
|
128
|
-
ctx.command("redeem <code>", "兑换 PRiSM 礼物码").action(wrap(async (context, code) => service.redeem(await service.sender(context), code)));
|
|
129
|
-
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)));
|
|
130
|
-
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)));
|
|
131
|
-
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)));
|
|
132
|
-
|
|
133
|
-
if (intervalMs > 0 && typeof ctx.setInterval === "function") {
|
|
134
|
-
ctx.setInterval(() => {
|
|
135
|
-
service.autoPowerOffLoop().catch(() => {
|
|
136
|
-
/* swallow */
|
|
137
|
-
});
|
|
138
|
-
}, intervalMs);
|
|
139
|
-
}
|
|
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));
|
|
115
|
+
ctx.on?.("dispose", () => service.dispose());
|
|
140
116
|
}
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
117
|
+
const DEFAULT_READ_ONLY_NOTICE = "请扫描店内二维码或碰 NFC,在网页或 App Clip 里入场、结账和操作设备。";
|
|
118
|
+
const BILLING_DISABLED_NOTICE = "本店未启用计费";
|
|
119
|
+
/* --------------------------- platform connection --------------------------- */
|
|
120
|
+
const SOCKET_OPEN = 1;
|
|
121
|
+
const REQUEST_TIMEOUT_MS = 30_000;
|
|
122
|
+
const PING_MS = 30_000;
|
|
123
|
+
const FIRST_RETRY_MS = 1000;
|
|
124
|
+
const MAX_RETRY_MS = 30_000;
|
|
125
|
+
/**
|
|
126
|
+
* The one connection to PRiSM. Requests go out as frames and are matched to
|
|
127
|
+
* their replies by id; the platform also pushes events down it. While it is
|
|
128
|
+
* down a request fails at once: queueing a checkout or a top-up to run later
|
|
129
|
+
* would make players repeat it, and a resend could run it twice.
|
|
130
|
+
*/
|
|
131
|
+
class PrismSocket {
|
|
132
|
+
open;
|
|
133
|
+
url;
|
|
134
|
+
token;
|
|
135
|
+
hello;
|
|
136
|
+
onEvent;
|
|
137
|
+
logger;
|
|
138
|
+
hooks;
|
|
139
|
+
socket = null;
|
|
140
|
+
pending = new Map();
|
|
141
|
+
retryMs = FIRST_RETRY_MS;
|
|
142
|
+
retryTimer = null;
|
|
143
|
+
pingTimer = null;
|
|
144
|
+
lastHeard = 0;
|
|
145
|
+
stopped = false;
|
|
146
|
+
sequence = 0;
|
|
147
|
+
/** Bumped by every hello being prepared, so only the newest one is sent. */
|
|
148
|
+
greeting = 0;
|
|
149
|
+
pongWaiters = [];
|
|
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) {
|
|
162
|
+
this.open = open;
|
|
163
|
+
this.url = url;
|
|
164
|
+
this.token = token;
|
|
165
|
+
this.hello = hello;
|
|
166
|
+
this.onEvent = onEvent;
|
|
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
|
+
}
|
|
148
181
|
}
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
182
|
+
start() {
|
|
183
|
+
this.stopped = false;
|
|
184
|
+
this.connect();
|
|
185
|
+
}
|
|
186
|
+
stop() {
|
|
187
|
+
this.stopped = true;
|
|
188
|
+
if (this.retryTimer)
|
|
189
|
+
clearTimeout(this.retryTimer);
|
|
190
|
+
if (this.pingTimer)
|
|
191
|
+
clearInterval(this.pingTimer);
|
|
192
|
+
this.socket?.close(1000, "dispose");
|
|
193
|
+
this.socket = null;
|
|
194
|
+
this.failPending();
|
|
195
|
+
}
|
|
196
|
+
connect() {
|
|
197
|
+
let socket;
|
|
198
|
+
try {
|
|
199
|
+
socket = this.open(this.url, { Authorization: `Bearer ${this.token}` });
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
this.logger?.warn("PRiSM connection failed", error);
|
|
203
|
+
this.reconnectLater();
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
this.socket = socket;
|
|
207
|
+
socket.addEventListener("open", () => {
|
|
208
|
+
this.lastHeard = Date.now();
|
|
209
|
+
void this.greet(socket, true);
|
|
210
|
+
if (this.pingTimer)
|
|
211
|
+
clearInterval(this.pingTimer);
|
|
212
|
+
this.pingTimer = setInterval(() => {
|
|
213
|
+
// Two missed pings: the connection is gone even if no close arrived.
|
|
214
|
+
if (Date.now() - this.lastHeard > PING_MS * 2)
|
|
215
|
+
socket.close(4000, "silent");
|
|
216
|
+
else if (socket.readyState === SOCKET_OPEN)
|
|
217
|
+
socket.send("ping");
|
|
218
|
+
}, PING_MS);
|
|
219
|
+
});
|
|
220
|
+
socket.addEventListener("message", (event) => this.receive(String(event?.data ?? "")));
|
|
221
|
+
socket.addEventListener("close", () => {
|
|
222
|
+
if (this.socket !== socket)
|
|
223
|
+
return;
|
|
224
|
+
this.socket = null;
|
|
225
|
+
if (this.pingTimer)
|
|
226
|
+
clearInterval(this.pingTimer);
|
|
227
|
+
this.failPending();
|
|
228
|
+
// The platform forgets what this bot watches with the connection; it is asked again after hello.
|
|
229
|
+
this.hooks?.onClose();
|
|
230
|
+
this.reconnectLater();
|
|
231
|
+
});
|
|
232
|
+
socket.addEventListener("error", (error) => this.logger?.warn("PRiSM connection error", error?.message ?? error));
|
|
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 });
|
|
153
260
|
}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
261
|
+
reconnectLater() {
|
|
262
|
+
if (this.stopped)
|
|
263
|
+
return;
|
|
264
|
+
if (this.retryTimer)
|
|
265
|
+
clearTimeout(this.retryTimer);
|
|
266
|
+
this.retryTimer = setTimeout(() => this.connect(), this.retryMs);
|
|
267
|
+
this.retryMs = Math.min(this.retryMs * 2, MAX_RETRY_MS);
|
|
268
|
+
}
|
|
269
|
+
failPending() {
|
|
270
|
+
for (const [, waiter] of this.pending) {
|
|
271
|
+
clearTimeout(waiter.timer);
|
|
272
|
+
waiter.reject(unreachable());
|
|
160
273
|
}
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
if (
|
|
166
|
-
|
|
274
|
+
this.pending.clear();
|
|
275
|
+
}
|
|
276
|
+
receive(raw) {
|
|
277
|
+
this.lastHeard = Date.now();
|
|
278
|
+
if (raw === "pong") {
|
|
279
|
+
this.pongWaiters.shift()?.();
|
|
280
|
+
return;
|
|
167
281
|
}
|
|
282
|
+
let frame;
|
|
168
283
|
try {
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
284
|
+
frame = JSON.parse(raw);
|
|
285
|
+
}
|
|
286
|
+
catch {
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
if (frame?.type === "response" && typeof frame.id === "string") {
|
|
290
|
+
const waiter = this.pending.get(frame.id);
|
|
291
|
+
if (!waiter)
|
|
292
|
+
return;
|
|
293
|
+
this.pending.delete(frame.id);
|
|
294
|
+
clearTimeout(waiter.timer);
|
|
295
|
+
waiter.resolve({ status: Number(frame.status) || 500, body: frame.body, serverMs: typeof frame.serverMs === "number" ? frame.serverMs : null });
|
|
296
|
+
}
|
|
297
|
+
else if (frame?.type === "event" && typeof frame.event === "string") {
|
|
298
|
+
try {
|
|
299
|
+
this.onEvent({ event: frame.event, data: frame.data });
|
|
173
300
|
}
|
|
174
|
-
|
|
175
|
-
|
|
301
|
+
catch (error) {
|
|
302
|
+
this.logger?.warn("PRiSM event handling failed", error);
|
|
176
303
|
}
|
|
177
|
-
|
|
178
|
-
|
|
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);
|
|
179
315
|
}
|
|
180
|
-
|
|
181
|
-
|
|
316
|
+
catch (error) {
|
|
317
|
+
this.logger?.warn("PRiSM Home Assistant watch failed", error);
|
|
182
318
|
}
|
|
183
|
-
return response && typeof response === "object" && Object.hasOwn(response, "data") ? response.data : response;
|
|
184
319
|
}
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
320
|
+
}
|
|
321
|
+
/** One heartbeat round trip in milliseconds: the network to the platform and nothing else. */
|
|
322
|
+
ping() {
|
|
323
|
+
const socket = this.socket;
|
|
324
|
+
if (!socket || socket.readyState !== SOCKET_OPEN)
|
|
325
|
+
return Promise.reject(unreachable());
|
|
326
|
+
return new Promise((resolve, reject) => {
|
|
327
|
+
const startedAt = performance.now();
|
|
328
|
+
const timer = setTimeout(() => {
|
|
329
|
+
const index = this.pongWaiters.indexOf(answered);
|
|
330
|
+
if (index >= 0)
|
|
331
|
+
this.pongWaiters.splice(index, 1);
|
|
332
|
+
reject(new PrismBotClientError("服务器没有及时回应", "API_TIMEOUT", 0, {}));
|
|
333
|
+
}, REQUEST_TIMEOUT_MS);
|
|
334
|
+
const answered = () => {
|
|
335
|
+
clearTimeout(timer);
|
|
336
|
+
resolve(performance.now() - startedAt);
|
|
337
|
+
};
|
|
338
|
+
this.pongWaiters.push(answered);
|
|
339
|
+
socket.send("ping");
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
request(frame) {
|
|
343
|
+
const socket = this.socket;
|
|
344
|
+
if (!socket || socket.readyState !== SOCKET_OPEN)
|
|
345
|
+
return Promise.reject(unreachable());
|
|
346
|
+
const id = `${Date.now().toString(36)}-${(this.sequence++).toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
347
|
+
return new Promise((resolve, reject) => {
|
|
348
|
+
const timer = setTimeout(() => {
|
|
349
|
+
this.pending.delete(id);
|
|
350
|
+
reject(new PrismBotClientError("服务器没有及时回应,请稍后确认结果", "API_TIMEOUT", 0, {}));
|
|
351
|
+
}, REQUEST_TIMEOUT_MS);
|
|
352
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
353
|
+
try {
|
|
354
|
+
socket.send(JSON.stringify({ type: "request", id, ...frame }));
|
|
355
|
+
}
|
|
356
|
+
catch {
|
|
357
|
+
clearTimeout(timer);
|
|
358
|
+
this.pending.delete(id);
|
|
359
|
+
reject(unreachable());
|
|
193
360
|
}
|
|
194
|
-
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
exports.PrismSocket = PrismSocket;
|
|
365
|
+
function unreachable() {
|
|
366
|
+
return new PrismBotClientError("暂时连不上服务器", "API_UNREACHABLE", 0, {});
|
|
367
|
+
}
|
|
368
|
+
function replyError(status, body) {
|
|
369
|
+
const err = body && typeof body === "object" && typeof body.error === "object" ? body.error : {};
|
|
370
|
+
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 ?? {});
|
|
371
|
+
}
|
|
372
|
+
function benchmarkCount(raw) {
|
|
373
|
+
const count = raw == null || raw === "" ? 5 : Number(raw);
|
|
374
|
+
return Number.isInteger(count) && count >= 1 && count <= 10 ? count : null;
|
|
375
|
+
}
|
|
376
|
+
function spread(samples) {
|
|
377
|
+
const average = samples.reduce((sum, sample) => sum + sample, 0) / samples.length;
|
|
378
|
+
return `最小 ${Math.round(Math.min(...samples))} / 平均 ${Math.round(average)} / 最大 ${Math.round(Math.max(...samples))} ms`;
|
|
379
|
+
}
|
|
380
|
+
function serverLine(timings) {
|
|
381
|
+
const known = timings.map((timing) => timing.serverMs).filter((value) => value !== null);
|
|
382
|
+
if (!known.length)
|
|
383
|
+
return [];
|
|
384
|
+
return [`服务端处理:平均 ${Math.round(known.reduce((sum, value) => sum + value, 0) / known.length)} ms`];
|
|
385
|
+
}
|
|
386
|
+
/** The platform connection URL for a shop. */
|
|
387
|
+
function platformSocketUrl(baseUrl, shopCode) {
|
|
388
|
+
const base = baseUrl.trim().replace(/\/+$/, "").replace(/^http/i, "ws");
|
|
389
|
+
return `${base}/api/v1/shops/${encodeURIComponent(shopCode)}/integration/ws`;
|
|
390
|
+
}
|
|
391
|
+
/* ----------------------------- api client ---------------------------------- */
|
|
392
|
+
class PrismApiClient {
|
|
393
|
+
socket;
|
|
394
|
+
http;
|
|
395
|
+
constructor(socket, http) {
|
|
396
|
+
this.socket = socket;
|
|
397
|
+
this.http = http;
|
|
398
|
+
}
|
|
399
|
+
async request(method, path, options) {
|
|
400
|
+
let target = path.replace(/^\/rpc\//, "");
|
|
401
|
+
for (const [key, value] of Object.entries(options.params ?? {})) {
|
|
402
|
+
target = target.replace(`:${key}`, encodeURIComponent(String(value)));
|
|
195
403
|
}
|
|
404
|
+
const { status, body } = await this.socket.request({
|
|
405
|
+
method,
|
|
406
|
+
path: target,
|
|
407
|
+
...(options.query ? { query: options.query } : {}),
|
|
408
|
+
...(method === "GET" ? {} : { body: options.body ?? {} }),
|
|
409
|
+
});
|
|
410
|
+
if (status >= 400)
|
|
411
|
+
throw replyError(status, body);
|
|
412
|
+
return body && typeof body === "object" && Object.hasOwn(body, "data") ? body.data : body;
|
|
413
|
+
}
|
|
414
|
+
confirmPlatformBinding(code, provider, subject) {
|
|
415
|
+
return this.request("POST", "/rpc/integration/platform-binding/confirm", { body: { code, provider, subject } });
|
|
196
416
|
}
|
|
197
417
|
identityBody(identity) {
|
|
198
418
|
return {
|
|
@@ -200,72 +420,95 @@ class PrismApiClient {
|
|
|
200
420
|
provider: identity.provider,
|
|
201
421
|
subject: identity.subject,
|
|
202
422
|
},
|
|
203
|
-
...(identity.autoRegister === undefined ? {} : { autoRegister: identity.autoRegister }),
|
|
204
423
|
...(identity.displayName === undefined ? {} : { displayName: identity.displayName }),
|
|
205
424
|
};
|
|
206
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. */
|
|
207
431
|
async resolveOrRegisterIdentity(identity) {
|
|
208
|
-
const
|
|
209
|
-
? "/rpc/integration/players/by-identity/register"
|
|
210
|
-
: "/rpc/integration/players/by-identity/resolve";
|
|
211
|
-
const result = await this.request("POST", endpoint, {
|
|
212
|
-
token: this.config.integrationToken,
|
|
432
|
+
const result = await this.request("POST", "/rpc/integration/players/by-identity/register", {
|
|
213
433
|
body: this.identityBody(identity),
|
|
214
434
|
});
|
|
215
435
|
return result.player;
|
|
216
436
|
}
|
|
217
437
|
async getVersion() {
|
|
218
|
-
return this.request("GET", "
|
|
438
|
+
return this.request("GET", "version", {});
|
|
219
439
|
}
|
|
220
|
-
|
|
440
|
+
/** Admit a player into the shop's default plan; `created` is false when it was already billing. */
|
|
441
|
+
async startSessionByIdentity(identity) {
|
|
221
442
|
return this.request("POST", "/rpc/integration/players/by-identity/session/start", {
|
|
222
|
-
|
|
223
|
-
body: {
|
|
224
|
-
...this.identityBody(identity),
|
|
225
|
-
...(body ?? {}),
|
|
226
|
-
},
|
|
443
|
+
body: { ...this.identityBody(identity), entry: true },
|
|
227
444
|
});
|
|
228
445
|
}
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
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 },
|
|
234
450
|
});
|
|
235
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
|
+
}
|
|
236
459
|
async getWalletByIdentity(identity) {
|
|
237
460
|
return this.request("POST", "/rpc/integration/players/by-identity/wallet", {
|
|
238
|
-
token: this.config.integrationToken,
|
|
239
461
|
body: this.identityBody(identity),
|
|
240
462
|
});
|
|
241
463
|
}
|
|
464
|
+
/** The wallet query over the platform connection, timed. */
|
|
465
|
+
async timeWalletOverSocket(identity) {
|
|
466
|
+
const startedAt = performance.now();
|
|
467
|
+
const reply = await this.socket.request({ method: "POST", path: "integration/players/by-identity/wallet", body: this.identityBody(identity) });
|
|
468
|
+
const ms = performance.now() - startedAt;
|
|
469
|
+
if (reply.status >= 400)
|
|
470
|
+
throw replyError(reply.status, reply.body);
|
|
471
|
+
return { ms, serverMs: reply.serverMs ?? null };
|
|
472
|
+
}
|
|
473
|
+
/** The same wallet query as a plain HTTP request, the way the Bot used to call, timed. */
|
|
474
|
+
async timeWalletOverHttp(identity) {
|
|
475
|
+
if (!this.http)
|
|
476
|
+
throw new PrismBotClientError("HTTP 测速不可用", "HTTP_UNAVAILABLE", 0, {});
|
|
477
|
+
const { post, baseUrl, shopCode, token } = this.http;
|
|
478
|
+
const url = `${baseUrl.trim().replace(/\/+$/, "")}/api/v1/shops/${encodeURIComponent(shopCode)}/integration/players/by-identity/wallet`;
|
|
479
|
+
const startedAt = performance.now();
|
|
480
|
+
const response = await post(url, { authorization: `Bearer ${token}`, "content-type": "application/json" }, this.identityBody(identity));
|
|
481
|
+
const ms = performance.now() - startedAt;
|
|
482
|
+
if (response.status >= 400)
|
|
483
|
+
throw replyError(response.status, response.data);
|
|
484
|
+
const server = Number.parseFloat(response.headers.get("x-response-time") ?? "");
|
|
485
|
+
return { ms, serverMs: Number.isFinite(server) ? server : null, colo: response.headers.get("cf-ray")?.split("-").pop() ?? null };
|
|
486
|
+
}
|
|
487
|
+
pingSocket() {
|
|
488
|
+
return this.socket.ping();
|
|
489
|
+
}
|
|
242
490
|
async getAssetsByIdentity(identity) {
|
|
243
491
|
return this.request("POST", "/rpc/integration/players/by-identity/assets", {
|
|
244
|
-
token: this.config.integrationToken,
|
|
245
492
|
body: this.identityBody(identity),
|
|
246
493
|
});
|
|
247
494
|
}
|
|
248
495
|
async getSessionHistoryByIdentity(identity) {
|
|
249
496
|
return this.request("POST", "/rpc/integration/players/by-identity/history", {
|
|
250
|
-
token: this.config.integrationToken,
|
|
251
497
|
body: this.identityBody(identity),
|
|
252
498
|
});
|
|
253
499
|
}
|
|
254
500
|
async previewCheckoutByIdentity(identity) {
|
|
255
501
|
return this.request("POST", "/rpc/integration/players/by-identity/checkout/preview", {
|
|
256
|
-
token: this.config.integrationToken,
|
|
257
502
|
body: this.identityBody(identity),
|
|
258
503
|
});
|
|
259
504
|
}
|
|
260
505
|
async confirmCheckoutByIdentity(identity, closeSessionsBeforeBalanceCheck = true) {
|
|
261
506
|
return this.request("POST", "/rpc/integration/players/by-identity/checkout/confirm", {
|
|
262
|
-
token: this.config.integrationToken,
|
|
263
507
|
body: { ...this.identityBody(identity), closeSessionsBeforeBalanceCheck },
|
|
264
508
|
});
|
|
265
509
|
}
|
|
266
510
|
async redeemCodeByIdentity(identity, code) {
|
|
267
511
|
return this.request("POST", "/rpc/integration/players/by-identity/redeem", {
|
|
268
|
-
token: this.config.integrationToken,
|
|
269
512
|
body: {
|
|
270
513
|
...this.identityBody(identity),
|
|
271
514
|
code,
|
|
@@ -274,7 +517,6 @@ class PrismApiClient {
|
|
|
274
517
|
}
|
|
275
518
|
async requestDeviceCommandByIdentity(identity, command, options) {
|
|
276
519
|
return this.request("POST", "/rpc/integration/players/by-identity/device-actions", {
|
|
277
|
-
token: this.config.integrationToken,
|
|
278
520
|
body: {
|
|
279
521
|
...this.identityBody(identity),
|
|
280
522
|
...(options?.staffOverride ? { staffOverride: true } : {}),
|
|
@@ -288,7 +530,6 @@ class PrismApiClient {
|
|
|
288
530
|
}
|
|
289
531
|
async requestScanByIdentity(identity, scan) {
|
|
290
532
|
return this.request("POST", "/rpc/integration/players/by-identity/device-actions", {
|
|
291
|
-
token: this.config.integrationToken,
|
|
292
533
|
body: {
|
|
293
534
|
...this.identityBody(identity),
|
|
294
535
|
target: {
|
|
@@ -305,79 +546,172 @@ class PrismApiClient {
|
|
|
305
546
|
});
|
|
306
547
|
}
|
|
307
548
|
async listActiveSessions() {
|
|
308
|
-
return this.request("GET", "/rpc/integration/sessions/active", {
|
|
309
|
-
token: this.config.integrationToken,
|
|
310
|
-
});
|
|
549
|
+
return this.request("GET", "/rpc/integration/sessions/active", {});
|
|
311
550
|
}
|
|
312
551
|
async listDeviceStates() {
|
|
313
|
-
return this.request("GET", "/rpc/integration/device-states", {
|
|
314
|
-
token: this.config.integrationToken,
|
|
315
|
-
});
|
|
316
|
-
}
|
|
317
|
-
async adjustAssetsByIdentity(identity, adjustments) {
|
|
318
|
-
return this.request("POST", "/rpc/integration/players/by-identity/assets/adjustments", {
|
|
319
|
-
token: this.config.integrationToken,
|
|
320
|
-
body: { ...this.identityBody(identity), adjustments },
|
|
321
|
-
});
|
|
552
|
+
return this.request("GET", "/rpc/integration/device-states", {});
|
|
322
553
|
}
|
|
323
554
|
async adjustWalletByIdentity(identity, amount, reason) {
|
|
324
555
|
return this.request("POST", "/rpc/integration/players/by-identity/wallet/adjustment", {
|
|
325
|
-
token: this.config.integrationToken,
|
|
326
556
|
body: { ...this.identityBody(identity), amount, reason },
|
|
327
557
|
});
|
|
328
558
|
}
|
|
329
559
|
async checkoutWithOverrideByIdentity(identity, total, reason) {
|
|
330
560
|
return this.request("POST", "/rpc/integration/players/by-identity/checkout/override", {
|
|
331
|
-
token: this.config.integrationToken,
|
|
332
561
|
body: { ...this.identityBody(identity), total, reason },
|
|
333
562
|
});
|
|
334
563
|
}
|
|
335
564
|
}
|
|
336
|
-
/* ------------------------------- service ----------------------------------- */
|
|
337
565
|
class PrismKoishiService {
|
|
338
|
-
|
|
339
|
-
|
|
566
|
+
ctx;
|
|
567
|
+
options;
|
|
340
568
|
logoutInFlight = new Map();
|
|
341
569
|
client;
|
|
342
570
|
logger;
|
|
343
|
-
|
|
344
|
-
|
|
571
|
+
socket = null;
|
|
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) {
|
|
581
|
+
this.ctx = ctx;
|
|
582
|
+
this.options = options;
|
|
345
583
|
this.logger = ctx.logger?.("prism");
|
|
346
|
-
if (
|
|
347
|
-
this.client =
|
|
584
|
+
if (options.client) {
|
|
585
|
+
this.client = options.client;
|
|
586
|
+
return;
|
|
348
587
|
}
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
588
|
+
if (!options.shopCode || !options.baseUrl || !options.integrationToken) {
|
|
589
|
+
throw new Error("PRiSM Koishi plugin requires 'shopCode', 'baseUrl' and 'integrationToken'.");
|
|
590
|
+
}
|
|
591
|
+
const open = options.socket ?? ((url, headers) => {
|
|
592
|
+
const http = ctx.http;
|
|
593
|
+
if (!http?.ws)
|
|
594
|
+
throw new Error("Koishi http service with WebSocket support is required.");
|
|
595
|
+
return http.ws(url, { headers });
|
|
596
|
+
});
|
|
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) => {
|
|
603
|
+
if (event.event === "idle.reminder")
|
|
604
|
+
void this.remindIdle(event.data);
|
|
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(),
|
|
355
610
|
}
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
async post(url, body, c) {
|
|
364
|
-
const res = await fetch(url, { method: "POST", headers: c.headers, body: JSON.stringify(body) });
|
|
365
|
-
if (!res.ok)
|
|
366
|
-
throw { response: { data: await res.json(), status: res.status } };
|
|
367
|
-
return res.json();
|
|
368
|
-
},
|
|
369
|
-
async put(url, body, c) {
|
|
370
|
-
const res = await fetch(url, { method: "PUT", headers: c.headers, body: JSON.stringify(body) });
|
|
371
|
-
if (!res.ok)
|
|
372
|
-
throw { response: { data: await res.json(), status: res.status } };
|
|
373
|
-
return res.json();
|
|
374
|
-
}
|
|
375
|
-
};
|
|
376
|
-
this.client = new PrismApiClient(http, {
|
|
377
|
-
baseUrl: config.baseUrl,
|
|
378
|
-
shopCode: config.shopCode,
|
|
379
|
-
integrationToken: config.integrationToken,
|
|
611
|
+
: undefined);
|
|
612
|
+
const post = options.httpPost ?? (async (url, headers, body) => {
|
|
613
|
+
const http = ctx.http;
|
|
614
|
+
if (typeof http !== "function")
|
|
615
|
+
throw new PrismBotClientError("HTTP 测速需要 Koishi 的 http 服务", "HTTP_UNAVAILABLE", 0, {});
|
|
616
|
+
const response = await http(url, {
|
|
617
|
+
method: "POST", headers, data: body, keepAlive: true, timeout: REQUEST_TIMEOUT_MS, validateStatus: () => true,
|
|
380
618
|
});
|
|
619
|
+
return { status: response.status, headers: response.headers, data: response.data };
|
|
620
|
+
});
|
|
621
|
+
this.client = new PrismApiClient(this.socket, { post, baseUrl: options.baseUrl, shopCode: options.shopCode, token: options.integrationToken });
|
|
622
|
+
this.socket.start();
|
|
623
|
+
}
|
|
624
|
+
dispose() {
|
|
625
|
+
this.watcher?.stop();
|
|
626
|
+
this.socket?.stop();
|
|
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
|
+
}
|
|
688
|
+
async bind(sender, code) {
|
|
689
|
+
try {
|
|
690
|
+
await this.client.confirmPlatformBinding(code, sender.provider, sender.id);
|
|
691
|
+
return "绑定成功,请返回网页继续操作";
|
|
692
|
+
}
|
|
693
|
+
catch (error) {
|
|
694
|
+
if (error instanceof PrismBotClientError && error.status > 0)
|
|
695
|
+
return error.message || "绑定失败,请重新生成验证码";
|
|
696
|
+
throw error;
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
/** Tell the configured channels a power-off is coming. Short: they can read a device name. */
|
|
700
|
+
async remindIdle(reminder) {
|
|
701
|
+
const channels = this.bot?.settings.idleChannelIds ?? [];
|
|
702
|
+
if (!channels.length || typeof this.ctx.broadcast !== "function")
|
|
703
|
+
return;
|
|
704
|
+
const now = (this.options.now?.() ?? new Date()).getTime();
|
|
705
|
+
const minutes = Math.max(1, Math.round((reminder.at - now) / 60_000));
|
|
706
|
+
const names = reminder.devices.map((device) => device.name).join("、");
|
|
707
|
+
const message = reminder.reason === "shop_empty"
|
|
708
|
+
? `店里没人,${minutes} 分钟后全部关机`
|
|
709
|
+
: `${names} 闲置中,${minutes} 分钟后关机。已入场的玩家发送 keep 设备名 可以延迟`;
|
|
710
|
+
try {
|
|
711
|
+
await this.ctx.broadcast(channels, message);
|
|
712
|
+
}
|
|
713
|
+
catch (error) {
|
|
714
|
+
this.logger?.warn("PRiSM idle reminder failed", error);
|
|
381
715
|
}
|
|
382
716
|
}
|
|
383
717
|
async sender(context) {
|
|
@@ -397,20 +731,20 @@ class PrismKoishiService {
|
|
|
397
731
|
catch { }
|
|
398
732
|
return { id, name, provider };
|
|
399
733
|
}
|
|
400
|
-
async register(sender) {
|
|
401
|
-
await this.client.resolveOrRegisterIdentity(this.identity(sender));
|
|
402
|
-
return "注册成功";
|
|
403
|
-
}
|
|
404
734
|
async loginForTarget(actor, targetSubject, bot) {
|
|
405
735
|
return this.withTarget(actor, targetSubject, async (sender, isTargeted) => {
|
|
406
|
-
await this.client.startSessionByIdentity(this.identity(sender)
|
|
407
|
-
|
|
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;
|
|
408
746
|
}, bot);
|
|
409
747
|
}
|
|
410
|
-
async login(sender) {
|
|
411
|
-
await this.client.startSessionByIdentity(this.identity(sender), this.loginSessionBody());
|
|
412
|
-
return "✅ 入场成功";
|
|
413
|
-
}
|
|
414
748
|
async withTarget(actor, targetSubject, action, bot) {
|
|
415
749
|
const target = await this.targetSender(actor, targetSubject, bot);
|
|
416
750
|
if (typeof target === "string")
|
|
@@ -424,7 +758,7 @@ class PrismKoishiService {
|
|
|
424
758
|
return "金额必须大于 0";
|
|
425
759
|
const isAddition = direction === 1;
|
|
426
760
|
await this.client.adjustWalletByIdentity(this.identity(sender), amount * direction, isAddition ? "Koishi 管理员增加余额" : "Koishi 管理员扣除余额");
|
|
427
|
-
return `✅ 已为用户 ${formatPlayerReference(sender)}${isAddition ? "增加" : "扣除"} ${formatNumber(amount)} ${this.config.currencyName}`;
|
|
761
|
+
return `✅ 已为用户 ${formatPlayerReference(sender)}${isAddition ? "增加" : "扣除"} ${formatNumber(amount)} ${(await this.config()).currencyName}`;
|
|
428
762
|
}, bot);
|
|
429
763
|
}
|
|
430
764
|
async overwriteTargetCheckout(actor, targetSubject, rawAmount, rawReason, bot) {
|
|
@@ -434,124 +768,95 @@ class PrismKoishiService {
|
|
|
434
768
|
return "金额必须为非负数";
|
|
435
769
|
const reason = cleanText(rawReason) || "管理员调价";
|
|
436
770
|
const result = (await this.client.checkoutWithOverrideByIdentity(this.identity(sender), total, reason));
|
|
437
|
-
const playerId = String(result.playerSettlement.playerId);
|
|
438
|
-
if (playerId)
|
|
439
|
-
this.removeMahjongPlayer(playerId);
|
|
440
771
|
return this.formatAndNotifyCheckout(result, sender, "✅ 覆盖结账成功 · 结算账单", bot);
|
|
441
772
|
}, bot);
|
|
442
773
|
}
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
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)
|
|
446
781
|
return "请指定麻将桌,例如 /上桌 a;可先使用 /麻将列表 查看可用桌位。";
|
|
447
|
-
const
|
|
448
|
-
if (!
|
|
449
|
-
return `未找到麻将桌「${
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
const playerId = String(player.id ?? "");
|
|
454
|
-
const activeResult = (await this.client.listActiveSessions());
|
|
455
|
-
const activeSessions = (activeResult.sessions ?? []);
|
|
456
|
-
this.syncMahjongTableStates(activeSessions);
|
|
457
|
-
if (!this.hasEntrySession(playerId, activeSessions)) {
|
|
458
|
-
return "请先入场后再上桌。";
|
|
459
|
-
}
|
|
460
|
-
const existing = this.mahjongTableForPlayer(playerId);
|
|
461
|
-
if (existing)
|
|
462
|
-
return `你已经在 ${existing},无需重复上桌。`;
|
|
463
|
-
const state = this.mahjongTables.get(tableKey) ?? { waiting: [], activeSessions: {} };
|
|
464
|
-
this.mahjongTables.set(tableKey, state);
|
|
465
|
-
const activeCount = Object.keys(state.activeSessions).length;
|
|
466
|
-
const tableSize = this.config.mahjongTableSize ?? 4;
|
|
467
|
-
if (activeCount >= tableSize) {
|
|
468
|
-
return `「${tableSubject}」正在游玩中(${activeCount}/${tableSize}),请等待本局结束后再上桌。`;
|
|
469
|
-
}
|
|
470
|
-
if (activeCount > 0) {
|
|
471
|
-
const label = tableConfig.displayName;
|
|
472
|
-
const result = (await this.client.startSessionByIdentity(this.identity(sender), {
|
|
473
|
-
pricingConfigIds: tableConfig.pricingConfigIds,
|
|
474
|
-
label,
|
|
475
|
-
entry: false,
|
|
476
|
-
}));
|
|
477
|
-
const session = (result?.session ?? {});
|
|
478
|
-
const sessionId = String(session.id ?? "");
|
|
479
|
-
if (sessionId) {
|
|
480
|
-
state.activeSessions[playerId] = sessionId;
|
|
481
|
-
}
|
|
482
|
-
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;
|
|
483
788
|
}
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
}
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
const
|
|
511
|
-
|
|
512
|
-
const
|
|
513
|
-
const
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
const
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
const
|
|
535
|
-
|
|
536
|
-
|
|
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("、")}` : "");
|
|
537
844
|
}
|
|
538
845
|
async listMahjongTables() {
|
|
539
|
-
const
|
|
540
|
-
|
|
541
|
-
const tableSize = this.config.mahjongTableSize ?? 4;
|
|
542
|
-
const tables = uniqueMahjongConfigs(this.mahjongTableConfigs());
|
|
846
|
+
const result = (await this.client.listMahjongTables());
|
|
847
|
+
const tables = (result?.tables ?? []);
|
|
543
848
|
if (tables.length === 0)
|
|
544
849
|
return "当前没有配置任何麻将机。";
|
|
545
850
|
const lines = [`🀄️ 麻将机列表(${tables.length} 台)`];
|
|
546
851
|
for (const table of tables) {
|
|
547
|
-
const
|
|
548
|
-
const
|
|
549
|
-
const waitingCount = state.waiting.length;
|
|
852
|
+
const playing = table.seats.filter((seat) => seat.playing).length;
|
|
853
|
+
const waiting = table.seats.length - playing;
|
|
550
854
|
const statuses = [
|
|
551
|
-
...(
|
|
552
|
-
...(
|
|
855
|
+
...(playing > 0 ? [`游玩中 ${playing}/${table.capacity}`] : []),
|
|
856
|
+
...(waiting > 0 ? [`等位 ${waiting}/${table.capacity}`] : []),
|
|
553
857
|
];
|
|
554
|
-
|
|
858
|
+
const aliases = table.aliases ?? [];
|
|
859
|
+
lines.push(`- ${table.name}|别名:${aliases.length > 0 ? aliases.join("、") : "无"}|${statuses.join(";") || "空闲"}`);
|
|
555
860
|
}
|
|
556
861
|
return lines.join("\n");
|
|
557
862
|
}
|
|
@@ -578,9 +883,6 @@ class PrismKoishiService {
|
|
|
578
883
|
}
|
|
579
884
|
async performLogout(sender, bot) {
|
|
580
885
|
const result = (await this.client.confirmCheckoutByIdentity(this.identity(sender), false));
|
|
581
|
-
const playerId = String(result.playerSettlement.playerId);
|
|
582
|
-
if (playerId)
|
|
583
|
-
this.removeMahjongPlayer(playerId);
|
|
584
886
|
return this.formatAndNotifyCheckout(result, sender, "✅ 退场成功 · 结算账单", bot);
|
|
585
887
|
}
|
|
586
888
|
async formatAndNotifyCheckout(result, sender, title, bot) {
|
|
@@ -625,40 +927,55 @@ class PrismKoishiService {
|
|
|
625
927
|
wallet: result.wallet,
|
|
626
928
|
};
|
|
627
929
|
const receipt = await this.formatCheckoutPreview(synthetic, sender, title, false);
|
|
628
|
-
|
|
629
|
-
const
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
return [identity.startsWith("private:") ? identity : `private:${identity}`];
|
|
634
|
-
return [];
|
|
635
|
-
});
|
|
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
|
+
: [];
|
|
636
935
|
if (channelIds.length > 0 && bot?.broadcast)
|
|
637
936
|
await bot.broadcast(channelIds, receipt);
|
|
638
937
|
return receipt;
|
|
639
938
|
}
|
|
640
939
|
async wallet(sender) {
|
|
641
940
|
const result = (await this.client.getWalletByIdentity(this.identity(sender)));
|
|
642
|
-
return formatWallet(result.wallet, this.config.currencyName);
|
|
941
|
+
return formatWallet(result.wallet, (await this.config()).currencyName);
|
|
643
942
|
}
|
|
943
|
+
/**
|
|
944
|
+
* The wallet query over plain HTTP. The first request usually has to open a
|
|
945
|
+
* connection (DNS, TCP, TLS), so it is reported apart from the reused ones.
|
|
946
|
+
*/
|
|
644
947
|
async benchmarkApi(sender, rawCount) {
|
|
645
|
-
const count =
|
|
646
|
-
if (
|
|
948
|
+
const count = benchmarkCount(rawCount);
|
|
949
|
+
if (count === null)
|
|
647
950
|
return "次数须为 1 到 10 的整数。";
|
|
648
|
-
const
|
|
649
|
-
for (let index = 0; index < count; index++)
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
951
|
+
const timings = [];
|
|
952
|
+
for (let index = 0; index < count; index++)
|
|
953
|
+
timings.push(await this.client.timeWalletOverHttp(this.identity(sender)));
|
|
954
|
+
const [first, ...rest] = timings;
|
|
955
|
+
return [
|
|
956
|
+
`📡 API 测速(HTTP,钱包查询 ${count} 次)`,
|
|
957
|
+
`首次:${Math.round(first.ms)} ms(含建立连接)`,
|
|
958
|
+
...(rest.length ? [`之后:${spread(rest.map((timing) => timing.ms))}`] : []),
|
|
959
|
+
...serverLine(timings),
|
|
960
|
+
...(first.colo ? [`节点:${first.colo}`] : []),
|
|
961
|
+
].join("\n");
|
|
962
|
+
}
|
|
963
|
+
/** Heartbeats (the network alone) and the same wallet query over the platform connection. */
|
|
964
|
+
async benchmarkWs(sender, rawCount) {
|
|
965
|
+
const count = benchmarkCount(rawCount);
|
|
966
|
+
if (count === null)
|
|
967
|
+
return "次数须为 1 到 10 的整数。";
|
|
968
|
+
const pings = [];
|
|
969
|
+
for (let index = 0; index < count; index++)
|
|
970
|
+
pings.push(await this.client.pingSocket());
|
|
971
|
+
const timings = [];
|
|
972
|
+
for (let index = 0; index < count; index++)
|
|
973
|
+
timings.push(await this.client.timeWalletOverSocket(this.identity(sender)));
|
|
657
974
|
return [
|
|
658
|
-
`📡
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
975
|
+
`📡 WS 测速(${count} 次)`,
|
|
976
|
+
`心跳:${spread(pings)}`,
|
|
977
|
+
`钱包查询:${spread(timings.map((timing) => timing.ms))}`,
|
|
978
|
+
...serverLine(timings),
|
|
662
979
|
].join("\n");
|
|
663
980
|
}
|
|
664
981
|
async versions() {
|
|
@@ -684,13 +1001,17 @@ class PrismKoishiService {
|
|
|
684
1001
|
}
|
|
685
1002
|
async history(sender) {
|
|
686
1003
|
const result = (await this.client.getSessionHistoryByIdentity(this.identity(sender)));
|
|
687
|
-
return formatHistory(result.sessions, this.config.currencyName);
|
|
1004
|
+
return formatHistory(result.sessions, (await this.config()).currencyName);
|
|
688
1005
|
}
|
|
1006
|
+
/** Open the door the bot's settings name. */
|
|
689
1007
|
async lock(sender) {
|
|
1008
|
+
const door = (await this.config()).door;
|
|
1009
|
+
if (!door)
|
|
1010
|
+
return "🔑 本店还没有设置 Bot 开的门";
|
|
690
1011
|
try {
|
|
691
1012
|
const result = await this.client.requestDeviceCommandByIdentity(this.identity(sender), {
|
|
692
1013
|
type: "door.open",
|
|
693
|
-
target: { kind: "facility", ref:
|
|
1014
|
+
target: { kind: "facility", ref: door.id },
|
|
694
1015
|
});
|
|
695
1016
|
const failure = this.getCommandFailureMessage(result);
|
|
696
1017
|
if (failure) {
|
|
@@ -755,7 +1076,7 @@ class PrismKoishiService {
|
|
|
755
1076
|
try {
|
|
756
1077
|
const result = await this.client.requestScanByIdentity(this.identity(sender), {
|
|
757
1078
|
deviceRef,
|
|
758
|
-
provider:
|
|
1079
|
+
provider: "aime",
|
|
759
1080
|
});
|
|
760
1081
|
const failure = deviceCommandFailureReason(result);
|
|
761
1082
|
if (failure) {
|
|
@@ -780,31 +1101,41 @@ class PrismKoishiService {
|
|
|
780
1101
|
return "兑换成功,但没有获得任何物品。";
|
|
781
1102
|
return ["✅ 兑换成功!您获得了以下物品:", ...grantedAssets.map(formatRedeemedItem)].join("\n");
|
|
782
1103
|
}
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
])
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
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);
|
|
808
1139
|
}
|
|
809
1140
|
async listDeviceStates(rawAlias) {
|
|
810
1141
|
const alias = cleanText(rawAlias);
|
|
@@ -823,27 +1154,30 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
823
1154
|
.map((d) => `${d.label || d.deviceId}: ${normalizeDeviceState(d.state)}`)
|
|
824
1155
|
.join("\n");
|
|
825
1156
|
}
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
1157
|
+
/** Keep a running device from being switched off as idle; never switches one on. */
|
|
1158
|
+
async keep(sender, deviceRef) {
|
|
1159
|
+
try {
|
|
1160
|
+
const result = await this.client.requestDeviceCommandByIdentity(this.identity(sender), {
|
|
1161
|
+
type: "power.keep",
|
|
1162
|
+
target: { kind: "facility", ref: deviceRef },
|
|
1163
|
+
});
|
|
1164
|
+
if (this.getCommandFailureMessage(result)) {
|
|
1165
|
+
this.logDeviceCommandFailure(result);
|
|
1166
|
+
return `延迟失败,${deviceCommandFailureReason(result)}`;
|
|
1167
|
+
}
|
|
1168
|
+
return `✅ ${result.action.payload.deviceLabel} 已延迟关机`;
|
|
1169
|
+
}
|
|
1170
|
+
catch (error) {
|
|
1171
|
+
this.logCommandError(error);
|
|
1172
|
+
return `延迟失败,${powerFailureReason(error)}`;
|
|
1173
|
+
}
|
|
841
1174
|
}
|
|
842
1175
|
/* ---------------------------- helpers ---------------------------------- */
|
|
843
|
-
async power(sender, deviceRef, state
|
|
1176
|
+
async power(sender, deviceRef, state) {
|
|
844
1177
|
const operation = state === "on" ? "启动" : "关闭";
|
|
845
|
-
const
|
|
846
|
-
|
|
1178
|
+
const config = await this.config();
|
|
1179
|
+
const staffOverride = state === "off" && config.settings.powerOffStaffOnly;
|
|
1180
|
+
if (staffOverride && !this.isStaff(config, sender)) {
|
|
847
1181
|
return `${operation}失败,权限不足`;
|
|
848
1182
|
}
|
|
849
1183
|
try {
|
|
@@ -873,10 +1207,10 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
873
1207
|
return null;
|
|
874
1208
|
}
|
|
875
1209
|
async resolvePlatformName(subject, provider) {
|
|
876
|
-
if (!this.
|
|
1210
|
+
if (!this.options.resolveDisplayName)
|
|
877
1211
|
return null;
|
|
878
1212
|
try {
|
|
879
|
-
return (await this.
|
|
1213
|
+
return (await this.options.resolveDisplayName(subject, provider)) ?? null;
|
|
880
1214
|
}
|
|
881
1215
|
catch {
|
|
882
1216
|
return null;
|
|
@@ -899,50 +1233,6 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
899
1233
|
|| player.playerId
|
|
900
1234
|
|| "未知玩家";
|
|
901
1235
|
}
|
|
902
|
-
async buildPlayerGroups(players, tableByLabel, provider) {
|
|
903
|
-
const groups = { groups: [] };
|
|
904
|
-
const groupByLabel = new Map();
|
|
905
|
-
const musicLabel = this.config.loginSessionLabel?.trim() || "音游区间";
|
|
906
|
-
for (const player of players.values()) {
|
|
907
|
-
player.displayName = await this.displayNameForPlayer(player, provider);
|
|
908
|
-
const nonMusic = player.sessions.filter((session) => Boolean(session.label) && session.label !== "entry" && session.label !== musicLabel);
|
|
909
|
-
const source = nonMusic.length > 0 ? nonMusic : player.sessions;
|
|
910
|
-
const selected = source.reduce((latest, session) => !latest || sessionStartedAt(session) > sessionStartedAt(latest) ? session : latest, undefined);
|
|
911
|
-
const label = selected?.label === "entry" ? musicLabel : selected?.label || musicLabel;
|
|
912
|
-
let group = groupByLabel.get(label);
|
|
913
|
-
if (!group) {
|
|
914
|
-
group = { label, table: tableByLabel.get(label), players: [] };
|
|
915
|
-
groupByLabel.set(label, group);
|
|
916
|
-
groups.groups.push(group);
|
|
917
|
-
}
|
|
918
|
-
group.players.push(player);
|
|
919
|
-
}
|
|
920
|
-
return groups;
|
|
921
|
-
}
|
|
922
|
-
mergeWaitingSeats(groups) {
|
|
923
|
-
for (const [tableId, state] of this.mahjongTables) {
|
|
924
|
-
const table = uniqueMahjongConfigs(this.mahjongTableConfigs()).find((candidate) => candidate.tableId === tableId);
|
|
925
|
-
if (!table)
|
|
926
|
-
continue;
|
|
927
|
-
const label = mahjongSessionLabel(table);
|
|
928
|
-
let group = groups.groups.find((candidate) => candidate.label === label);
|
|
929
|
-
if (!group) {
|
|
930
|
-
group = { label, table, players: [] };
|
|
931
|
-
groups.groups.push(group);
|
|
932
|
-
}
|
|
933
|
-
for (const seat of state.waiting) {
|
|
934
|
-
if (group.players.some((player) => player.playerId === seat.playerId))
|
|
935
|
-
continue;
|
|
936
|
-
const existing = groups.groups.flatMap((candidate) => candidate.players)
|
|
937
|
-
.find((player) => player.playerId === seat.playerId);
|
|
938
|
-
for (const candidate of groups.groups) {
|
|
939
|
-
if (candidate !== group)
|
|
940
|
-
candidate.players = candidate.players.filter((player) => player.playerId !== seat.playerId);
|
|
941
|
-
}
|
|
942
|
-
group.players.push(existing ?? { playerId: seat.playerId, sessions: [], displayName: seat.displayName });
|
|
943
|
-
}
|
|
944
|
-
}
|
|
945
|
-
}
|
|
946
1236
|
async resolvePlayerDisplay(sender, playerId) {
|
|
947
1237
|
if (!sender)
|
|
948
1238
|
return playerId || "未知玩家";
|
|
@@ -952,67 +1242,13 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
952
1242
|
|| "未知昵称";
|
|
953
1243
|
return `玩家:${name}(${sender.provider}:${sender.id})`;
|
|
954
1244
|
}
|
|
955
|
-
mahjongTableForPlayer(playerId) {
|
|
956
|
-
for (const [tableId, state] of this.mahjongTables) {
|
|
957
|
-
if (state.activeSessions[playerId])
|
|
958
|
-
return tableId;
|
|
959
|
-
if (state.waiting.some((seat) => seat.playerId === playerId))
|
|
960
|
-
return tableId;
|
|
961
|
-
}
|
|
962
|
-
return null;
|
|
963
|
-
}
|
|
964
|
-
removeMahjongPlayer(playerId) {
|
|
965
|
-
for (const state of this.mahjongTables.values()) {
|
|
966
|
-
delete state.activeSessions[playerId];
|
|
967
|
-
state.waiting = state.waiting.filter((seat) => seat.playerId !== playerId);
|
|
968
|
-
}
|
|
969
|
-
}
|
|
970
|
-
mahjongTableConfigs() {
|
|
971
|
-
return resolveMahjongTableConfigs(this.config.mahjongTableConfigs ?? []);
|
|
972
|
-
}
|
|
973
|
-
syncMahjongTableStates(sessions) {
|
|
974
|
-
const tables = uniqueMahjongConfigs(this.mahjongTableConfigs());
|
|
975
|
-
const tableByLabel = new Map(tables.map((table) => [
|
|
976
|
-
mahjongSessionLabel(table),
|
|
977
|
-
table,
|
|
978
|
-
]));
|
|
979
|
-
// All playerIds that still have at least one active session in the backend.
|
|
980
|
-
// Used to evict waiting seats for players who have fully checked out externally.
|
|
981
|
-
const allActivePlayerIds = new Set(sessions.map((s) => String(s.playerId ?? "")).filter(Boolean));
|
|
982
|
-
const activeByTable = new Map();
|
|
983
|
-
for (const session of sessions) {
|
|
984
|
-
const table = tableByLabel.get(session.label ?? "");
|
|
985
|
-
const playerId = String(session.playerId ?? "");
|
|
986
|
-
const sessionId = String(session.id ?? "");
|
|
987
|
-
if (!table || !playerId || !sessionId)
|
|
988
|
-
continue;
|
|
989
|
-
const active = activeByTable.get(table.tableId) ?? {};
|
|
990
|
-
active[playerId] = sessionId;
|
|
991
|
-
activeByTable.set(table.tableId, active);
|
|
992
|
-
}
|
|
993
|
-
for (const table of tables) {
|
|
994
|
-
const state = this.mahjongTables.get(table.tableId) ?? { waiting: [], activeSessions: {} };
|
|
995
|
-
state.activeSessions = activeByTable.get(table.tableId) ?? {};
|
|
996
|
-
// Remove seats that have been promoted to active, or whose players have
|
|
997
|
-
// fully left the backend (no entry session remaining — orphan eviction).
|
|
998
|
-
state.waiting = state.waiting.filter((seat) => !state.activeSessions[seat.playerId] && allActivePlayerIds.has(seat.playerId));
|
|
999
|
-
if (state.waiting.length > 0 || Object.keys(state.activeSessions).length > 0 || this.mahjongTables.has(table.tableId)) {
|
|
1000
|
-
this.mahjongTables.set(table.tableId, state);
|
|
1001
|
-
}
|
|
1002
|
-
}
|
|
1003
|
-
}
|
|
1004
1245
|
async resolvePlayer(sender) {
|
|
1005
1246
|
return (await this.client.resolveOrRegisterIdentity(this.identity(sender)));
|
|
1006
1247
|
}
|
|
1007
|
-
hasEntrySession(playerId, sessions) {
|
|
1008
|
-
const label = this.config.loginSessionLabel?.trim();
|
|
1009
|
-
return sessions.some((session) => session.playerId === playerId && (session.label === "entry" || (label ? session.label === label : true)));
|
|
1010
|
-
}
|
|
1011
1248
|
identity(sender) {
|
|
1012
1249
|
return {
|
|
1013
1250
|
provider: sender.provider,
|
|
1014
1251
|
subject: sender.id,
|
|
1015
|
-
autoRegister: this.config.autoRegister,
|
|
1016
1252
|
displayName: sender.name || `${sender.provider} ${sender.id}`,
|
|
1017
1253
|
};
|
|
1018
1254
|
}
|
|
@@ -1027,9 +1263,12 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
1027
1263
|
return "请在目标平台使用该命令";
|
|
1028
1264
|
if (!subject)
|
|
1029
1265
|
return "无法获取目标平台身份";
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
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 "权限不足";
|
|
1033
1272
|
try {
|
|
1034
1273
|
const user = await bot?.getUser?.(subject);
|
|
1035
1274
|
return { id: subject, name: user?.name || subject, provider };
|
|
@@ -1038,35 +1277,8 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
1038
1277
|
return { id: subject, name: subject, provider };
|
|
1039
1278
|
}
|
|
1040
1279
|
}
|
|
1041
|
-
loginSessionBody() {
|
|
1042
|
-
const pricingConfigIds = (this.config.loginPricingConfigIds ?? [])
|
|
1043
|
-
.map((id) => id.trim())
|
|
1044
|
-
.filter(Boolean);
|
|
1045
|
-
const label = this.config.loginSessionLabel?.trim();
|
|
1046
|
-
return {
|
|
1047
|
-
entry: true,
|
|
1048
|
-
...(pricingConfigIds.length === 0 ? {} : { pricingConfigIds }),
|
|
1049
|
-
...(label ? { label } : {}),
|
|
1050
|
-
};
|
|
1051
|
-
}
|
|
1052
|
-
staffDenied(sender) {
|
|
1053
|
-
if (!this.config.enableStaffCommands)
|
|
1054
|
-
return "员工命令未启用";
|
|
1055
|
-
const allowed = this.config.staffUserIds ?? [];
|
|
1056
|
-
if (allowed.length > 0 && !matchesPlatformIdentity(allowed, sender))
|
|
1057
|
-
return "权限不足";
|
|
1058
|
-
return null;
|
|
1059
|
-
}
|
|
1060
|
-
targetStaffDenied(sender) {
|
|
1061
|
-
if (!this.config.enableStaffCommands)
|
|
1062
|
-
return "员工命令未启用";
|
|
1063
|
-
const allowed = this.config.staffUserIds ?? [];
|
|
1064
|
-
if (!matchesPlatformIdentity(allowed, sender))
|
|
1065
|
-
return "权限不足";
|
|
1066
|
-
return null;
|
|
1067
|
-
}
|
|
1068
1280
|
async formatCheckoutPreview(result, sender, title = "【结算账单】", isPreview) {
|
|
1069
|
-
const currency = this.config.currencyName;
|
|
1281
|
+
const currency = (await this.config()).currencyName;
|
|
1070
1282
|
const preview = result.settlementPreview;
|
|
1071
1283
|
const playerId = preview.playerId;
|
|
1072
1284
|
const subtotal = preview.subtotal;
|
|
@@ -1093,12 +1305,12 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
1093
1305
|
const validEnds = sessionPreviews.map(s => s.endedAt || (s.status === "active" ? preview.previewedAt : null)).filter(value => (0, display_time_js_1.parseDateTime)(value));
|
|
1094
1306
|
if (validStarts.length > 0) {
|
|
1095
1307
|
const overallStart = validStarts.reduce((a, b) => Date.parse(a) < Date.parse(b) ? a : b);
|
|
1096
|
-
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();
|
|
1097
1309
|
const offsets = [...new Set([(0, display_time_js_1.apiOffsetLabel)(overallStart), (0, display_time_js_1.apiOffsetLabel)(overallEnd)])].join(" / ");
|
|
1098
1310
|
lines.push(`⏰ 游玩时间:${(0, display_time_js_1.formatHM)(overallStart)}–${(0, display_time_js_1.formatHM)(overallEnd)}(${offsets})`);
|
|
1099
1311
|
}
|
|
1100
1312
|
for (const sPrev of sessionPreviews) {
|
|
1101
|
-
const label = sPrev?.label === "entry" ?
|
|
1313
|
+
const label = sPrev?.label === "entry" ? DEFAULT_PLAN_LABEL : sPrev?.label || "计时区间";
|
|
1102
1314
|
const startDt = (0, display_time_js_1.parseDateTime)(sPrev?.startedAt);
|
|
1103
1315
|
const endDt = sessionDisplayEnd(sPrev, previewedAt);
|
|
1104
1316
|
const status = sPrev?.status ?? "active";
|
|
@@ -1176,8 +1388,8 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
1176
1388
|
handleCommandError(error) {
|
|
1177
1389
|
this.logCommandError(error);
|
|
1178
1390
|
if (error instanceof PrismBotClientError) {
|
|
1179
|
-
if (error.code?.startsWith("LOCATION_") && this.
|
|
1180
|
-
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)}`;
|
|
1181
1393
|
}
|
|
1182
1394
|
return humanReadableBotError(error);
|
|
1183
1395
|
}
|
|
@@ -1196,9 +1408,10 @@ ${table.players.map(player => player.name).join("、")}`),
|
|
|
1196
1408
|
function humanReadableBotError(error) {
|
|
1197
1409
|
if (error.code === "INVALID_PLATFORM_IDENTITY")
|
|
1198
1410
|
return error.message;
|
|
1199
|
-
if (error.code === "
|
|
1200
|
-
return "
|
|
1201
|
-
|
|
1411
|
+
if (error.code === "BOT_DISABLED")
|
|
1412
|
+
return "Bot 已被店铺停用";
|
|
1413
|
+
if (error.code === "BILLING_DISABLED")
|
|
1414
|
+
return BILLING_DISABLED_NOTICE;
|
|
1202
1415
|
if (error.code === "PLAYER_HAS_NO_UNSETTLED_SESSIONS") {
|
|
1203
1416
|
return "您当前没有未结算的账单,无需结账。";
|
|
1204
1417
|
}
|
|
@@ -1214,7 +1427,9 @@ function humanReadableBotError(error) {
|
|
|
1214
1427
|
if (error.code === "INSUFFICIENT_BALANCE") {
|
|
1215
1428
|
return "余额不足,暂时不能结账。请先充值,或由店员在后台改价后再结账。";
|
|
1216
1429
|
}
|
|
1217
|
-
if (error.code === "API_UNREACHABLE"
|
|
1430
|
+
if (error.code === "API_UNREACHABLE")
|
|
1431
|
+
return "操作失败,暂时连不上服务器。";
|
|
1432
|
+
if (error.code === "NETWORK_ERROR" || error.code === "HTTP_0") {
|
|
1218
1433
|
return genericCommandFailure();
|
|
1219
1434
|
}
|
|
1220
1435
|
if (error.code === "API_TIMEOUT") {
|
|
@@ -1234,6 +1449,8 @@ function powerFailureReason(error) {
|
|
|
1234
1449
|
return "玩家未入场";
|
|
1235
1450
|
if (error.code === "PLAYER_IDENTITY_NOT_FOUND")
|
|
1236
1451
|
return "玩家未注册";
|
|
1452
|
+
if (error.code === "BILLING_DISABLED")
|
|
1453
|
+
return BILLING_DISABLED_NOTICE;
|
|
1237
1454
|
return "请稍后再试";
|
|
1238
1455
|
}
|
|
1239
1456
|
return "请稍后再试";
|
|
@@ -1249,6 +1466,8 @@ function deviceActionFailureReason(error) {
|
|
|
1249
1466
|
return "玩家未绑定 Aime 卡";
|
|
1250
1467
|
if (error.code === "COIN_COMMAND_COOLDOWN_ACTIVE")
|
|
1251
1468
|
return "投币冷却中,请稍后再试";
|
|
1469
|
+
if (error.code === "BILLING_DISABLED")
|
|
1470
|
+
return BILLING_DISABLED_NOTICE;
|
|
1252
1471
|
return "请稍后再试";
|
|
1253
1472
|
}
|
|
1254
1473
|
function deviceCommandFailureReason(result) {
|
|
@@ -1286,52 +1505,66 @@ function normalizeDeviceState(value) {
|
|
|
1286
1505
|
}
|
|
1287
1506
|
return raw;
|
|
1288
1507
|
}
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
const tableId = displayName;
|
|
1294
|
-
const aliases = [...new Set((input.aliases ?? []).map(cleanText).filter(Boolean))];
|
|
1295
|
-
const pricingConfigIds = (input.pricingConfigIds ?? []).map(cleanText).filter(Boolean);
|
|
1296
|
-
if (!tableId || !displayName || pricingConfigIds.length === 0)
|
|
1297
|
-
continue;
|
|
1298
|
-
const table = { tableId, displayName, aliases, pricingConfigIds };
|
|
1299
|
-
for (const alias of aliases)
|
|
1300
|
-
tables.set(alias, table);
|
|
1301
|
-
}
|
|
1302
|
-
return tables;
|
|
1303
|
-
}
|
|
1304
|
-
function uniqueMahjongConfigs(tables) {
|
|
1305
|
-
return [...new Map([...tables.values()].map((table) => [table.tableId, table])).values()];
|
|
1306
|
-
}
|
|
1307
|
-
function mahjongSessionLabel(table) {
|
|
1308
|
-
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;
|
|
1309
1512
|
}
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
const player = players.get(playerId) ?? { playerId, sessions: [] };
|
|
1317
|
-
player.sessions.push(session);
|
|
1318
|
-
players.set(playerId, player);
|
|
1319
|
-
}
|
|
1320
|
-
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;
|
|
1321
1519
|
}
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
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
|
+
};
|
|
1325
1555
|
}
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
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);
|
|
1329
1562
|
if (total === 0)
|
|
1330
1563
|
return "🫥 窝里目前没有玩家呢";
|
|
1331
1564
|
const lines = [`[总计 ${total} 人]`];
|
|
1332
1565
|
for (const group of populatedGroups) {
|
|
1333
|
-
const heading = group.
|
|
1334
|
-
? `${group.
|
|
1566
|
+
const heading = group.capacity !== undefined
|
|
1567
|
+
? `${group.label} ( ${group.players.length}/${group.capacity} )`
|
|
1335
1568
|
: `${group.label} ( ${group.players.length}人 )`;
|
|
1336
1569
|
lines.push(`\n${heading}:\n${formatPlayerNames(group.players)}`);
|
|
1337
1570
|
}
|
|
@@ -1365,11 +1598,6 @@ function formatReleaseVersion(value) {
|
|
|
1365
1598
|
const revision = cleanText(record.revision);
|
|
1366
1599
|
return !revision || revision === "unknown" ? release : `${release} (${revision})`;
|
|
1367
1600
|
}
|
|
1368
|
-
function matchesPlatformIdentity(identities, sender) {
|
|
1369
|
-
return identities.includes(`${sender.provider}:${sender.id}`)
|
|
1370
|
-
// Legacy unqualified staff lists belong to the original adapter only.
|
|
1371
|
-
|| (sender.provider === "onebot" && identities.includes(sender.id));
|
|
1372
|
-
}
|
|
1373
1601
|
function formatPlayerReference(sender) {
|
|
1374
1602
|
const name = sender.name && sender.name !== sender.id ? sender.name : "未知昵称";
|
|
1375
1603
|
return `${name}(${sender.provider}:${sender.id})`;
|
|
@@ -1442,12 +1670,6 @@ function sessionDisplayEnd(session, previewedAt) {
|
|
|
1442
1670
|
function now(config) {
|
|
1443
1671
|
return config?.now ? config.now() : new Date();
|
|
1444
1672
|
}
|
|
1445
|
-
function minDate(dates) {
|
|
1446
|
-
return dates.reduce((acc, d) => (d.getTime() < acc.getTime() ? d : acc), dates[0]);
|
|
1447
|
-
}
|
|
1448
|
-
function maxDate(dates) {
|
|
1449
|
-
return dates.reduce((acc, d) => (d.getTime() > acc.getTime() ? d : acc), dates[0]);
|
|
1450
|
-
}
|
|
1451
1673
|
function formatInventoryItem(row) {
|
|
1452
1674
|
let line = `- ${row.assetName || row.assetCode || "资产"} (x${formatNumber(row.quantity)})`;
|
|
1453
1675
|
if (row.expiresAt)
|