@mindlink-ai/dsh-wechat-bot 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.md +201 -2
- package/bridge/ilink.js +118 -0
- package/bridge/render.js +71 -0
- package/client.js +355 -0
- package/cordis.patch.yml +4 -0
- package/icon.svg +4 -0
- package/index.js +798 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +40 -4
- package/vendor/qrcode.cjs +2297 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 思链科技(MindLink)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,202 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mindlink-ai/dsh-wechat-bot
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
个人微信 bot 的 DSH 插件:把「微信官方 iLink(ClawBot)通道」封装成
|
|
4
|
+
|
|
5
|
+
- **左侧边栏入口「微信bot」**:点开主面板即可看到连接状态、账号信息、扫码登录入口、最近推送与最近消息;
|
|
6
|
+
- **Agent 工具**:`wechat_status` / `wechat_login` / `wechat_send` / `wechat_recent`,供定时任务调用把日报推送到你的微信;
|
|
7
|
+
- **同源调试接口**:`/wechat-bot/state`、`/wechat-bot/login`、`/wechat-bot/send`(与 GUI 同端口,无独立端口暴露)。
|
|
8
|
+
|
|
9
|
+
## 安装(给其他 DSH 用户)
|
|
10
|
+
|
|
11
|
+
在 DSH 的插件管理器(左侧边栏「插件」→ 安装插件)里输入以下任一目标:
|
|
12
|
+
|
|
13
|
+
| 方式 | 输入 |
|
|
14
|
+
|---|---|
|
|
15
|
+
| npm 包名(推荐,发布后) | `@mindlink-ai/dsh-wechat-bot` |
|
|
16
|
+
| GitHub 仓库地址 | `https://github.com/<org>/wechat-bot-plugin` |
|
|
17
|
+
| 本地目录 | 插件目录绝对路径 |
|
|
18
|
+
|
|
19
|
+
安装后左侧边栏出现「微信bot」,工具列表出现 `wechat_*` 工具。
|
|
20
|
+
|
|
21
|
+
**运行要求**:DSH Web/桌面 profile(需要 `webServer`、`tools`、`sessionController` 服务);手机微信需支持 ClawBot 插件;Node ≥ 20(由 DSH 自带,无需另装)。
|
|
22
|
+
|
|
23
|
+
## 发布到 npm(维护者)
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
cd wechat-bot-plugin
|
|
27
|
+
|
|
28
|
+
# 1) 登录 npm(@mindlink-ai scope 需属于你的 npm 账号或组织)
|
|
29
|
+
npm login
|
|
30
|
+
|
|
31
|
+
# 2) 发布(包已声明 publishConfig.access=public,scoped 包必须 public)
|
|
32
|
+
npm publish --access public
|
|
33
|
+
|
|
34
|
+
# 3) 验证
|
|
35
|
+
npm view @mindlink-ai/dsh-wechat-bot version
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
> 本机 npm 默认源可能指向失效镜像(如旧淘宝源)。发布前确认:
|
|
39
|
+
> `npm config get registry`,必要时 `npm config set registry https://registry.npmjs.org`。
|
|
40
|
+
> 若遇到 `EPERM` 缓存目录错误,可临时指定可写缓存:`npm publish --cache /tmp/npm-cache`。
|
|
41
|
+
|
|
42
|
+
升级流程:改代码 → `npm version patch`(或 minor/major)→ `git push --follow-tags` → `npm publish`。
|
|
43
|
+
|
|
44
|
+
### 自动发布(GitHub Actions)
|
|
45
|
+
|
|
46
|
+
仓库已内置 [`.github/workflows/publish.yml`](.github/workflows/publish.yml):推送 `v*` 标签时自动校验版本并发布到 npm。
|
|
47
|
+
|
|
48
|
+
> **npm token 有效期限制**:自 2025-10 起,写权限的 granular token **最长 90 天**(新建默认只有 7 天),
|
|
49
|
+
> 所以 CI 里长期放 `NPM_TOKEN` 需要定期轮换。更推荐 **npm Trusted Publishing(OIDC)**:不用任何长期 token,
|
|
50
|
+
> 也就没有 90 天问题,并自动生成 provenance 供应链签名。
|
|
51
|
+
|
|
52
|
+
#### 方式 A(推荐):Trusted Publishing(OIDC,无 token)
|
|
53
|
+
|
|
54
|
+
1. 首次发布要先把包发布到 npm(手动一次):
|
|
55
|
+
```bash
|
|
56
|
+
npm publish --access public --otp=<验证器6位码>
|
|
57
|
+
```
|
|
58
|
+
2. 打开 npm 包页面 → Settings → **Trusted Publisher** → 选择 **GitHub Actions**,填写:
|
|
59
|
+
- Organization / Repository:你的仓库
|
|
60
|
+
- Workflow file name:`publish.yml`
|
|
61
|
+
3. 仓库无需配置 `NPM_TOKEN`。之后:
|
|
62
|
+
```bash
|
|
63
|
+
npm version patch
|
|
64
|
+
git push --follow-tags
|
|
65
|
+
```
|
|
66
|
+
Action 通过 OIDC 直接发布(已含 `--provenance`)。
|
|
67
|
+
|
|
68
|
+
#### 方式 B(备选):NPM_TOKEN
|
|
69
|
+
|
|
70
|
+
1. 生成 **Granular Access Token**(`Read and write` + 作用域 `@mindlink-ai` + 勾选 **Bypass 2FA**),
|
|
71
|
+
注意**最长 90 天**,到期需重新生成。
|
|
72
|
+
2. 仓库 Settings → Secrets and variables → Actions 新建 `NPM_TOKEN`。
|
|
73
|
+
3. 把 workflow 的 publish 步骤临时改回 token 模式:
|
|
74
|
+
```yaml
|
|
75
|
+
- name: Publish to npm
|
|
76
|
+
run: npm publish --access public
|
|
77
|
+
env:
|
|
78
|
+
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
## 首次使用
|
|
83
|
+
|
|
84
|
+
> 数据与配置目录:`~/.dsh/wechat-bot/`(`credentials.json` / `state.json` / `settings.json` / `push.log`),可用环境变量 `DSH_WECHAT_BOT_DIR` 覆盖。
|
|
85
|
+
> 会话转发的默认工作目录是用户主目录(`os.homedir()`);如需指定,编辑 `settings.json` 的 `workspaceCwd`,例如 `"workspaceCwd": "D:\\\\projects\\\\wechat-chat"`。
|
|
86
|
+
|
|
87
|
+
1. 打开左侧边栏「微信bot」→ 点「开始 / 刷新登录」;
|
|
88
|
+
2. 面板出现二维码链接 → 复制到手机微信打开并确认;
|
|
89
|
+
3. 登录成功后,**在微信里给机器人发一条任意消息**(让 bot 记录 `context_token`);
|
|
90
|
+
4. 回到面板点「发送到微信」验证链路;
|
|
91
|
+
5. 定时任务里调用 `wechat_send`(可传日报文件绝对路径)。
|
|
92
|
+
|
|
93
|
+
## 数据与凭证
|
|
94
|
+
|
|
95
|
+
- 状态与凭证目录:`~/.dsh/wechat-bot/`(`credentials.json` / `state.json` / `settings.json` / `push.log`)
|
|
96
|
+
- 可用环境变量 `DSH_WECHAT_BOT_DIR` 覆盖;
|
|
97
|
+
- 首次启动会尝试从旧版桥接目录 `E:\Administrator\Documents\daily-news\wechat` 迁移凭证与上下文,无需重复扫码(若旧凭证仍有效)。
|
|
98
|
+
|
|
99
|
+
## 作者信息
|
|
100
|
+
|
|
101
|
+
- 作者:思链科技(MindLink)
|
|
102
|
+
- 插件:`@mindlink-ai/dsh-wechat-bot` v1.0.0
|
|
103
|
+
- 通道:微信官方 iLink(ClawBot);本地优先,聊天数据只留在本机
|
|
104
|
+
- 许可:MIT
|
|
105
|
+
|
|
106
|
+
## 页面与路径
|
|
107
|
+
|
|
108
|
+
- 侧边栏入口:`sidebar.panellist` 注册项 `id = wechat-bot`(不是独立 URL 路由,点击切换主面板)
|
|
109
|
+
- 主面板:`main` keyed slot,`key = wechat-bot`(渲染文件 `client.js`)
|
|
110
|
+
- Host 同源调试页:`http://127.0.0.1:<GUI端口>/wechat-bot/`
|
|
111
|
+
- 状态接口:`/wechat-bot/state`
|
|
112
|
+
|
|
113
|
+
## 其他插件如何调用
|
|
114
|
+
|
|
115
|
+
### 方式 1:Host 服务 `wechatBot`(推荐,同进程零网络)
|
|
116
|
+
|
|
117
|
+
其他 Host 插件声明依赖后直接调用:
|
|
118
|
+
|
|
119
|
+
```js
|
|
120
|
+
// 你的插件 index.js
|
|
121
|
+
export const inject = ['wechatBot']
|
|
122
|
+
|
|
123
|
+
export function apply(ctx) {
|
|
124
|
+
const bot = ctx.get('wechatBot')
|
|
125
|
+
|
|
126
|
+
// 1) 推送一段文本
|
|
127
|
+
await bot.send('日报已生成,请查收')
|
|
128
|
+
|
|
129
|
+
// 2) 推送日报文件:自动压缩成群发版短消息 + 1900 字节分片
|
|
130
|
+
await bot.sendFile('E:\\Administrator\\Documents\\daily-news\\2026-11-11-应急行业日报.md')
|
|
131
|
+
|
|
132
|
+
// 3) 查状态 / 最近消息
|
|
133
|
+
const state = bot.status() // { connection, account, lastPush, counters, ... }
|
|
134
|
+
const msgs = bot.recent(20) // 最近收到的入站消息(仅元数据)
|
|
135
|
+
|
|
136
|
+
// 4) 登录控制(一般交给面板,脚本化时才用)
|
|
137
|
+
await bot.login('start') // start | refresh | logout
|
|
138
|
+
}
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
返回值约定:`{ ok, chunks, chars, target }`;失败为 `{ ok:false, error, message }`,`error` 取值:
|
|
142
|
+
`not_logged_in`(未扫码)、`not_online`(连接失效/异常)、`no_context`(需要先给机器人发一条消息)、`read_failed`、`send_failed`。
|
|
143
|
+
|
|
144
|
+
服务方法:
|
|
145
|
+
|
|
146
|
+
| 方法 | 说明 |
|
|
147
|
+
|---|---|
|
|
148
|
+
| `status()` | 连接状态 + 账号 + 计数 + 最近推送 |
|
|
149
|
+
| `send(text, opts?)` | 推送文本,`opts.source` 仅用于审计 |
|
|
150
|
+
| `sendFile(path)` | 读取日报 Markdown → 压缩 → 分片推送 |
|
|
151
|
+
| `sendDigest(path)` | `sendFile` 的别名 |
|
|
152
|
+
| `login(action)` | `start` / `refresh` / `logout` |
|
|
153
|
+
| `recent(limit)` | 最近入站消息(≤100) |
|
|
154
|
+
|
|
155
|
+
> 服务在插件激活时通过 `ctx.provide('wechatBot', api)` 注册;依赖方 `inject: ['wechatBot']` 后 Cordis 会自动等待该服务可用。
|
|
156
|
+
|
|
157
|
+
### 方式 2:同源 HTTP(跨进程 / Client 插件可用)
|
|
158
|
+
|
|
159
|
+
与 DSH Web GUI 同端口,仅同源请求通过:
|
|
160
|
+
|
|
161
|
+
```
|
|
162
|
+
GET /wechat-bot/state → 连接/账号/计数状态
|
|
163
|
+
GET /wechat-bot/qr.png → 当前登录二维码 PNG(登录中才有)
|
|
164
|
+
POST /wechat-bot/login → { "action": "start" | "cancel" | "logout" }
|
|
165
|
+
POST /wechat-bot/send → { "text": "要推送的文本" }
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Host 插件里拿端口:`ctx.get('webServer')?.getOrigin()`。
|
|
169
|
+
|
|
170
|
+
### 方式 3:Agent 工具(给模型用,不是给插件用)
|
|
171
|
+
|
|
172
|
+
`wechat_status` / `wechat_login` / `wechat_send` / `wechat_recent` 由 Agent 在会话中调用(定时任务走这条);插件代码不要依赖工具,直接走方式 1。
|
|
173
|
+
|
|
174
|
+
### 示例
|
|
175
|
+
|
|
176
|
+
见 [examples/consumer-plugin](E:\Administrator\Documents\wechat-bot-plugin\examples\consumer-plugin):一个最小插件,`inject: ['wechatBot']` 后调用 `sendFile` 推送日报。
|
|
177
|
+
|
|
178
|
+
## 微信侧指令与消息路由
|
|
179
|
+
|
|
180
|
+
微信发给机器人的消息按规则分流:
|
|
181
|
+
|
|
182
|
+
- **以 `/` 开头的消息 = 指令**,直接由插件处理并回复,不进入 DSH 会话:
|
|
183
|
+
| 指令 | 作用 |
|
|
184
|
+
|---|---|
|
|
185
|
+
| `/help` | 指令列表 |
|
|
186
|
+
| `/status` | 连接、账号、计数、最近推送 |
|
|
187
|
+
| `/login` | 扫码登录,回复二维码链接 |
|
|
188
|
+
| `/logout` | 退出登录 |
|
|
189
|
+
| `/recent` | 最近收到的消息 |
|
|
190
|
+
| `/news` | 让 DSH 跑今天的新闻简报(转交会话,结果回传) |
|
|
191
|
+
| `/new` | 重置对话会话,下一条消息新建 DSH 会话 |
|
|
192
|
+
- **其余消息全部转交给 DSH 会话**:插件通过 `sessionController.prompt()` 把文本作为用户消息注入 `chatSessionId` 对应的会话(未设置时自动新建,cwd 默认 `E:\Administrator\Documents`),Agent 处理完后,插件在 `turn/end` 时把本轮助手文本回传微信。
|
|
193
|
+
|
|
194
|
+
实现位置:`index.js` 的「微信 ⇄ DSH 会话转发」段(`forwardToChat` / `flushChatTurn` / `session/event` 监听)。会话转发可通过 `settings.chatForward` 关闭。
|
|
195
|
+
|
|
196
|
+
## 已知限制
|
|
197
|
+
|
|
198
|
+
- **二维码渲染为纯 JS**:登录二维码由随插件打包的 `vendor/qrcode.cjs`(qrcode-generator,MIT,© Kazuhiko Arase)在 Host 进程内生成 GIF data URL,然后在面板中以 `<img>` 直接显示;不依赖 Python、不访问网络。
|
|
199
|
+
|
|
200
|
+
- iLink 会话约 24 小时过期,过期后需要重新扫码(面板会提示「连接失效」);
|
|
201
|
+
- 个人微信群无法加入官方机器人,因此推送目标是**你与机器人的 1:1 会话**,群里需要手动转发一次;
|
|
202
|
+
- 推送依赖最近一次入站消息带来的 `context_token`:长时间没人给机器人发消息时,可能需要先发一句任意内容。
|
package/bridge/ilink.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// iLink(微信 ClawBot)协议客户端:扫码登录 / 长轮询收消息 / 发送文本
|
|
2
|
+
// 依据公开协议整理:ilinkai.weixin.qq.com
|
|
3
|
+
import { randomBytes } from 'node:crypto';
|
|
4
|
+
|
|
5
|
+
const DEFAULT_BASE = 'https://ilinkai.weixin.qq.com';
|
|
6
|
+
const CHANNEL_VERSION = '1.0.2';
|
|
7
|
+
const ROUTE_TAG = '1001';
|
|
8
|
+
|
|
9
|
+
export class ILinkError extends Error {
|
|
10
|
+
constructor(code, message, extra = {}) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = 'ILinkError';
|
|
13
|
+
this.code = code;
|
|
14
|
+
Object.assign(this, extra);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const randomUin = () => Buffer.from(String(randomBytes(4).readUInt32BE(0))).toString('base64');
|
|
19
|
+
|
|
20
|
+
function headers(auth) {
|
|
21
|
+
const h = {
|
|
22
|
+
'Content-Type': 'application/json',
|
|
23
|
+
AuthorizationType: 'ilink_bot_token',
|
|
24
|
+
'X-WECHAT-UIN': randomUin(),
|
|
25
|
+
SKRouteTag: ROUTE_TAG,
|
|
26
|
+
};
|
|
27
|
+
if (auth?.token) h.Authorization = `Bearer ${auth.token}`;
|
|
28
|
+
return h;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function post(base, auth, path, body, signal) {
|
|
32
|
+
const res = await fetch(`${base}${path}`, {
|
|
33
|
+
method: 'POST',
|
|
34
|
+
headers: headers(auth),
|
|
35
|
+
body: JSON.stringify(body),
|
|
36
|
+
signal,
|
|
37
|
+
});
|
|
38
|
+
const text = await res.text();
|
|
39
|
+
let json = {};
|
|
40
|
+
try {
|
|
41
|
+
json = text ? JSON.parse(text) : {};
|
|
42
|
+
} catch {
|
|
43
|
+
/* 非 JSON 按失败处理 */
|
|
44
|
+
}
|
|
45
|
+
if (json.ret === -14 || json.errcode === -14) {
|
|
46
|
+
throw new ILinkError('session-expired', '微信连接已失效(-14),需要重新扫码登录', { ret: -14 });
|
|
47
|
+
}
|
|
48
|
+
if (!res.ok || (json.ret !== undefined && json.ret !== 0)) {
|
|
49
|
+
throw new ILinkError('request-failed', `iLink 请求失败: HTTP ${res.status} ${text.slice(0, 200)}`, { httpStatus: res.status });
|
|
50
|
+
}
|
|
51
|
+
return json;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export async function getBotQrcode(base = DEFAULT_BASE) {
|
|
55
|
+
const res = await fetch(`${base}/ilink/bot/get_bot_qrcode?bot_type=3`, { headers: { SKRouteTag: ROUTE_TAG } });
|
|
56
|
+
const text = await res.text();
|
|
57
|
+
if (!res.ok) throw new ILinkError('qrcode-failed', `获取二维码失败: HTTP ${res.status} ${text.slice(0, 200)}`);
|
|
58
|
+
const json = JSON.parse(text);
|
|
59
|
+
return { qrcode: json.qrcode, url: json.qrcode_img_content, base };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export async function pollQrcodeStatus(qrcode, base = DEFAULT_BASE) {
|
|
63
|
+
const controller = new AbortController();
|
|
64
|
+
const timer = setTimeout(() => controller.abort(), 40000);
|
|
65
|
+
try {
|
|
66
|
+
const res = await fetch(`${base}/ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(qrcode)}`, {
|
|
67
|
+
headers: { 'iLink-App-ClientVersion': '1', SKRouteTag: ROUTE_TAG },
|
|
68
|
+
signal: controller.signal,
|
|
69
|
+
});
|
|
70
|
+
const text = await res.text();
|
|
71
|
+
if (!res.ok) return { status: 'wait' };
|
|
72
|
+
return JSON.parse(text);
|
|
73
|
+
} catch {
|
|
74
|
+
return { status: 'wait' };
|
|
75
|
+
} finally {
|
|
76
|
+
clearTimeout(timer);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export async function getUpdates(auth, cursor = '', signal, timeoutMs = 35000) {
|
|
81
|
+
const controller = new AbortController();
|
|
82
|
+
const onAbort = () => controller.abort();
|
|
83
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
84
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs + 10000);
|
|
85
|
+
try {
|
|
86
|
+
const json = await post(auth.baseUrl || DEFAULT_BASE, auth, '/ilink/bot/getupdates',
|
|
87
|
+
{ get_updates_buf: cursor, base_info: { channel_version: CHANNEL_VERSION } }, controller.signal);
|
|
88
|
+
return {
|
|
89
|
+
msgs: Array.isArray(json.msgs) ? json.msgs : [],
|
|
90
|
+
cursor: json.get_updates_buf || cursor,
|
|
91
|
+
timeoutMs: json.longpolling_timeout_ms,
|
|
92
|
+
};
|
|
93
|
+
} catch (error) {
|
|
94
|
+
if (error.code === 'session-expired') throw error;
|
|
95
|
+
if (error.name === 'AbortError' && !signal?.aborted) return { msgs: [], cursor, timeoutMs };
|
|
96
|
+
throw error;
|
|
97
|
+
} finally {
|
|
98
|
+
clearTimeout(timer);
|
|
99
|
+
signal?.removeEventListener('abort', onAbort);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export async function sendText(auth, { toUserId, contextToken, text, clientId }) {
|
|
104
|
+
if (!toUserId) throw new ILinkError('bad-argument', '缺少 to_user_id');
|
|
105
|
+
if (!contextToken) throw new ILinkError('missing-context-token', '缺少 context_token(该会话最近没有收到过消息)');
|
|
106
|
+
await post(auth.baseUrl || DEFAULT_BASE, auth, '/ilink/bot/sendmessage', {
|
|
107
|
+
msg: {
|
|
108
|
+
from_user_id: '',
|
|
109
|
+
to_user_id: toUserId,
|
|
110
|
+
client_id: clientId || `dsh-wechat-${Date.now()}-${randomBytes(3).toString('hex')}`,
|
|
111
|
+
message_type: 2,
|
|
112
|
+
message_state: 2,
|
|
113
|
+
context_token: contextToken,
|
|
114
|
+
item_list: [{ type: 1, text_item: { text } }],
|
|
115
|
+
},
|
|
116
|
+
base_info: { channel_version: CHANNEL_VERSION },
|
|
117
|
+
});
|
|
118
|
+
}
|
package/bridge/render.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// 把《应急行业日报》Markdown 压缩成适合微信单聊的短消息,并按字节分片。
|
|
2
|
+
// 纯函数,便于工具与面板复用。
|
|
3
|
+
|
|
4
|
+
/** 提取速览 + 每主题第一条(标题/日期/链接) */
|
|
5
|
+
export function renderDigest(md) {
|
|
6
|
+
const lines = String(md || '').split(/\r?\n/);
|
|
7
|
+
const out = [];
|
|
8
|
+
let title = '应急行业日报';
|
|
9
|
+
for (const line of lines) {
|
|
10
|
+
const m = line.match(/^#\s+(.+)$/);
|
|
11
|
+
if (m) {
|
|
12
|
+
title = m[1].trim();
|
|
13
|
+
break;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
out.push(`【${title}】`, '');
|
|
17
|
+
const bullets = lines.filter((l) => /^-\s*【/.test(l)).map((l) => l.replace(/^-\s*/, '').trim());
|
|
18
|
+
if (bullets.length) {
|
|
19
|
+
out.push('今日速览');
|
|
20
|
+
bullets.slice(0, 6).forEach((b, i) => out.push(`${i + 1}. ${b}`));
|
|
21
|
+
out.push('');
|
|
22
|
+
}
|
|
23
|
+
let section = '';
|
|
24
|
+
const perSection = new Map();
|
|
25
|
+
for (let i = 0; i < lines.length; i++) {
|
|
26
|
+
const h2 = lines[i].match(/^##\s+(.+)$/);
|
|
27
|
+
if (h2) {
|
|
28
|
+
section = h2[1].trim();
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
const h3 = lines[i].match(/^###\s+(.+)$/);
|
|
32
|
+
if (h3 && section && !/速览|持续跟踪|启示|数据说明/.test(section)) {
|
|
33
|
+
const item = { title: h3[1].replace(/^\d+\.\s*/, '').trim(), date: '', link: '' };
|
|
34
|
+
for (let j = i + 1; j < Math.min(i + 8, lines.length); j++) {
|
|
35
|
+
if (/^###|^##\s/.test(lines[j])) break;
|
|
36
|
+
const d = lines[j].match(/\*\*日期\*\*[::]\s*([^||]+)/);
|
|
37
|
+
if (d && !item.date) item.date = d[1].trim();
|
|
38
|
+
const l = lines[j].match(/(https?:\/\/[^\s)>]+)/);
|
|
39
|
+
if (l && !item.link) item.link = l[1];
|
|
40
|
+
}
|
|
41
|
+
if (!perSection.has(section)) perSection.set(section, []);
|
|
42
|
+
if (perSection.get(section).length < 1) perSection.get(section).push(item);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
for (const [name, items] of perSection) {
|
|
46
|
+
out.push(`▎${name}`);
|
|
47
|
+
for (const it of items) {
|
|
48
|
+
out.push(`· ${it.title}${it.date ? `(${it.date})` : ''}`);
|
|
49
|
+
if (it.link) out.push(` ${it.link}`);
|
|
50
|
+
}
|
|
51
|
+
out.push('');
|
|
52
|
+
}
|
|
53
|
+
out.push('完整版见 DSH 工作区 daily-news 目录。');
|
|
54
|
+
return out.join('\n').replace(/\n{3,}/g, '\n\n').trim();
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** 按 UTF-8 字节上限切片,优先在换行处断开 */
|
|
58
|
+
export function chunkByBytes(text, maxBytes = 1900) {
|
|
59
|
+
const chunks = [];
|
|
60
|
+
let rest = String(text || '');
|
|
61
|
+
while (Buffer.byteLength(rest, 'utf8') > maxBytes) {
|
|
62
|
+
let cut = rest.length;
|
|
63
|
+
while (Buffer.byteLength(rest.slice(0, cut), 'utf8') > maxBytes) cut = Math.max(1, Math.floor(cut * 0.9));
|
|
64
|
+
const nl = rest.lastIndexOf('\n', cut);
|
|
65
|
+
if (nl > cut * 0.5) cut = nl + 1;
|
|
66
|
+
chunks.push(rest.slice(0, cut).trimEnd());
|
|
67
|
+
rest = rest.slice(cut).trimStart();
|
|
68
|
+
}
|
|
69
|
+
if (rest.trim()) chunks.push(rest.trim());
|
|
70
|
+
return chunks.length ? chunks : [''];
|
|
71
|
+
}
|