@alemonjs/onebot 0.2.2 → 0.2.3

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
@@ -1,7 +1,5 @@
1
1
  # [https://alemonjs.com/](https://alemonjs.com/)
2
2
 
3
- 跨平台开发的事件驱动机器人
4
-
5
3
  - alemomn.config.yaml
6
4
 
7
5
  ```yaml
package/lib/index.d.ts CHANGED
@@ -4,6 +4,7 @@ import { OneBotClient } from './sdk/wss.js';
4
4
  type Client = typeof OneBotClient.prototype;
5
5
  declare const client: Client;
6
6
  declare const platform = "onebot";
7
- declare const _default: () => alemonjs.ClientAPI;
7
+ declare const _default: alemonjs.DefinePlatformValue;
8
8
 
9
- export { type Client, client, _default as default, platform };
9
+ export { client, _default as default, platform };
10
+ export type { Client };
package/lib/index.js CHANGED
@@ -1,5 +1,6 @@
1
- import { defineBot, getConfigValue, useUserHashKey, OnProcessor } from 'alemonjs';
1
+ import { getConfigValue, useUserHashKey, onProcessor, createResult, ResultCode } from 'alemonjs';
2
2
  import { OneBotClient } from './sdk/wss.js';
3
+ import { createServer } from './server/index.js';
3
4
 
4
5
  const client = new Proxy({}, {
5
6
  get: (_, prop) => {
@@ -12,12 +13,11 @@ const client = new Proxy({}, {
12
13
  }
13
14
  });
14
15
  const platform = 'onebot';
15
- var index = defineBot(() => {
16
+ var index = definePlatform(() => {
16
17
  let value = getConfigValue();
17
18
  if (!value)
18
19
  value = {};
19
20
  const config = value[platform];
20
- //
21
21
  const client = new OneBotClient({
22
22
  // url
23
23
  url: config?.url ?? '',
@@ -28,20 +28,16 @@ var index = defineBot(() => {
28
28
  // 反向连接端口
29
29
  reverse_port: config?.reverse_port ?? 17158
30
30
  });
31
- //
32
31
  client.connect();
33
- //
34
32
  client.on('META', event => {
35
33
  if (event?.self_id) {
36
34
  String(event.self_id);
37
35
  }
38
36
  });
39
- //
40
37
  client.on('MESSAGES', event => {
41
38
  const uis = config.master_uids ?? [];
42
39
  let msg = '';
43
40
  const arr = [];
44
- // let at_users = []
45
41
  for (const item of event.message) {
46
42
  if (item.type == 'text') {
47
43
  msg = item.data.text;
@@ -76,7 +72,6 @@ var index = defineBot(() => {
76
72
  Platform: platform,
77
73
  // 频道
78
74
  GuildId: String(event.group_id),
79
- // guild_name: event.group_name,
80
75
  // 子频道
81
76
  ChannelId: String(event.group_id),
82
77
  IsMaster: uis.includes(String(event.user_id)),
@@ -93,74 +88,204 @@ var index = defineBot(() => {
93
88
  // 创建时间
94
89
  CreateAt: Date.now(),
95
90
  // 标签
96
- tag: 'MESSAGES',
91
+ tag: 'message.create',
97
92
  //
98
93
  value: null
99
94
  };
100
- // 当访问的时候获取
101
- Object.defineProperty(e, 'value', {
102
- get() {
103
- return event;
95
+ // 处理消息
96
+ onProcessor('message.create', e, event);
97
+ });
98
+ client.on('DIRECT_MESSAGE', (event) => {
99
+ const uis = config.master_uids ?? [];
100
+ let msg = '';
101
+ const arr = [];
102
+ for (const item of event.message) {
103
+ if (item.type == 'text') {
104
+ msg = item.data.text;
105
+ }
106
+ }
107
+ for (const item of arr) {
108
+ msg = msg.replace(item.text, '').trim();
109
+ }
110
+ const url = `https://q1.qlogo.cn/g?b=qq&s=0&nk=${event.user_id}`;
111
+ const UserAvatar = {
112
+ toBuffer: async () => {
113
+ const arrayBuffer = await fetch(url).then(res => res.arrayBuffer());
114
+ return Buffer.from(arrayBuffer);
115
+ },
116
+ toBase64: async () => {
117
+ const arrayBuffer = await fetch(url).then(res => res.arrayBuffer());
118
+ return Buffer.from(arrayBuffer).toString('base64');
119
+ },
120
+ toURL: async () => {
121
+ return url;
104
122
  }
123
+ };
124
+ const UserId = String(event.user_id);
125
+ const UserKey = useUserHashKey({
126
+ Platform: platform,
127
+ UserId
105
128
  });
129
+ // 定义消
130
+ const e = {
131
+ name: 'private.message.create',
132
+ // 平台类型
133
+ Platform: platform,
134
+ // 频道
135
+ // GuildId: String(event.group_id),
136
+ // 子频道
137
+ // ChannelId: String(event.group_id),
138
+ IsMaster: uis.includes(String(event.user_id)),
139
+ IsBot: false,
140
+ UserId: UserId,
141
+ UserName: event.sender.nickname,
142
+ UserKey,
143
+ UserAvatar: UserAvatar,
144
+ // message
145
+ MessageId: String(event.message_id),
146
+ MessageText: msg,
147
+ // 用户openId
148
+ OpenId: String(event.user_id),
149
+ // 创建时间
150
+ CreateAt: Date.now(),
151
+ // 标签
152
+ tag: 'private.message.create',
153
+ //
154
+ value: null
155
+ };
106
156
  // 处理消息
107
- OnProcessor(e, 'message.create');
108
- });
109
- client.on('DIRECT_MESSAGE', () => {
110
- // const e = {
111
- // isMaster: event.user_id == masterId,
112
- // msg_txt: event.raw_message,
113
- // msg: event.raw_message.trim(),
114
- // msg_id: event.message_id,
115
- // open_id: event.user_id,
116
- // user_id: event.user_id,
117
- // user_avatar:
118
- // event.platform == 'qq'
119
- // ? `https://q1.qlogo.cn/g?b=qq&s=0&nk=${event.user_id}`
120
- // : '',
121
- // user_name: event.sender.nickname,
157
+ onProcessor('private.message.create', e, event);
122
158
  });
123
159
  // 错误处理
124
160
  client.on('ERROR', event => {
125
161
  console.error('ERROR', event);
126
162
  });
127
163
  global.client = client;
164
+ createServer(client);
165
+ const sendGroup = async (event, val) => {
166
+ if (val.length < 0)
167
+ return Promise.all([]);
168
+ const content = val
169
+ .filter(item => item.type == 'Link' || item.type == 'Mention' || item.type == 'Text')
170
+ .map(item => item.value)
171
+ .join('');
172
+ if (content) {
173
+ return Promise.all([content].map(item => {
174
+ client.sendGroupMessage({
175
+ group_id: event.ChannelId,
176
+ message: [
177
+ {
178
+ type: 'text',
179
+ data: {
180
+ text: item
181
+ }
182
+ }
183
+ ]
184
+ });
185
+ return createResult(ResultCode.Ok, 'client.groupOpenMessages', {
186
+ id: null
187
+ });
188
+ }));
189
+ }
190
+ const images = val.filter(item => item.type == 'Image').map(item => item.value);
191
+ if (images) {
192
+ return Promise.all(images.map(item => {
193
+ client.sendGroupMessage({
194
+ group_id: event.ChannelId,
195
+ message: [
196
+ {
197
+ type: 'image',
198
+ data: {
199
+ file: `base64://${item.toString('base64')}`
200
+ }
201
+ }
202
+ ]
203
+ });
204
+ return createResult(ResultCode.Ok, 'client.groupOpenMessages', {
205
+ id: null
206
+ });
207
+ }));
208
+ }
209
+ return Promise.all([]);
210
+ };
211
+ /**
212
+ *
213
+ * @param event
214
+ * @param val
215
+ * @returns
216
+ */
217
+ const sendPrivate = async (event, val) => {
218
+ if (val.length < 0)
219
+ return Promise.all([]);
220
+ const content = val
221
+ .filter(item => item.type == 'Link' || item.type == 'Mention' || item.type == 'Text')
222
+ .map(item => item.value)
223
+ .join('');
224
+ if (content) {
225
+ return Promise.all([content].map(item => {
226
+ client.sendGroupMessage({
227
+ group_id: event.ChannelId,
228
+ message: [
229
+ {
230
+ type: 'text',
231
+ data: {
232
+ text: item
233
+ }
234
+ }
235
+ ]
236
+ });
237
+ return createResult(ResultCode.Ok, 'client.groupOpenMessages', {
238
+ id: null
239
+ });
240
+ })).catch(err => [
241
+ createResult(ResultCode.Fail, err?.response?.data ?? err?.message ?? err, null)
242
+ ]);
243
+ }
244
+ const images = val.filter(item => item.type == 'Image').map(item => item.value);
245
+ if (images) {
246
+ return Promise.all(images.map(item => {
247
+ client.sendGroupMessage({
248
+ group_id: event.ChannelId,
249
+ message: [
250
+ {
251
+ type: 'image',
252
+ data: {
253
+ file: `base64://${item.toString('base64')}`
254
+ }
255
+ }
256
+ ]
257
+ });
258
+ return createResult(ResultCode.Ok, 'client.groupOpenMessages', {
259
+ id: null
260
+ });
261
+ })).catch(err => [
262
+ createResult(ResultCode.Fail, err?.response?.data ?? err?.message ?? err, null)
263
+ ]);
264
+ }
265
+ return Promise.all([]);
266
+ };
128
267
  return {
268
+ platform,
129
269
  api: {
270
+ active: {
271
+ send: {
272
+ channel: (event, val) => {
273
+ return sendGroup(event, val);
274
+ },
275
+ user: (event, val) => {
276
+ return sendPrivate(event, val);
277
+ }
278
+ }
279
+ },
130
280
  use: {
131
281
  send: (event, val) => {
132
282
  if (val.length < 0)
133
283
  return Promise.all([]);
134
- const content = val
135
- .filter(item => item.type == 'Link' || item.type == 'Mention' || item.type == 'Text')
136
- .map(item => item.value)
137
- .join('');
138
- if (content) {
139
- return Promise.all([content].map(item => client.sendGroupMessage({
140
- group_id: event.ChannelId,
141
- message: [
142
- {
143
- type: 'text',
144
- data: {
145
- text: item
146
- }
147
- }
148
- ]
149
- })));
284
+ if (event['name'] == 'private.message.create') {
285
+ return sendPrivate(event, val);
150
286
  }
151
- const images = val.filter(item => item.type == 'Image').map(item => item.value);
152
- if (images) {
153
- return Promise.all(images.map(item => client.sendGroupMessage({
154
- group_id: event.ChannelId,
155
- message: [
156
- {
157
- type: 'image',
158
- data: {
159
- file: `base64://${item.toString('base64')}`
160
- }
161
- }
162
- ]
163
- })));
287
+ else if (event['name'] == 'message.create') {
288
+ return sendGroup(event, val);
164
289
  }
165
290
  return Promise.all([]);
166
291
  },
package/lib/sdk/wss.d.ts CHANGED
@@ -4,6 +4,10 @@ type OneBotEventMap = {
4
4
  DIRECT_MESSAGE: DIRECT_MESSAGE_TYPE;
5
5
  MESSAGES: MESSAGES_TYPE;
6
6
  META: meta_event_lifecycle | meta_event_heartbeat;
7
+ REQUEST_ADD_FRIEND: any;
8
+ REQUEST_ADD_GROUP: any;
9
+ NOTICE_GROUP_MEMBER_INCREASE: any;
10
+ NOTICE_GROUP_MEMBER_REDUCE: any;
7
11
  ERROR: any;
8
12
  };
9
13
  /**
@@ -35,7 +39,16 @@ declare class OneBotClient {
35
39
  */
36
40
  connect(): Promise<void>;
37
41
  /**
38
- *
42
+ * 发送私聊消息
43
+ * @param options
44
+ * @returns
45
+ */
46
+ sendPrivateMessage(options: {
47
+ user_id: number;
48
+ message: any[];
49
+ }): void;
50
+ /**
51
+ * 发送群消息
39
52
  * @param options
40
53
  * @returns
41
54
  */
@@ -44,13 +57,53 @@ declare class OneBotClient {
44
57
  message: any[];
45
58
  }): void;
46
59
  /**
60
+ * 发送消息
47
61
  * @param options
48
62
  * @returns
49
63
  */
50
- sendPrivateMessage(options: {
51
- user_id: number;
64
+ sendMessage(options: {
65
+ message_type: 'private' | 'group';
66
+ group_id?: number;
67
+ user_id?: number;
52
68
  message: any[];
53
69
  }): void;
70
+ /**
71
+ * 好友列表
72
+ */
73
+ getFriendList(): void;
74
+ /**
75
+ * 群列表
76
+ */
77
+ getGroupList(): void;
78
+ /**
79
+ * 群成员列表
80
+ * @param options
81
+ * @returns
82
+ */
83
+ getGroupMemberList(options: {
84
+ group_id: number;
85
+ }): void;
86
+ /**
87
+ * 处理好友请求
88
+ * @param options
89
+ * @returns
90
+ */
91
+ setFriendAddRequest(options: {
92
+ flag: string;
93
+ approve: boolean;
94
+ remark?: string;
95
+ }): void;
96
+ /**
97
+ * 处理群请求
98
+ * @param options
99
+ * @returns
100
+ */
101
+ setGroupAddRequest(options: {
102
+ flag: string;
103
+ sub_type: string;
104
+ approve: boolean;
105
+ reason?: string;
106
+ }): void;
54
107
  /**
55
108
  * @param options
56
109
  * @returns
@@ -61,7 +114,7 @@ declare class OneBotClient {
61
114
  [key: string]: any;
62
115
  };
63
116
  echo?: string;
64
- }): Promise<unknown> | undefined;
117
+ }): Promise<unknown>;
65
118
  }
66
119
 
67
120
  export { OneBotClient };
package/lib/sdk/wss.js CHANGED
@@ -1,4 +1,4 @@
1
- import ws from 'ws';
1
+ import WebSocket, { WebSocketServer } from 'ws';
2
2
  import { randomUUID } from 'crypto';
3
3
 
4
4
  /**
@@ -72,20 +72,40 @@ class OneBotClient {
72
72
  this.#events['DIRECT_MESSAGE'](event);
73
73
  }
74
74
  else {
75
- console.info('未知消息类型', event);
75
+ // console.info('未知消息类型', event)
76
76
  }
77
77
  return;
78
78
  }
79
79
  else if (event?.post_type == 'notice') {
80
- console.info('暂未处理事件', event);
80
+ if (event?.notice_type == 'group_increase') {
81
+ // 群成员增加
82
+ if (this.#events['NOTICE_GROUP_MEMBER_INCREASE'])
83
+ this.#events['NOTICE_GROUP_MEMBER_INCREASE'](event);
84
+ }
85
+ else if (event?.notice_type == 'group_decrease') {
86
+ // 群成员减少
87
+ if (this.#events['NOTICE_GROUP_MEMBER_REDUCE'])
88
+ this.#events['NOTICE_GROUP_MEMBER_REDUCE'](event);
89
+ }
81
90
  return;
82
91
  }
83
92
  else if (event?.post_type == 'request') {
84
- console.info('暂未处理事件', event);
93
+ // 收到加群 或 加好友的请求。
94
+ if (event?.request_type == 'friend') {
95
+ if (this.#events['REQUEST_ADD_FRIEND'])
96
+ this.#events['REQUEST_ADD_FRIEND'](event);
97
+ }
98
+ else if (event?.request_type == 'group') {
99
+ if (this.#events['REQUEST_ADD_GROUP'])
100
+ this.#events['REQUEST_ADD_GROUP'](event);
101
+ }
85
102
  return;
86
103
  }
87
- else {
88
- console.info('未知事件', event);
104
+ else if (event?.echo === 'get_friend_list' || event?.echo === 'get_group_list' || event?.echo === 'get_group_member_list') {
105
+ // 处理获取好友列表和群列表的响应
106
+ // if (this.#events['META']) this.#events['META'](event)
107
+ // console.debug('响应', event)
108
+ return;
89
109
  }
90
110
  if (!event?.post_type && event?.echo && this.#echo[event?.echo]) {
91
111
  if (![0, 1].includes(event?.retcode))
@@ -115,7 +135,7 @@ class OneBotClient {
115
135
  if (!this.#ws) {
116
136
  if (reverse_enable) {
117
137
  // reverse_open
118
- const server = new ws.Server({ port: reverse_port ?? 17158 });
138
+ const server = new WebSocketServer({ port: reverse_port ?? 17158 });
119
139
  server.on('connection', ws => {
120
140
  this.#ws = ws;
121
141
  // message
@@ -127,7 +147,7 @@ class OneBotClient {
127
147
  }
128
148
  else {
129
149
  // forward_open
130
- this.#ws = new ws(url, c);
150
+ this.#ws = new WebSocket(url, c);
131
151
  this.#ws.on('open', () => {
132
152
  console.debug(`open:${url}`);
133
153
  });
@@ -139,7 +159,21 @@ class OneBotClient {
139
159
  }
140
160
  }
141
161
  /**
142
- *
162
+ * 发送私聊消息
163
+ * @param options
164
+ * @returns
165
+ */
166
+ sendPrivateMessage(options) {
167
+ if (!this.#ws)
168
+ return;
169
+ return this.#ws.send(JSON.stringify({
170
+ action: 'send_private_msg',
171
+ params: options,
172
+ echo: randomUUID()
173
+ }));
174
+ }
175
+ /**
176
+ * 发送群消息
143
177
  * @param options
144
178
  * @returns
145
179
  */
@@ -153,14 +187,81 @@ class OneBotClient {
153
187
  }));
154
188
  }
155
189
  /**
190
+ * 发送消息
156
191
  * @param options
157
192
  * @returns
158
193
  */
159
- sendPrivateMessage(options) {
194
+ sendMessage(options) {
160
195
  if (!this.#ws)
161
196
  return;
162
197
  return this.#ws.send(JSON.stringify({
163
- action: 'send_private_msg',
198
+ action: 'send_msg',
199
+ params: options,
200
+ echo: randomUUID()
201
+ }));
202
+ }
203
+ /**
204
+ * 好友列表
205
+ */
206
+ getFriendList() {
207
+ if (!this.#ws)
208
+ return;
209
+ return this.#ws.send(JSON.stringify({
210
+ action: 'get_friend_list',
211
+ params: {},
212
+ echo: 'get_friend_list'
213
+ }));
214
+ }
215
+ /**
216
+ * 群列表
217
+ */
218
+ getGroupList() {
219
+ if (!this.#ws)
220
+ return;
221
+ return this.#ws.send(JSON.stringify({
222
+ action: 'get_group_list',
223
+ params: {},
224
+ echo: 'get_group_list'
225
+ }));
226
+ }
227
+ /**
228
+ * 群成员列表
229
+ * @param options
230
+ * @returns
231
+ */
232
+ getGroupMemberList(options) {
233
+ if (!this.#ws)
234
+ return;
235
+ return this.#ws.send(JSON.stringify({
236
+ action: 'get_group_member_list',
237
+ params: options,
238
+ echo: 'get_group_member_list'
239
+ }));
240
+ }
241
+ /**
242
+ * 处理好友请求
243
+ * @param options
244
+ * @returns
245
+ */
246
+ setFriendAddRequest(options) {
247
+ if (!this.#ws)
248
+ return;
249
+ return this.#ws.send(JSON.stringify({
250
+ action: 'set_friend_add_request',
251
+ params: options,
252
+ echo: randomUUID()
253
+ }));
254
+ }
255
+ /**
256
+ * 处理群请求
257
+ * @param options
258
+ * @returns
259
+ */
260
+ setGroupAddRequest(options) {
261
+ if (!this.#ws)
262
+ return;
263
+ return this.#ws.send(JSON.stringify({
264
+ action: 'set_group_add_request',
164
265
  params: options,
165
266
  echo: randomUUID()
166
267
  }));
@@ -0,0 +1,41 @@
1
+ import Koa from 'koa';
2
+ import Router from 'koa-router';
3
+
4
+ // 使用koa + router 写 hello world
5
+ const createServer = (client) => {
6
+ const app = new Koa();
7
+ const router = new Router();
8
+ const port = 8080; // 端口号
9
+ // 检测
10
+ router.get('/', (ctx) => {
11
+ ctx.body = 'Hello, World!';
12
+ });
13
+ // 获取群列表
14
+ router.get('/get_group_list', async (ctx) => {
15
+ client.getGroupList();
16
+ ctx.body = 'Hello, World!';
17
+ });
18
+ // 获取好友列表
19
+ router.get('/get_friend_list', async (ctx) => {
20
+ client.getFriendList();
21
+ ctx.body = 'Hello, World!';
22
+ });
23
+ // 获取群成员列表
24
+ router.get('/get_group_member_list', async (ctx) => {
25
+ const group_id = ctx.query.group_id;
26
+ if (!group_id) {
27
+ ctx.status = 400;
28
+ ctx.body = 'group_id is required';
29
+ return;
30
+ }
31
+ client.getGroupMemberList({ group_id: Number(group_id) });
32
+ ctx.body = 'Hello, World!';
33
+ });
34
+ app.use(router.routes());
35
+ app.use(router.allowedMethods());
36
+ app.listen(port, () => {
37
+ console.log(`Server is running at http://localhost:${port}`);
38
+ });
39
+ };
40
+
41
+ export { createServer };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alemonjs/onebot",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "description": "onebot",
5
5
  "author": "lemonade",
6
6
  "license": "MIT",
@@ -17,16 +17,22 @@
17
17
  },
18
18
  "./package": "./package.json"
19
19
  },
20
- "devDependencies": {
21
- "@rollup/plugin-typescript": "^11.1.6",
22
- "lvyjs": "^0.2.13",
23
- "rollup": "^4.18.1",
24
- "rollup-plugin-dts": "^6.1.1",
25
- "tsx": "^4.19.1"
26
- },
27
20
  "keywords": [
28
21
  "alemonjs"
29
22
  ],
23
+ "dependencies": {
24
+ "ws": "^8.18.1"
25
+ },
26
+ "alemonjs": {
27
+ "desktop": {
28
+ "platform": [
29
+ {
30
+ "name": "onebot"
31
+ }
32
+ ],
33
+ "logo": "antd.RobotOutlined"
34
+ }
35
+ },
30
36
  "publishConfig": {
31
37
  "registry": "https://registry.npmjs.org",
32
38
  "access": "public"