koishi-plugin-prism 0.5.3 → 0.6.1

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 CHANGED
@@ -26,6 +26,7 @@ Koishi 里只填怎么连到店铺:
26
26
  | `baseUrl` | `string` | **必填**。PRiSM Next Server 的访问基准 URL(如 `https://prism-mmw.neri.moe`)。 |
27
27
  | `shopCode` | `string` | 可选。店铺公开编号;接入凭据已经指明店铺,**不需要填**。旧配置保留也能用。 |
28
28
  | `integrationToken` | `string` | **必填**。从 PRiSM 网页后台生成的 Integration API 令牌。 |
29
+ | `syncNames` | `boolean` | 可选,默认开。连上后约一分钟、之后每 6 小时读 Bot 所在每个群的成员昵称发给 PRiSM,补全本店玩家的名字;关掉后只在玩家自己发命令时更新。 |
29
30
 
30
31
  其余一切都在 PRiSM 网页里设置:每个令牌对应一个 Bot,Bot 在店铺里是一个**资源**。在**商户工作台 → 资源 → 这个 Bot → Bot 设置**里可以改:
31
32
 
@@ -41,8 +42,8 @@ Koishi 里只填怎么连到店铺:
41
42
  | 账单私聊店员 | 玩家退场或店员覆盖结账后,把同一份账单私聊给同一聊天平台上的店员。 |
42
43
  | 门锁 | `lock` 打开的门(带门锁能力的资源);店里只有一扇门时默认就是它。没有门时 `lock` 回复本店还没有设置。 |
43
44
  | 入场后自动获取门锁密码 | 默认关闭。打开后 `login`/`入场` 成功时顺带生成一个 8 位 TTLock 临时密码(有效期 3 分钟)一并回复;门锁失败只多一行提示,不会让入场失败。没有门锁时不生效。 |
44
- | 播报与提醒 | 只有一处设置:**播报群**(Koishi 的 `平台:频道` 格式,如群 `onebot:群号`、私聊 `onebot:private:QQ号`)和**提醒提前量**(分钟)。闲置提醒和店内动态都发到这一处,不再分成两个群。 |
45
- | 播报这些 | 在后台按事件类型逐项勾选(`announceEvents`),平台按勾选只发相应的动态,写好要说的话并直接发到播报群(其中的玩家由插件换成群里的称呼)。分三组:**现场发生的事**(开机、关机、刷卡、上机、机台投币、开局扣币、投币计数清零,来自机台和 Home Assistant 的回报,不论在哪里操作的都只说一次)、**通过平台的操作**(通过平台开机/关机、闲置自动关机、通过平台刷卡、通过平台投币,只说明有人在平台上发起了它)和**提醒**(闲置关机提醒,提前量为 0 时不提醒)。这个 Bot 自己执行的命令已经回复过,不再播报。 |
45
+ | 播报与提醒 | 在后台 Bot 设置的「播报」里建**播报组**:每组是一种听众,有自己的目的地(Koishi 的 `平台:频道` 格式,如群 `onebot:群号`、私聊 `onebot:private:QQ号`,私聊店员也这样写),以及一整张事件表:每个事件播不播、只听哪些来源、用什么文案。没有播报组就什么都不播。另有闲置关机提醒的**提前量**(分钟),为 0 时不提醒。 |
46
+ | 播报这些 | 平台按播报组决定发什么、发到哪里,并按那一组的文案写好要说的话,插件直接发出(其中的玩家由插件换成群里的称呼)。事件按话题分组,每个话题里分**尝试**(有人要求做某件事以及结果:已发出、被拒绝、失败,比如开机、投币、虚拟刷卡、结账)和**事实**(真的发生了的事,比如设备开机、游戏读到卡、结账完成),另有闲置关机提醒和系统维护两种**提醒**。这个 Bot 自己执行的命令已经回复过,不再播报。 |
46
47
 
47
48
  播报与闲置提醒直接通过对应平台的第一个在线机器人发送,不依赖 Koishi 的数据库、频道分配或 silent 标记,是否播报由 PRiSM 设置决定。群聊填写 `平台:频道`,私聊填写 `平台:private:用户ID`;频道 ID 内的冒号保持原样。连续播报不会修改缓存的频道列表,单个目标发送失败会记录目标及错误并继续其他目标和后续播报。相同平台有多个机器人时,第一个在线账号须能访问目标群;离线时不缓存补发。
48
49
 
@@ -166,6 +167,12 @@ npm version minor --no-git-tag-version
166
167
 
167
168
  绑定支持 Koishi 提供的各适配器标识,身份值保持字符串,不限定数字格式。店员和账单私聊按「平台标识 + 身份值」认人,相同号码的其他平台不会继承权限或通知。管理员代操作使用目标平台标识,禁止通过当前适配器误操作另一个平台。`/list` 只用当前平台的身份查询昵称,缺失时使用后台名称。源码和 npm 发行包需要分别核对版本。
168
169
 
170
+ ### 0.6.0
171
+
172
+ - 玩家的名字按平台分开存:说到一个玩家时用他在本平台的名字(平台在每个身份上保存的称呼),一个人绑了两个平台也不会被来回改名。
173
+ - 批量补名:连上平台约一分钟后、之后每 6 小时,读 Bot 所在每个群的成员列表,把成员的昵称分批发给平台,让从旧系统导入的「Player 75」这类占位名、以及从没用过 Bot 命令的玩家也有名字。平台只保留本店玩家的名字。配置 `syncNames: false` 可关闭。
174
+ - 需要支持 `names` 帧和身份名字(迁移 `0057`)的 PRiSM。
175
+
169
176
  ### 0.5.3
170
177
 
171
178
  插件改为只转发命令:`login`、`logout`、`wallet` 等命令连同参数原样发给平台(`command` 帧),平台执行、判断权限(只读模式、店员、计费)、写好回复,插件照发(`say` 帧);账单私聊店员、入场附带的门锁密码也由平台决定发到哪。店内动态和闲置提醒同样由平台写好、按 Bot 的监听规则发到规则指定的群或个人,插件不再读取 Bot 设置,也不再收 `shop.event`。插件自己只保留 `versions`、`api测速`、`ws测速` 和 Home Assistant 监听。播报新增机台投币、开局扣币、投币计数清零(需要机台 IO 开启 `cabinetMonitor`),以及来自 Home Assistant 的开机、关机;刷卡改为在游戏取到卡时播报,网页刷卡和实体卡一样只说一次;`下桌` 不必再指定桌号。需要支持命令协议的 PRiSM,店铺所在的 PRiSM 升级之前不要升级到此版本。
@@ -205,3 +212,13 @@ Koishi 配置只剩 `baseUrl` 和 `integrationToken`(`shopCode` 可选、已
205
212
  ## 时间展示
206
213
 
207
214
  账单、历史与资产到期的时间由平台按店铺时区写好,例如「⏰ 游玩时间:18:00–19:00(UTC+08:00)」,不依赖 Bot 服务器时区。
215
+
216
+ ### Bot 定时播报
217
+
218
+ 播报组支持定时发送固定文字,可选每天、每周指定星期或指定日期单次发送,时间使用店铺时区,收件人沿用播报组。每组最多 20 条,每条最多 2000 字。需使用支持 schedules 的新版 Koishi 插件。
219
+
220
+ 插件 hello 声明 schedules: true,平台返回 schedules 帧(timeZone、rules)。rules 为启用且有目的地的规则,包含 id、time(HH:mm)、text、to,可选 date(YYYY-MM-DD)或 weekdays(0 为周日)。平台在重新 hello 时下发全量配置,配置变化通过 config.changed 让插件重新 hello。旧插件继续工作。定时播报由插件本地按分钟检查,无需增加服务端 alarm 或轮询请求。
221
+
222
+ 断线、停用或配置更新会取消旧计时,重连后恢复。离线错过的分钟跳过,夏令时跳过的时间也跳过,重复的当地时间在同一进程内每天最多发一次。发送失败沿用播报错误日志,不自动补发。单个 Bot 凭据应只运行一个插件实例,多实例各自计时可能重复发送。进程重启后仅安排后续分钟。
223
+
224
+ 0.6.1 增加由平台下发配置的本地定时播报,支持每天、每周和单次公告。
package/lib/index.d.ts CHANGED
@@ -28,6 +28,14 @@ export type PrismKoishiPluginConfig = {
28
28
  httpPost?: HttpPost;
29
29
  /** Opens connections to Home Assistant; defaults to Koishi's `ctx.http.ws`. Mainly for tests. */
30
30
  haSocket?: SocketFactory;
31
+ /**
32
+ * Read the members of every group the bots are in and tell the platform what
33
+ * each is called, so a shop's players get their chat names even when they
34
+ * never send the bot a command. On by default; `false` turns it off.
35
+ */
36
+ syncNames?: boolean;
37
+ /** When the first name read runs after starting; a minute by default. Mainly for tests. */
38
+ nameSyncFirstMs?: number;
31
39
  };
32
40
  /** A plain HTTP POST answering with its status, headers and decoded body. */
33
41
  export type HttpPost = (url: string, headers: Record<string, string>, body: unknown) => Promise<{
@@ -62,6 +70,17 @@ export type KoishiLikeContext = {
62
70
  isActive: boolean;
63
71
  sendMessage(channelId: string, content: string): Promise<unknown>;
64
72
  sendPrivateMessage(userId: string, content: string): Promise<unknown>;
73
+ /** Koishi's paged lists: the groups the bot is in, and a group's members. */
74
+ getGuildList?(next?: string): Promise<{
75
+ data: Array<{
76
+ id: string;
77
+ }>;
78
+ next?: string;
79
+ }>;
80
+ getGuildMemberList?(guildId: string, next?: string): Promise<{
81
+ data: GuildMember[];
82
+ next?: string;
83
+ }>;
65
84
  }>;
66
85
  on?(event: "dispose", listener: () => void): void;
67
86
  };
@@ -85,15 +104,26 @@ export type KoishiActionContext = {
85
104
  };
86
105
  };
87
106
  export declare function applyPrismKoishiPlugin(ctx: KoishiLikeContext, config: PrismKoishiPluginConfig): void;
88
- /** A player as the platform names one in what it says. */
107
+ /** A player as the platform names one in what it says; `name` on an identity is what that platform calls them. */
89
108
  type MessagePlayer = {
90
109
  playerId: string;
91
110
  displayName: string | null;
92
111
  identities: Array<{
93
112
  provider: string;
94
113
  subject: string;
114
+ name?: string;
95
115
  }>;
96
116
  };
117
+ /** A group member as a Koishi adapter lists one. */
118
+ type GuildMember = {
119
+ user?: {
120
+ id?: string;
121
+ name?: string;
122
+ nick?: string;
123
+ };
124
+ nick?: string;
125
+ name?: string;
126
+ };
97
127
  /**
98
128
  * What the platform writes for a bot to say (PRiSM's core `bot-message.ts`):
99
129
  * text, and players the bot names as its chat knows them. A segment of a kind
@@ -129,12 +159,6 @@ type SocketReply = {
129
159
  body: any;
130
160
  serverMs?: number | null;
131
161
  };
132
- /**
133
- * The one connection to PRiSM. Commands go out as `command` frames and the
134
- * platform answers with `say` frames naming them; the shop's news comes as
135
- * `say` frames naming none. While it is down a command fails at once:
136
- * queueing a checkout or a top-up to run later would make players repeat it.
137
- */
138
162
  export declare class PrismSocket {
139
163
  private readonly open;
140
164
  private readonly url;
@@ -157,6 +181,8 @@ export declare class PrismSocket {
157
181
  private retryTimer;
158
182
  private pingTimer;
159
183
  private lastHeard;
184
+ private scheduleTimer?;
185
+ private readonly sentDate;
160
186
  private stopped;
161
187
  private sequence;
162
188
  private readonly pongWaiters;
@@ -184,6 +210,7 @@ export declare class PrismSocket {
184
210
  private greet;
185
211
  private reconnectLater;
186
212
  private failPending;
213
+ private schedule;
187
214
  private receive;
188
215
  private nextId;
189
216
  /**
package/lib/index.js CHANGED
@@ -21,6 +21,7 @@ exports.Config = koishi_1.Schema.object({
21
21
  baseUrl: koishi_1.Schema.string().required().description("PRiSM 后端地址,例如 https://link.neri.moe"),
22
22
  shopCode: koishi_1.Schema.string().description("可选:店铺编号。接入凭据已经指明店铺,无需填写;旧配置仍认。"),
23
23
  integrationToken: koishi_1.Schema.string().role("secret").required().description("集成 API Token;其余设置在 PRiSM 商户工作台 → 资源 → 这个 Bot → Bot 设置"),
24
+ syncNames: koishi_1.Schema.boolean().default(true).description("定期读取 Bot 所在群的成员昵称,补全店里玩家的名字(只保留本店玩家)"),
24
25
  });
25
26
  function apply(ctx, config) {
26
27
  applyPrismKoishiPlugin(ctx, config);
@@ -94,12 +95,12 @@ const FIRST_RETRY_MS = 1000;
94
95
  const MAX_RETRY_MS = 30_000;
95
96
  const UNREACHABLE = "操作失败,暂时连不上服务器。";
96
97
  const TIMED_OUT = "服务器没有及时回应,请稍后确认结果";
97
- /**
98
- * The one connection to PRiSM. Commands go out as `command` frames and the
99
- * platform answers with `say` frames naming them; the shop's news comes as
100
- * `say` frames naming none. While it is down a command fails at once:
101
- * queueing a checkout or a top-up to run later would make players repeat it.
102
- */
98
+ /** How often the bots' group members are read again for their names. */
99
+ const NAME_SYNC_MS = 6 * 60 * 60_000;
100
+ /** The first read waits for the connection to settle. */
101
+ const NAME_SYNC_FIRST_MS = 60_000;
102
+ /** Names per report; the platform takes at most 500. */
103
+ const NAMES_PER_REPORT = 200;
103
104
  class PrismSocket {
104
105
  open;
105
106
  url;
@@ -116,6 +117,8 @@ class PrismSocket {
116
117
  retryTimer = null;
117
118
  pingTimer = null;
118
119
  lastHeard = 0;
120
+ scheduleTimer;
121
+ sentDate = new Map();
119
122
  stopped = false;
120
123
  sequence = 0;
121
124
  pongWaiters = [];
@@ -155,6 +158,7 @@ class PrismSocket {
155
158
  }
156
159
  stop() {
157
160
  this.stopped = true;
161
+ clearTimeout(this.scheduleTimer);
158
162
  if (this.retryTimer)
159
163
  clearTimeout(this.retryTimer);
160
164
  if (this.pingTimer)
@@ -188,11 +192,13 @@ class PrismSocket {
188
192
  socket.send("ping");
189
193
  }, PING_MS);
190
194
  });
191
- socket.addEventListener("message", (event) => this.receive(String(event?.data ?? "")));
195
+ socket.addEventListener("message", (event) => { if (this.socket === socket)
196
+ this.receive(String(event?.data ?? "")); });
192
197
  socket.addEventListener("close", () => {
193
198
  if (this.socket !== socket)
194
199
  return;
195
200
  this.socket = null;
201
+ clearTimeout(this.scheduleTimer);
196
202
  if (this.pingTimer)
197
203
  clearInterval(this.pingTimer);
198
204
  this.failPending();
@@ -204,7 +210,8 @@ class PrismSocket {
204
210
  }
205
211
  /** Hello: on connecting, and again when the platform says the bot's settings changed, so it rereads them. */
206
212
  greet() {
207
- this.send({ type: "hello", commands: 1, ...this.hello() });
213
+ clearTimeout(this.scheduleTimer);
214
+ this.send({ type: "hello", commands: 1, schedules: true, ...this.hello() });
208
215
  }
209
216
  reconnectLater() {
210
217
  if (this.stopped)
@@ -224,6 +231,35 @@ class PrismSocket {
224
231
  onSay(null);
225
232
  this.listening.clear();
226
233
  }
234
+ schedule(rules, timeZone) {
235
+ clearTimeout(this.scheduleTimer);
236
+ const active = new Set(rules.map(rule => rule.id));
237
+ for (const id of this.sentDate.keys())
238
+ if (!active.has(id))
239
+ this.sentDate.delete(id);
240
+ if (!rules.length)
241
+ return;
242
+ const clock = new Intl.DateTimeFormat("en-CA", {
243
+ timeZone, year: "numeric", month: "2-digit", day: "2-digit",
244
+ hourCycle: "h23", hour: "2-digit", minute: "2-digit",
245
+ });
246
+ const tick = () => {
247
+ const parts = Object.fromEntries(clock.formatToParts(Date.now()).map(part => [part.type, part.value]));
248
+ const date = `${parts.year}-${parts.month}-${parts.day}`;
249
+ const weekday = new Date(date + "T00:00:00Z").getUTCDay();
250
+ for (const rule of rules) {
251
+ if (rule.time !== `${parts.hour}:${parts.minute}` || (rule.date && rule.date !== date)
252
+ || (rule.weekdays && !rule.weekdays.includes(weekday)) || this.sentDate.get(rule.id) === date)
253
+ continue;
254
+ this.sentDate.set(rule.id, date);
255
+ for (const to of rule.to)
256
+ this.onNews({ type: "say", to, message: [{ text: rule.text }] });
257
+ }
258
+ arm();
259
+ };
260
+ const arm = () => { this.scheduleTimer = setTimeout(tick, 60000 - Date.now() % 60000); };
261
+ arm();
262
+ }
227
263
  receive(raw) {
228
264
  this.lastHeard = Date.now();
229
265
  if (raw === "pong") {
@@ -237,6 +273,10 @@ class PrismSocket {
237
273
  catch {
238
274
  return;
239
275
  }
276
+ if (frame?.type === "schedules" && Array.isArray(frame.rules)) {
277
+ this.schedule(frame.rules, frame.timeZone);
278
+ return;
279
+ }
240
280
  if (frame?.type === "say" && Array.isArray(frame.message)) {
241
281
  const say = frame;
242
282
  if (typeof say.replyTo !== "string") {
@@ -408,11 +448,53 @@ class PrismKoishiService {
408
448
  return { status: response.status, headers: response.headers, data: response.data };
409
449
  });
410
450
  this.socket.start();
451
+ this.scheduleNames(options.nameSyncFirstMs ?? NAME_SYNC_FIRST_MS);
411
452
  }
412
453
  dispose() {
454
+ if (this.nameTimer)
455
+ clearTimeout(this.nameTimer);
413
456
  this.watcher?.stop();
414
457
  this.socket.stop();
415
458
  }
459
+ nameTimer = null;
460
+ /** Read names now and then, from the first read on, unless turned off. */
461
+ scheduleNames(delay) {
462
+ if (this.options.syncNames === false)
463
+ return;
464
+ this.nameTimer = setTimeout(() => {
465
+ void this.syncNames()
466
+ .catch((error) => this.logger?.warn("PRiSM name sync failed", error))
467
+ .finally(() => this.scheduleNames(NAME_SYNC_MS));
468
+ }, delay);
469
+ }
470
+ /**
471
+ * Every group each bot is in, member by member: what the platform calls them
472
+ * (their nickname, not a group card, which differs from group to group),
473
+ * sent to the platform in batches. The platform keeps the names of the
474
+ * shop's players among them and ignores everyone else.
475
+ */
476
+ async syncNames() {
477
+ const names = new Map();
478
+ for (const bot of this.ctx.bots ?? []) {
479
+ if (!bot.isActive || !bot.getGuildList || !bot.getGuildMemberList)
480
+ continue;
481
+ const provider = String(bot.platform || "").toLowerCase();
482
+ if (!/^[a-z][a-z0-9_-]{0,63}$/.test(provider))
483
+ continue;
484
+ for await (const guild of pages((next) => bot.getGuildList(next))) {
485
+ for await (const member of pages((next) => bot.getGuildMemberList(guild.id, next))) {
486
+ const subject = String(member.user?.id ?? "").trim();
487
+ const name = String(member.user?.name || member.user?.nick || member.name || member.nick || "").trim();
488
+ if (subject && name)
489
+ names.set(`${provider}:${subject}`, { provider, subject, name });
490
+ }
491
+ }
492
+ }
493
+ const list = [...names.values()];
494
+ for (let start = 0; start < list.length; start += NAMES_PER_REPORT)
495
+ this.socket.send({ type: "names", names: list.slice(start, start + NAMES_PER_REPORT) });
496
+ return list.length;
497
+ }
416
498
  /* ----------------------------- commands -------------------------------- */
417
499
  /**
418
500
  * Hand a command to the platform and answer with the first thing it says
@@ -547,6 +629,10 @@ class PrismKoishiService {
547
629
  async playerName(player, provider) {
548
630
  const identities = Array.isArray(player.identities) ? player.identities : [];
549
631
  const identity = identities.find((candidate) => candidate.provider === provider) ?? identities[0];
632
+ // What this chat's platform calls them, as the platform keeps it for each identity.
633
+ const own = identities.find((candidate) => candidate.provider === provider && candidate.name);
634
+ if (own?.name)
635
+ return own.name;
550
636
  if (identity && this.options.resolveDisplayName) {
551
637
  try {
552
638
  const name = await this.options.resolveDisplayName(identity.subject, identity.provider);
@@ -687,3 +773,20 @@ exports.default = {
687
773
  ConfigSchema: exports.Config,
688
774
  apply,
689
775
  };
776
+ /** Every item of a Koishi paged list, page after page; a page that fails ends the list. */
777
+ async function* pages(read) {
778
+ let next;
779
+ for (let page = 0; page < 1000; page++) {
780
+ let result;
781
+ try {
782
+ result = await read(next);
783
+ }
784
+ catch {
785
+ return;
786
+ }
787
+ yield* result.data ?? [];
788
+ if (!result.next || result.next === next)
789
+ return;
790
+ next = result.next;
791
+ }
792
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "koishi-plugin-prism",
3
- "version": "0.5.3",
3
+ "version": "0.6.1",
4
4
  "description": "PRiSM Next 计费与设备管理系统的 Koishi 机器人集成插件",
5
5
  "main": "./lib/index.js",
6
6
  "exports": {