Ver código fonte

Merge branch 'koishi' into fleets-koishi

Mike L 4 anos atrás
pai
commit
41b1d13164
4 arquivos alterados com 37 adições e 16 exclusões
  1. 13 2
      dist/koishi.js
  2. 4 4
      dist/webshot.js
  3. 14 3
      src/koishi.ts
  4. 6 7
      src/webshot.ts

+ 13 - 2
dist/koishi.js

@@ -24,7 +24,7 @@ exports.Message = {
     ellipseBase64: (msg) => msg.replace(/(?<=\[CQ:.*base64:\/\/).*?(,|\])/g, '...$1'),
     separateAttachment: (msg) => {
         const attachments = [];
-        const message = msg.replace(/\[CQ:(image|video|record),.*?\]/g, code => {
+        const message = msg.replace(/\[CQ:(video|record),.*?\]/g, code => {
             attachments.push(code);
             return '';
         });
@@ -147,9 +147,20 @@ class default_1 {
                 }
             }), true);
         };
+        this.listen = (logMsg = 'connecting to bot provider...') => __awaiter(this, void 0, void 0, function* () {
+            logger.warn(logMsg);
+            try {
+                yield this.app.start();
+            }
+            catch (err) {
+                logger.error(`error connecting to bot provider at ${this.app.options.server}, will retry in 2.5s...`);
+                yield koishi_1.sleep(2500);
+                yield this.listen('retry connecting...');
+            }
+        });
         this.connect = () => __awaiter(this, void 0, void 0, function* () {
             this.initBot();
-            yield this.app.start();
+            yield this.listen();
             this.bot = this.app.getBot('onebot');
         });
         logger.warn(`Initialized koishi on ${opt.host}:${opt.port} with access_token ${opt.access_token}`);

+ 4 - 4
dist/webshot.js

@@ -29,7 +29,7 @@ class Webshot extends CallableInstance {
             axios_1.default({
                 method: 'get',
                 url,
-                responseType: 'stream',
+                responseType: 'arraybuffer',
                 timeout: 150000,
             }).then(res => {
                 if (res.status === 200) {
@@ -47,8 +47,8 @@ class Webshot extends CallableInstance {
         }).then(data => {
             var _a;
             return (ext => {
-                const mediaTempFilePath = temp.path({ suffix: ext });
-                data.pipe(fs_1.createWriteStream(mediaTempFilePath));
+                const mediaTempFilePath = temp.path({ suffix: `.${ext}` });
+                fs_1.writeFileSync(mediaTempFilePath, Buffer.from(data));
                 const path = `file://${mediaTempFilePath}`;
                 switch (ext) {
                     case 'jpg':
@@ -73,7 +73,7 @@ class Webshot extends CallableInstance {
             promise = promise.then(() => {
                 logger.info(`working on ${user.screen_name}/${fleet.fleet_id}`);
             });
-            let messageChain;
+            let messageChain = '';
             const author = `${user.name} (@${user.screen_name}):\n`;
             const date = `${new Date(fleet.created_at)}\n`;
             let text = (_b = author + date + ((_a = fleet.media_bounding_boxes) === null || _a === void 0 ? void 0 : _a.map(box => box.entity.value).join('\n'))) !== null && _b !== void 0 ? _b : '';

+ 14 - 3
src/koishi.ts

@@ -1,4 +1,4 @@
-import { App, Bot, segment, Session } from 'koishi';
+import { App, Bot, segment, Session, sleep } from 'koishi';
 import 'koishi-adapter-onebot';
 
 import { parseCmd, view } from './command';
@@ -28,7 +28,7 @@ export const Message = {
   ellipseBase64: (msg: string) => msg.replace(/(?<=\[CQ:.*base64:\/\/).*?(,|\])/g, '...$1'),
   separateAttachment: (msg: string) => {
     const attachments: string[] = [];
-    const message = msg.replace(/\[CQ:(image|video|record),.*?\]/g, code => {
+    const message = msg.replace(/\[CQ:(video|record),.*?\]/g, code => {
       attachments.push(code);
       return '';
     });
@@ -165,9 +165,20 @@ export default class {
     }, true);
   };
 
+  private listen = async (logMsg = 'connecting to bot provider...'): Promise<void> => {
+    logger.warn(logMsg);
+    try {
+      await this.app.start();
+    } catch (err) {
+      logger.error(`error connecting to bot provider at ${this.app.options.server}, will retry in 2.5s...`);
+      await sleep(2500);
+      await this.listen('retry connecting...');
+    }
+  };
+
   public connect = async () => {
     this.initBot();
-    await this.app.start();
+    await this.listen();
     this.bot = this.app.getBot('onebot');
   };
 

+ 6 - 7
src/webshot.ts

@@ -1,5 +1,4 @@
-import { createWriteStream } from 'fs';
-import { Stream } from 'stream';
+import { writeFileSync } from 'fs';
 
 import axios from 'axios';
 import * as CallableInstance from 'callable-instance';
@@ -35,12 +34,12 @@ class Webshot extends CallableInstance<[FullUser, Fleets, (...args) => void, num
     onready();
   }
 
-  private fetchMedia = (url: string): Promise<string> => new Promise<Stream>((resolve, reject) => {
+  private fetchMedia = (url: string): Promise<string> => new Promise<ArrayBuffer>((resolve, reject) => {
     logger.info(`fetching ${url}`);
     axios({
       method: 'get',
       url,
-      responseType: 'stream',
+      responseType: 'arraybuffer',
       timeout: 150000,
     }).then(res => {
       if (res.status === 200) {
@@ -56,8 +55,8 @@ class Webshot extends CallableInstance<[FullUser, Fleets, (...args) => void, num
     });
   }).then(data =>
     (ext => {
-      const mediaTempFilePath = temp.path({suffix: ext});
-      data.pipe(createWriteStream(mediaTempFilePath));
+      const mediaTempFilePath = temp.path({suffix: `.${ext}`});
+      writeFileSync(mediaTempFilePath, Buffer.from(data));
       const path = `file://${mediaTempFilePath}`;
       switch (ext) {
         case 'jpg':
@@ -84,7 +83,7 @@ class Webshot extends CallableInstance<[FullUser, Fleets, (...args) => void, num
       promise = promise.then(() => {
         logger.info(`working on ${user.screen_name}/${fleet.fleet_id}`);
       });
-      let messageChain: '';
+      let messageChain = '';
 
       // text processing
       const author = `${user.name} (@${user.screen_name}):\n`;