@alemonjs/onebot 0.2.0 → 0.2.2

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
@@ -6,8 +6,9 @@
6
6
 
7
7
  ```yaml
8
8
  onebot:
9
- url: ''
10
- token: ''
9
+ url: '' # 正向url
10
+ token: '' # access_token
11
+ reverse_enable: false # 启用后正向连接配置失效,地址:ws://127.0.0.1:17158
12
+ reverse_port: 17158 # 返向连接服务端口,启用反向连接后生效
11
13
  master_key: null
12
- version: 'v11'
13
14
  ```
package/lib/index.d.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  import * as alemonjs from 'alemonjs';
2
+ import { OneBotClient } from './sdk/wss.js';
2
3
 
4
+ type Client = typeof OneBotClient.prototype;
5
+ declare const client: Client;
6
+ declare const platform = "onebot";
3
7
  declare const _default: () => alemonjs.ClientAPI;
4
8
 
5
- export { _default as default };
9
+ export { type Client, client, _default as default, platform };
package/lib/index.js CHANGED
@@ -1,16 +1,175 @@
1
- import { defineBot, getConfig } from 'alemonjs';
2
- import INDEXV12 from './index-12.js';
3
- import INDEXV11 from './index-11.js';
1
+ import { defineBot, getConfigValue, useUserHashKey, OnProcessor } from 'alemonjs';
2
+ import { OneBotClient } from './sdk/wss.js';
4
3
 
5
- var index = defineBot(() => {
6
- const cfg = getConfig();
7
- const config = cfg.value?.onebot;
8
- if (!config)
9
- return;
10
- if (config.version === 'v12') {
11
- return INDEXV12();
4
+ const client = new Proxy({}, {
5
+ get: (_, prop) => {
6
+ if (prop in global.client) {
7
+ const original = global.client[prop];
8
+ // 防止函数内this丢失
9
+ return typeof original === 'function' ? original.bind(global.client) : original;
10
+ }
11
+ return undefined;
12
12
  }
13
- return INDEXV11();
13
+ });
14
+ const platform = 'onebot';
15
+ var index = defineBot(() => {
16
+ let value = getConfigValue();
17
+ if (!value)
18
+ value = {};
19
+ const config = value[platform];
20
+ //
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
+ //
32
+ client.connect();
33
+ //
34
+ client.on('META', event => {
35
+ if (event?.self_id) {
36
+ String(event.self_id);
37
+ }
38
+ });
39
+ //
40
+ client.on('MESSAGES', event => {
41
+ const uis = config.master_uids ?? [];
42
+ let msg = '';
43
+ const arr = [];
44
+ // let at_users = []
45
+ for (const item of event.message) {
46
+ if (item.type == 'text') {
47
+ msg = item.data.text;
48
+ }
49
+ }
50
+ for (const item of arr) {
51
+ msg = msg.replace(item.text, '').trim();
52
+ }
53
+ const url = `https://q1.qlogo.cn/g?b=qq&s=0&nk=${event.user_id}`;
54
+ const UserAvatar = {
55
+ toBuffer: async () => {
56
+ const arrayBuffer = await fetch(url).then(res => res.arrayBuffer());
57
+ return Buffer.from(arrayBuffer);
58
+ },
59
+ toBase64: async () => {
60
+ const arrayBuffer = await fetch(url).then(res => res.arrayBuffer());
61
+ return Buffer.from(arrayBuffer).toString('base64');
62
+ },
63
+ toURL: async () => {
64
+ return url;
65
+ }
66
+ };
67
+ const UserId = String(event.user_id);
68
+ const UserKey = useUserHashKey({
69
+ Platform: platform,
70
+ UserId
71
+ });
72
+ // 定义消
73
+ const e = {
74
+ name: 'message.create',
75
+ // 平台类型
76
+ Platform: platform,
77
+ // 频道
78
+ GuildId: String(event.group_id),
79
+ // guild_name: event.group_name,
80
+ // 子频道
81
+ ChannelId: String(event.group_id),
82
+ IsMaster: uis.includes(String(event.user_id)),
83
+ IsBot: false,
84
+ UserId: UserId,
85
+ UserName: event.sender.nickname,
86
+ UserKey,
87
+ UserAvatar: UserAvatar,
88
+ // message
89
+ MessageId: String(event.message_id),
90
+ MessageText: msg,
91
+ // 用户openId
92
+ OpenId: String(event.user_id),
93
+ // 创建时间
94
+ CreateAt: Date.now(),
95
+ // 标签
96
+ tag: 'MESSAGES',
97
+ //
98
+ value: null
99
+ };
100
+ // 当访问的时候获取
101
+ Object.defineProperty(e, 'value', {
102
+ get() {
103
+ return event;
104
+ }
105
+ });
106
+ // 处理消息
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,
122
+ });
123
+ // 错误处理
124
+ client.on('ERROR', event => {
125
+ console.error('ERROR', event);
126
+ });
127
+ global.client = client;
128
+ return {
129
+ api: {
130
+ use: {
131
+ send: (event, val) => {
132
+ if (val.length < 0)
133
+ 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
+ })));
150
+ }
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
+ })));
164
+ }
165
+ return Promise.all([]);
166
+ },
167
+ mention: async () => {
168
+ return [];
169
+ }
170
+ }
171
+ }
172
+ };
14
173
  });
15
174
 
16
- export { index as default };
175
+ export { client, index as default, platform };
@@ -0,0 +1,90 @@
1
+ interface Sender {
2
+ user_id: number;
3
+ nickname: string;
4
+ card: string;
5
+ role: 'admin' | 'member';
6
+ }
7
+ type Message = {
8
+ type: 'image';
9
+ data: {
10
+ file: string;
11
+ sub_type: number;
12
+ file_id: string;
13
+ url: string;
14
+ file_size: string;
15
+ file_unique: string;
16
+ };
17
+ } | {
18
+ type: 'text';
19
+ data: {
20
+ text: string;
21
+ };
22
+ } | {
23
+ type: 'json';
24
+ data: string;
25
+ } | {
26
+ type: 'forward';
27
+ data: {
28
+ id: number;
29
+ content: any[];
30
+ };
31
+ };
32
+ interface MESSAGES_TYPE {
33
+ self_id: number;
34
+ user_id: number;
35
+ time: number;
36
+ message_id: number;
37
+ message_seq: number;
38
+ real_id: number;
39
+ message_type: 'group';
40
+ sender: Sender;
41
+ raw_message: string;
42
+ font: number;
43
+ sub_type: 'normal';
44
+ message: Message[];
45
+ message_format: 'array';
46
+ post_type: 'message';
47
+ group_id: number;
48
+ }
49
+ interface DIRECT_MESSAGE_TYPE {
50
+ self_id: number;
51
+ user_id: number;
52
+ time: number;
53
+ message_id: number;
54
+ message_seq: number;
55
+ real_id: number;
56
+ message_type: 'private';
57
+ sender: {
58
+ user_id: 1715713638;
59
+ nickname: string;
60
+ card: '';
61
+ };
62
+ raw_message: string;
63
+ font: 14;
64
+ sub_type: 'group' | 'friend';
65
+ message: Message[];
66
+ message_format: 'array';
67
+ post_type: 'message';
68
+ group_id: number;
69
+ temp_source: number;
70
+ }
71
+ interface meta_event_lifecycle {
72
+ time: number;
73
+ self_id: number;
74
+ post_type: 'meta_event';
75
+ meta_event_type: 'lifecycle';
76
+ sub_type: 'connect';
77
+ }
78
+ interface meta_event_heartbeat {
79
+ time: number;
80
+ self_id: number;
81
+ post_type: 'meta_event';
82
+ meta_event_type: 'heartbeat';
83
+ status: {
84
+ online: boolean;
85
+ good: boolean;
86
+ };
87
+ interval: number;
88
+ }
89
+
90
+ export type { DIRECT_MESSAGE_TYPE, MESSAGES_TYPE, meta_event_heartbeat, meta_event_lifecycle };
@@ -0,0 +1,67 @@
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
+ ERROR: any;
8
+ };
9
+ /**
10
+ * 连接
11
+ */
12
+ declare class OneBotClient {
13
+ #private;
14
+ /**
15
+ * 设置配置
16
+ * @param opstion
17
+ */
18
+ constructor(opstion: {
19
+ url: string;
20
+ access_token: string;
21
+ reverse_enable: boolean;
22
+ reverse_port: number;
23
+ });
24
+ timeout: number;
25
+ /**
26
+ * 注册事件处理程序
27
+ * @param key 事件名称
28
+ * @param val 事件处理函数
29
+ */
30
+ on<T extends keyof OneBotEventMap>(key: T, val: (event: OneBotEventMap[T]) => any): this;
31
+ /**
32
+ *
33
+ * @param cfg
34
+ * @param conversation
35
+ */
36
+ connect(): Promise<void>;
37
+ /**
38
+ *
39
+ * @param options
40
+ * @returns
41
+ */
42
+ sendGroupMessage(options: {
43
+ group_id: number;
44
+ message: any[];
45
+ }): void;
46
+ /**
47
+ * @param options
48
+ * @returns
49
+ */
50
+ sendPrivateMessage(options: {
51
+ user_id: number;
52
+ message: any[];
53
+ }): void;
54
+ /**
55
+ * @param options
56
+ * @returns
57
+ */
58
+ sendApi(options: {
59
+ action: string;
60
+ params?: {
61
+ [key: string]: any;
62
+ };
63
+ echo?: string;
64
+ }): Promise<unknown> | undefined;
65
+ }
66
+
67
+ export { OneBotClient };
@@ -1,4 +1,5 @@
1
1
  import ws from 'ws';
2
+ import { randomUUID } from 'crypto';
2
3
 
3
4
  /**
4
5
  * 连接
@@ -6,7 +7,9 @@ import ws from 'ws';
6
7
  class OneBotClient {
7
8
  #options = {
8
9
  url: '',
9
- access_token: ''
10
+ access_token: '',
11
+ reverse_enable: false,
12
+ reverse_port: 17158
10
13
  };
11
14
  /**
12
15
  * 设置配置
@@ -19,8 +22,10 @@ class OneBotClient {
19
22
  }
20
23
  }
21
24
  }
22
- #ws;
25
+ #ws = null;
23
26
  #events = {};
27
+ #echo = {};
28
+ timeout = 30000;
24
29
  /**
25
30
  * 注册事件处理程序
26
31
  * @param key 事件名称
@@ -36,7 +41,7 @@ class OneBotClient {
36
41
  * @param conversation
37
42
  */
38
43
  async connect() {
39
- const { url, access_token: token } = this.#options;
44
+ const { url, access_token: token, reverse_enable, reverse_port } = this.#options;
40
45
  const c = token == '' || !token
41
46
  ? {}
42
47
  : {
@@ -44,15 +49,7 @@ class OneBotClient {
44
49
  ['Authorization']: `Bearer ${token}`
45
50
  }
46
51
  };
47
- if (!this.#ws) {
48
- this.#ws = new ws(url, c);
49
- }
50
- // open
51
- this.#ws.on('open', () => {
52
- console.debug(`open:${url}`);
53
- });
54
- // message
55
- this.#ws.on('message', async (data) => {
52
+ const onMessage = async (data) => {
56
53
  try {
57
54
  const event = JSON.parse(data.toString());
58
55
  if (!event) {
@@ -89,22 +86,57 @@ class OneBotClient {
89
86
  }
90
87
  else {
91
88
  console.info('未知事件', event);
92
- return;
89
+ }
90
+ if (!event?.post_type && event?.echo && this.#echo[event?.echo]) {
91
+ if (![0, 1].includes(event?.retcode))
92
+ this.#echo[event?.echo].reject(Object.assign(this.#echo[event?.echo].request, { error: event }));
93
+ else
94
+ this.#echo[event?.echo].resolve(event?.data
95
+ ? new Proxy(event, {
96
+ get: (target, prop) => target.event[prop] ?? target[prop]
97
+ })
98
+ : event);
99
+ clearTimeout(this.#echo[event?.echo].timeout);
100
+ delete this.#echo[event?.echo];
93
101
  }
94
102
  }
95
103
  catch (err) {
96
104
  if (this.#events['ERROR'])
97
105
  this.#events['ERROR'](err);
98
106
  }
99
- });
100
- // close
101
- this.#ws.on('close', (code, reason) => {
107
+ };
108
+ const onClose = (code, reason) => {
102
109
  if (this.#events['ERROR'])
103
110
  this.#events['ERROR']({
104
111
  de: code,
105
112
  reason: reason.toString('utf8')
106
113
  });
107
- });
114
+ };
115
+ if (!this.#ws) {
116
+ if (reverse_enable) {
117
+ // reverse_open
118
+ const server = new ws.Server({ port: reverse_port ?? 17158 });
119
+ server.on('connection', ws => {
120
+ this.#ws = ws;
121
+ // message
122
+ this.#ws.on('message', onMessage);
123
+ // close
124
+ this.#ws.on('close', onClose);
125
+ console.info('connected: ws://127.0.0.1:' + reverse_port);
126
+ });
127
+ }
128
+ else {
129
+ // forward_open
130
+ this.#ws = new ws(url, c);
131
+ this.#ws.on('open', () => {
132
+ console.debug(`open:${url}`);
133
+ });
134
+ // message
135
+ this.#ws.on('message', onMessage);
136
+ // close
137
+ this.#ws.on('close', onClose);
138
+ }
139
+ }
108
140
  }
109
141
  /**
110
142
  *
@@ -112,10 +144,12 @@ class OneBotClient {
112
144
  * @returns
113
145
  */
114
146
  sendGroupMessage(options) {
147
+ if (!this.#ws)
148
+ return;
115
149
  return this.#ws.send(JSON.stringify({
116
150
  action: 'send_group_msg',
117
151
  params: options,
118
- echo: '1234'
152
+ echo: randomUUID()
119
153
  }));
120
154
  }
121
155
  /**
@@ -123,10 +157,33 @@ class OneBotClient {
123
157
  * @returns
124
158
  */
125
159
  sendPrivateMessage(options) {
160
+ if (!this.#ws)
161
+ return;
126
162
  return this.#ws.send(JSON.stringify({
127
163
  action: 'send_private_msg',
128
164
  params: options,
129
- echo: '1234'
165
+ echo: randomUUID()
166
+ }));
167
+ }
168
+ /**
169
+ * @param options
170
+ * @returns
171
+ */
172
+ sendApi(options) {
173
+ if (!this.#ws)
174
+ return;
175
+ if (!options.echo)
176
+ options.echo = randomUUID();
177
+ this.#ws.send(JSON.stringify(options));
178
+ return new Promise((resolve, reject) => (this.#echo[options.echo] = {
179
+ request: options,
180
+ resolve,
181
+ reject,
182
+ timeout: setTimeout(() => {
183
+ reject(Object.assign(options, { timeout: this.timeout }));
184
+ delete this.#echo[options.echo];
185
+ console.error('请求超时:', options);
186
+ }, this.timeout)
130
187
  }));
131
188
  }
132
189
  }
package/package.json CHANGED
@@ -1,23 +1,31 @@
1
1
  {
2
2
  "name": "@alemonjs/onebot",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "onebot",
5
5
  "author": "lemonade",
6
6
  "license": "MIT",
7
7
  "type": "module",
8
8
  "main": "lib/index.js",
9
9
  "types": "lib",
10
+ "scripts": {
11
+ "build": "node bundle.js"
12
+ },
10
13
  "exports": {
11
14
  ".": {
12
15
  "import": "./lib/index.js",
13
16
  "types": "./lib/index.d.ts"
14
- }
17
+ },
18
+ "./package": "./package.json"
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"
15
26
  },
16
27
  "keywords": [
17
- "alemonjs",
18
- "onebot",
19
- "bot",
20
- "chat-bot"
28
+ "alemonjs"
21
29
  ],
22
30
  "publishConfig": {
23
31
  "registry": "https://registry.npmjs.org",
package/lib/index-11.js DELETED
@@ -1,159 +0,0 @@
1
- import { defineBot, getConfig, useUserHashKey, OnProcessor } from 'alemonjs';
2
- import { OneBotClient } from './sdk-v11/wss.js';
3
-
4
- var INDEXV11 = defineBot(() => {
5
- const cfg = getConfig();
6
- const config = cfg.value?.onebot;
7
- if (!config)
8
- return;
9
- //
10
- const client = new OneBotClient({
11
- // url
12
- url: config?.url ?? '',
13
- // token
14
- access_token: config?.token ?? ''
15
- });
16
- const Platform = 'onebot';
17
- //
18
- client.connect();
19
- //
20
- client.on('META', event => {
21
- if (event?.self_id) {
22
- String(event.self_id);
23
- }
24
- });
25
- //
26
- client.on('MESSAGES', event => {
27
- const uis = config.master_uids ?? [];
28
- let msg = '';
29
- const arr = [];
30
- // let at_users = []
31
- for (const item of event.message) {
32
- if (item.type == 'text') {
33
- msg = item.data.text;
34
- }
35
- }
36
- for (const item of arr) {
37
- msg = msg.replace(item.text, '').trim();
38
- }
39
- const url = `https://q1.qlogo.cn/g?b=qq&s=0&nk=${event.user_id}`;
40
- const UserAvatar = {
41
- toBuffer: async () => {
42
- const arrayBuffer = await fetch(url).then(res => res.arrayBuffer());
43
- return Buffer.from(arrayBuffer);
44
- },
45
- toBase64: async () => {
46
- const arrayBuffer = await fetch(url).then(res => res.arrayBuffer());
47
- return Buffer.from(arrayBuffer).toString('base64');
48
- },
49
- toURL: async () => {
50
- return url;
51
- }
52
- };
53
- const UserId = String(event.user_id);
54
- const UserKey = useUserHashKey({
55
- Platform,
56
- UserId
57
- });
58
- // 定义消
59
- const e = {
60
- // 平台类型
61
- Platform: Platform,
62
- // 频道
63
- GuildId: String(event.group_id),
64
- // guild_name: event.group_name,
65
- // 子频道
66
- ChannelId: String(event.group_id),
67
- IsMaster: uis.includes(String(event.user_id)),
68
- IsBot: false,
69
- UserId: UserId,
70
- UserName: event.sender.nickname,
71
- UserKey,
72
- UserAvatar: UserAvatar,
73
- // message
74
- MessageId: String(event.message_id),
75
- MessageText: msg,
76
- // 用户openId
77
- OpenId: String(event.user_id),
78
- // 创建时间
79
- CreateAt: Date.now(),
80
- // 标签
81
- tag: 'MESSAGES',
82
- //
83
- value: null
84
- };
85
- // 当访问的时候获取
86
- Object.defineProperty(e, 'value', {
87
- get() {
88
- return event;
89
- }
90
- });
91
- // 处理消息
92
- OnProcessor(e, 'message.create');
93
- });
94
- client.on('DIRECT_MESSAGE', () => {
95
- // const e = {
96
- // isMaster: event.user_id == masterId,
97
- // msg_txt: event.raw_message,
98
- // msg: event.raw_message.trim(),
99
- // msg_id: event.message_id,
100
- // open_id: event.user_id,
101
- // user_id: event.user_id,
102
- // user_avatar:
103
- // event.platform == 'qq'
104
- // ? `https://q1.qlogo.cn/g?b=qq&s=0&nk=${event.user_id}`
105
- // : '',
106
- // user_name: event.sender.nickname,
107
- });
108
- // 错误处理
109
- client.on('ERROR', event => {
110
- console.error('ERROR', event);
111
- });
112
- return {
113
- api: {
114
- use: {
115
- send: (event, val) => {
116
- if (val.length < 0)
117
- return Promise.all([]);
118
- const content = val
119
- .filter(item => item.type == 'Link' || item.type == 'Mention' || item.type == 'Text')
120
- .map(item => item.value)
121
- .join('');
122
- if (content) {
123
- return Promise.all([content].map(item => client.sendGroupMessage({
124
- group_id: event.ChannelId,
125
- message: [
126
- {
127
- type: 'text',
128
- data: {
129
- text: item
130
- }
131
- }
132
- ]
133
- })));
134
- }
135
- const images = val.filter(item => item.type == 'Image').map(item => item.value);
136
- if (images) {
137
- return Promise.all(images.map(item => client.sendGroupMessage({
138
- group_id: event.ChannelId,
139
- message: [
140
- {
141
- type: 'image',
142
- data: {
143
- file: `base64://${item.toString('base64')}`
144
- }
145
- }
146
- ]
147
- })));
148
- }
149
- return Promise.all([]);
150
- },
151
- mention: async () => {
152
- return [];
153
- }
154
- }
155
- }
156
- };
157
- });
158
-
159
- export { INDEXV11 as default };
package/lib/index-12.js DELETED
@@ -1,175 +0,0 @@
1
- import { defineBot, getConfig, useUserHashKey, OnProcessor } from 'alemonjs';
2
- import { OneBotClient } from './sdk-v12/wss.js';
3
-
4
- var INDEXV12 = defineBot(() => {
5
- const cfg = getConfig();
6
- const config = cfg.value?.onebot;
7
- if (!config)
8
- return;
9
- //
10
- const client = new OneBotClient({
11
- // url
12
- url: config?.url ?? '',
13
- // token
14
- access_token: config?.token ?? ''
15
- });
16
- const Platform = 'onebot';
17
- //
18
- client.connect();
19
- //
20
- client.on('META', event => {
21
- const bot = event.status.bots[0];
22
- if (!bot)
23
- return;
24
- if (bot.self) {
25
- bot.self.user_id;
26
- }
27
- if (bot.nickname) {
28
- bot.nickname;
29
- }
30
- if (bot.avatar) {
31
- bot?.avatar ?? '';
32
- }
33
- });
34
- //
35
- client.on('MESSAGES', event => {
36
- const uis = config.master_uids ?? [];
37
- let msg = '';
38
- const arr = [];
39
- let at_users = [];
40
- for (const item of event.message) {
41
- if (item.type == 'mention') {
42
- arr.push(item.data);
43
- at_users.push({
44
- avatar: '',
45
- bot: false,
46
- id: item.data.user_id,
47
- name: item.data.text.replace(/^@/, '')
48
- });
49
- }
50
- else if (item.type == 'text') {
51
- msg = item.data.text;
52
- }
53
- }
54
- for (const item of arr) {
55
- msg = msg.replace(item.text, '').trim();
56
- }
57
- const url = event.platform == 'qq' ? `https://q1.qlogo.cn/g?b=qq&s=0&nk=${event.user_id}` : '';
58
- const UserAvatar = {
59
- toBuffer: async () => {
60
- const arrayBuffer = await fetch(url).then(res => res.arrayBuffer());
61
- return Buffer.from(arrayBuffer);
62
- },
63
- toBase64: async () => {
64
- const arrayBuffer = await fetch(url).then(res => res.arrayBuffer());
65
- return Buffer.from(arrayBuffer).toString('base64');
66
- },
67
- toURL: async () => {
68
- return url;
69
- }
70
- };
71
- const UserId = String(event.user_id);
72
- const UserKey = useUserHashKey({
73
- Platform,
74
- UserId
75
- });
76
- // 定义消
77
- const e = {
78
- // 平台类型
79
- Platform: Platform,
80
- // 频道
81
- GuildId: event.group_id,
82
- // guild_name: event.group_name,
83
- // 子频道
84
- ChannelId: event.group_id,
85
- // uyser
86
- IsMaster: uis.includes(String(event.user_id)),
87
- UserId: UserId,
88
- IsBot: false,
89
- UserKey,
90
- UserName: event.sender.nickname,
91
- UserAvatar: UserAvatar,
92
- // message
93
- MessageId: event.message_id,
94
- MessageText: msg,
95
- OpenId: event.user_id,
96
- CreateAt: Date.now(),
97
- // ohther
98
- tag: 'MESSAGES',
99
- value: null
100
- };
101
- // 当访问的时候获取
102
- Object.defineProperty(e, 'value', {
103
- get() {
104
- return event;
105
- }
106
- });
107
- // 处理消息
108
- OnProcessor(e, 'message.create');
109
- });
110
- client.on('DIRECT_MESSAGE', () => {
111
- // const e = {
112
- // isMaster: event.user_id == masterId,
113
- // msg_txt: event.raw_message,
114
- // msg: event.raw_message.trim(),
115
- // msg_id: event.message_id,
116
- // open_id: event.user_id,
117
- // user_id: event.user_id,
118
- // user_avatar:
119
- // event.platform == 'qq'
120
- // ? `https://q1.qlogo.cn/g?b=qq&s=0&nk=${event.user_id}`
121
- // : '',
122
- // user_name: event.sender.nickname,
123
- });
124
- // 错误处理
125
- client.on('ERROR', event => {
126
- console.error(event);
127
- });
128
- return {
129
- api: {
130
- use: {
131
- send: (event, val) => {
132
- if (val.length < 0)
133
- 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
- })));
150
- }
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_id: item
160
- }
161
- }
162
- ]
163
- })));
164
- }
165
- return Promise.all([]);
166
- },
167
- mention: async () => {
168
- return [];
169
- }
170
- }
171
- }
172
- };
173
- });
174
-
175
- export { INDEXV12 as default };
@@ -1,122 +0,0 @@
1
- import ws from 'ws';
2
-
3
- /**
4
- * 连接
5
- */
6
- class OneBotClient {
7
- #options = {
8
- url: '',
9
- access_token: ''
10
- };
11
- /**
12
- * 设置配置
13
- * @param opstion
14
- */
15
- constructor(opstion) {
16
- for (const key in opstion) {
17
- if (Object.prototype.hasOwnProperty.call(opstion, key)) {
18
- this.#options[key] = opstion[key];
19
- }
20
- }
21
- }
22
- #ws;
23
- #events = {};
24
- /**
25
- * 注册事件处理程序
26
- * @param key 事件名称
27
- * @param val 事件处理函数
28
- */
29
- on(key, val) {
30
- this.#events[key] = val;
31
- return this;
32
- }
33
- /**
34
- *
35
- * @param cfg
36
- * @param conversation
37
- */
38
- async connect() {
39
- const { url, access_token: token } = this.#options;
40
- const c = token == '' || !token
41
- ? {}
42
- : {
43
- headers: {
44
- ['Authorization']: `Bearer ${token}`
45
- }
46
- };
47
- if (!this.#ws) {
48
- this.#ws = new ws(url, c);
49
- }
50
- // open
51
- this.#ws.on('open', () => {
52
- console.debug(`open:${url}`);
53
- });
54
- // message
55
- this.#ws.on('message', async (data) => {
56
- try {
57
- const event = JSON.parse(data.toString());
58
- if (event) {
59
- if (event?.type == 'meta' && this.#events['META']) {
60
- if (event.status && event.status.bots) {
61
- this.#events['META'](event);
62
- }
63
- }
64
- else if (event?.type == 'message') {
65
- if (event.detail_type == 'private' && this.#events['DIRECT_MESSAGE']) {
66
- await this.#events['DIRECT_MESSAGE'](event);
67
- }
68
- else if (event.detail_type != 'private' && this.#events['MESSAGES']) {
69
- await this.#events['MESSAGES'](event);
70
- }
71
- else {
72
- //
73
- }
74
- }
75
- }
76
- else {
77
- if (event?.status != 'ok') {
78
- if (this.#events['ERROR'])
79
- this.#events['ERROR'](event);
80
- }
81
- }
82
- }
83
- catch (err) {
84
- if (this.#events['ERROR'])
85
- this.#events['ERROR'](err);
86
- }
87
- });
88
- // close
89
- this.#ws.on('close', (code, reason) => {
90
- if (this.#events['ERROR'])
91
- this.#events['ERROR']({
92
- de: code,
93
- reason: reason.toString('utf8')
94
- });
95
- });
96
- }
97
- /**
98
- *
99
- * @param options
100
- * @returns
101
- */
102
- sendGroupMessage(options) {
103
- return this.#ws.send(JSON.stringify({
104
- action: 'send_group_msg',
105
- params: options,
106
- echo: '1234'
107
- }));
108
- }
109
- /**
110
- * @param options
111
- * @returns
112
- */
113
- sendPrivateMessage(options) {
114
- return this.#ws.send(JSON.stringify({
115
- action: 'send_private_msg',
116
- params: options,
117
- echo: '1234'
118
- }));
119
- }
120
- }
121
-
122
- export { OneBotClient };