Browse Source

use websocket; retry initial connection on error

Mike L 3 years ago
parent
commit
4a5f1e7ebe
9 changed files with 50 additions and 39 deletions
  1. 3 3
      README.md
  2. 2 2
      config.example.json
  3. 17 11
      dist/koishi.js
  4. 3 3
      dist/main.js
  5. 2 1
      dist/twitter.js
  6. 0 1
      package.json
  7. 18 13
      src/koishi.ts
  8. 3 3
      src/main.ts
  9. 2 2
      src/twitter.ts

+ 3 - 3
README.md

@@ -22,9 +22,9 @@
 
 | 配置项 | 说明 | 默认 |
 | --- | --- | --- |
-| cq_access_token | OneBot HTTP API authKey(需与插件一致,插件若未<br />配置本项会在 console 显示生成值,请将其填入) | (必填) |
-| cq_http_host | OneBot HTTP API 插件服务端地址 | 127.0.0.1 |
-| cq_http_port | OneBot HTTP API 插件服务端口 | 8080 |
+| cq_access_token | OneBot HTTP API access_token(需与插件一致,<br />插件若未配置本项即为空,建议配置为独特值) | ""(空) |
+| cq_ws_host | OneBot HTTP API 插件服务端地址 | 127.0.0.1 |
+| cq_ws_port | OneBot HTTP API 插件服务端口 | 6700 |
 | cq_bot_qq | OneBot HTTP API 登录的目标机器人 QQ 号 | 10000(示例值,必填) |
 | twitter_consumer_key | Twitter App consumer_key | (必填) |
 | twitter_consumer_secret |  Twitter App consumer_secret | (必填) |

+ 2 - 2
config.example.json

@@ -1,7 +1,7 @@
 {
   "cq_access_token": "",
-  "cq_http_host": "127.0.0.1",
-  "cq_http_port": 5700,
+  "cq_ws_host": "127.0.0.1",
+  "cq_ws_port": 6700,
   "cq_bot_qq": 10000,
   "twitter_consumer_key": "",
   "twitter_consumer_secret": "",

+ 17 - 11
dist/koishi.js

@@ -10,7 +10,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
 };
 Object.defineProperty(exports, "__esModule", { value: true });
 exports.ellipseBase64InMessage = exports.message = void 0;
-const getPort = require("get-port");
 const koishi_1 = require("koishi");
 require("koishi-adapter-onebot");
 const command_1 = require("./command");
@@ -62,20 +61,16 @@ class default_1 {
             logger.info(response);
         })
             .catch(reason => {
+            reason = exports.ellipseBase64InMessage(reason);
             logger.error(`error pushing data to ${JSON.stringify(subscriber.chatID)}, reason: ${reason}`);
             throw Error(reason);
         });
-        this.initBot = () => __awaiter(this, void 0, void 0, function* () {
-            const port = yield getPort();
+        this.initBot = () => {
             this.app = new koishi_1.App({
                 type: 'onebot',
-                port,
-                server: `http://${this.botInfo.host}:${this.botInfo.port}`,
+                server: `ws://${this.botInfo.host}:${this.botInfo.port}`,
                 selfId: this.botInfo.bot_id.toString(),
                 token: this.botInfo.access_token,
-                onebot: {
-                    quickOperation: 100,
-                },
                 axiosConfig: {
                     maxContentLength: Infinity,
                 },
@@ -164,11 +159,22 @@ count 与 since/until 并用时,取二者中实际查询结果较少者
 其中不包含原生转推(实际上用户只发了 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* () {
-            yield this.initBot();
-            yield this.app.start();
+            this.initBot();
+            yield this.listen();
             this.bot = this.app.getBot('onebot');
         });
         logger.warn(`Initialized koishi on ${opt.host}:${opt.port} with access_token ${opt.access_token}`);

+ 3 - 3
dist/main.js

@@ -51,7 +51,7 @@ const requiredFields = [
     'cq_bot_qq', ...(config.mode || exampleConfig.mode) === 0 ? ['playwright_ws_spec_endpoint'] : [],
 ];
 const warningFields = [
-    'cq_http_host', 'cq_http_port', 'cq_access_token',
+    'cq_ws_host', 'cq_ws_port', 'cq_access_token',
 ];
 const optionalFields = [
     'lockfile', 'work_interval', 'webshot_delay', 'loglevel', 'mode', 'resume_on_start',
@@ -109,8 +109,8 @@ if (!config.resume_on_start) {
 }
 const qq = new koishi_1.default({
     access_token: config.cq_access_token,
-    host: config.cq_http_host,
-    port: config.cq_http_port,
+    host: config.cq_ws_host,
+    port: config.cq_ws_port,
     bot_id: config.cq_bot_qq,
     list: (c, a, cb) => command_1.list(c, a, cb, lock),
     sub: (c, a, cb) => command_1.sub(c, a, cb, lock, config.lockfile),

+ 2 - 1
dist/twitter.js

@@ -14,6 +14,7 @@ const fs = require("fs");
 const path = require("path");
 const Twitter = require("twitter");
 const loggers_1 = require("./loggers");
+const koishi_1 = require("./koishi");
 const utils_1 = require("./utils");
 const webshot_1 = require("./webshot");
 class ScreenNameNormalizer {
@@ -141,7 +142,7 @@ class default_1 {
         };
         this.sendTweets = (source, ...to) => (msg, text, author) => {
             to.forEach(subscriber => {
-                logger.info(`pushing data${source ? ` of ${source}` : ''} to ${JSON.stringify(subscriber)}`);
+                logger.info(`pushing data${source ? ` of ${koishi_1.ellipseBase64InMessage(source)}` : ''} to ${JSON.stringify(subscriber)}`);
                 retryOnError(() => this.bot.sendTo(subscriber, msg), (_, count, terminate) => {
                     if (count <= maxTrials) {
                         logger.warn(`retry sending to ${subscriber.chatID} for the ${ordinal(count)} time...`);

+ 0 - 1
package.json

@@ -32,7 +32,6 @@
   "dependencies": {
     "callable-instance": "^2.0.0",
     "command-line-usage": "^5.0.5",
-    "get-port": "^5.1.1",
     "html-entities": "^1.3.1",
     "koishi": "^3.10.0",
     "koishi-adapter-onebot": "^3.0.8",

+ 18 - 13
src/koishi.ts

@@ -1,5 +1,4 @@
-import * as getPort from 'get-port';
-import { App, Bot, segment, Session } from 'koishi';
+import { App, Bot, segment, Session, sleep } from 'koishi';
 import 'koishi-adapter-onebot';
 
 import { parseCmd, query, view } from './command';
@@ -68,22 +67,17 @@ export default class {
       logger.info(response);
     })
     .catch(reason => {
+      reason = ellipseBase64InMessage(reason);
       logger.error(`error pushing data to ${JSON.stringify(subscriber.chatID)}, reason: ${reason}`);
       throw Error(reason);
     });
 
-  private initBot = async () => {
-    const port = await getPort();
-
+  private initBot = () => {
     this.app = new App({
       type: 'onebot',
-      port,
-      server: `http://${this.botInfo.host}:${this.botInfo.port}`,
+      server: `ws://${this.botInfo.host}:${this.botInfo.port}`,
       selfId: this.botInfo.bot_id.toString(),
       token: this.botInfo.access_token,
-      onebot: {
-        quickOperation: 100,
-      },
       axiosConfig: {
         maxContentLength: Infinity,
       },
@@ -176,12 +170,23 @@ count 与 since/until 并用时,取二者中实际查询结果较少者
               );
           }
       }
-    });
+    }, 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 () => {
-    await this.initBot();
-    await this.app.start();
+    this.initBot();
+    await this.listen();
     this.bot = this.app.getBot('onebot');
   };
 

+ 3 - 3
src/main.ts

@@ -61,7 +61,7 @@ const requiredFields = [
 ];
 
 const warningFields = [
-  'cq_http_host', 'cq_http_port', 'cq_access_token',
+  'cq_ws_host', 'cq_ws_port', 'cq_access_token',
 ];
 
 const optionalFields = [
@@ -122,8 +122,8 @@ if (!config.resume_on_start) {
 
 const qq = new QQBot({
   access_token: config.cq_access_token,
-  host: config.cq_http_host,
-  port: config.cq_http_port,
+  host: config.cq_ws_host,
+  port: config.cq_ws_port,
   bot_id: config.cq_bot_qq,
   list: (c, a, cb) => list(c, a, cb, lock),
   sub: (c, a, cb) => sub(c, a, cb, lock, config.lockfile),

+ 2 - 2
src/twitter.ts

@@ -4,7 +4,7 @@ import * as Twitter from 'twitter';
 import TwitterTypes from 'twitter-d';
 
 import { getLogger } from './loggers';
-import QQBot from './koishi';
+import QQBot, { ellipseBase64InMessage } from './koishi';
 import { chainPromises, BigNumOps } from './utils';
 import Webshot from './webshot';
 
@@ -276,7 +276,7 @@ export default class {
 
   private sendTweets = (source?: string, ...to: IChat[]) => (msg: string, text: string, author: string) => {
     to.forEach(subscriber => {
-      logger.info(`pushing data${source ? ` of ${source}` : ''} to ${JSON.stringify(subscriber)}`);
+      logger.info(`pushing data${source ? ` of ${ellipseBase64InMessage(source)}` : ''} to ${JSON.stringify(subscriber)}`);
       retryOnError(
         () => this.bot.sendTo(subscriber, msg),
         (_, count, terminate: (doNothing: Promise<void>) => void) => {