koishi-plugin-prism 0.4.1 → 0.5.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 +13 -1
- package/lib/ha-watch.d.ts +4 -3
- package/lib/index.d.ts +12 -2
- package/lib/index.js +78 -26
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -40,7 +40,11 @@ Koishi 里只填怎么连到店铺:
|
|
|
40
40
|
| 门锁 | `lock` 打开的门(带门锁能力的资源);店里只有一扇门时默认就是它。没有门时 `lock` 回复本店还没有设置。 |
|
|
41
41
|
| 入场后自动获取门锁密码 | 默认关闭。打开后 `login`/`入场` 成功时顺带生成一个 8 位 TTLock 临时密码(有效期 3 分钟)一并回复;门锁失败只多一行提示,不会让入场失败。没有门锁时不生效。 |
|
|
42
42
|
| 播报与提醒 | 只有一处设置:**播报群**(Koishi 的 `平台:频道` 格式,如群 `onebot:群号`、私聊 `onebot:private:QQ号`)和**提醒提前量**(分钟)。闲置提醒和店内动态都发到这一处,不再分成两个群。 |
|
|
43
|
-
| 播报这些 | 五个开关,各自默认关闭:设备闲置(关机前提醒,提前量为 0
|
|
43
|
+
| 播报这些 | 五个开关,各自默认关闭:设备闲置(关机前提醒,提前量为 0 时不提醒)、开机/关机(由本地 HA 事件触发,含手动开关和自动关机)、上机(刷卡或投币后开始占用机台)、刷卡、投币。刷卡或投币同时上机时只发一条:开了「上机」按上机播报,否则按刷卡/投币播报。刷卡、投币、上机不重复播报这个 Bot 自己的命令。下机不播报。 |
|
|
44
|
+
|
|
45
|
+
播报与提醒直接通过对应平台的第一个可用机器人发送,无需 Koishi 本地数据库或频道分配,也不读取 Koishi 数据库中的 silent 标记;是否播报由 PRiSM 的上述开关决定。群聊填写 `平台:频道`,私聊填写 `平台:private:用户ID`。同一 Koishi 实例有多个同平台账号时,应确保第一个可用账号能访问配置的目标群。单个目标发送失败会记录目标与错误,并继续其他目标和后续播报;平台未连接时不会缓存补发。
|
|
46
|
+
|
|
47
|
+
电源播报由当前承担 HA 监听任务的 Bot 直接根据 HA 事件发送,平台只提供实体到资源名称的映射(`integration/bot.powerResources`),不参与播报触发。Bot 在内存中维护按 HA 连接与实体区分的状态表,仅播报明确的 `on ↔ off` 变化;首次连接、重连和重新分配任务的全量快照只建立基线,`unknown`/`unavailable` 及恢复时不播报,不补报断线期间的变化。共享一个电源实体的资源合并为一条。平台电源事件不再用于播报,Bot 自己执行的开关机也会在 HA 确认实际改变后播报;不再附带操作人或自动关机原因。监听仍受平台调度,平台断线时仍停止 HA 监听;未分配监听任务的 Bot 不发电源播报。多个监听 Bot 各自按自身配置发送,相同目标群应只在一个 Bot 上开启电源播报。
|
|
44
48
|
|
|
45
49
|
**店员**是在这家店工作、并在网页里绑定了聊天平台身份的人:Bot 按「平台 + 账号」认人,`onebot:114514` 是店员不代表 `telegram:114514` 也是。**货币名称**取店铺的余额资产名,**麻将桌**和**门锁**取店铺的资源,都不需要在 Koishi 里重复填写。店铺没有整店计费开关。Bot 属于一个资源组,`login`/`入场` 开始的是这个资源组(或 Bot 资源专属)的计费方案;平台下发的 `billingEnabled` 只表示通过这个 Bot 入场是否计费。为 `false` 时 Bot 不请求平台,直接回复「这里不计费,无需入场」;平台拒绝时(例如资源组刚改成免费)回复同样的话。钱包、账单、结账、兑换、上下桌、`list` 等命令属于玩家或各自的资源,跟 Bot 所在资源组无关,一律交给平台处理。旧平台整店未启用计费时返回的 `BILLING_DISABLED` 仍提示「本店未启用计费」。
|
|
46
50
|
|
|
@@ -155,6 +159,14 @@ npm version minor --no-git-tag-version
|
|
|
155
159
|
|
|
156
160
|
绑定支持 Koishi 提供的各适配器标识,身份值保持字符串,不限定数字格式。店员和账单私聊按「平台标识 + 身份值」认人,相同号码的其他平台不会继承权限或通知。管理员代操作使用目标平台标识,禁止通过当前适配器误操作另一个平台。`/list` 只用当前平台的身份查询昵称,缺失时使用后台名称。源码和 npm 发行包需要分别核对版本。
|
|
157
161
|
|
|
162
|
+
### 0.5.0
|
|
163
|
+
|
|
164
|
+
电源播报改为基于 Bot 本地监听到的 HA 状态变化,覆盖 HA 能感知的手动开关和自动化操作;首次快照和重连不误报,共享电源合并播报。需要先升级配套 PRiSM 后端,使 `integration/bot` 提供 `powerResources` 映射,再升级插件;旧后端缺少映射时不发电源播报,其他播报照常。
|
|
165
|
+
|
|
166
|
+
### 0.4.2
|
|
167
|
+
|
|
168
|
+
修复店内动态与闲置提醒使用 `ctx.broadcast` 导致的数据库依赖警告及漏发:改用适配器消息接口,连续播报不会修改缓存的频道配置,目标群不必预先存在于 Koishi 的频道数据库。支持群聊和私聊,单个目标失败不影响其他目标。
|
|
169
|
+
|
|
158
170
|
### 0.4.1
|
|
159
171
|
|
|
160
172
|
Bot 作为 Home Assistant 监听者时的心跳从 30 秒改成 60 秒,与机台 IO 一致,平台因此用同一个租约(150 秒)衡量两者。同一个间隔也是向 Home Assistant 发的 `ping`,所以 Home Assistant 停止应答现在最多 60 秒后才发现(原来 30 秒)。
|
package/lib/ha-watch.d.ts
CHANGED
|
@@ -54,7 +54,7 @@ export type EntityState = {
|
|
|
54
54
|
export declare function applyEvent(states: Map<string, EntityState>, event: unknown): string[];
|
|
55
55
|
export declare function statesFrame(term: number, connection: string, full: boolean, states: Map<string, EntityState>, ids: string[]): {
|
|
56
56
|
type: string;
|
|
57
|
-
method:
|
|
57
|
+
method: "ha.states";
|
|
58
58
|
params: {
|
|
59
59
|
term: number;
|
|
60
60
|
connection: string;
|
|
@@ -70,7 +70,7 @@ export declare function statesFrame(term: number, connection: string, full: bool
|
|
|
70
70
|
};
|
|
71
71
|
export declare function statusFrame(term: number, connection: string, connected: boolean, error: string | null): {
|
|
72
72
|
type: string;
|
|
73
|
-
method:
|
|
73
|
+
method: "ha.status";
|
|
74
74
|
params: {
|
|
75
75
|
term: number;
|
|
76
76
|
connection: string;
|
|
@@ -78,6 +78,7 @@ export declare function statusFrame(term: number, connection: string, connected:
|
|
|
78
78
|
error: string | null;
|
|
79
79
|
};
|
|
80
80
|
};
|
|
81
|
+
export type HaFrame = ReturnType<typeof statesFrame> | ReturnType<typeof statusFrame>;
|
|
81
82
|
/** `http(s)://host[:port]` to the WebSocket API address; null for anything else. */
|
|
82
83
|
export declare function websocketUrl(base: string): string | null;
|
|
83
84
|
/** The addresses in the order to try them: rotated to start at the one that worked last. */
|
|
@@ -96,7 +97,7 @@ export declare class HaWatcher {
|
|
|
96
97
|
private generation;
|
|
97
98
|
private readonly aborts;
|
|
98
99
|
private readonly waits;
|
|
99
|
-
constructor(open: SocketFactory, send: (frame:
|
|
100
|
+
constructor(open: SocketFactory, send: (frame: HaFrame) => void, logger?: Logger | undefined, timing?: HaTiming);
|
|
100
101
|
/** Watch what the platform asked for, in place of whatever was watched before. */
|
|
101
102
|
watch(watch: HaWatch): void;
|
|
102
103
|
/** Stop watching, and drop every Home Assistant connection. */
|
package/lib/index.d.ts
CHANGED
|
@@ -66,6 +66,12 @@ export type BotConfig = {
|
|
|
66
66
|
aliases: string[];
|
|
67
67
|
capacity: number;
|
|
68
68
|
}>;
|
|
69
|
+
powerResources: Array<{
|
|
70
|
+
id: string;
|
|
71
|
+
name: string;
|
|
72
|
+
connectionId: string;
|
|
73
|
+
entityId: string;
|
|
74
|
+
}>;
|
|
69
75
|
};
|
|
70
76
|
export type PrismKoishiPluginConfig = {
|
|
71
77
|
/**
|
|
@@ -120,8 +126,12 @@ export type KoishiLikeContext = {
|
|
|
120
126
|
logger?(name: string): {
|
|
121
127
|
warn(...args: unknown[]): void;
|
|
122
128
|
};
|
|
123
|
-
|
|
124
|
-
|
|
129
|
+
bots?: Array<{
|
|
130
|
+
platform: string;
|
|
131
|
+
isActive: boolean;
|
|
132
|
+
sendMessage(channelId: string, content: string): Promise<unknown>;
|
|
133
|
+
sendPrivateMessage(userId: string, content: string): Promise<unknown>;
|
|
134
|
+
}>;
|
|
125
135
|
on?(event: "dispose", listener: () => void): void;
|
|
126
136
|
};
|
|
127
137
|
export type KoishiActionContext = {
|
package/lib/index.js
CHANGED
|
@@ -595,6 +595,8 @@ class PrismKoishiService {
|
|
|
595
595
|
bot = null;
|
|
596
596
|
/** Announcements still being sent; each waits for the one before. */
|
|
597
597
|
announcing = Promise.resolve();
|
|
598
|
+
/** The current connection's baseline; a reconnect supplies a fresh full snapshot. */
|
|
599
|
+
powerStates = new Map();
|
|
598
600
|
/** The read in flight, shared by commands arriving together. */
|
|
599
601
|
reading = null;
|
|
600
602
|
reads = 0;
|
|
@@ -621,20 +623,27 @@ class PrismKoishiService {
|
|
|
621
623
|
// says nothing about Home Assistant: then there is no watching to offer.
|
|
622
624
|
const haOpen = options.haSocket ?? (options.socket ? null : open);
|
|
623
625
|
if (haOpen)
|
|
624
|
-
this.watcher = new ha_watch_js_1.HaWatcher(haOpen, (frame) =>
|
|
626
|
+
this.watcher = new ha_watch_js_1.HaWatcher(haOpen, (frame) => {
|
|
627
|
+
this.observePower(frame);
|
|
628
|
+
this.socket?.send(frame);
|
|
629
|
+
}, this.logger);
|
|
625
630
|
this.socket = new PrismSocket(open, platformSocketUrl(options.baseUrl), options.integrationToken, () => this.hello(), (event) => {
|
|
626
631
|
if (event.event === "idle.reminder")
|
|
627
632
|
void this.remindIdle(event.data);
|
|
628
633
|
// One at a time, so the channels read them in the order they happened.
|
|
629
634
|
else if (event.event === "shop.event")
|
|
630
|
-
this.
|
|
631
|
-
.then(() => this.announce(event.data))
|
|
632
|
-
.catch((error) => this.logger?.warn("PRiSM event announcement failed", error));
|
|
635
|
+
this.queueAnnouncement(() => this.announce(event.data));
|
|
633
636
|
}, this.logger, this.watcher
|
|
634
637
|
? {
|
|
635
638
|
// Only a bot whose settings allow it watches, whatever the platform asks.
|
|
636
|
-
onWatch: (watch) =>
|
|
637
|
-
|
|
639
|
+
onWatch: (watch) => {
|
|
640
|
+
this.powerStates.clear();
|
|
641
|
+
if (watch && this.watching)
|
|
642
|
+
this.watcher.watch(watch);
|
|
643
|
+
else
|
|
644
|
+
this.watcher.stop();
|
|
645
|
+
},
|
|
646
|
+
onClose: () => { this.powerStates.clear(); this.watcher.stop(); },
|
|
638
647
|
}
|
|
639
648
|
: undefined);
|
|
640
649
|
const post = options.httpPost ?? (async (url, headers, body) => {
|
|
@@ -739,20 +748,70 @@ class PrismKoishiService {
|
|
|
739
748
|
* command already.
|
|
740
749
|
*/
|
|
741
750
|
async announce(event) {
|
|
751
|
+
// Platform power events remain for older plugins; HA is the only trigger here.
|
|
752
|
+
if (event.kind === "power")
|
|
753
|
+
return;
|
|
742
754
|
const bot = this.bot;
|
|
743
755
|
const channels = bot?.settings.announceChannelIds ?? [];
|
|
744
|
-
if (!bot || !channels.length
|
|
756
|
+
if (!bot || !channels.length)
|
|
745
757
|
return;
|
|
746
758
|
if (event.botId && event.botId === bot.bot.id)
|
|
747
759
|
return;
|
|
748
760
|
const message = await this.announcement(event, bot.settings);
|
|
749
761
|
if (!message)
|
|
750
762
|
return;
|
|
751
|
-
|
|
752
|
-
|
|
763
|
+
await this.broadcast(channels, message);
|
|
764
|
+
}
|
|
765
|
+
queueAnnouncement(send) {
|
|
766
|
+
this.announcing = this.announcing.then(send)
|
|
767
|
+
.catch((error) => this.logger?.warn("PRiSM event announcement failed", error));
|
|
768
|
+
}
|
|
769
|
+
observePower(frame) {
|
|
770
|
+
const { connection } = frame.params;
|
|
771
|
+
if (frame.method === "ha.status") {
|
|
772
|
+
if (!frame.params.connected)
|
|
773
|
+
this.powerStates.delete(connection);
|
|
774
|
+
return;
|
|
753
775
|
}
|
|
754
|
-
|
|
755
|
-
|
|
776
|
+
const { full, states } = frame.params;
|
|
777
|
+
const previous = full ? new Map() : (this.powerStates.get(connection) ?? new Map());
|
|
778
|
+
for (const state of states) {
|
|
779
|
+
const before = previous.get(state.entity_id);
|
|
780
|
+
previous.set(state.entity_id, state.state);
|
|
781
|
+
if ((before !== "on" && before !== "off") || (state.state !== "on" && state.state !== "off") || before === state.state)
|
|
782
|
+
continue;
|
|
783
|
+
const bot = this.bot;
|
|
784
|
+
if (!bot?.settings.announcePower || !bot.settings.announceChannelIds.length)
|
|
785
|
+
continue;
|
|
786
|
+
const resources = bot.powerResources.filter((resource) => resource.connectionId === connection && resource.entityId === state.entity_id);
|
|
787
|
+
if (!resources.length)
|
|
788
|
+
continue;
|
|
789
|
+
const message = `${state.state === "on" ? "✅" : "🛑"} ${resources.map((resource) => resource.name).join("、")} 已${state.state === "on" ? "开机" : "关机"}`;
|
|
790
|
+
this.queueAnnouncement(() => this.broadcast(bot.settings.announceChannelIds, message));
|
|
791
|
+
}
|
|
792
|
+
this.powerStates.set(connection, previous);
|
|
793
|
+
}
|
|
794
|
+
/** Explicit targets need neither Koishi's channel database nor its mutable broadcast list. */
|
|
795
|
+
async broadcast(channels, message) {
|
|
796
|
+
for (const target of channels) {
|
|
797
|
+
try {
|
|
798
|
+
const separator = target.indexOf(":");
|
|
799
|
+
if (separator < 1 || separator === target.length - 1)
|
|
800
|
+
throw new Error(`无效的播报频道:${target}`);
|
|
801
|
+
const platform = target.slice(0, separator), channel = target.slice(separator + 1);
|
|
802
|
+
if (channel === "private:")
|
|
803
|
+
throw new Error(`无效的私聊目标:${target}`);
|
|
804
|
+
const bot = this.ctx.bots?.find((bot) => bot.platform === platform && bot.isActive);
|
|
805
|
+
if (!bot)
|
|
806
|
+
throw new Error(`没有可用的 ${platform} 机器人`);
|
|
807
|
+
if (channel.startsWith("private:"))
|
|
808
|
+
await bot.sendPrivateMessage(channel.slice(8), message);
|
|
809
|
+
else
|
|
810
|
+
await bot.sendMessage(channel, message);
|
|
811
|
+
}
|
|
812
|
+
catch (error) {
|
|
813
|
+
this.logger?.warn(`PRiSM announcement to ${target} failed`, error);
|
|
814
|
+
}
|
|
756
815
|
}
|
|
757
816
|
}
|
|
758
817
|
async announcement(event, settings) {
|
|
@@ -768,14 +827,6 @@ class PrismKoishiService {
|
|
|
768
827
|
sessions: [{ playerDisplayName: event.player.displayName ?? undefined, identities: event.player.identities }],
|
|
769
828
|
}, provider);
|
|
770
829
|
};
|
|
771
|
-
if (event.kind === "power") {
|
|
772
|
-
if (!settings.announcePower)
|
|
773
|
-
return null;
|
|
774
|
-
if (event.by === "system")
|
|
775
|
-
return event.state === "off" ? `💤 ${place} 闲置,已自动关机` : `✅ ${place} 已开机`;
|
|
776
|
-
const by = event.player ? `(${await who()})` : "";
|
|
777
|
-
return event.state === "on" ? `✅ ${place} 已开机${by}` : `🛑 ${place} 已关机${by}`;
|
|
778
|
-
}
|
|
779
830
|
if (event.kind === "card") {
|
|
780
831
|
if (event.started && settings.announceStarts)
|
|
781
832
|
return `🎮 ${await who()} 在 ${place} 刷卡上机`;
|
|
@@ -794,7 +845,7 @@ class PrismKoishiService {
|
|
|
794
845
|
async remindIdle(reminder) {
|
|
795
846
|
const settings = this.bot?.settings;
|
|
796
847
|
const channels = settings?.announceChannelIds ?? [];
|
|
797
|
-
if (!settings?.announceIdle || !channels.length
|
|
848
|
+
if (!settings?.announceIdle || !channels.length)
|
|
798
849
|
return;
|
|
799
850
|
const now = (this.options.now?.() ?? new Date()).getTime();
|
|
800
851
|
const minutes = Math.max(1, Math.round((reminder.at - now) / 60_000));
|
|
@@ -802,12 +853,7 @@ class PrismKoishiService {
|
|
|
802
853
|
const message = reminder.reason === "shop_empty"
|
|
803
854
|
? `店里没人,${minutes} 分钟后全部关机`
|
|
804
855
|
: `${names} 闲置中,${minutes} 分钟后关机。已入场的玩家发送 keep 设备名 可以延迟`;
|
|
805
|
-
|
|
806
|
-
await this.ctx.broadcast(channels, message);
|
|
807
|
-
}
|
|
808
|
-
catch (error) {
|
|
809
|
-
this.logger?.warn("PRiSM idle reminder failed", error);
|
|
810
|
-
}
|
|
856
|
+
await this.broadcast(channels, message);
|
|
811
857
|
}
|
|
812
858
|
async sender(context) {
|
|
813
859
|
const id = cleanText(context.session?.userId);
|
|
@@ -1672,6 +1718,12 @@ function parseBotConfig(value) {
|
|
|
1672
1718
|
},
|
|
1673
1719
|
billingEnabled: record.billingEnabled !== false,
|
|
1674
1720
|
currencyName: cleanText(record.currencyName) || "余额",
|
|
1721
|
+
powerResources: (Array.isArray(record.powerResources) ? record.powerResources : [])
|
|
1722
|
+
.map((resource) => ({
|
|
1723
|
+
id: cleanText(resource?.id), name: cleanText(resource?.name) || cleanText(resource?.id),
|
|
1724
|
+
connectionId: cleanText(resource?.connectionId), entityId: cleanText(resource?.entityId),
|
|
1725
|
+
}))
|
|
1726
|
+
.filter((resource) => resource.id && resource.connectionId && resource.entityId),
|
|
1675
1727
|
staff: (Array.isArray(record.staff) ? record.staff : [])
|
|
1676
1728
|
.map((identity) => ({ provider: cleanText(identity?.provider).toLowerCase(), subject: cleanText(identity?.subject) }))
|
|
1677
1729
|
.filter((identity) => identity.provider && identity.subject),
|