@alemonjs/onebot 0.2.1 → 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,13 +1,12 @@
1
1
  # [https://alemonjs.com/](https://alemonjs.com/)
2
2
 
3
- 跨平台开发的事件驱动机器人
4
-
5
3
  - alemomn.config.yaml
6
4
 
7
5
  ```yaml
8
6
  onebot:
9
- url: ''
10
- token: ''
7
+ url: '' # 正向url
8
+ token: '' # access_token
9
+ reverse_enable: false # 启用后正向连接配置失效,地址:ws://127.0.0.1:17158
10
+ reverse_port: 17158 # 返向连接服务端口,启用反向连接后生效
11
11
  master_key: null
12
- version: 'v11'
13
12
  ```
package/lib/index.d.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import * as alemonjs from 'alemonjs';
2
- import { OneBotClient } from './sdk-v11/wss.js';
2
+ import { OneBotClient } from './sdk/wss.js';
3
3
 
4
- declare const platform = "onebot";
5
- type Client = OneBotClient;
4
+ type Client = typeof OneBotClient.prototype;
6
5
  declare const client: Client;
7
- declare const _default: () => alemonjs.ClientAPI;
6
+ declare const platform = "onebot";
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,25 +1,300 @@
1
- import { defineBot, getConfig } from 'alemonjs';
2
- import INDEXV12 from './index-12.js';
3
- import INDEXV11 from './index-11.js';
1
+ import { getConfigValue, useUserHashKey, onProcessor, createResult, ResultCode } from 'alemonjs';
2
+ import { OneBotClient } from './sdk/wss.js';
3
+ import { createServer } from './server/index.js';
4
4
 
5
- const platform = 'onebot';
6
5
  const client = new Proxy({}, {
7
6
  get: (_, prop) => {
8
7
  if (prop in global.client) {
9
- return global.client[prop];
8
+ const original = global.client[prop];
9
+ // 防止函数内this丢失
10
+ return typeof original === 'function' ? original.bind(global.client) : original;
10
11
  }
11
12
  return undefined;
12
13
  }
13
14
  });
14
- var index = defineBot(() => {
15
- const cfg = getConfig();
16
- const config = cfg.value?.onebot;
17
- if (!config)
18
- return;
19
- if (config.version === 'v12') {
20
- return INDEXV12();
21
- }
22
- return INDEXV11();
15
+ const platform = 'onebot';
16
+ var index = definePlatform(() => {
17
+ let value = getConfigValue();
18
+ if (!value)
19
+ value = {};
20
+ const config = value[platform];
21
+ const client = new OneBotClient({
22
+ // url
23
+ url: config?.url ?? '',
24
+ // token
25
+ access_token: config?.token ?? '',
26
+ // 是否开启反向连接,正向连接失效
27
+ reverse_enable: config?.reverse_enable ?? false,
28
+ // 反向连接端口
29
+ reverse_port: config?.reverse_port ?? 17158
30
+ });
31
+ client.connect();
32
+ client.on('META', event => {
33
+ if (event?.self_id) {
34
+ String(event.self_id);
35
+ }
36
+ });
37
+ client.on('MESSAGES', event => {
38
+ const uis = config.master_uids ?? [];
39
+ let msg = '';
40
+ const arr = [];
41
+ for (const item of event.message) {
42
+ if (item.type == 'text') {
43
+ msg = item.data.text;
44
+ }
45
+ }
46
+ for (const item of arr) {
47
+ msg = msg.replace(item.text, '').trim();
48
+ }
49
+ const url = `https://q1.qlogo.cn/g?b=qq&s=0&nk=${event.user_id}`;
50
+ const UserAvatar = {
51
+ toBuffer: async () => {
52
+ const arrayBuffer = await fetch(url).then(res => res.arrayBuffer());
53
+ return Buffer.from(arrayBuffer);
54
+ },
55
+ toBase64: async () => {
56
+ const arrayBuffer = await fetch(url).then(res => res.arrayBuffer());
57
+ return Buffer.from(arrayBuffer).toString('base64');
58
+ },
59
+ toURL: async () => {
60
+ return url;
61
+ }
62
+ };
63
+ const UserId = String(event.user_id);
64
+ const UserKey = useUserHashKey({
65
+ Platform: platform,
66
+ UserId
67
+ });
68
+ // 定义消
69
+ const e = {
70
+ name: 'message.create',
71
+ // 平台类型
72
+ Platform: platform,
73
+ // 频道
74
+ GuildId: String(event.group_id),
75
+ // 子频道
76
+ ChannelId: String(event.group_id),
77
+ IsMaster: uis.includes(String(event.user_id)),
78
+ IsBot: false,
79
+ UserId: UserId,
80
+ UserName: event.sender.nickname,
81
+ UserKey,
82
+ UserAvatar: UserAvatar,
83
+ // message
84
+ MessageId: String(event.message_id),
85
+ MessageText: msg,
86
+ // 用户openId
87
+ OpenId: String(event.user_id),
88
+ // 创建时间
89
+ CreateAt: Date.now(),
90
+ // 标签
91
+ tag: 'message.create',
92
+ //
93
+ value: null
94
+ };
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;
122
+ }
123
+ };
124
+ const UserId = String(event.user_id);
125
+ const UserKey = useUserHashKey({
126
+ Platform: platform,
127
+ UserId
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
+ };
156
+ // 处理消息
157
+ onProcessor('private.message.create', e, event);
158
+ });
159
+ // 错误处理
160
+ client.on('ERROR', event => {
161
+ console.error('ERROR', event);
162
+ });
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
+ };
267
+ return {
268
+ platform,
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
+ },
280
+ use: {
281
+ send: (event, val) => {
282
+ if (val.length < 0)
283
+ return Promise.all([]);
284
+ if (event['name'] == 'private.message.create') {
285
+ return sendPrivate(event, val);
286
+ }
287
+ else if (event['name'] == 'message.create') {
288
+ return sendGroup(event, val);
289
+ }
290
+ return Promise.all([]);
291
+ },
292
+ mention: async () => {
293
+ return [];
294
+ }
295
+ }
296
+ }
297
+ };
23
298
  });
24
299
 
25
300
  export { client, index as default, platform };
@@ -0,0 +1,120 @@
1
+ import { DIRECT_MESSAGE_TYPE, MESSAGES_TYPE, meta_event_lifecycle, meta_event_heartbeat } from './type.js';
2
+
3
+ type OneBotEventMap = {
4
+ DIRECT_MESSAGE: DIRECT_MESSAGE_TYPE;
5
+ MESSAGES: MESSAGES_TYPE;
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;
11
+ ERROR: any;
12
+ };
13
+ /**
14
+ * 连接
15
+ */
16
+ declare class OneBotClient {
17
+ #private;
18
+ /**
19
+ * 设置配置
20
+ * @param opstion
21
+ */
22
+ constructor(opstion: {
23
+ url: string;
24
+ access_token: string;
25
+ reverse_enable: boolean;
26
+ reverse_port: number;
27
+ });
28
+ timeout: number;
29
+ /**
30
+ * 注册事件处理程序
31
+ * @param key 事件名称
32
+ * @param val 事件处理函数
33
+ */
34
+ on<T extends keyof OneBotEventMap>(key: T, val: (event: OneBotEventMap[T]) => any): this;
35
+ /**
36
+ *
37
+ * @param cfg
38
+ * @param conversation
39
+ */
40
+ connect(): Promise<void>;
41
+ /**
42
+ * 发送私聊消息
43
+ * @param options
44
+ * @returns
45
+ */
46
+ sendPrivateMessage(options: {
47
+ user_id: number;
48
+ message: any[];
49
+ }): void;
50
+ /**
51
+ * 发送群消息
52
+ * @param options
53
+ * @returns
54
+ */
55
+ sendGroupMessage(options: {
56
+ group_id: number;
57
+ message: any[];
58
+ }): void;
59
+ /**
60
+ * 发送消息
61
+ * @param options
62
+ * @returns
63
+ */
64
+ sendMessage(options: {
65
+ message_type: 'private' | 'group';
66
+ group_id?: number;
67
+ user_id?: number;
68
+ message: any[];
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;
107
+ /**
108
+ * @param options
109
+ * @returns
110
+ */
111
+ sendApi(options: {
112
+ action: string;
113
+ params?: {
114
+ [key: string]: any;
115
+ };
116
+ echo?: string;
117
+ }): Promise<unknown>;
118
+ }
119
+
120
+ export { OneBotClient };