@x.ken/wecom 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/README.md +268 -0
- package/clawdbot.plugin.json +11 -0
- package/index.ts +17 -0
- package/package.json +17 -0
- package/src/access-token.ts +56 -0
- package/src/channel.ts +114 -0
- package/src/client.ts +124 -0
- package/src/config-schema.ts +19 -0
- package/src/crypto.ts +113 -0
- package/src/gateway.ts +413 -0
- package/src/message-parser.ts +195 -0
- package/src/multipart.ts +70 -0
- package/src/official-api.ts +150 -0
- package/src/runtime.ts +12 -0
package/README.md
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
# Clawdbot WeCom Plugin
|
|
2
|
+
|
|
3
|
+
企业微信(WeCom)集成插件,支持通过企业微信与 AI 进行对话。
|
|
4
|
+
|
|
5
|
+
## 功能特性
|
|
6
|
+
|
|
7
|
+
- ✅ **企业微信消息接收**:支持加密消息解密和多种消息类型(文本、图片、语音、视频、位置、链接)
|
|
8
|
+
- ✅ **企业微信消息发送**:通过企业微信官方 API 发送消息
|
|
9
|
+
- ✅ **Access Token 管理**:自动缓存和刷新 Access Token
|
|
10
|
+
- ✅ **多账号管理**:支持配置多个独立账号
|
|
11
|
+
|
|
12
|
+
## 快速开始
|
|
13
|
+
|
|
14
|
+
### 1. 安装配置
|
|
15
|
+
|
|
16
|
+
在 `~/.clawdbot/clawdbot.json` 中添加:
|
|
17
|
+
|
|
18
|
+
```json5
|
|
19
|
+
{
|
|
20
|
+
"plugins": {
|
|
21
|
+
"enabled": ["wecom"]
|
|
22
|
+
},
|
|
23
|
+
|
|
24
|
+
"channels": {
|
|
25
|
+
"wecom": {
|
|
26
|
+
"enabled": true,
|
|
27
|
+
|
|
28
|
+
// 企业微信应用配置
|
|
29
|
+
"corpid": "ww1234567890abcdef", // 企业ID
|
|
30
|
+
"corpsecret": "your-corp-secret", // 应用Secret
|
|
31
|
+
"agentid": 1000002, // 应用AgentId
|
|
32
|
+
"token": "your-token", // 消息验证Token
|
|
33
|
+
"encodingAESKey": "your-encoding-aes-key", // 消息加密密钥
|
|
34
|
+
|
|
35
|
+
// 自定义系统提示词(可选)
|
|
36
|
+
"systemPrompt": "你是一个专业的AI助手"
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
**如何获取配置参数**:
|
|
43
|
+
1. 登录[企业微信管理后台](https://work.weixin.qq.com/)
|
|
44
|
+
2. 进入"应用管理" → 选择或创建应用
|
|
45
|
+
3. 在应用详情页获取:
|
|
46
|
+
- `AgentId`:应用ID
|
|
47
|
+
- `Secret`:点击"查看Secret"获取
|
|
48
|
+
4. 在"接收消息"设置中获取:
|
|
49
|
+
- `Token`:点击"随机获取"
|
|
50
|
+
- `EncodingAESKey`:点击"随机获取"
|
|
51
|
+
5. 在"我的企业"中查看 `企业ID (CorpID)`
|
|
52
|
+
|
|
53
|
+
### 2. 启动 Gateway
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
clawdbot gateway run --port 18789
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### 3. 配置企业微信应用
|
|
60
|
+
|
|
61
|
+
在企业微信管理后台,配置应用回调 URL:
|
|
62
|
+
|
|
63
|
+
```
|
|
64
|
+
http://your-gateway-host:18789/wecom/message
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
企业微信会发送 GET 请求验证 URL,插件会自动处理验证流程。
|
|
68
|
+
|
|
69
|
+
### 4. 测试接收消息
|
|
70
|
+
|
|
71
|
+
在企业微信应用中发送消息,Gateway 会自动接收、解密并转发给 Clawdbot 进行 AI 对话。
|
|
72
|
+
|
|
73
|
+
## 架构设计
|
|
74
|
+
|
|
75
|
+
### 消息接收流程(企业微信 → Clawdbot)
|
|
76
|
+
|
|
77
|
+
```
|
|
78
|
+
企业微信用户发送消息
|
|
79
|
+
↓ POST /wecom/message(加密 XML)
|
|
80
|
+
Gateway(接收)
|
|
81
|
+
↓ 验证签名
|
|
82
|
+
↓ 解密消息
|
|
83
|
+
↓ 解析 XML
|
|
84
|
+
↓ 转换为内部格式
|
|
85
|
+
Clawdbot Agent(AI 处理)
|
|
86
|
+
↓ 生成回复
|
|
87
|
+
Gateway(发送回复)
|
|
88
|
+
↓ 调用企业微信 API
|
|
89
|
+
企业微信用户接收回复
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### 消息发送流程(Clawdbot → 企业微信)
|
|
93
|
+
|
|
94
|
+
```
|
|
95
|
+
Clawdbot Agent(生成回复)
|
|
96
|
+
↓
|
|
97
|
+
Gateway(发送)
|
|
98
|
+
↓
|
|
99
|
+
企业微信官方 API(发送)
|
|
100
|
+
↓
|
|
101
|
+
企业微信用户接收
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## API 端点
|
|
105
|
+
|
|
106
|
+
### GET /wecom/message
|
|
107
|
+
|
|
108
|
+
企业微信 URL 验证端点(首次配置时使用)
|
|
109
|
+
|
|
110
|
+
**查询参数**:
|
|
111
|
+
- `msg_signature`: 消息签名
|
|
112
|
+
- `timestamp`: 时间戳
|
|
113
|
+
- `nonce`: 随机数
|
|
114
|
+
- `echostr`: 加密的验证字符串
|
|
115
|
+
|
|
116
|
+
插件会自动验证签名、解密并返回明文 echostr。
|
|
117
|
+
|
|
118
|
+
### POST /wecom/message
|
|
119
|
+
|
|
120
|
+
接收企业微信加密消息
|
|
121
|
+
|
|
122
|
+
**Content-Type**: `text/xml` 或 `application/xml`
|
|
123
|
+
|
|
124
|
+
**查询参数**:
|
|
125
|
+
- `msg_signature`: 消息签名
|
|
126
|
+
- `timestamp`: 时间戳
|
|
127
|
+
- `nonce`: 随机数
|
|
128
|
+
|
|
129
|
+
**请求体**(XML):
|
|
130
|
+
```xml
|
|
131
|
+
<xml>
|
|
132
|
+
<ToUserName><![CDATA[corpid]]></ToUserName>
|
|
133
|
+
<Encrypt><![CDATA[加密的消息内容]]></Encrypt>
|
|
134
|
+
</xml>
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
**支持的消息类型**:
|
|
138
|
+
- **文本消息**:直接处理文本内容
|
|
139
|
+
- **图片消息**:提取图片 URL 并发送给 Clawdbot
|
|
140
|
+
- **语音消息**:显示语音信息(格式、MediaId)
|
|
141
|
+
- **视频消息**:显示视频信息(MediaId)
|
|
142
|
+
- **位置消息**:格式化位置信息(坐标、标签)
|
|
143
|
+
- **链接消息**:提取标题、描述、URL
|
|
144
|
+
|
|
145
|
+
**响应**:返回 `success` 文本(企业微信要求)
|
|
146
|
+
|
|
147
|
+
### GET /wecom/messages?email=xxx
|
|
148
|
+
|
|
149
|
+
轮询获取待发送的消息(异步模式)
|
|
150
|
+
|
|
151
|
+
**响应格式**:
|
|
152
|
+
|
|
153
|
+
```json
|
|
154
|
+
{
|
|
155
|
+
"messages": [
|
|
156
|
+
{
|
|
157
|
+
"text": "回复内容",
|
|
158
|
+
"mediaUrl": "https://..."
|
|
159
|
+
}
|
|
160
|
+
]
|
|
161
|
+
}
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
## 配置参数
|
|
165
|
+
|
|
166
|
+
### 企业微信官方 API 配置
|
|
167
|
+
|
|
168
|
+
| 参数 | 类型 | 必需 | 说明 |
|
|
169
|
+
|------|------|------|------|
|
|
170
|
+
| `corpid` | string | 是 | 企业微信 Corp ID |
|
|
171
|
+
| `corpsecret` | string | 是 | 企业微信应用 Secret |
|
|
172
|
+
| `agentid` | number | 是 | 企业微信应用 Agent ID |
|
|
173
|
+
| `token` | string | 是 | 企业微信应用 Token(用于消息验证)|
|
|
174
|
+
| `encodingAESKey` | string | 是 | 消息加密密钥(43位字符)|
|
|
175
|
+
|
|
176
|
+
**如何获取**:
|
|
177
|
+
1. 登录[企业微信管理后台](https://work.weixin.qq.com/)
|
|
178
|
+
2. 进入"应用管理" → 选择或创建应用
|
|
179
|
+
3. 在应用详情页获取 `AgentId` 和 `Secret`
|
|
180
|
+
4. 在"接收消息"设置中获取 `Token` 和 `EncodingAESKey`
|
|
181
|
+
5. 在"我的企业"中查看 `企业ID (CorpID)`
|
|
182
|
+
|
|
183
|
+
**配置命令**:
|
|
184
|
+
```bash
|
|
185
|
+
clawdbot config set channels.wecom.corpid "ww1234567890abcdef"
|
|
186
|
+
clawdbot config set channels.wecom.corpsecret "your-corp-secret"
|
|
187
|
+
clawdbot config set channels.wecom.agentid 1000002
|
|
188
|
+
clawdbot config set channels.wecom.token "your-token"
|
|
189
|
+
clawdbot config set channels.wecom.encodingAESKey "your-encoding-aes-key"
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
### 可选配置
|
|
193
|
+
|
|
194
|
+
| 参数 | 类型 | 必需 | 说明 |
|
|
195
|
+
|------|------|------|------|
|
|
196
|
+
| `systemPrompt` | string | 否 | 自定义系统提示词片段 |
|
|
197
|
+
|
|
198
|
+
## 文件结构
|
|
199
|
+
|
|
200
|
+
```
|
|
201
|
+
clawdbot-wechat-plugin/
|
|
202
|
+
├── src/
|
|
203
|
+
│ ├── channel.ts # 渠道插件定义
|
|
204
|
+
│ ├── client.ts # 消息发送客户端
|
|
205
|
+
│ ├── config-schema.ts # 配置 Schema
|
|
206
|
+
│ ├── gateway.ts # Gateway HTTP 路由
|
|
207
|
+
│ ├── multipart.ts # Multipart 解析器
|
|
208
|
+
│ ├── runtime.ts # 运行时管理
|
|
209
|
+
│ ├── crypto.ts # 加密/解密工具
|
|
210
|
+
│ ├── message-parser.ts # 消息解析
|
|
211
|
+
│ ├── official-api.ts # 企业微信官方 API
|
|
212
|
+
│ └── access-token.ts # Access Token 管理
|
|
213
|
+
├── index.ts # 插件入口
|
|
214
|
+
├── package.json
|
|
215
|
+
├── clawdbot.plugin.json
|
|
216
|
+
└── README.md # 本文档
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
## 开发
|
|
220
|
+
|
|
221
|
+
### 构建
|
|
222
|
+
|
|
223
|
+
```bash
|
|
224
|
+
cd clawdbot-wechat-plugin
|
|
225
|
+
pnpm install
|
|
226
|
+
pnpm build
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
### 测试
|
|
230
|
+
|
|
231
|
+
```bash
|
|
232
|
+
# 单元测试
|
|
233
|
+
pnpm test
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
## 故障排查
|
|
237
|
+
|
|
238
|
+
### 企业微信发送失败
|
|
239
|
+
|
|
240
|
+
**症状**:日志显示 "企业微信 API 调用失败"
|
|
241
|
+
|
|
242
|
+
**解决方法**:
|
|
243
|
+
1. 检查查 `corpid`、`corpsecret` 和 `agentid` 是否正确
|
|
244
|
+
2. 确认收件人 UserID 在企业微信系统中存在
|
|
245
|
+
3. 检查消息内容长度(最多 2048 字节)
|
|
246
|
+
4. 验证 API 配额是否已用完
|
|
247
|
+
|
|
248
|
+
### 消息验证失败
|
|
249
|
+
|
|
250
|
+
**症状**:企业微信配置回调 URL 时验证失败
|
|
251
|
+
|
|
252
|
+
**解决方法**:
|
|
253
|
+
1. 检查 `token` 和 `encodingAESKey` 是否正确
|
|
254
|
+
2. 确认 Gateway 正在运行并可访问
|
|
255
|
+
3. 检查网络连接
|
|
256
|
+
|
|
257
|
+
## 许可证
|
|
258
|
+
|
|
259
|
+
MIT
|
|
260
|
+
|
|
261
|
+
## 贡献
|
|
262
|
+
|
|
263
|
+
欢迎提交 Issue 和 Pull Request!
|
|
264
|
+
|
|
265
|
+
## 联系方式
|
|
266
|
+
|
|
267
|
+
- 项目主页: https://github.com/clawdbot/clawdbot
|
|
268
|
+
- 文档: https://docs.clawd.bot
|
package/index.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { ClawdbotPluginApi } from "clawdbot/plugin-sdk";
|
|
2
|
+
import { emptyPluginConfigSchema } from "clawdbot/plugin-sdk";
|
|
3
|
+
import { wecomPlugin } from "./src/channel.js";
|
|
4
|
+
import { setWeComRuntime } from "./src/runtime.js";
|
|
5
|
+
|
|
6
|
+
const plugin = {
|
|
7
|
+
id: "wecom",
|
|
8
|
+
name: "WeCom",
|
|
9
|
+
description: "企业微信集成",
|
|
10
|
+
configSchema: emptyPluginConfigSchema(),
|
|
11
|
+
register(api: ClawdbotPluginApi) {
|
|
12
|
+
setWeComRuntime(api.runtime);
|
|
13
|
+
api.registerChannel({ plugin: wecomPlugin });
|
|
14
|
+
},
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export default plugin;
|
package/package.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@x.ken/wecom",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Clawdbot WeCom (企业微信) integration plugin",
|
|
6
|
+
"clawdbot": {
|
|
7
|
+
"extensions": [
|
|
8
|
+
"./index.ts"
|
|
9
|
+
]
|
|
10
|
+
},
|
|
11
|
+
"dependencies": {
|
|
12
|
+
"fast-xml-parser": "^4.3.4"
|
|
13
|
+
},
|
|
14
|
+
"peerDependencies": {
|
|
15
|
+
"clawdbot": "*"
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
interface AccessTokenCache {
|
|
2
|
+
token: string;
|
|
3
|
+
expiresAt: number;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export class WeComAccessTokenManager {
|
|
7
|
+
private cache: Map<string, AccessTokenCache> = new Map();
|
|
8
|
+
|
|
9
|
+
async getAccessToken(corpid: string, corpsecret: string): Promise<string> {
|
|
10
|
+
const cacheKey = `${corpid}:${corpsecret}`;
|
|
11
|
+
const cached = this.cache.get(cacheKey);
|
|
12
|
+
|
|
13
|
+
if (cached && cached.expiresAt > Date.now() + 5 * 60 * 1000) {
|
|
14
|
+
return cached.token;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const url = `https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${encodeURIComponent(
|
|
18
|
+
corpid
|
|
19
|
+
)}&corpsecret=${encodeURIComponent(corpsecret)}`;
|
|
20
|
+
|
|
21
|
+
const response = await fetch(url);
|
|
22
|
+
if (!response.ok) {
|
|
23
|
+
throw new Error(
|
|
24
|
+
`Failed to get access token: ${response.status} ${response.statusText}`
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const data = await response.json();
|
|
29
|
+
|
|
30
|
+
if (data.errcode !== 0) {
|
|
31
|
+
throw new Error(
|
|
32
|
+
`WeChat API error: ${data.errcode} - ${data.errmsg}`
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const expiresIn = (data.expires_in || 7200) * 1000;
|
|
37
|
+
const expiresAt = Date.now() + expiresIn - 10 * 60 * 1000;
|
|
38
|
+
|
|
39
|
+
this.cache.set(cacheKey, {
|
|
40
|
+
token: data.access_token,
|
|
41
|
+
expiresAt,
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
return data.access_token;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
clearCache(corpid?: string, corpsecret?: string) {
|
|
48
|
+
if (corpid && corpsecret) {
|
|
49
|
+
this.cache.delete(`${corpid}:${corpsecret}`);
|
|
50
|
+
} else {
|
|
51
|
+
this.cache.clear();
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export const accessTokenManager = new WeComAccessTokenManager();
|
package/src/channel.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import {
|
|
2
|
+
buildChannelConfigSchema,
|
|
3
|
+
type ChannelPlugin,
|
|
4
|
+
type ResolvedChannelAccount,
|
|
5
|
+
DEFAULT_ACCOUNT_ID
|
|
6
|
+
} from "clawdbot/plugin-sdk";
|
|
7
|
+
import { WeComConfigSchema, type WeComAccountConfigSchema } from "./config-schema.js";
|
|
8
|
+
import { startWeComAccount } from "./gateway.js";
|
|
9
|
+
import { wecomClient } from "./client.js";
|
|
10
|
+
import { getWeComRuntime } from "./runtime.js";
|
|
11
|
+
import type { z } from "zod";
|
|
12
|
+
|
|
13
|
+
type WeComConfig = z.infer<typeof WeComConfigSchema>;
|
|
14
|
+
type ResolvedWeComAccount = ResolvedChannelAccount<WeComConfig>;
|
|
15
|
+
|
|
16
|
+
export const wecomPlugin: ChannelPlugin<ResolvedWeComAccount> = {
|
|
17
|
+
id: "wecom",
|
|
18
|
+
meta: {
|
|
19
|
+
id: "wecom",
|
|
20
|
+
name: "WeCom",
|
|
21
|
+
description: "企业微信集成",
|
|
22
|
+
hidden: false,
|
|
23
|
+
quickstartAllowFrom: true,
|
|
24
|
+
},
|
|
25
|
+
capabilities: {
|
|
26
|
+
chatTypes: ["direct"],
|
|
27
|
+
media: true,
|
|
28
|
+
text: true,
|
|
29
|
+
blockStreaming: true,
|
|
30
|
+
},
|
|
31
|
+
configSchema: buildChannelConfigSchema(WeComConfigSchema),
|
|
32
|
+
config: {
|
|
33
|
+
listAccountIds: (cfg) => {
|
|
34
|
+
const accounts = cfg.channels?.["wecom"]?.accounts;
|
|
35
|
+
const ids = accounts ? Object.keys(accounts) : [];
|
|
36
|
+
if (ids.length === 0 || !ids.includes(DEFAULT_ACCOUNT_ID)) {
|
|
37
|
+
ids.unshift(DEFAULT_ACCOUNT_ID);
|
|
38
|
+
}
|
|
39
|
+
return ids;
|
|
40
|
+
},
|
|
41
|
+
resolveAccount: (cfg, accountId) => {
|
|
42
|
+
const wecom = cfg.channels?.["wecom"];
|
|
43
|
+
const resolvedId = accountId ?? DEFAULT_ACCOUNT_ID;
|
|
44
|
+
const account = wecom?.accounts?.[resolvedId];
|
|
45
|
+
const defaults = { ...wecom };
|
|
46
|
+
if (defaults.accounts) delete defaults.accounts;
|
|
47
|
+
|
|
48
|
+
const config = { ...defaults, ...account } as any;
|
|
49
|
+
|
|
50
|
+
return {
|
|
51
|
+
accountId: resolvedId,
|
|
52
|
+
name: account?.name || resolvedId,
|
|
53
|
+
enabled: account?.enabled ?? wecom?.enabled ?? true,
|
|
54
|
+
config: config,
|
|
55
|
+
tokenSource: "config",
|
|
56
|
+
token: "",
|
|
57
|
+
};
|
|
58
|
+
},
|
|
59
|
+
defaultAccountId: () => DEFAULT_ACCOUNT_ID,
|
|
60
|
+
describeAccount: (account) => ({
|
|
61
|
+
accountId: account.accountId,
|
|
62
|
+
name: account.name,
|
|
63
|
+
enabled: account.enabled,
|
|
64
|
+
configured: true,
|
|
65
|
+
tokenSource: "config",
|
|
66
|
+
}),
|
|
67
|
+
},
|
|
68
|
+
gateway: {
|
|
69
|
+
startAccount: startWeComAccount,
|
|
70
|
+
},
|
|
71
|
+
outbound: {
|
|
72
|
+
deliveryMode: "direct",
|
|
73
|
+
sendText: async ({ to, text, accountId }) => {
|
|
74
|
+
const runtime = getWeComRuntime();
|
|
75
|
+
const cfg = await runtime.config.loadConfig();
|
|
76
|
+
const wecom = cfg.channels?.["wecom"];
|
|
77
|
+
const resolvedId = accountId ?? DEFAULT_ACCOUNT_ID;
|
|
78
|
+
const account = wecom?.accounts?.[resolvedId];
|
|
79
|
+
const defaults = { ...wecom };
|
|
80
|
+
if (defaults.accounts) delete defaults.accounts;
|
|
81
|
+
const config = { ...defaults, ...account } as any;
|
|
82
|
+
|
|
83
|
+
await wecomClient.sendMessage(to, { text }, {
|
|
84
|
+
corpid: config.corpid,
|
|
85
|
+
corpsecret: config.corpsecret,
|
|
86
|
+
agentid: config.agentid,
|
|
87
|
+
token: config.token,
|
|
88
|
+
encodingAESKey: config.encodingAESKey
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
return { channel: "wecom", ok: true };
|
|
92
|
+
},
|
|
93
|
+
sendMedia: async ({ to, text, mediaUrl, accountId }) => {
|
|
94
|
+
const runtime = getWeComRuntime();
|
|
95
|
+
const cfg = await runtime.config.loadConfig();
|
|
96
|
+
const wecom = cfg.channels?.["wecom"];
|
|
97
|
+
const resolvedId = accountId ?? DEFAULT_ACCOUNT_ID;
|
|
98
|
+
const account = wecom?.accounts?.[resolvedId];
|
|
99
|
+
const defaults = { ...wecom };
|
|
100
|
+
if (defaults.accounts) delete defaults.accounts;
|
|
101
|
+
const config = { ...defaults, ...account } as any;
|
|
102
|
+
|
|
103
|
+
await wecomClient.sendMessage(to, { text, mediaUrl }, {
|
|
104
|
+
corpid: config.corpid,
|
|
105
|
+
corpsecret: config.corpsecret,
|
|
106
|
+
agentid: config.agentid,
|
|
107
|
+
token: config.token,
|
|
108
|
+
encodingAESKey: config.encodingAESKey
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
return { channel: "wecom", ok: true };
|
|
112
|
+
}
|
|
113
|
+
},
|
|
114
|
+
};
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type { ServerResponse } from "node:http";
|
|
2
|
+
import { wecomOfficialAPI } from "./official-api.js";
|
|
3
|
+
|
|
4
|
+
export interface WeComMessage {
|
|
5
|
+
text?: string;
|
|
6
|
+
mediaUrl?: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export class WeComClient {
|
|
10
|
+
private outboundQueue = new Map<string, WeComMessage[]>();
|
|
11
|
+
private pendingRequests = new Map<string, ServerResponse>();
|
|
12
|
+
|
|
13
|
+
constructor() {}
|
|
14
|
+
|
|
15
|
+
registerPendingRequest(userId: string, res: ServerResponse, timeoutMs: number = 30000) {
|
|
16
|
+
if (this.pendingRequests.has(userId)) {
|
|
17
|
+
const oldRes = this.pendingRequests.get(userId);
|
|
18
|
+
if (oldRes && !oldRes.writableEnded) {
|
|
19
|
+
try {
|
|
20
|
+
oldRes.statusCode = 409;
|
|
21
|
+
oldRes.end(JSON.stringify({ error: "New synchronous request superseded this one" }));
|
|
22
|
+
} catch (e) {
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
this.pendingRequests.set(userId, res);
|
|
27
|
+
|
|
28
|
+
setTimeout(() => {
|
|
29
|
+
if (this.pendingRequests.get(userId) === res) {
|
|
30
|
+
this.pendingRequests.delete(userId);
|
|
31
|
+
if (!res.writableEnded) {
|
|
32
|
+
try {
|
|
33
|
+
res.statusCode = 202;
|
|
34
|
+
res.setHeader("Content-Type", "application/json");
|
|
35
|
+
res.end(JSON.stringify({ status: "accepted", message: "Processing continued, poll for results." }));
|
|
36
|
+
} catch (e) {
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}, timeoutMs);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async sendMessage(userId: string, message: WeComMessage, config: {
|
|
44
|
+
corpid?: string,
|
|
45
|
+
corpsecret?: string,
|
|
46
|
+
agentid?: number,
|
|
47
|
+
token?: string,
|
|
48
|
+
encodingAESKey?: string
|
|
49
|
+
}) {
|
|
50
|
+
const pendingRes = this.pendingRequests.get(userId);
|
|
51
|
+
if (pendingRes && !pendingRes.writableEnded) {
|
|
52
|
+
this.pendingRequests.delete(userId);
|
|
53
|
+
try {
|
|
54
|
+
pendingRes.statusCode = 200;
|
|
55
|
+
pendingRes.setHeader("Content-Type", "application/json");
|
|
56
|
+
pendingRes.end(JSON.stringify(message));
|
|
57
|
+
return;
|
|
58
|
+
} catch (e) {
|
|
59
|
+
console.error("WeCom: Failed to write sync response", e);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
console.log("[WeCom Client] sendMessage called with config:", {
|
|
64
|
+
hasCorpid: !!config.corpid,
|
|
65
|
+
hasCorpsecret: !!config.corpsecret,
|
|
66
|
+
hasAgentid: !!config.agentid,
|
|
67
|
+
corpidValue: config.corpid,
|
|
68
|
+
agentidValue: config.agentid
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
if (config.corpid && config.corpsecret && config.agentid) {
|
|
72
|
+
try {
|
|
73
|
+
let finalText = message.text || "";
|
|
74
|
+
|
|
75
|
+
if (message.mediaUrl) {
|
|
76
|
+
finalText = finalText
|
|
77
|
+
? `${finalText}\n\n📎 附件: ${message.mediaUrl}`
|
|
78
|
+
: `📎 附件: ${message.mediaUrl}`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const payload = {
|
|
82
|
+
msgtype: "text" as const,
|
|
83
|
+
agentid: config.agentid,
|
|
84
|
+
touser: userId,
|
|
85
|
+
text: {
|
|
86
|
+
content: finalText,
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
console.log("[WeCom Client] Sending via official API, payload:", payload);
|
|
91
|
+
|
|
92
|
+
const result = await wecomOfficialAPI.sendMessage(
|
|
93
|
+
config.corpid,
|
|
94
|
+
config.corpsecret,
|
|
95
|
+
payload
|
|
96
|
+
);
|
|
97
|
+
|
|
98
|
+
console.log("[WeCom Client] Official API send success:", result);
|
|
99
|
+
return;
|
|
100
|
+
} catch (error) {
|
|
101
|
+
console.error("[WeCom Client] Official API error:", error);
|
|
102
|
+
throw error; // Re-throw so caller knows it failed
|
|
103
|
+
}
|
|
104
|
+
} else {
|
|
105
|
+
console.log("[WeCom Client] Config incomplete, falling back to queue:");
|
|
106
|
+
console.log(" - corpid:", config.corpid);
|
|
107
|
+
console.log(" - corpsecret:", config.corpsecret ? "set" : "missing");
|
|
108
|
+
console.log(" - agentid:", config.agentid);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
console.log("消息加入队列:", userId);
|
|
112
|
+
const queue = this.outboundQueue.get(userId) ?? [];
|
|
113
|
+
queue.push(message);
|
|
114
|
+
this.outboundQueue.set(userId, queue);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
getPendingMessages(userId: string): WeComMessage[] {
|
|
118
|
+
const messages = this.outboundQueue.get(userId) ?? [];
|
|
119
|
+
this.outboundQueue.delete(userId);
|
|
120
|
+
return messages;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export const wecomClient = new WeComClient();
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
export const WeComAccountConfigSchema = z.object({
|
|
4
|
+
enabled: z.boolean().optional(),
|
|
5
|
+
|
|
6
|
+
// 企业微信应用配置
|
|
7
|
+
corpid: z.string().optional().describe("企业微信 Corp ID"),
|
|
8
|
+
corpsecret: z.string().optional().describe("企业微信 Corp Secret"),
|
|
9
|
+
agentid: z.number().optional().describe("企业微信应用 Agent ID"),
|
|
10
|
+
token: z.string().optional().describe("企业微信应用 Token"),
|
|
11
|
+
encodingAESKey: z.string().optional().describe("企业微信消息加密密钥"),
|
|
12
|
+
|
|
13
|
+
// 自定义系统提示词
|
|
14
|
+
systemPrompt: z.string().optional().describe("自定义系统提示词片段"),
|
|
15
|
+
}).strict();
|
|
16
|
+
|
|
17
|
+
export const WeComConfigSchema = WeComAccountConfigSchema.extend({
|
|
18
|
+
accounts: z.record(z.string(), WeComAccountConfigSchema.optional()).optional(),
|
|
19
|
+
}).strict();
|