Sfoglia il codice sorgente

fix stupid mistake, workaround failed image

Mike L 4 anni fa
parent
commit
c9588996e6
6 ha cambiato i file con 65 aggiunte e 43 eliminazioni
  1. 6 1
      dist/mirai.js
  2. 14 2
      dist/twitter.js
  3. 10 20
      dist/webshot.js
  4. 9 3
      src/mirai.ts
  5. 14 3
      src/twitter.ts
  6. 12 14
      src/webshot.ts

+ 6 - 1
dist/mirai.js

@@ -11,6 +11,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
 Object.defineProperty(exports, "__esModule", { value: true });
 const axios_1 = require("axios");
 const mirai_ts_1 = require("mirai-ts");
+const message_1 = require("mirai-ts/dist/message");
 const helper_1 = require("./helper");
 const loggers_1 = require("./loggers");
 const logger = loggers_1.getLogger('qqbot');
@@ -19,6 +20,7 @@ const ChatTypeMap = {
     FriendMessage: "private" /* Private */,
     TempMessage: "temp" /* Temp */,
 };
+exports.MiraiMessage = message_1.default;
 class default_1 {
     constructor(opt) {
         this.sendTo = (subscriber, msg) => (() => {
@@ -33,7 +35,10 @@ class default_1 {
             logger.info(`pushing data to ${subscriber.chatID} was successful, response:`);
             logger.info(response);
         })
-            .catch(reason => logger.error(`error pushing data to ${subscriber.chatID}, reason: ${reason}`));
+            .catch(reason => {
+            logger.error(`error pushing data to ${subscriber.chatID}, reason: ${reason}`);
+            throw Error(reason);
+        });
         this.initBot = () => {
             this.bot = new mirai_ts_1.default({
                 authKey: this.botInfo.access_token,

+ 14 - 2
dist/twitter.js

@@ -4,6 +4,7 @@ const fs = require("fs");
 const path = require("path");
 const Twitter = require("twitter");
 const loggers_1 = require("./loggers");
+const mirai_1 = require("./mirai");
 const webshot_1 = require("./webshot");
 const logger = loggers_1.getLogger('twitter');
 class default_1 {
@@ -67,7 +68,7 @@ class default_1 {
                                 logger.warn(`error on fetching tweets for ${lock.feed[lock.workon]}: ${JSON.stringify(error)}`);
                                 lock.threads[lock.feed[lock.workon]].subscribers.forEach(subscriber => {
                                     logger.info(`sending notfound message of ${lock.feed[lock.workon]} to ${JSON.stringify(subscriber)}`);
-                                    this.bot.sendTo(subscriber, `链接 ${lock.feed[lock.workon]} 指向的用户或列表不存在,请退订。`);
+                                    this.bot.sendTo(subscriber, `链接 ${lock.feed[lock.workon]} 指向的用户或列表不存在,请退订。`).catch();
                                 });
                             }
                             else {
@@ -95,7 +96,18 @@ class default_1 {
                 return this.webshot(tweets, msg => {
                     lock.threads[lock.feed[lock.workon]].subscribers.forEach(subscriber => {
                         logger.info(`pushing data of thread ${lock.feed[lock.workon]} to ${JSON.stringify(subscriber)}`);
-                        this.bot.sendTo(subscriber, msg);
+                        this.bot.sendTo(subscriber, msg)
+                            .catch(reason => {
+                            if (typeof (msg) !== 'string') {
+                                logger.warn(`retry sending to ${subscriber.chatID}`);
+                                msg.forEach((message, pos) => {
+                                    if (message.type === 'Image') {
+                                        msg[pos] = mirai_1.MiraiMessage.Plain(`[失败的图片:${message.path}]`);
+                                    }
+                                });
+                                this.bot.sendTo(subscriber, msg).catch();
+                            }
+                        });
                     });
                 }, this.webshotDelay)
                     .then(() => {

+ 10 - 20
dist/webshot.js

@@ -1,25 +1,15 @@
 "use strict";
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
-    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
-    return new (P || (P = Promise))(function (resolve, reject) {
-        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
-        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
-        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
-        step((generator = generator.apply(thisArg, _arguments || [])).next());
-    });
-};
 Object.defineProperty(exports, "__esModule", { value: true });
 const axios_1 = require("axios");
 const CallableInstance = require("callable-instance");
 const fs_1 = require("fs");
 const html_entities_1 = require("html-entities");
-const message_1 = require("mirai-ts/dist/message");
 const pngjs_1 = require("pngjs");
 const puppeteer = require("puppeteer");
 const loggers_1 = require("./loggers");
-const writeOutTo = (path, data) => __awaiter(void 0, void 0, void 0, function* () {
-    yield new Promise(resolve => data.pipe(fs_1.createWriteStream(path)).on('close', resolve));
-    return path;
+const mirai_1 = require("./mirai");
+const writeOutTo = (path, data) => new Promise(resolve => {
+    data.pipe(fs_1.createWriteStream(path)).on('close', () => resolve(path));
 });
 const xmlEntities = new html_entities_1.XmlEntities();
 const typeInZH = {
@@ -206,7 +196,7 @@ class Webshot extends CallableInstance {
                     });
                 }
                 if (this.mode > 0)
-                    messageChain.push(message_1.default.Plain(author + xmlEntities.decode(text)));
+                    messageChain.push(mirai_1.MiraiMessage.Plain(author + xmlEntities.decode(text)));
             });
             // invoke webshot
             if (this.mode === 0) {
@@ -214,16 +204,16 @@ class Webshot extends CallableInstance {
                 promise = promise.then(() => this.renderWebshot(url, 1920, webshotDelay))
                     .then(webshotFilePath => {
                     if (webshotFilePath)
-                        messageChain.push(message_1.default.Image('', '', baseName(webshotFilePath)));
+                        messageChain.push(mirai_1.MiraiMessage.Image('', '', baseName(webshotFilePath)));
                 });
                 // fetch extra images
             }
             else if (1 - this.mode % 2) {
                 if (originTwi.extended_entities) {
-                    promise = promise.then(() => originTwi.extended_entities.media.forEach(media => {
-                        this.fetchImage(media.media_url_https, `${twi.user.screen_name}-${twi.id_str}--`)
-                            .then(path => messageChain.push(message_1.default.Image('', '', baseName(path))));
-                    }));
+                    originTwi.extended_entities.media.forEach(media => promise = promise.then(() => this.fetchImage(media.media_url_https, `${twi.user.screen_name}-${twi.id_str}--`)
+                        .then(path => {
+                        messageChain.push(mirai_1.MiraiMessage.Image('', '', baseName(path)));
+                    })));
                 }
                 // append URLs, if any
             }
@@ -234,7 +224,7 @@ class Webshot extends CallableInstance {
                             .filter(urlObj => urlObj.indices[0] < originTwi.display_text_range[1])
                             .map(urlObj => urlObj.expanded_url);
                         if (urls.length) {
-                            messageChain.push(message_1.default.Plain(urls.join('\n')));
+                            messageChain.push(mirai_1.MiraiMessage.Plain(urls.join('\n')));
                         }
                     });
                 }

+ 9 - 3
src/mirai.ts

@@ -1,5 +1,6 @@
 import axios from 'axios';
 import Mirai, { MessageType } from 'mirai-ts';
+import Message from 'mirai-ts/dist/message';
 
 import command from './helper';
 import { getLogger } from './loggers';
@@ -22,12 +23,15 @@ const ChatTypeMap: Record<MessageType.ChatMessageType, ChatType> = {
   TempMessage: ChatType.Temp,
 };
 
+export type MessageChain = MessageType.MessageChain;
+export const MiraiMessage = Message;
+
 export default class {
 
   private botInfo: IQQProps;
   public bot: Mirai;
 
-  public sendTo = (subscriber: IChat, msg) =>
+  public sendTo = (subscriber: IChat, msg: string | MessageChain) =>
     (() => {
       switch (subscriber.chatType) {
         case 'group':
@@ -40,8 +44,10 @@ export default class {
       logger.info(`pushing data to ${subscriber.chatID} was successful, response:`);
       logger.info(response);
     })
-    .catch(reason =>
-      logger.error(`error pushing data to ${subscriber.chatID}, reason: ${reason}`))
+    .catch(reason => {
+      logger.error(`error pushing data to ${subscriber.chatID}, reason: ${reason}`);
+      throw Error(reason);
+    })
 
   private initBot = () => {
     this.bot = new Mirai({

+ 14 - 3
src/twitter.ts

@@ -3,7 +3,7 @@ import * as path from 'path';
 import * as Twitter from 'twitter';
 
 import { getLogger } from './loggers';
-import QQBot from './mirai';
+import QQBot, { MessageChain, MiraiMessage as Message } from './mirai';
 import Webshot from './webshot';
 
 interface IWorkerOption {
@@ -113,7 +113,7 @@ export default class {
               logger.warn(`error on fetching tweets for ${lock.feed[lock.workon]}: ${JSON.stringify(error)}`);
               lock.threads[lock.feed[lock.workon]].subscribers.forEach(subscriber => {
                 logger.info(`sending notfound message of ${lock.feed[lock.workon]} to ${JSON.stringify(subscriber)}`);
-                this.bot.sendTo(subscriber, `链接 ${lock.feed[lock.workon]} 指向的用户或列表不存在,请退订。`);
+                this.bot.sendTo(subscriber, `链接 ${lock.feed[lock.workon]} 指向的用户或列表不存在,请退订。`).catch();
               });
             } else {
               logger.error(`unhandled error on fetching tweets for ${lock.feed[lock.workon]}: ${JSON.stringify(error)}`);
@@ -138,7 +138,18 @@ export default class {
       return (this.webshot as any)(tweets, msg => {
         lock.threads[lock.feed[lock.workon]].subscribers.forEach(subscriber => {
           logger.info(`pushing data of thread ${lock.feed[lock.workon]} to ${JSON.stringify(subscriber)}`);
-          this.bot.sendTo(subscriber, msg);
+          this.bot.sendTo(subscriber, msg)
+          .catch(reason => { // workaround for https://github.com/mamoe/mirai/issues/194
+            if (typeof(msg) !== 'string') {
+              logger.warn(`retry sending to ${subscriber.chatID}`);
+              (msg as MessageChain).forEach((message, pos) => {
+                if (message.type === 'Image') {
+                  msg[pos] = Message.Plain(`[失败的图片:${message.path}]`);
+                }
+              });
+              this.bot.sendTo(subscriber, msg).catch();
+            }
+          });
         });
       }, this.webshotDelay)
         .then(() => {

+ 12 - 14
src/webshot.ts

@@ -2,19 +2,18 @@ import axios from 'axios';
 import * as CallableInstance from 'callable-instance';
 import { createWriteStream, existsSync, mkdirSync } from 'fs';
 import { XmlEntities } from 'html-entities';
-import { MessageType } from 'mirai-ts';
-import Message from 'mirai-ts/dist/message';
 import { PNG } from 'pngjs';
 import * as puppeteer from 'puppeteer';
 import { Browser } from 'puppeteer';
 import { Stream } from 'stream';
 
 import { getLogger } from './loggers';
+import { MessageChain, MiraiMessage as Message } from './mirai';
 
-const writeOutTo = async (path: string, data: PNG | Stream) => {
-  await new Promise(resolve => data.pipe(createWriteStream(path)).on('close', resolve));
-  return path;
-};
+const writeOutTo = (path: string, data: PNG | Stream) =>
+  new Promise<string>(resolve => {
+    data.pipe(createWriteStream(path)).on('close', () => resolve(path));
+  });
 
 const xmlEntities = new XmlEntities();
 
@@ -29,8 +28,6 @@ const logger = getLogger('webshot');
 const mkdirP = dir => { if (!existsSync(dir)) mkdirSync(dir, {recursive: true}); };
 const baseName = path => path.split(/[/\\]/).slice(-1)[0];
 
-type MessageChain = MessageType.MessageChain;
-
 class Webshot extends CallableInstance<[number], Promise<void>> {
 
   private browser: Browser;
@@ -227,12 +224,13 @@ class Webshot extends CallableInstance<[number], Promise<void>> {
       // fetch extra images
       } else if (1 - this.mode % 2) {
         if (originTwi.extended_entities) {
-          promise = promise.then(() => originTwi.extended_entities.media.forEach(media => {
-            this.fetchImage(media.media_url_https, `${twi.user.screen_name}-${twi.id_str}--`)
-            .then(path =>
-              messageChain.push(Message.Image('', '', baseName(path)))
-            );
-          }));
+          originTwi.extended_entities.media.forEach(media =>
+            promise = promise.then(() =>
+              this.fetchImage(media.media_url_https, `${twi.user.screen_name}-${twi.id_str}--`)
+              .then(path => {
+                messageChain.push(Message.Image('', '', baseName(path)));
+              })
+          ));
         }
 
       // append URLs, if any