onebots 0.2.6 → 0.4.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.
@@ -0,0 +1,33 @@
1
+ port: 6727 # 监听端口
2
+ log_level: info # 日志等级
3
+ platform: 5 # 机器人客户端协议(1:Android 2:APad 3:Watch 4:IMac 5:IPad)
4
+ timeout: 30 #登录超时时间(秒)
5
+ general: # 通用配置,在单个配置省略时的默认值
6
+ V11: # oneBotV11的通用配置
7
+ heartbeat: 3 # 心跳间隔 (秒)
8
+ access_token: '' # 访问api的token
9
+ post_timeout: 15 # 上报超时时间,(秒)
10
+ secret: '' # 上报数据的sha1签名密钥
11
+ rate_limit_interval: 4 # ws心跳间隔(秒)
12
+ post_message_format: string # "string"或"array"
13
+ reconnect_interval: 3 # 重连间隔 (秒)
14
+ use_http: true # 是否使用 http
15
+ enable_cors: true # 是否允许跨域
16
+ use_ws: true # 是否使用websocket
17
+ http_reverse: [ ] # http上报地址
18
+ ws_reverse: [ ] # 反向ws连接地址
19
+ V12: # oneBotV12的通用配置
20
+ heartbeat: 3 # 心跳间隔 (秒)
21
+ access_token: '' # 访问api的token
22
+ request_timeout: 15 # 上报超时时间 (秒)
23
+ reconnect_interval: 3 # 重连间隔 (秒)
24
+ enable_cors: true # 是否允许跨域
25
+ use_http: true # 是否启用http
26
+ use_ws: true # 是否启用 websocket
27
+ webhook: [ ] # http 上报地址
28
+ ws_reverse: [ ] # 反向ws连接地址
29
+ # 每个账号的单独配置(用于覆盖通用配置)
30
+ 123456789:
31
+ version: V11 # 使用的oneBot版本
32
+ password: abcedfghi # 账号密码,未配置则扫码登陆
33
+ # 。。。其他配置项参见上方对应oneBot版本的通用配置
package/lib/db.d.ts CHANGED
@@ -1,15 +1,14 @@
1
- export declare class Db {
1
+ import { Keys, Value } from "@zhinjs/shared";
2
+ export declare class Database<T extends object = object> {
2
3
  private readonly path;
3
4
  private data;
4
- private raw_data;
5
- constructor(path: string, force_create?: boolean);
6
- get(key: string, escape?: boolean): any;
7
- set(key: string, value: any, escape?: boolean): any;
8
- has(key: string, escape?: boolean): boolean;
9
- delete(key: string, escape?: boolean): boolean;
10
- write(): void;
5
+ constructor(path: string);
6
+ sync(defaultValue: T): void;
7
+ get<K extends Keys<T>>(key: K): Value<T, K>;
8
+ delete<K extends Keys<T>>(key: K): boolean;
9
+ set<K extends Keys<T>>(key: K, value: Value<T, K>): void;
11
10
  }
12
- export declare namespace Db {
11
+ export declare namespace Database {
13
12
  interface Config {
14
13
  path: string;
15
14
  force?: boolean;
package/lib/db.js CHANGED
@@ -1,76 +1,58 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Db = void 0;
3
+ exports.Database = void 0;
4
4
  const fs_1 = require("fs");
5
- class Db {
6
- constructor(path, force_create = true) {
5
+ const shared_1 = require("@zhinjs/shared");
6
+ class Database {
7
+ constructor(path) {
7
8
  this.path = path;
8
9
  this.data = {};
9
- this.raw_data = '{}';
10
10
  if (!this.path.toLowerCase().endsWith('.json'))
11
11
  this.path = this.path + '.json';
12
- if (!(0, fs_1.existsSync)(this.path) && force_create) {
13
- (0, fs_1.writeFileSync)(this.path, this.raw_data);
14
- }
15
- try {
16
- const raw_data = (0, fs_1.readFileSync)(this.path, 'utf8');
17
- this.raw_data = raw_data || this.raw_data;
18
- this.data = JSON.parse(this.raw_data);
19
- }
20
- catch (error) {
21
- const { message } = error;
22
- if (!message.includes('ENOENT: no such file or directory')) {
23
- throw error;
24
- }
12
+ if (!(0, fs_1.existsSync)(this.path)) {
13
+ (0, fs_1.writeFileSync)(this.path, "", "utf-8");
25
14
  }
26
15
  }
27
- get(key, escape = true) {
28
- const func = new Function(`return this.data.${key}`);
29
- const _this = this;
30
- let result;
16
+ sync(defaultValue) {
31
17
  try {
32
- result = escape ? func.apply(this) : this.data[key];
18
+ this.data = JSON.parse((0, fs_1.readFileSync)(this.path, 'utf-8'));
33
19
  }
34
20
  catch {
35
- throw new Error('不可达的位置:' + key.toString());
21
+ this.data = defaultValue;
22
+ (0, fs_1.writeFileSync)(this.path, JSON.stringify(defaultValue, null, 2), "utf-8");
36
23
  }
37
- return result && typeof result === 'object' ? new Proxy(result, {
38
- get(target, p, receiver) {
39
- return Reflect.get(target, p, receiver);
24
+ }
25
+ get(key) {
26
+ const value = (0, shared_1.getValue)(this.data, key);
27
+ if (typeof value !== 'object')
28
+ return value;
29
+ const saveValue = () => {
30
+ this.set(key, value);
31
+ };
32
+ return new Proxy(value, {
33
+ set(target, k, v) {
34
+ const res = Reflect.set(target, k, v);
35
+ saveValue();
36
+ return res;
37
+ },
38
+ deleteProperty(target, p) {
39
+ const res = Reflect.deleteProperty(target, p);
40
+ saveValue();
41
+ return res;
40
42
  },
41
- set(target, p, value, receiver) {
42
- const res = Reflect.set(target, p, value, receiver);
43
- _this.set(key, result);
43
+ defineProperty(target, p, r) {
44
+ const res = Reflect.defineProperty(target, p, r);
45
+ saveValue();
44
46
  return res;
45
47
  }
46
- }) : result;
47
- }
48
- set(key, value, escape = true) {
49
- const func = new Function('value', `return this.data.${key}=value`);
50
- let result = escape ? func.apply(this, [value]) : this.data[key] = value;
51
- this.write();
52
- return result;
48
+ });
53
49
  }
54
- has(key, escape = true) {
55
- return escape ? new Function(`return !!this.data.${key}`).apply(this) : !!this.data[key];
50
+ delete(key) {
51
+ return (0, shared_1.deleteValue)(this.data, key);
56
52
  }
57
- delete(key, escape = true) {
58
- const result = escape ? new Function(`return delete this.data.${key}`).apply(this) : delete this.data[key];
59
- this.write();
60
- return result;
61
- }
62
- write() {
63
- try {
64
- const raw_data = JSON.stringify(this.data);
65
- if (raw_data !== this.raw_data) {
66
- (0, fs_1.writeFileSync)(this.path, raw_data);
67
- this.raw_data = raw_data;
68
- }
69
- }
70
- catch (error) {
71
- this.data = JSON.parse(this.raw_data);
72
- throw error;
73
- }
53
+ set(key, value) {
54
+ (0, shared_1.setValue)(this.data, key, value);
55
+ return (0, fs_1.writeFileSync)(this.path, JSON.stringify(this.data, null, 2), 'utf-8');
74
56
  }
75
57
  }
76
- exports.Db = Db;
58
+ exports.Database = Database;
@@ -1,6 +1,5 @@
1
1
  import { V12 } from '../../../service/V12';
2
2
  import { Action } from "./";
3
- import { V11 } from "../../../service/V11";
4
3
  export declare class CommonAction {
5
4
  sendMessage(): void;
6
5
  /**
@@ -18,7 +17,7 @@ export declare class CommonAction {
18
17
  * 获取 Cookies
19
18
  * @param domain {string} 域名
20
19
  */
21
- getCookies(this: V11, domain: string): string;
20
+ getCookies(this: V12, domain: string): string;
22
21
  getStatus(this: V12): {
23
22
  good: boolean;
24
23
  bots: {
@@ -40,4 +39,7 @@ export declare class CommonAction {
40
39
  login(this: V12, password?: string): Promise<unknown>;
41
40
  logout(this: V12, keepalive?: boolean): Promise<unknown>;
42
41
  getSupportedActions(this: V12): string[];
42
+ uploadFile(this: V12, type: 'url' | 'path' | 'data', name: string, url?: string, path?: string, data?: string, sha256?: string, headers?: Record<string, any>): string;
43
+ uploadFileFragmented(this: V12, stage: 'prepare' | 'transfer' | 'finish', name?: string, total_size?: number, file_id?: string, offset?: number, data?: string, sha256?: string): string | true;
44
+ getFile(this: V12, file_id: string): V12.FileInfo;
43
45
  }
@@ -5,6 +5,8 @@ const icqq_1 = require("icqq");
5
5
  const utils_1 = require("../../../utils");
6
6
  const onebot_1 = require("../../../onebot");
7
7
  const utils_2 = require("../../../utils");
8
+ const crypto_1 = require("crypto");
9
+ const sha = (data) => (0, crypto_1.createHash)("sha1").update(data).digest();
8
10
  class CommonAction {
9
11
  sendMessage() { }
10
12
  /**
@@ -119,5 +121,53 @@ class CommonAction {
119
121
  return key !== 'constructor';
120
122
  }).map(utils_2.toLine);
121
123
  }
124
+ uploadFile(type, name, url, path, data, sha256, headers) {
125
+ const fileInfo = {
126
+ name,
127
+ url,
128
+ type,
129
+ path,
130
+ data,
131
+ sha256,
132
+ headers
133
+ };
134
+ return this.saveFile(fileInfo);
135
+ }
136
+ uploadFileFragmented(stage, name, total_size, file_id, offset, data, sha256) {
137
+ switch (stage) {
138
+ case "prepare": {
139
+ if (!name || !total_size)
140
+ throw new Error('请输入name和total_size');
141
+ return this.saveFile({
142
+ name,
143
+ type: 'data',
144
+ total_size,
145
+ data: Buffer.alloc(0).toString('base64')
146
+ });
147
+ }
148
+ case "transfer": {
149
+ if (!file_id || !offset || !data)
150
+ throw new Error('请输入file_id、offset和data');
151
+ const fileInfo = this.getFile(file_id);
152
+ fileInfo.data = Buffer.concat([
153
+ Buffer.from(fileInfo.data),
154
+ Buffer.from(data)
155
+ ]).toString('base64');
156
+ return true;
157
+ }
158
+ case "finish": {
159
+ if (!file_id || sha256)
160
+ throw new Error('请输入file_id和sha256');
161
+ const fileInfo = this.getFile(file_id);
162
+ if (sha(Buffer.from(fileInfo.data)).toString('hex') === sha256)
163
+ return file_id;
164
+ this.delFile(file_id);
165
+ throw new Error('文件已被篡改');
166
+ }
167
+ }
168
+ }
169
+ getFile(file_id) {
170
+ return this.getFile(file_id);
171
+ }
122
172
  }
123
173
  exports.CommonAction = CommonAction;
@@ -16,7 +16,7 @@ class FriendAction {
16
16
  * @param source {import('onebots/lib/service/v12').SegmentElem<'reply'>} 引用内容
17
17
  */
18
18
  async sendPrivateMsg(user_id, message, source) {
19
- let { element, quote, music, share } = await utils_1.processMessage.apply(this.client, [message, source]);
19
+ let { element, quote, music, share } = await utils_1.processMessage.apply(this, [message, source]);
20
20
  if (music)
21
21
  await this.client.pickFriend(user_id).shareMusic(music.data.platform, music.data.id);
22
22
  if (share)
@@ -10,7 +10,7 @@ class GroupAction {
10
10
  * @param source {import('onebots/lib/service/v12').SegmentElem<'reply'>} 引用内容
11
11
  */
12
12
  async sendGroupMsg(group_id, message, source) {
13
- let { element, quote, music, share } = await utils_1.processMessage.apply(this.client, [message, source]);
13
+ let { element, quote, music, share } = await utils_1.processMessage.apply(this, [message, source]);
14
14
  if (music)
15
15
  await this.client.pickGroup(group_id).shareMusic(music.data.platform, music.data.id);
16
16
  if (share)
@@ -19,7 +19,7 @@ class GuildAction {
19
19
  * @param message {import('icqq/lib/service').Sendable} 消息
20
20
  */
21
21
  async sendGuildMsg(guild_id, channel_id, message) {
22
- const { element } = await utils_1.processMessage.apply(this.client, [message]);
22
+ const { element } = await utils_1.processMessage.apply(this, [message]);
23
23
  if (!element.length)
24
24
  return;
25
25
  return await this.client.sendGuildMsg(guild_id, channel_id, element);
@@ -22,7 +22,13 @@ export declare class V12 extends EventEmitter implements OneBot.Base {
22
22
  private db;
23
23
  constructor(oneBot: OneBot<'V12'>, client: Client, config: V12.Config);
24
24
  get history(): V12.Payload<keyof Action>[];
25
- set history(value: V12.Payload<keyof Action>[]);
25
+ getFile(file_id: string): V12.FileInfo;
26
+ delFile(file_id: string): boolean;
27
+ saveFile(fileInfo: V12.FileInfo): string;
28
+ get files(): ({
29
+ file_id: string;
30
+ } & V12.FileInfo)[];
31
+ set history(value: any[]);
26
32
  start(path?: string): void;
27
33
  private startHttp;
28
34
  private startWebhook;
@@ -220,4 +226,14 @@ export declare namespace V12 {
220
226
  params: Record<string, any>;
221
227
  echo?: number;
222
228
  };
229
+ type FileInfo = {
230
+ type: 'url' | 'path' | 'data';
231
+ name: string;
232
+ url?: string;
233
+ headers?: Record<string, any>;
234
+ path?: string;
235
+ data?: string;
236
+ sha256?: string;
237
+ total_size?: number;
238
+ };
223
239
  }
@@ -28,15 +28,35 @@ class V12 extends events_1.EventEmitter {
28
28
  this.version = 'V12';
29
29
  this.timestamp = Date.now();
30
30
  this.wsr = new Set();
31
- this.db = new db_1.Db((0, path_1.join)(app_1.App.configDir, 'data', this.oneBot.uin + '.json'));
32
- if (!this.history)
33
- this.history = [];
31
+ this.db = new db_1.Database((0, path_1.join)(app_1.App.configDir, 'data', this.oneBot.uin + '.json'));
32
+ this.db.sync({ eventBuffer: [], files: {} });
34
33
  this.action = new action_1.Action();
35
34
  this.logger = this.oneBot.app.getLogger(this.oneBot.uin, this.version);
36
35
  }
37
36
  get history() {
38
37
  return this.db.get('eventBuffer');
39
38
  }
39
+ getFile(file_id) {
40
+ return this.db.get(`files.${file_id}`);
41
+ }
42
+ delFile(file_id) {
43
+ const files = this.db.get(`files`);
44
+ return delete files[file_id];
45
+ }
46
+ saveFile(fileInfo) {
47
+ const file_id = (0, utils_2.uuid)();
48
+ this.db.set(`files.${file_id}`, fileInfo);
49
+ return file_id;
50
+ }
51
+ get files() {
52
+ const files = this.db.get('files');
53
+ return Object.keys(files).map((file_id) => {
54
+ return {
55
+ file_id,
56
+ ...files[file_id]
57
+ };
58
+ });
59
+ }
40
60
  set history(value) {
41
61
  this.db.set('eventBuffer', value);
42
62
  }
@@ -1,6 +1,6 @@
1
- import { Client, MessageElem } from "icqq";
1
+ import { MessageElem } from "icqq";
2
2
  import { V12 } from "../../service/V12";
3
- export declare function processMessage(this: Client, message: V12.Sendable, source?: V12.SegmentElem<'reply'>): Promise<{
3
+ export declare function processMessage(this: V12, message: V12.Sendable, source?: V12.SegmentElem<'reply'>): Promise<{
4
4
  element: MessageElem[];
5
5
  music?: V12.SegmentElem<'music'>;
6
6
  share?: V12.SegmentElem<'share'>;
@@ -25,6 +25,14 @@ async function processMessage(message, source) {
25
25
  'forward', 'node',
26
26
  'music', 'share', 'xml', 'json', 'location', // 分享类
27
27
  ].includes(n.type));
28
+ segments.forEach(seg => {
29
+ if (['image', 'video', 'audio'].includes(seg.type)) {
30
+ const { file_id } = seg.data;
31
+ const fileInfo = this.getFile(file_id);
32
+ if (fileInfo)
33
+ seg.data['file_id'] = fileInfo.url || fileInfo.path || `base64://${fileInfo.data}`;
34
+ }
35
+ });
28
36
  const element = V12_1.V12.fromSegment(segments);
29
37
  return { element, quote: quote || source, share, music };
30
38
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "onebots",
3
- "version": "0.2.6",
3
+ "version": "0.4.0",
4
4
  "description": "基于icqq的多例oneBot实现",
5
5
  "engines": {
6
6
  "node": ">=16"
@@ -11,7 +11,7 @@
11
11
  },
12
12
  "scripts": {
13
13
  "start": "node .",
14
- "build": "tsc --project tsconfig.json && tsc-alias -p tsconfig.json",
14
+ "build": "tsc --project tsconfig.json && tsc-alias -p tsconfig.json && cp -r src/config.sample.yaml lib/config.sample.yaml",
15
15
  "dev": "ts-node-dev -r tsconfig-paths/register ./src/bin.ts -c config.yaml",
16
16
  "pub": "npm publish --access public",
17
17
  "docs:dev": "vitepress dev docs --port 8989",
@@ -54,6 +54,7 @@
54
54
  ],
55
55
  "dependencies": {
56
56
  "@koa/router": "^10.1.1",
57
+ "@zhinjs/shared": "^0.0.9",
57
58
  "icqq": "^0.3.6",
58
59
  "icqq-cq-enable": "^1.0.0",
59
60
  "js-yaml": "^4.1.0",