瀏覽代碼

Merge branch 'koishi-guild' into mediaonly-koishi-guild

Mike L 2 年之前
父節點
當前提交
6ef87f4ae8
共有 10 個文件被更改,包括 898 次插入761 次删除
  1. 12 33
      dist/command.js
  2. 125 106
      dist/koishi.js
  3. 206 141
      dist/twitter.js
  4. 59 80
      dist/webshot.js
  5. 13 12
      package.json
  6. 10 28
      src/command.ts
  7. 132 117
      src/koishi.ts
  8. 17 11
      src/model.d.ts
  9. 258 156
      src/twitter.ts
  10. 66 77
      src/webshot.ts

+ 12 - 33
dist/command.js

@@ -28,49 +28,28 @@ function parseCmd(message) {
     };
 }
 exports.parseCmd = parseCmd;
-function parseLink(link) {
-    let match = /twitter.com\/([^\/?#]+)\/lists\/([^\/?#]+)/.exec(link) ||
-        /^([^\/?#]+)\/([^\/?#]+)$/.exec(link);
-    if (match)
-        return [match[1], `/lists/${match[2]}`];
-    match =
-        /twitter.com\/([^\/?#]+)\/status\/(\d+)/.exec(link);
-    if (match)
-        return [match[1], `/status/${match[2]}`];
-    match =
-        /twitter.com\/([^\/?#]+)/.exec(link) ||
-            /^([^\/?#]+)$/.exec(link);
-    if (match)
-        return [match[1]];
-    return;
-}
-function linkBuilder(userName, more = '') {
-    if (!userName)
-        return;
-    return `https://twitter.com/${userName}${more}`;
-}
 function linkFinder(checkedMatch, chat, lock) {
     var _a;
-    const normalizedLink = linkBuilder(twitter_1.ScreenNameNormalizer.normalize(checkedMatch[0]), (_a = checkedMatch[1]) === null || _a === void 0 ? void 0 : _a.toLowerCase());
+    const normalizedLink = (0, twitter_1.linkBuilder)(twitter_1.ScreenNameNormalizer.normalize(checkedMatch[0]), (_a = checkedMatch[1]) === null || _a === void 0 ? void 0 : _a.toLowerCase());
     const link = Object.keys(lock.threads).find(realLink => normalizedLink === realLink.replace(/\/@/, '/').toLowerCase());
     if (!link)
         return [null, -1];
-    const index = lock.threads[link].subscribers.findIndex(({ chatID, chatType }) => chat.chatID === chatID && chat.chatType === chatType);
+    const index = lock.threads[link].subscribers.findIndex(({ chatID, chatType }) => chat.chatID.toString() === chatID.toString() && chat.chatType === chatType);
     return [link, index];
 }
 function sub(chat, args, reply, lock, lockfile) {
-    if (chat.chatType === "temp") {
+    if (chat.chatType === 'temp') {
         return reply('请先添加机器人为好友。');
     }
     if (args.length === 0) {
         return reply('找不到要订阅媒体推文的链接。');
     }
-    const match = parseLink(args[0]);
+    const match = (0, twitter_1.parseLink)(args[0]);
     if (!match) {
         return reply(`订阅链接格式错误:
 示例:
 https://twitter.com/Saito_Shuka
-https://twitter.com/rikakomoe/lists/lovelive
+https://twitter.com/_satou_riko/lists/lovelive
 https://twitter.com/TomoyoKurosawa/status/1294613494860361729`);
     }
     let offset = '0';
@@ -103,12 +82,12 @@ https://twitter.com/TomoyoKurosawa/status/1294613494860361729`);
         return subscribeTo(realLink);
     const [rawUserName, more] = match;
     if (rawUserName.toLowerCase() === 'i' && /lists\/(\d+)/.exec(more)) {
-        return subscribeTo(linkBuilder('i', more), { addNew: true });
+        return subscribeTo((0, twitter_1.linkBuilder)('i', more), { addNew: true });
     }
     twitter_1.ScreenNameNormalizer.normalizeLive(rawUserName).then(userName => {
         if (!userName)
             return reply(`找不到用户 ${rawUserName.replace(/^@?(.*)$/, '@$1')}。`);
-        const link = linkBuilder(userName, more);
+        const link = (0, twitter_1.linkBuilder)(userName, more);
         const msg = (offset === '0') ?
             undefined :
             `已为此聊天订阅 ${link} 的媒体动态并回溯到此动态 ID(含)之后的第一条媒体动态。
@@ -118,11 +97,11 @@ https://twitter.com/TomoyoKurosawa/status/1294613494860361729`);
 }
 exports.sub = sub;
 function unsubAll(chat, args, reply, lock, lockfile) {
-    if (chat.chatType === "temp") {
+    if (chat.chatType === 'temp') {
         return reply('请先添加机器人为好友。');
     }
     Object.entries(lock.threads).forEach(([link, { subscribers }]) => {
-        const index = subscribers.indexOf(chat);
+        const index = subscribers.findIndex(({ chatID, chatType }) => chat.chatID.toString() === chatID.toString() && chat.chatType === chatType);
         if (index === -1)
             return;
         subscribers.splice(index, 1);
@@ -133,13 +112,13 @@ function unsubAll(chat, args, reply, lock, lockfile) {
 }
 exports.unsubAll = unsubAll;
 function unsub(chat, args, reply, lock, lockfile) {
-    if (chat.chatType === "temp") {
+    if (chat.chatType === 'temp') {
         return reply('请先添加机器人为好友。');
     }
     if (args.length === 0) {
         return reply('找不到要退订媒体推文的链接。');
     }
-    const match = parseLink(args[0]);
+    const match = (0, twitter_1.parseLink)(args[0]);
     if (!match) {
         return reply('链接格式有误。');
     }
@@ -155,7 +134,7 @@ function unsub(chat, args, reply, lock, lockfile) {
 }
 exports.unsub = unsub;
 function list(chat, _, reply, lock) {
-    if (chat.chatType === "temp") {
+    if (chat.chatType === 'temp') {
         return reply('请先添加机器人为好友。');
     }
     const links = [];

+ 125 - 106
dist/koishi.js

@@ -11,25 +11,36 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
 Object.defineProperty(exports, "__esModule", { value: true });
 exports.Message = void 0;
 const koishi_1 = require("koishi");
-require("koishi-adapter-onebot");
+const plugin_adapter_onebot_1 = require("@koishijs/plugin-adapter-onebot");
 const command_1 = require("./command");
 const loggers_1 = require("./loggers");
-const utils_1 = require("./utils");
 const logger = (0, loggers_1.getLogger)('qqbot');
-const cqUrlFix = (factory) => (...args) => factory(...args).replace(/(?<=\[CQ:.*)url=(?=(base64|file|https?):\/\/)/, 'file=');
 exports.Message = {
-    Image: cqUrlFix(koishi_1.segment.image),
-    Video: cqUrlFix(koishi_1.segment.video),
-    Voice: cqUrlFix(koishi_1.segment.audio),
-    ellipseBase64: (msg) => msg.replace(/(?<=\[CQ:.*base64:\/\/).*?(,|\])/g, '...$1'),
+    Image: koishi_1.segment.image,
+    Video: koishi_1.segment.video,
+    Voice: koishi_1.segment.audio,
     separateAttachment: (msg) => {
         const attachments = [];
-        const message = msg.replace(/\[CQ:(video|record),.*?\]/g, code => {
+        const message = msg.replace(/<(video|record) .*?\/>/g, code => {
             attachments.push(code);
             return '';
         });
         return { message, attachments };
     },
+    parseCQCode: (cqStr) => plugin_adapter_onebot_1.CQCode.parse(cqStr).map(seg => {
+        if (typeof seg.attrs.file === 'string') {
+            seg.attrs.url = seg.attrs.file;
+            delete seg.attrs.file;
+        }
+        return seg;
+    }).join(''),
+    toCQCode: (segStr) => koishi_1.segment.parse(segStr).map(seg => {
+        if (typeof seg.attrs.url === 'string') {
+            seg.attrs.file = seg.attrs.url;
+            delete seg.attrs.url;
+        }
+        return (0, plugin_adapter_onebot_1.CQCode)(seg.type, seg.attrs);
+    }).join(''),
 };
 class default_1 {
     constructor(opt) {
@@ -56,169 +67,168 @@ class default_1 {
             if (wasEmpty)
                 this.next(type, id);
         };
+        this.getSender = ({ chatID, chatType }) => (msg) => (chatType === 'guild' ? this.sendToChannel :
+            chatType === 'group' ? this.sendToGroup :
+                this.sendToUser)(chatID.toString(), msg);
         this.getChat = (session) => __awaiter(this, void 0, void 0, function* () {
+            if (session.type !== 'message')
+                return null;
+            if (session.subsubtype === 'guild') {
+                return {
+                    chatID: `${session.onebot.guild_id}:${session.onebot.channel_id}`,
+                    chatType: 'guild',
+                };
+            }
             switch (session.subtype) {
                 case 'private':
-                    if (session.sender.groupId) {
+                    const { group_id: groupId } = session.onebot.sender;
+                    if (groupId) {
                         const friendList = yield session.bot.getFriendList();
                         if (!friendList.some(friendItem => friendItem.userId === session.userId)) {
-                            this.tempSenders[session.userId] = session.sender.groupId;
+                            this.tempSenders[session.userId] = groupId;
                             return {
                                 chatID: {
                                     qq: Number(session.userId),
-                                    group: Number(session.sender.groupId),
+                                    group: Number(groupId),
                                     toString: () => session.userId,
                                 },
-                                chatType: "temp",
+                                chatType: 'temp',
                             };
                         }
                     }
                     return {
                         chatID: Number(session.userId),
-                        chatType: "private",
+                        chatType: 'private',
                     };
                 case 'group':
                     return {
-                        chatID: Number(session.groupId),
-                        chatType: "group",
+                        chatID: Number(session.guildId),
+                        chatType: 'group',
                     };
             }
         });
+        this.sendToChannel = (guildChannel, message) => new Promise((resolve, reject) => {
+            const [guildID, channelID] = guildChannel.split(':');
+            this.enqueue('guild', guildChannel, () => this.bot.guildBot.sendMessage(channelID, message, guildID)
+                .then(([response]) => resolve(response)).catch(reject));
+        });
         this.sendToGroup = (groupID, message) => new Promise((resolve, reject) => {
-            this.enqueue('group', groupID, () => this.bot.sendMessage(groupID, message).then(resolve).catch(reject));
+            this.enqueue('group', groupID, () => this.bot.sendMessage(groupID, message)
+                .then(([response]) => resolve(response)).catch(reject));
         });
         this.sendToUser = (userID, message) => new Promise((resolve, reject) => {
-            this.enqueue('private', userID, () => this.bot.sendPrivateMessage(userID, message).then(resolve).catch(reject));
+            this.enqueue('private', userID, () => this.bot.sendPrivateMessage(userID, message)
+                .then(([response]) => resolve(response)).catch(reject));
         });
-        this.sendTo = (subscriber, messageChain, noErrors = false) => Promise.all((splitted => [splitted.message, ...splitted.attachments])(exports.Message.separateAttachment(messageChain)).map(msg => {
-            switch (subscriber.chatType) {
-                case 'group':
-                    return this.sendToGroup(subscriber.chatID.toString(), msg);
-                case 'private':
-                    return this.sendToUser(subscriber.chatID.toString(), msg);
-                case 'temp':
-                    return this.sendToUser(subscriber.chatID.qq.toString(), msg);
-            }
-        }))
+        this.sendTo = (subscriber, messageChain, noErrors = false) => Promise.all((splitted => [splitted.message, ...splitted.attachments])(exports.Message.separateAttachment(messageChain)).map(this.getSender(subscriber)))
             .then(response => {
             if (response === undefined)
                 return;
             logger.info(`pushing data to ${JSON.stringify(subscriber.chatID)} was successful, response: ${response}`);
         })
             .catch(reason => {
-            logger.error(exports.Message.ellipseBase64(`error pushing data to ${JSON.stringify(subscriber.chatID)}, reason: ${reason}`));
+            logger.error(`error pushing data to ${JSON.stringify(subscriber.chatID)}, reason: ${reason}`);
             if (!noErrors)
                 throw reason instanceof Error ? reason : Error(reason);
         });
         this.initBot = () => {
-            this.app = new koishi_1.App({
-                type: 'onebot',
-                server: `ws://${this.botInfo.host}:${this.botInfo.port}`,
-                selfId: this.botInfo.bot_id.toString(),
-                token: this.botInfo.access_token,
-                axiosConfig: {
-                    maxContentLength: Infinity,
-                },
-                processMessage: msg => msg.trim(),
-            });
+            this.app = new koishi_1.App();
+            this.app.plugin(plugin_adapter_onebot_1.default, this.config);
             this.app.on('friend-request', (session) => __awaiter(this, void 0, void 0, function* () {
                 const userString = `${session.username}(${session.userId})`;
-                let groupId;
-                let groupString;
-                if (session.username in this.tempSenders)
-                    groupId = this.tempSenders[session.userId].toString();
                 logger.debug(`detected new friend request event: ${userString}`);
-                return session.bot.getGroupList().then(groupList => {
-                    if (groupList.some(groupItem => {
-                        const test = groupItem.groupId === groupId;
-                        if (test)
-                            groupString = `${groupItem.groupName}(${groupId})`;
-                        return test;
-                    })) {
-                        return session.bot.handleFriendRequest(session.messageId, true)
-                            .then(() => { logger.info(`accepted friend request from ${userString} (from group ${groupString})`); })
-                            .catch(error => { logger.error(`error accepting friend request from ${userString}, error: ${error}`); });
+                try {
+                    const isTemp = session.username in this.tempSenders;
+                    const { guildId, guildName } = isTemp ?
+                        yield session.bot.getGuild(this.tempSenders[session.userId].toString()) :
+                        (yield session.bot.getGuildList()).find(({ guildId }) => __awaiter(this, void 0, void 0, function* () {
+                            try {
+                                return yield this.bot.getGuildMember(guildId, session.userId);
+                            }
+                            catch (_b) { }
+                        }));
+                    try {
+                        const groupString = `${guildName}(${guildId})`;
+                        yield session.bot.handleFriendRequest(session.messageId, true);
+                        logger.info(`accepted friend request from ${userString} (${isTemp ? 'from' : 'found in'} group ${groupString})`);
                     }
-                    (0, utils_1.chainPromises)(groupList.map(groupItem => (done) => Promise.resolve(done ||
-                        this.bot.getGroupMember(groupItem.groupId, session.userId).then(() => {
-                            groupString = `${groupItem.groupName}(${groupItem.groupId})`;
-                            return session.bot.handleFriendRequest(session.messageId, true)
-                                .then(() => { logger.info(`accepted friend request from ${userString} (found in group ${groupString})`); })
-                                .catch(error => { logger.error(`error accepting friend request from ${userString}, error: ${error}`); })
-                                .then(() => true);
-                        }).catch(() => false)))).then(done => {
-                        if (done)
-                            return;
-                        logger.warn(`received friend request from ${userString} (stranger)`);
-                        logger.warn('please manually accept this friend request');
-                    });
-                });
+                    catch (error) {
+                        logger.error(`error accepting friend request from ${userString}, error: ${error}`);
+                    }
+                }
+                catch (_a) {
+                    logger.warn(`received friend request from ${userString} (stranger)`);
+                    logger.warn('please manually accept this friend request');
+                }
             }));
-            this.app.on('group-request', (session) => __awaiter(this, void 0, void 0, function* () {
+            this.app.on('guild-request', (session) => __awaiter(this, void 0, void 0, function* () {
                 const userString = `${session.username}(${session.userId})`;
-                const groupString = `${session.groupName}(${session.groupId})`;
+                const groupString = `${session.guildName}(${session.guildId})`;
                 logger.debug(`detected group invitation event: ${groupString}}`);
-                return session.bot.getFriendList().then(friendList => {
-                    if (friendList.some(friendItem => friendItem.userId = session.userId)) {
-                        return session.bot.handleGroupRequest(session.messageId, true)
-                            .then(() => { logger.info(`accepted group invitation from ${userString} (friend)`); })
-                            .catch(error => { logger.error(`error accepting group invitation from ${userString}, error: ${error}`); });
+                const friendList = yield session.bot.getFriendList();
+                if (friendList.some(friendItem => friendItem.userId = session.userId)) {
+                    try {
+                        session.bot.handleGuildRequest(session.messageId, true);
+                        logger.info(`accepted group invitation from ${userString} (friend)`);
                     }
-                    logger.warn(`received group invitation from ${userString} (stranger)`);
-                    logger.warn('please manually accept this group invitation');
-                });
+                    catch (error) {
+                        logger.error(`error accepting group invitation from ${userString}, error: ${error}`);
+                    }
+                }
+                logger.warn(`received group invitation from ${userString} (stranger)`);
+                logger.warn('please manually accept this group invitation');
             }));
             this.app.middleware((session) => __awaiter(this, void 0, void 0, function* () {
                 const chat = yield this.getChat(session);
+                let userString = `${session.username}(${session.userId})`;
+                if (chat.chatType === 'temp') {
+                    const group = yield session.bot.getGuild(chat.chatID.group.toString());
+                    userString += ` (from group ${group.guildName}(${group.guildId}))`;
+                }
                 const cmdObj = (0, command_1.parseCmd)(session.content);
-                const reply = (msg) => __awaiter(this, void 0, void 0, function* () {
-                    const userString = `${session.username}(${session.userId})`;
-                    return (chat.chatType === "group" ? this.sendToGroup : this.sendToUser)(chat.chatID.toString(), msg)
-                        .catch(error => { logger.error(`error replying to message from ${userString}, error: ${error}`); });
+                const reply = (msg) => this.getSender(chat)(msg).catch(error => {
+                    if (chat.chatType === 'temp') {
+                        return logger.info(`ignored error while replying to ${userString}`);
+                    }
+                    logger.error(`error replying to message from ${userString}, error: ${error}`);
                 });
                 switch (cmdObj.cmd) {
-                    case 'twitterpic_view':
-                    case 'twitterpic_get':
+                    case 'twipic_view':
                         (0, command_1.view)(chat, cmdObj.args, reply);
                         break;
-                    case 'twitterpic_resendlast':
+                    case 'twipic_resendlast':
                         (0, command_1.resendLast)(chat, cmdObj.args, reply);
                         break;
-                    case 'twitterpic_query':
-                    case 'twitterpic_gettimeline':
+                    case 'twipic_query':
                         (0, command_1.query)(chat, cmdObj.args, reply);
                         break;
-                    case 'twitterpic_sub':
-                    case 'twitterpic_subscribe':
+                    case 'twipic_sub':
                         this.botInfo.sub(chat, cmdObj.args, reply);
                         break;
-                    case 'twitterpic_unsub':
-                    case 'twitterpic_unsubscribe':
+                    case 'twipic_unsub':
                         this.botInfo.unsub(chat, cmdObj.args, reply);
                         break;
-                    case 'twitterpic_unsuball':
-                    case 'bye':
+                    case 'twipic_unsuball':
                         this.botInfo.unsubAll(chat, cmdObj.args, reply);
                         break;
-                    case 'ping':
-                    case 'twitterpic':
+                    case 'twipic_listsub':
                         this.botInfo.list(chat, cmdObj.args, reply);
                         break;
                     case 'help':
-                        if (cmdObj.args.length === 0) {
+                        if (cmdObj.args[0] === 'twipic') {
                             reply(`推特媒体推文搬运机器人:
-/twitterpic - 查询当前聊天中的媒体推文订阅
-/twitterpic_sub[scribe]〈链接|用户名〉- 订阅 Twitter 媒体推文搬运
-/twitterpic_unsub[scribe]〈链接|用户名〉- 退订 Twitter 媒体推文搬运
-/twitterpic_view〈链接|表达式〉[{force|refresh}={on|off}] - 查看推文(可选强制重新载入)
-/twitterpic_resendlast〈用户名〉- 强制重发该用户最后一条媒体推文
-/twitterpic_query〈链接|用户名〉[参数列表...] - 查询时间线(详见 /help twitterpic_query)\
-${chat.chatType === "temp" ?
+/twipic_listsub - 查询当前聊天中的媒体推文订阅
+/twipic_sub〈链接|用户名〉- 订阅 Twitter 媒体推文搬运
+/twipic_unsub〈链接|用户名〉- 退订 Twitter 媒体推文搬运
+/twipic_view〈链接|表达式〉[{force|refresh}={on|off}] - 查看推文(可选强制重新载入)
+/twipic_resendlast〈用户名〉- 强制重发该用户最后一条媒体推文
+/twipic_query〈链接|用户名〉[参数列表...] - 查询时间线(详见 /help twipic_query)\
+${chat.chatType === 'temp' ?
                                 '\n(当前游客模式下无法使用订阅功能,请先添加本账号为好友。)' : ''}`);
                         }
-                        else if (cmdObj.args[0] === 'twitterpic_query') {
+                        else if (cmdObj.args[0] === 'twipic_query') {
                             reply(`查询时间线中的媒体推文:
-/twitterpic_query〈链接|用户名〉[〈参数 1〉=〈值 1〉〈参数 2〉=〈值 2〉...]
+/twipic_query〈链接|用户名〉[〈参数 1〉=〈值 1〉〈参数 2〉=〈值 2〉...]
 
 参数列表(方框内全部为可选,留空则为默认):
     count:查询数量上限(类型:非零整数,最大值正负 50)[默认值:10]
@@ -231,7 +241,7 @@ ${chat.chatType === "temp" ?
 推荐的日期格式:2012-12-22 12:22 UTC+2 (日期和时间均为可选,可分别添加)
 count 为正时,从新向旧查询;为负时,从旧向新查询
 count 与 since/until 并用时,取二者中实际查询结果较少者
-例子:/twitterpic_query RiccaTachibana count=5 since="2019-12-30\
+例子:/twipic_query RiccaTachibana count=5 since="2019-12-30\
  UTC+9" until="2020-01-06 UTC+8" norts=on
     从起始时间点(含)到结束时间点(不含)从新到旧获取最多 5 条媒体推文,\
 其中不包含原生转推(实际上用户只发了 1 条)`));
@@ -245,7 +255,7 @@ count 与 since/until 并用时,取二者中实际查询结果较少者
                 yield this.app.start();
             }
             catch (err) {
-                logger.error(`error connecting to bot provider at ${this.app.options.server}, will retry in 2.5s...`);
+                logger.error(`error connecting to bot provider at ${this.config.endpoint}, will retry in 2.5s...`);
                 yield (0, koishi_1.sleep)(2500);
                 yield this.listen('retry connecting...');
             }
@@ -253,10 +263,19 @@ count 与 since/until 并用时,取二者中实际查询结果较少者
         this.connect = () => __awaiter(this, void 0, void 0, function* () {
             this.initBot();
             yield this.listen();
-            this.bot = this.app.getBot('onebot');
+            this.bot = this.app.bots.find(bot => bot.selfId === this.config.selfId);
         });
         logger.warn(`Initialized koishi on ${opt.host}:${opt.port} with access_token ${opt.access_token}`);
         this.botInfo = opt;
     }
+    get config() {
+        return {
+            protocol: 'ws',
+            endpoint: `ws://${this.botInfo.host}:${this.botInfo.port}`,
+            selfId: this.botInfo.bot_id.toString(),
+            token: this.botInfo.access_token,
+        };
+    }
+    ;
 }
 exports.default = default_1;

+ 206 - 141
dist/twitter.js

@@ -9,28 +9,54 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
     });
 };
 Object.defineProperty(exports, "__esModule", { value: true });
-exports.sendTimeline = exports.sendTweet = exports.ScreenNameNormalizer = void 0;
+exports.sendTimeline = exports.sendTweet = exports.ScreenNameNormalizer = exports.linkBuilder = exports.parseLink = void 0;
 const fs = require("fs");
 const path = require("path");
-const Twitter = require("twitter");
+const Twitter = require("twitter-api-v2");
 const loggers_1 = require("./loggers");
+const koishi_1 = require("./koishi");
 const redis_1 = require("./redis");
 const utils_1 = require("./utils");
 const webshot_1 = require("./webshot");
+const parseLink = (link) => {
+    let match = /twitter.com\/([^\/?#]+)\/lists\/([^\/?#]+)/.exec(link) ||
+        /^([^\/?#]+)\/([^\/?#]+)$/.exec(link);
+    if (match)
+        return [match[1], `/lists/${match[2]}`];
+    match =
+        /twitter.com\/([^\/?#]+)\/status\/(\d+)/.exec(link);
+    if (match)
+        return [match[1], `/status/${match[2]}`];
+    match =
+        /twitter.com\/([^\/?#]+)/.exec(link) ||
+            /^([^\/?#]+)$/.exec(link);
+    if (match)
+        return [match[1]];
+    return;
+};
+exports.parseLink = parseLink;
+const linkBuilder = (userName, more = '') => {
+    if (!userName)
+        return;
+    return `https://twitter.com/${userName}${more}`;
+};
+exports.linkBuilder = linkBuilder;
 class ScreenNameNormalizer {
     static normalizeLive(username) {
         return __awaiter(this, void 0, void 0, function* () {
+            username = this.normalize(username);
             if (this._queryUser) {
                 return yield this._queryUser(username)
+                    .then(userNameId => userNameId.split(':')[0])
                     .catch((err) => {
-                    if (err[0].code !== 50) {
-                        logger.warn(`error looking up user: ${err[0].message}`);
+                    if (err.title === 'Not Found Error') {
+                        logger.warn(`error looking up user: ${showApiError(err)}`);
                         return username;
                     }
                     return null;
                 });
             }
-            return this.normalize(username);
+            return username;
         });
     }
 }
@@ -73,13 +99,37 @@ const retryOnError = (doWork, onRetry) => new Promise(resolve => {
     };
     doWork().then(resolve).catch(error => retry(error, 1));
 });
+const showApiError = (err) => err.errors && err.errors[0].message || err.detail || err.stack || JSON.stringify(err);
+const toMutableConst = (o) => {
+    return o;
+};
+const v2SingleParams = toMutableConst({
+    expansions: ['attachments.media_keys', 'author_id', 'referenced_tweets.id'],
+    'tweet.fields': ['created_at', 'entities'],
+    'media.fields': ['url', 'variants', 'alt_text'],
+    'user.fields': ['id', 'name', 'username']
+});
+;
 class default_1 {
     constructor(opt) {
         this.launch = () => {
-            this.webshot = new webshot_1.default(this.wsUrl, this.mode, () => setTimeout(this.work, this.workInterval * 1000));
+            this.client.appLogin().then(client => {
+                this.client = client.readOnly;
+                this.webshot = new webshot_1.default(this.wsUrl, this.mode, () => setTimeout(this.work, this.workInterval * 1000));
+            });
+        };
+        this.queryUser = (username) => {
+            const thread = this.lock.threads[(0, exports.linkBuilder)(username)];
+            if (thread && thread.id)
+                return Promise.resolve(`${username}:${thread.id}`);
+            return this.client.v2.userByUsername(username).then(({ data: { username, id }, errors }) => {
+                if (errors && errors.length > 0)
+                    throw errors[0];
+                if (thread)
+                    thread.id = id;
+                return `${username}:${id}`;
+            });
         };
-        this.queryUser = (username) => this.client.get('users/show', { screen_name: username })
-            .then((user) => user.screen_name);
         this.queryTimelineReverse = (conf) => {
             if (!conf.since)
                 return this.queryTimeline(conf);
@@ -102,49 +152,47 @@ class default_1 {
         };
         this.queryTimeline = ({ username, count, since, until, noreps, norts }) => {
             username = username.replace(/^@?(.*)$/, '@$1');
-            logger.info(`querying timeline of ${username} with config: ${JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (count && { count })), (since && { since })), (until && { until })), (noreps && { noreps })), (norts && { norts })))}`);
-            const fetchTimeline = (config = {
-                screen_name: username.slice(1),
-                trim_user: true,
-                exclude_replies: noreps !== null && noreps !== void 0 ? noreps : true,
-                include_rts: !(norts !== null && norts !== void 0 ? norts : false),
-                since_id: since,
-                max_id: until,
-                tweet_mode: 'extended',
-            }, tweets = []) => this.client.get('statuses/user_timeline', config)
-                .then((newTweets) => {
-                if (newTweets.length) {
-                    logger.debug(`fetched tweets: ${JSON.stringify(newTweets)}`);
-                    config.max_id = utils_1.BigNumOps.plus('-1', newTweets[newTweets.length - 1].id_str);
-                    logger.info(`timeline query of ${username} yielded ${newTweets.length} new tweets, next query will start at offset ${config.max_id}`);
-                    tweets.push(...newTweets.filter(tweet => tweet.extended_entities));
-                }
-                if (!newTweets.length || tweets.length >= count) {
-                    logger.info(`timeline query of ${username} finished successfully, ${tweets.length} tweets with extended entities have been fetched`);
-                    return tweets.slice(0, count);
-                }
-                return fetchTimeline(config, tweets);
+            return this.queryUser(username.slice(1)).then(userNameId => {
+                const getMore = (lastTweets = []) => {
+                    logger.info(`querying timeline of ${username} with config: ${JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (count && { count })), (since && { since })), (until && { until })), (noreps && { noreps })), (norts && { norts })))}`);
+                    return this.get('userTimeline', userNameId.split(':')[1], Object.assign(Object.assign({ expansions: ['attachments.media_keys', 'author_id'], 'tweet.fields': ['created_at'], exclude: [
+                            ...(noreps !== null && noreps !== void 0 ? noreps : true) ? ['replies'] : [],
+                            ...(norts !== null && norts !== void 0 ? norts : false) ? ['retweets'] : [],
+                        ], max_results: Math.min(Math.max(count || 0, 20), 100) }, (since && { since_id: since })), (until && { until_id: until }))).then(newTweets => {
+                        logger.info(`timeline query of ${username} yielded ${newTweets.length} new tweets`);
+                        const tweets = lastTweets.concat(newTweets.filter(({ data }) => (data.attachments || {}).media_keys));
+                        if (tweets.length < count) {
+                            until = utils_1.BigNumOps.plus('-1', newTweets.slice(-1)[0].data.id);
+                            logger.info(`starting next query at offset ${until}...`);
+                            return getMore(tweets);
+                        }
+                        logger.info(`timeline query of ${username} finished successfully, ${tweets.length} media tweets have been fetched`);
+                        return tweets.slice(0, count);
+                    });
+                };
+                return getMore();
             });
-            return fetchTimeline();
         };
-        this.workOnTweets = (tweets, sendTweets, refresh = false) => Promise.all(tweets.map(tweet => ((this.redis && !refresh) ?
-            this.redis.waitForProcess(`webshot/${tweet.id_str}`, this.webshotDelay * 4)
-                .then(() => this.redis.getContent(`webshot/${tweet.id_str}`)) :
+        this.workOnTweets = (tweets, sendTweets, refresh = false) => Promise.all(tweets.map(({ data, includes }) => ((this.redis && !refresh) ?
+            this.redis.waitForProcess(`webshot/${data.id}`, this.webshotDelay * 4)
+                .then(() => this.redis.getContent(`webshot/${data.id}`)) :
             Promise.reject())
             .then(content => {
             if (content === null)
                 throw Error();
-            logger.info(`retrieved cached webshot of tweet ${tweet.id_str} from redis database`);
+            logger.info(`retrieved cached webshot of tweet ${data.id} from redis database, message chain:`);
             const { msg, text, author } = JSON.parse(content);
-            let cacheId = tweet.id_str;
-            if (tweet.retweeted_status)
-                cacheId += `,rt:${tweet.retweeted_status.id_str}`;
-            sendTweets(cacheId, msg, text, author);
+            let cacheId = data.id;
+            const retweetRef = (data.referenced_tweets || []).find(ref => ref.type === 'retweeted');
+            if (retweetRef)
+                cacheId += `,rt:${retweetRef.id}`;
+            logger.info(JSON.stringify(koishi_1.Message.parseCQCode(msg)));
+            sendTweets(cacheId, koishi_1.Message.parseCQCode(msg), text, author);
             return null;
         })
             .catch(() => {
-            this.redis.startProcess(`webshot/${tweet.id_str}`);
-            return tweet;
+            this.redis.startProcess(`webshot/${data.id}`);
+            return { data, includes };
         }))).then(tweets => this.webshot(tweets.filter(t => t), (cacheId, msg, text, author) => {
             Promise.resolve()
                 .then(() => {
@@ -152,38 +200,35 @@ class default_1 {
                     return;
                 const [twid, rtid] = cacheId.split(',rt:');
                 logger.info(`caching webshot of tweet ${twid} to redis database`);
-                this.redis.cacheContent(`webshot/${twid}`, JSON.stringify({ msg, text, author, rtid }))
-                    .then(() => this.redis.finishProcess(`webshot/${twid}`));
+                this.redis.cacheContent(`webshot/${twid}`, JSON.stringify({ msg: koishi_1.Message.toCQCode(msg), text, author, rtid })).then(() => this.redis.finishProcess(`webshot/${twid}`));
             })
                 .then(() => sendTweets(cacheId, msg, text, author));
         }, this.webshotDelay));
-        this.getTweet = (id, sender, refresh = false) => {
-            const endpoint = 'statuses/show';
-            const config = {
-                id,
-                tweet_mode: 'extended',
-            };
-            return ((this.redis && !refresh) ?
-                this.redis.waitForProcess(`webshot/${id}`, this.webshotDelay * 4)
-                    .then(() => this.redis.getContent(`webshot/${id}`))
-                    .then(content => {
-                    if (content === null)
-                        throw Error();
-                    const { rtid } = JSON.parse(content);
-                    return { id_str: id, retweeted_status: rtid ? { id_str: rtid } : undefined };
-                }) :
-                Promise.reject())
-                .catch(() => this.client.get(endpoint, config))
-                .then((tweet) => {
-                if (tweet.id) {
-                    logger.debug(`api returned tweet ${JSON.stringify(tweet)} for query id=${id}`);
-                }
-                else {
-                    logger.debug(`skipped querying api as this tweet has been cached`);
-                }
-                return this.workOnTweets([tweet], sender, refresh);
-            });
-        };
+        this.getTweet = (id, sender, refresh = false) => ((this.redis && !refresh) ?
+            this.redis.waitForProcess(`webshot/${id}`, this.webshotDelay * 4)
+                .then(() => this.redis.getContent(`webshot/${id}`))
+                .then(content => {
+                if (content === null)
+                    throw Error();
+                const { rtid } = JSON.parse(content);
+                return { data: Object.assign({ id }, rtid && { referenced_tweets: [{ type: 'retweeted', id: rtid }] }) };
+            }) :
+            Promise.reject())
+            .catch(() => this.client.v2.singleTweet(id, v2SingleParams))
+            .then((tweet) => {
+            if (tweet.data.text) {
+                logger.debug(`api returned tweet ${JSON.stringify(tweet)} for query id=${id}`);
+                const retweetRef = (tweet.data.referenced_tweets || []).find(ref => ref.type === 'retweeted');
+                if (retweetRef)
+                    return this.client.v2.singleTweet(retweetRef.id, v2SingleParams)
+                        .then(({ includes: { media } }) => (Object.assign(Object.assign({}, tweet), { includes: Object.assign(Object.assign({}, tweet.includes), { media }) })));
+            }
+            else {
+                logger.debug(`skipped querying api as this tweet has been cached`);
+            }
+            return tweet;
+        })
+            .then((tweet) => this.workOnTweets([tweet], sender, refresh));
         this.sendTweets = (config = { reportOnSkip: false, force: false }, ...to) => (id, msg, text, author) => {
             to.forEach(subscriber => {
                 const [twid, rtid] = id.split(',rt:');
@@ -217,6 +262,41 @@ class default_1 {
                 });
             });
         };
+        this.get = (type, targetId, params) => {
+            const { since_id, max_results } = params;
+            const getMore = (res) => {
+                if (res.errors && res.errors.length > 0) {
+                    const [err] = res.errors;
+                    if (!res.data)
+                        throw err;
+                    if (err.title === 'Authorization Error') {
+                        logger.warn(`non-fatal error while querying ${type} with id ${targetId}, error: ${err.detail}`);
+                    }
+                }
+                if (!res.meta.next_token ||
+                    utils_1.BigNumOps.compare(res.tweets.slice(-1)[0].id, since_id || '0') !== 1 ||
+                    !since_id && res.meta.result_count >= max_results)
+                    return res;
+                return res.fetchNext().then(getMore);
+            };
+            if (type === 'listTweets')
+                delete params.since_id;
+            return this.client.v2[type](targetId, params).then(getMore)
+                .then(({ includes, tweets }) => tweets.map((tweet) => ({
+                data: tweet,
+                includes: {
+                    media: includes.medias(tweet),
+                    users: [includes.author(tweet)]
+                }
+            })))
+                .then(tweets => Promise.all(tweets.map(tweet => {
+                const retweetRef = (tweet.data.referenced_tweets || []).find(ref => ref.type === 'retweeted');
+                if (retweetRef)
+                    return this.client.v2.singleTweet(retweetRef.id, v2SingleParams)
+                        .then(({ includes: { media } }) => (Object.assign(Object.assign({}, tweet), { includes: Object.assign(Object.assign({}, tweet.includes), { media }) })));
+                return tweet;
+            })));
+        };
         this.work = () => {
             const lock = this.lock;
             if (this.workInterval < 1)
@@ -242,65 +322,49 @@ class default_1 {
             const currentFeed = lock.feed[lock.workon];
             logger.debug(`pulling feed ${currentFeed}`);
             const promise = new Promise(resolve => {
-                let match = /https:\/\/twitter.com\/([^\/]+)\/lists\/([^\/]+)/.exec(currentFeed);
-                let config;
+                let job = Promise.resolve();
+                let id = lock.threads[currentFeed].id;
                 let endpoint;
+                let match = /https:\/\/twitter.com\/([^\/]+)\/lists\/([^\/]+)/.exec(currentFeed);
                 if (match) {
+                    endpoint = 'listTweets';
                     if (match[1] === 'i') {
-                        config = {
-                            list_id: match[2],
-                            tweet_mode: 'extended',
-                        };
+                        id = match[2];
                     }
-                    else {
-                        config = {
+                    else if (id === undefined) {
+                        job = job.then(() => this.client.v1.list({
                             owner_screen_name: match[1],
                             slug: match[2],
-                            tweet_mode: 'extended',
-                        };
+                        })).then(({ id_str }) => {
+                            lock.threads[currentFeed].id = id = id_str;
+                        });
                     }
-                    endpoint = 'lists/statuses';
                 }
                 else {
                     match = /https:\/\/twitter.com\/([^\/]+)/.exec(currentFeed);
                     if (match) {
-                        config = {
-                            screen_name: match[1],
-                            exclude_replies: false,
-                            tweet_mode: 'extended',
-                        };
-                        endpoint = 'statuses/user_timeline';
-                    }
-                }
-                if (endpoint) {
-                    const offset = lock.threads[currentFeed].offset;
-                    config.include_rts = false;
-                    if (offset > 0)
-                        config.since_id = offset;
-                    if (offset < -1)
-                        config.max_id = offset.slice(1);
-                    const getMore = (lastTweets = []) => this.client.get(endpoint, config, (error, tweets) => {
-                        if (error) {
-                            if (error instanceof Array && error.length > 0 && error[0].code === 34) {
-                                logger.warn(`error on fetching tweets for ${currentFeed}: ${JSON.stringify(error)}`);
-                                lock.threads[currentFeed].subscribers.forEach(subscriber => {
-                                    logger.info(`sending notfound message of ${currentFeed} to ${JSON.stringify(subscriber)}`);
-                                    this.bot.sendTo(subscriber, `链接 ${currentFeed} 指向的用户或列表不存在,请退订。`).catch();
-                                });
-                            }
-                            else {
-                                logger.error(`unhandled error on fetching tweets for ${currentFeed}: ${JSON.stringify(error)}`);
-                            }
+                        endpoint = 'userTimeline';
+                        if (id === undefined) {
+                            job = job.then(() => this.queryUser(match[1].replace(/^@?(.*)$/, '$1'))).then(userNameId => {
+                                lock.threads[currentFeed].id = id = userNameId.split(':')[1];
+                            });
                         }
-                        if (!(tweets instanceof Array) || tweets.length === 0)
-                            return resolve(lastTweets);
-                        if (offset <= 0)
-                            return resolve(lastTweets.concat(tweets));
-                        config.max_id = utils_1.BigNumOps.plus(tweets.slice(-1)[0].id_str, '-1');
-                        getMore(lastTweets.concat(tweets));
-                    });
-                    getMore();
+                    }
                 }
+                const offset = lock.threads[currentFeed].offset;
+                job.then(() => this.get(endpoint, id, Object.assign(Object.assign(Object.assign(Object.assign({}, v2SingleParams), { max_results: 20, exclude: ['retweets'] }), (offset > 0) && { since_id: offset }), (offset < -1) && { until_id: offset.slice(1) }))).catch((err) => {
+                    if (err.title === 'Not Found Error') {
+                        logger.warn(`error on fetching tweets for ${currentFeed}: ${showApiError(err)}`);
+                        lock.threads[currentFeed].subscribers.forEach(subscriber => {
+                            logger.info(`sending notfound message of ${currentFeed} to ${JSON.stringify(subscriber)}`);
+                            this.bot.sendTo(subscriber, `链接 ${currentFeed} 指向的用户或列表不存在,请退订。`).catch();
+                        });
+                    }
+                    else {
+                        logger.error(`unhandled error on fetching tweets for ${currentFeed}: ${showApiError(err)}`);
+                    }
+                    return [];
+                }).then(resolve);
             });
             promise.then((tweets) => {
                 logger.debug(`api returned ${JSON.stringify(tweets)} for feed ${currentFeed}`);
@@ -314,11 +378,15 @@ class default_1 {
                     updateDate();
                     return;
                 }
-                const topOfFeed = tweets[0].id_str;
+                const currentUser = tweets[0].includes.users.find(user => user.id === currentThread.id);
+                if (currentUser.username !== (0, exports.parseLink)(currentFeed)[1]) {
+                    lock.feed[lock.workon] = (0, exports.linkBuilder)(currentUser.username);
+                }
+                const topOfFeed = tweets[0].data.id;
                 logger.info(`current offset: ${currentThread.offset}, current top of feed: ${topOfFeed}`);
-                const bottomOfFeed = tweets[tweets.length - 1].id_str;
+                const bottomOfFeed = tweets.slice(-1)[0].data.id;
                 const updateOffset = () => setOffset(topOfFeed);
-                tweets = tweets.filter(twi => twi.extended_entities);
+                tweets = tweets.filter(({ data }) => (data.attachments || {}).media_keys);
                 logger.info(`found ${tweets.length} tweets with extended entities`);
                 if (currentThread.offset === '-1') {
                     updateOffset();
@@ -351,12 +419,10 @@ class default_1 {
                 }, timeout);
             });
         };
-        this.client = new Twitter({
-            consumer_key: opt.consumerKey,
-            consumer_secret: opt.consumerSecret,
-            access_token_key: opt.accessTokenKey,
-            access_token_secret: opt.accessTokenSecret,
-        });
+        this.client = new Twitter.TwitterApi({
+            appKey: opt.consumerKey,
+            appSecret: opt.consumerSecret,
+        }).readOnly;
         this.lockfile = opt.lockfile;
         this.lock = opt.lock;
         this.workInterval = opt.workInterval;
@@ -374,16 +440,16 @@ class default_1 {
                 count: 1 - Number(match[1]),
                 noreps: { on: true, off: false }[match[3].replace(/.*,noreps=([^,]*).*/, '$1')],
                 norts: { on: true, off: false }[match[3].replace(/.*,norts=([^,]*).*/, '$1')],
-            }).then(tweets => tweets.slice(-1)[0].id_str);
+            }).then(tweets => tweets.slice(-1)[0].data.id);
             (match ? query() : Promise.resolve(idOrQuery))
                 .then((id) => this.getTweet(id, this.sendTweets({ sourceInfo: `tweet ${id}`, reportOnSkip: true, force: forceRefresh }, receiver), forceRefresh))
                 .catch((err) => {
-                var _a;
-                if (((_a = err[0]) === null || _a === void 0 ? void 0 : _a.code) === 34)
+                if (err.title !== 'Not Found Error') {
+                    logger.warn(`error retrieving tweet: ${showApiError(err)}`);
+                    this.bot.sendTo(receiver, `获取推文时出现错误:${showApiError(err)}`);
+                }
+                if (err.resource_type === 'user') {
                     return this.bot.sendTo(receiver, `找不到用户 ${match[2].replace(/^@?(.*)$/, '@$1')}。`);
-                if (err[0].code !== 144) {
-                    logger.warn(`error retrieving tweet: ${err[0].message}`);
-                    this.bot.sendTo(receiver, `获取推文时出现错误:${err[0].message}`);
                 }
                 this.bot.sendTo(receiver, '找不到请求的推文,它可能已被删除。');
             });
@@ -398,19 +464,18 @@ class default_1 {
                 noreps: { on: true, off: false }[noreps],
                 norts: { on: true, off: false }[norts],
             })
-                .then(tweets => (0, utils_1.chainPromises)(tweets.map(tweet => () => this.bot.sendTo(receiver, `\
-编号:${tweet.id_str}
-时间:${tweet.created_at}
-媒体:${tweet.extended_entities ? '有' : '无'}
-正文:\n${tweet.full_text.replace(/^([\s\S\n]{50})[\s\S\n]+?( https:\/\/t.co\/.*)?$/, '$1…$2')}`))
+                .then(tweets => (0, utils_1.chainPromises)(tweets.map(({ data }) => () => this.bot.sendTo(receiver, `\
+编号:${data.id}
+时间:${data.created_at}
+媒体:${(data.attachments || {}).media_keys ? '有' : '无'}
+正文:\n${data.text.replace(/^([\s\S\n]{50})[\s\S\n]+?( https:\/\/t.co\/.*)?$/, '$1…$2')}`))
                 .concat(() => this.bot.sendTo(receiver, tweets.length ?
-                '时间线查询完毕,使用 /twitterpic_view <编号> 查看媒体推文详细内容。' :
+                '时间线查询完毕,使用 /twipic_view <编号> 查看媒体推文详细内容。' :
                 '时间线查询完毕,没有找到符合条件的媒体推文。'))))
                 .catch((err) => {
-                var _a, _b, _c;
-                if (((_a = err[0]) === null || _a === void 0 ? void 0 : _a.code) !== 34) {
-                    logger.warn(`error retrieving timeline: ${((_b = err[0]) === null || _b === void 0 ? void 0 : _b.message) || err}`);
-                    return this.bot.sendTo(receiver, `获取时间线时出现错误:${((_c = err[0]) === null || _c === void 0 ? void 0 : _c.message) || err}`);
+                if (err.title !== 'Not Found Error') {
+                    logger.warn(`error retrieving timeline: ${showApiError(err)}`);
+                    return this.bot.sendTo(receiver, `获取时间线时出现错误:${showApiError(err)}`);
                 }
                 this.bot.sendTo(receiver, `找不到用户 ${username.replace(/^@?(.*)$/, '@$1')}。`);
             });

+ 59 - 80
dist/webshot.js

@@ -13,17 +13,10 @@ const loggers_1 = require("./loggers");
 const koishi_1 = require("./koishi");
 const utils_1 = require("./utils");
 const xmlEntities = new html_entities_1.XmlEntities();
-const ZHType = (type) => new class extends String {
-    constructor() {
-        super(...arguments);
-        this.type = super.toString();
-        this.toString = () => `[${super.toString()}]`;
-    }
-}(type);
 const typeInZH = {
-    photo: ZHType('图片'),
-    video: ZHType('视频'),
-    animated_gif: ZHType('GIF'),
+    photo: '图片',
+    video: '视频',
+    animated_gif: 'GIF',
 };
 const logger = (0, loggers_1.getLogger)('webshot');
 const axiosGet = (url, responseType, timeout = 150000) => {
@@ -126,11 +119,13 @@ class Webshot extends CallableInstance {
                         .then(gotoUrlAndWaitForTweet)
                         .then(() => page.addStyleTag({
                         content: 'header,#layers{display:none!important}article{background-color:transparent!important}' +
-                            '[data-testid="caret"],[role="group"],[data-testid="tweet"] [class*=" "]+:last-child>*+[class*=" "]~div{display:none}',
+                            '[data-testid="caret"],[role="group"],[dir] div>a:nth-last-child(3)~span,' +
+                            '[data-testid="tweet"] [class*=" "]+:last-child>*+[class*=" "]+[role="group"]~div{display:none!important}',
                     }))
                         .then(() => page.addStyleTag({
-                        content: '*{font-family:-apple-system,".Helvetica Neue DeskInterface",Hiragino Sans,Hiragino Sans GB,sans-serif!important}' +
-                            '*{-webkit-font-smoothing:antialiased!important}',
+                        content: '*{font-family:-apple-system,".Helvetica Neue DeskInterface",' +
+                            'Hiragino Sans,Hiragino Sans GB,sans-serif!important}' +
+                            '*{-webkit-font-smoothing:antialiased!important;-webkit-locale:"ja"}',
                     }))
                         .then(() => page.evaluate(() => {
                         const poll = setInterval(() => {
@@ -142,7 +137,7 @@ class Webshot extends CallableInstance {
                             });
                         }, 250);
                     }))
-                        .then(() => page.waitForSelector('xpath=//section/*/*/div[.//article[not(.//time[not(ancestor::div[@aria-labelledby])])]]', { state: 'attached', timeout: getTimeout() }))
+                        .then(() => page.waitForSelector('xpath=//section/*/*/div[.//article//a[@aria-describedby]/time]', { state: 'attached', timeout: getTimeout() }))
                         .then(handle => handle.evaluate(div => div.classList.add('mainTweet'))
                         .then(() => page.addStyleTag({ content: 'div.mainTweet~div{display:none;}' }))
                         .then(() => handle))
@@ -165,7 +160,7 @@ class Webshot extends CallableInstance {
                             logger.warn(`saved debug html to ${path}`);
                         }).then(() => page.route('**/*', route => route.abort().catch(() => { }))).then(() => page.screenshot({ fullPage: true })).then(screenshot => {
                             sharpToFile(sharp(screenshot).jpeg({ quality: 90 })).then(fileUri => {
-                                logger.warn(`saved debug screenshot to ${fileUri.substring(7)}`);
+                                logger.warn(`saved debug screenshot to ${fileUri.slice(7)}`);
                             });
                         }).then(() => null);
                     })
@@ -255,34 +250,41 @@ class Webshot extends CallableInstance {
         }
     }
     webshot(tweets, callback, webshotDelay) {
-        const promises = tweets.map((twi, index) => {
+        const promises = tweets.map(({ data, includes: { media, users: [user] } }, index) => {
             let promise = (0, util_1.promisify)(setTimeout)(webshotDelay / 4 * index).then(() => {
-                logger.info(`working on ${twi.user.screen_name}/${twi.id_str}`);
+                logger.info(`working on ${user.username}/${data.id}`);
             });
-            const originTwi = twi.retweeted_status || twi;
             let messageChain = '';
             let truncatedAt;
-            let author = `${twi.user.name} (@${twi.user.screen_name}):\n`;
-            author += `${new Date(twi.created_at)}\n`;
-            if (twi.retweeted_status)
-                author += `RT @${twi.retweeted_status.user.screen_name}: `;
-            let text = originTwi.full_text;
+            let author = `${user.name} (@${user.username}):\n`;
+            author += `${new Date(data.created_at)}\n`;
+            let text = data.text;
+            const rtTweet = (data.referenced_tweets || []).find(refTweet => refTweet.type === 'retweeted');
+            if (rtTweet) {
+                const match = /^(RT @.+?: )(.*)/.exec(text);
+                author += match[1];
+                text = match[2];
+            }
+            const urls = data.entities && data.entities.urls || [];
             promise = promise.then(() => {
-                if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
-                    originTwi.entities.urls.forEach(url => {
+                if (urls.length) {
+                    urls.forEach(url => {
                         text = text.replace(new RegExp(url.url, 'gm'), url.expanded_url);
                     });
                 }
-                if (originTwi.extended_entities) {
-                    originTwi.extended_entities.media.forEach(media => {
-                        text = text.replace(new RegExp(media.url, 'gm'), this.mode === 1 ? typeInZH[media.type] : '');
+                if (media) {
+                    media.forEach(entity => {
+                        const mediaUrl = urls.find((url) => url.media_key);
+                        if (!mediaUrl)
+                            return;
+                        text = text.replace(new RegExp(mediaUrl.expanded_url, 'gm'), this.mode === 1 ? `[${typeInZH[entity.type]}]` : '');
                     });
                 }
                 if (this.mode > 0)
                     messageChain += (author + xmlEntities.decode(text));
             });
             if (this.mode === 0) {
-                const url = `https://mobile.twitter.com/${twi.user.screen_name}/status/${twi.id_str}`;
+                const url = `https://mobile.twitter.com/${user.username}/status/${data.id}`;
                 promise = promise.then(() => this.renderWebshot(url, 1920, webshotDelay, (_, tweetHandle) => tweetHandle.evaluate(div => {
                     try {
                         const selector = '[data-testid="tweet"] :nth-child(2)>:first-child a';
@@ -315,29 +317,24 @@ class Webshot extends CallableInstance {
                     }
                     if (cardMedia.tagName === 'VIDEO' && typeof cardMedia.getAttribute('poster') === 'string') {
                         match = /^(.*\/amplify_video_thumb\/(\d+)\/img\/.*$)/.exec(cardMedia.getAttribute('poster'));
+                        if (!match)
+                            match = [, cardMedia.getAttribute('poster'), '.*'];
                     }
                     if (!match)
                         return {};
-                    const [media_url_https, id_str] = match.slice(1);
+                    const [url, id] = match.slice(1);
                     return {
                         type: cardMedia.tagName,
                         entityBase: {
-                            media_url: media_url_https.replace(/^https/, 'http'),
-                            media_url_https,
-                            url: '',
-                            display_url: '',
-                            expanded_url: '',
-                            id: Number(id_str),
-                            id_str,
-                            sizes: undefined,
+                            url,
+                            media_key: `${{ IMG: 3, VIDEO: 7 }[cardMedia.tagName]}_${id}`,
                         }
                     };
                 }).then(({ type, entityBase }) => {
-                    var _a;
                     if (!type)
                         return;
-                    const media = (_a = (originTwi.extended_entities || (originTwi.extended_entities = {}))).media || (_a.media = []);
-                    if (media.some(entity => entity.id_str === entityBase.id_str))
+                    media || (media = []);
+                    if (media.some(entity => entity.media_key === entityBase.media_key))
                         return;
                     if (type === 'IMG')
                         media.push(Object.assign(Object.assign({}, entityBase), { type: 'photo' }));
@@ -345,11 +342,10 @@ class Webshot extends CallableInstance {
                         page.evaluate(id_str => {
                             var _a;
                             return (_a = window['__scrapedVideoUrls']) === null || _a === void 0 ? void 0 : _a.find(videoUrl => new RegExp(`.*/amplify_video/${id_str}/pl/[^/]*\\.m3u8(?:\\?|$)`).exec(videoUrl));
-                        }, entityBase.id_str).then(streamlistUrl => axiosGet(streamlistUrl, 'text')
+                        }, entityBase.media_key.slice(2)).then(streamlistUrl => axiosGet(streamlistUrl, 'text')
                             .then(utils_1.M3u8.parseStreamlist)
                             .then(playlists => playlists.sort((pl1, pl2) => pl2.bandwidth - pl1.bandwidth)[0])
-                            .then(({ bandwidth, playlistPath, resolution }) => {
-                            const [width, height] = /(.*)x(.*)/.exec(resolution).slice(1).map(Number);
+                            .then(({ bandwidth, playlistPath }) => {
                             const playlistUrl = new URL(playlistPath, streamlistUrl);
                             return axiosGet(playlistUrl.href, 'text')
                                 .then(playlist => utils_1.M3u8.parsePlaylist(playlist))
@@ -359,16 +355,14 @@ class Webshot extends CallableInstance {
                                     fs.writeFileSync(mediaTempFilePath, Buffer.from(data), { flag: 'a' });
                                 })))
                                     .then(() => ({
-                                    duration_millis: duration * 1000,
-                                    aspect_ratio: [width, height],
                                     variants: [{
-                                            bitrate: bandwidth,
+                                            bit_rate: bandwidth,
                                             content_type: { mp4: 'video/mp4', ts: 'video/mp2t' }[ext],
                                             url: `file://${mediaTempFilePath}`,
                                         }]
                                 }));
                             });
-                        })).then(videoInfo => media.push(Object.assign(Object.assign({}, entityBase), { type: 'video', video_info: videoInfo }))).catch(error => {
+                        })).then(videoInfo => media.push(Object.assign(Object.assign(Object.assign({}, entityBase), { type: 'video' }), videoInfo))).catch(error => {
                             logger.error(`error while fetching scraped video, error: ${error}`);
                             logger.warn('unable to fetch scraped video, ignoring...');
                         });
@@ -385,19 +379,19 @@ class Webshot extends CallableInstance {
             }
             if (1 - this.mode % 2)
                 promise = promise.then(() => {
-                    if (originTwi.extended_entities) {
-                        return (0, utils_1.chainPromises)(originTwi.extended_entities.media.map(media => () => {
+                    if (media) {
+                        return (0, utils_1.chainPromises)(media.map(entity => () => {
                             let url;
-                            if (media.type === 'photo') {
-                                url = media.media_url_https.replace(/\.([a-z]+)$/, '?format=$1') + '&name=orig';
+                            if (entity.type === 'photo') {
+                                url = entity.url.replace(/\.([a-z]+)$/, '?format=$1') + '&name=orig';
                             }
                             else {
-                                url = media.video_info.variants
-                                    .filter(variant => variant.bitrate !== undefined)
-                                    .sort((var1, var2) => var2.bitrate - var1.bitrate)
+                                url = entity.variants
+                                    .filter(variant => variant.bit_rate !== undefined)
+                                    .sort((var1, var2) => var2.bit_rate - var1.bit_rate)
                                     .map(variant => variant.url)[0];
                             }
-                            const altMessage = `\n[失败的${typeInZH[media.type].type}:${url}]`;
+                            const altMessage = `\n[失败的${typeInZH[entity.type]}:${url}]`;
                             return this.fetchMedia(url)
                                 .catch(error => {
                                 logger.warn('unable to fetch media, sending plain text instead...');
@@ -407,38 +401,23 @@ class Webshot extends CallableInstance {
                         }));
                     }
                 });
-            if (this.mode === 0) {
-                if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
-                    promise = promise.then(() => {
-                        const urls = originTwi.entities.urls
-                            .filter(urlObj => urlObj.indices[0] < originTwi.display_text_range[1])
-                            .map(urlObj => `\n\ud83d\udd17 ${urlObj.expanded_url}`);
-                        if (urls.length) {
-                            messageChain += urls.join('');
-                        }
-                    });
-                }
-            }
             promise = promise.then(() => {
                 if (truncatedAt) {
-                    messageChain += `\n回复此命令查看对话串中更早的推文:\n/twitter_view ${truncatedAt}`;
+                    messageChain += `\n回复此命令查看对话串中更早的推文:\n/twi_view ${truncatedAt}`;
                 }
             });
-            if (originTwi.is_quote_status) {
+            const quotedTweet = (data.referenced_tweets || []).find(refTweet => refTweet.type === 'quoted');
+            if (quotedTweet) {
                 promise = promise.then(() => {
-                    var _a, _b;
-                    const match = /\/status\/(\d+)/.exec((_a = originTwi.quoted_status_permalink) === null || _a === void 0 ? void 0 : _a.expanded);
-                    const blockQuoteIdStr = match ? match[1] : (_b = originTwi.quoted_status) === null || _b === void 0 ? void 0 : _b.id_str;
-                    if (blockQuoteIdStr)
-                        messageChain += `\n回复此命令查看引用的推文:\n/twitter_view ${blockQuoteIdStr}`;
+                    messageChain += `\n回复此命令查看引用的推文:\n/twi_view ${quotedTweet.id}`;
                 });
             }
             return promise.then(() => {
-                logger.info(`done working on ${twi.user.screen_name}/${twi.id_str}, message chain:`);
-                logger.info(JSON.stringify(koishi_1.Message.ellipseBase64(messageChain)));
-                let cacheId = twi.id_str;
-                if (twi.retweeted_status)
-                    cacheId += `,rt:${twi.retweeted_status.id_str}`;
+                logger.info(`done working on ${user.username}/${data.id}, message chain:`);
+                logger.info(JSON.stringify(messageChain));
+                let cacheId = data.id;
+                if (rtTweet)
+                    cacheId += `,rt:${rtTweet.id}`;
                 callback(cacheId, messageChain, xmlEntities.decode(text), author);
             });
         });

+ 13 - 12
package.json

@@ -1,14 +1,14 @@
 {
-  "name": "@CL-Jeremy/mirai-twitter-bot",
-  "version": "0.4.0",
-  "description": "Mirai Twitter Bot",
+  "name": "gocqhttp-twitter-bot",
+  "version": "0.9.0",
+  "description": "GoCQHTTP Twitter Bot",
   "main": "./dist/main.js",
   "bin": {
-    "mirai-twitter-bot": "./dist/main.js"
+    "twitter-bot": "./dist/main.js"
   },
   "repository": {
     "type": "git",
-    "url": "git+https://github.com/CL-Jeremy/mirai-twitter-bot.git"
+    "url": "https://mikeslab.dix.asia/gogs/Pirami/gocqhttp-twitter-bot.git"
   },
   "publishConfig": {
     "registry": "https://npm.pkg.github.com/"
@@ -30,20 +30,23 @@
     "lint": "npx eslint --fix --ext .ts ./"
   },
   "dependencies": {
+    "@koishijs/core": "^4.11.1",
+    "@koishijs/plugin-adapter-onebot": "^5.5.3",
+    "@minatojs/core": "^2.0.3",
+    "axios": "^1.2.2",
     "callable-instance": "^2.0.0",
     "command-line-usage": "^5.0.5",
     "html-entities": "^1.3.1",
-    "koishi": "^3.10.0",
-    "koishi-adapter-onebot": "^3.0.8",
+    "koishi": "^4.11.1",
     "log4js": "^6.3.0",
     "playwright": "^1.9.1",
     "pngjs": "^5.0.0",
     "read-all-stream": "^3.1.0",
     "redis": "^3.1.2",
     "sha1": "^1.1.1",
-    "sharp": "^0.25.4",
+    "sharp": "^0.28.3",
     "temp": "^0.9.1",
-    "twitter": "^1.7.1",
+    "twitter-api-v2": "^1.12.8",
     "typescript": "^4.5.5"
   },
   "devDependencies": {
@@ -54,7 +57,6 @@
     "@types/redis": "^2.8.6",
     "@types/sharp": "^0.25.0",
     "@types/temp": "^0.8.34",
-    "@types/twitter": "^1.7.0",
     "@typescript-eslint/eslint-plugin": "^4.22.0",
     "@typescript-eslint/parser": "^4.22.0",
     "eslint": "^7.25.0",
@@ -62,7 +64,6 @@
     "eslint-plugin-jsdoc": "^32.3.1",
     "eslint-plugin-prefer-arrow": "^1.2.3",
     "eslint-plugin-react": "^7.23.2",
-    "tslint-config-prettier": "^1.13.0",
-    "twitter-d": "^0.4.0"
+    "tslint-config-prettier": "^1.13.0"
   }
 }

+ 10 - 28
src/command.ts

@@ -6,7 +6,7 @@ import * as path from 'path';
 
 import { relativeDate } from './datetime';
 import { getLogger } from './loggers';
-import { sendTimeline, sendTweet, ScreenNameNormalizer as normalizer } from './twitter';
+import { linkBuilder, parseLink, sendTimeline, sendTweet, ScreenNameNormalizer as normalizer } from './twitter';
 import { BigNumOps } from './utils';
 
 const logger = getLogger('command');
@@ -34,26 +34,6 @@ function parseCmd(message: string): {
   };
 }
 
-function parseLink(link: string): string[] {
-  let match =
-    /twitter.com\/([^\/?#]+)\/lists\/([^\/?#]+)/.exec(link) ||
-    /^([^\/?#]+)\/([^\/?#]+)$/.exec(link);
-  if (match) return [match[1], `/lists/${match[2]}`];
-  match =
-    /twitter.com\/([^\/?#]+)\/status\/(\d+)/.exec(link);
-  if (match) return [match[1], `/status/${match[2]}`];
-  match =
-    /twitter.com\/([^\/?#]+)/.exec(link) ||
-    /^([^\/?#]+)$/.exec(link);
-  if (match) return [match[1]];
-  return;
-}
-
-function linkBuilder(userName: string, more = ''): string {
-  if (!userName) return;
-  return `https://twitter.com/${userName}${more}`;
-}
-
 function linkFinder(checkedMatch: string[], chat: IChat, lock: ILock): [string, number] {
   const normalizedLink =
     linkBuilder(normalizer.normalize(checkedMatch[0]), checkedMatch[1]?.toLowerCase());
@@ -62,7 +42,7 @@ function linkFinder(checkedMatch: string[], chat: IChat, lock: ILock): [string,
   );
   if (!link) return [null, -1];
   const index = lock.threads[link].subscribers.findIndex(({chatID, chatType}) =>
-    chat.chatID === chatID && chat.chatType === chatType
+    chat.chatID.toString() === chatID.toString() && chat.chatType === chatType
   );
   return [link, index];
 }
@@ -70,7 +50,7 @@ function linkFinder(checkedMatch: string[], chat: IChat, lock: ILock): [string,
 function sub(chat: IChat, args: string[], reply: (msg: string) => any,
   lock: ILock, lockfile: string
 ): void {
-  if (chat.chatType === ChatType.Temp) {
+  if (chat.chatType === 'temp') {
     return reply('请先添加机器人为好友。');
   }
   if (args.length === 0) {
@@ -81,7 +61,7 @@ function sub(chat: IChat, args: string[], reply: (msg: string) => any,
     return reply(`订阅链接格式错误:
 示例:
 https://twitter.com/Saito_Shuka
-https://twitter.com/rikakomoe/lists/lovelive
+https://twitter.com/_satou_riko/lists/lovelive
 https://twitter.com/TomoyoKurosawa/status/1294613494860361729`);
   }
   let offset = '0';
@@ -128,11 +108,13 @@ https://twitter.com/TomoyoKurosawa/status/1294613494860361729`);
 function unsubAll(chat: IChat, args: string[], reply: (msg: string) => any,
   lock: ILock, lockfile: string
 ): void {
-  if (chat.chatType === ChatType.Temp) {
+  if (chat.chatType === 'temp') {
     return reply('请先添加机器人为好友。');
   }
   Object.entries(lock.threads).forEach(([link, {subscribers}]) => {
-    const index = subscribers.indexOf(chat);
+    const index = subscribers.findIndex(({chatID, chatType}) =>
+      chat.chatID.toString() === chatID.toString() && chat.chatType === chatType
+    );
     if (index === -1) return;
     subscribers.splice(index, 1);
     fs.writeFileSync(path.resolve(lockfile), JSON.stringify(lock));
@@ -144,7 +126,7 @@ function unsubAll(chat: IChat, args: string[], reply: (msg: string) => any,
 function unsub(chat: IChat, args: string[], reply: (msg: string) => any,
   lock: ILock, lockfile: string
 ): void {
-  if (chat.chatType === ChatType.Temp) {
+  if (chat.chatType === 'temp') {
     return reply('请先添加机器人为好友。');
   }
   if (args.length === 0) {
@@ -165,7 +147,7 @@ function unsub(chat: IChat, args: string[], reply: (msg: string) => any,
 }
 
 function list(chat: IChat, _: string[], reply: (msg: string) => any, lock: ILock): void {
-  if (chat.chatType === ChatType.Temp) {
+  if (chat.chatType === 'temp') {
     return reply('请先添加机器人为好友。');
   }
   const links = [];

+ 132 - 117
src/koishi.ts

@@ -1,15 +1,11 @@
-import { App, Bot, segment, Session, sleep } from 'koishi';
-import 'koishi-adapter-onebot';
-import { Message as CQMessage, SenderInfo } from 'koishi-adapter-onebot';
+import { App, segment, Session, sleep } from 'koishi';
+import onebot, { WsClient, OneBotBot, CQCode } from '@koishijs/plugin-adapter-onebot';
 
 import { parseCmd, query, view, resendLast } from './command';
 import { getLogger } from './loggers';
-import { chainPromises } from './utils';
 
 const logger = getLogger('qqbot');
 
-type CQSession = Session & CQMessage & {sender: SenderInfo & {groupId?: number}};
-
 interface IQQProps {
   access_token: string;
   host: string;
@@ -21,35 +17,53 @@ interface IQQProps {
   unsubAll(chat: IChat, args: string[], replyfn: (msg: string) => any): void;
 }
 
-const cqUrlFix = (factory: segment.Factory<string | ArrayBuffer | Buffer>) =>
-  (...args: Parameters<typeof factory>) => 
-    factory(...args).replace(/(?<=\[CQ:.*)url=(?=(base64|file|https?):\/\/)/, 'file=');
-
 export const Message = {
-  Image: cqUrlFix(segment.image),
-  Video: cqUrlFix(segment.video),
-  Voice: cqUrlFix(segment.audio),
-  ellipseBase64: (msg: string) => msg.replace(/(?<=\[CQ:.*base64:\/\/).*?(,|\])/g, '...$1'),
+  Image: segment.image,
+  Video: segment.video,
+  Voice: segment.audio,
   separateAttachment: (msg: string) => {
     const attachments: string[] = [];
-    const message = msg.replace(/\[CQ:(video|record),.*?\]/g, code => {
+    const message = msg.replace(/<(video|record) .*?\/>/g, code => {
       attachments.push(code);
       return '';
     });
     return {message, attachments};
   },
+  parseCQCode: (cqStr: string) => CQCode.parse(cqStr).map(seg => {
+    if (typeof seg.attrs.file === 'string') {
+      seg.attrs.url = seg.attrs.file;
+      delete seg.attrs.file;
+    }
+    return seg;
+  }).join(''),
+  toCQCode: (segStr: string) => segment.parse(segStr).map(seg => {
+    if (typeof seg.attrs.url === 'string') {
+      seg.attrs.file = seg.attrs.url;
+      delete seg.attrs.url;
+    }
+    return CQCode(seg.type, seg.attrs);
+  }).join(''),
 };
 
 export default class {
 
   private botInfo: IQQProps;
   private app: App;
-  public bot: Bot;
+  public bot: OneBotBot;
 
   private messageQueues: {[key: string]: (() => Promise<void>)[]} = {};
-  private tempSenders: {[key: number]: number} = {};
+  private tempSenders: {[key: number | string]: number} = {};
 
-  private next = (type: 'private' | 'group', id: string) => {
+  private get config(): onebot.Config & WsClient.Config {
+    return {
+      protocol: 'ws',
+      endpoint: `ws://${this.botInfo.host}:${this.botInfo.port}`,
+      selfId: this.botInfo.bot_id.toString(),
+      token: this.botInfo.access_token,
+    };
+  };
+
+  private next = (type: ChatType, id: string) => {
     const queue = this.messageQueues[`${type}:${id}`];
     if (queue && queue.length) {
       queue[0]().then(() => {
@@ -60,7 +74,7 @@ export default class {
     }
   };
 
-  private enqueue = (type: 'private' | 'group', id: string, resolver: () => Promise<void>) => {
+  private enqueue = (type: ChatType, id: string, resolver: () => Promise<void>) => {
     let wasEmpty = false;
     const queue = this.messageQueues[`${type}:${id}`] ||= (() => { wasEmpty = true; return []; })();
     queue.push(() => sleep(200).then(resolver));
@@ -68,177 +82,178 @@ export default class {
     if (wasEmpty) this.next(type, id);
   };
 
-  private getChat = async (session: CQSession): Promise<IChat> => {
+  private getSender = ({chatID, chatType}: IChat) =>
+    (msg: string) => (
+      chatType === 'guild' ? this.sendToChannel :
+      chatType === 'group' ? this.sendToGroup :
+      this.sendToUser
+    )(chatID.toString(), msg);
+
+  private getChat = async (session: Session): Promise<IChat> => {
+    if (session.type !== 'message') return null;
+    if (session.subsubtype === 'guild') {
+      return {
+        chatID: `${session.onebot.guild_id}:${session.onebot.channel_id}`,
+        chatType: 'guild',
+      };
+    }
     switch (session.subtype) {
       case 'private':
-        if (session.sender.groupId) { // temp message
+        const {group_id: groupId} = session.onebot.sender as any;
+        if (groupId) { // temp message
           const friendList = await session.bot.getFriendList();
           if (!friendList.some(friendItem => friendItem.userId === session.userId)) {
-            this.tempSenders[session.userId] = session.sender.groupId;
+            this.tempSenders[session.userId] = groupId;
             return {
               chatID: {
                 qq: Number(session.userId),
-                group: Number(session.sender.groupId),
+                group: Number(groupId),
                 toString: () => session.userId,
               },
-              chatType: ChatType.Temp,
+              chatType: 'temp',
             };
           }
         }
         return { // already befriended
           chatID: Number(session.userId),
-          chatType: ChatType.Private,
+          chatType: 'private',
         };
       case 'group':
         return {
-          chatID: Number(session.groupId),
-          chatType: ChatType.Group,
+          chatID: Number(session.guildId),
+          chatType: 'group',
         };
     }
   };
 
+  private sendToChannel = (guildChannel: string, message: string) => new Promise<string>((resolve, reject) => {
+    const [guildID, channelID] = guildChannel.split(':');
+    this.enqueue('guild', guildChannel, () => this.bot.guildBot.sendMessage(channelID, message, guildID)
+      .then(([response]) => resolve(response)).catch(reject));
+  });
+
   private sendToGroup = (groupID: string, message: string) => new Promise<string>((resolve, reject) => {
-    this.enqueue('group', groupID, () => this.bot.sendMessage(groupID, message).then(resolve).catch(reject));
+    this.enqueue('group', groupID, () => this.bot.sendMessage(groupID, message)
+      .then(([response]) => resolve(response)).catch(reject));
   });
 
   private sendToUser = (userID: string, message: string) => new Promise<string>((resolve, reject) => {
-    this.enqueue('private', userID, () => this.bot.sendPrivateMessage(userID, message).then(resolve).catch(reject));
+    this.enqueue('private', userID, () => this.bot.sendPrivateMessage(userID, message)
+    .then(([response]) => resolve(response)).catch(reject));
   });
 
   public sendTo = (subscriber: IChat, messageChain: string, noErrors = false) => Promise.all(
     (splitted => [splitted.message, ...splitted.attachments])(
       Message.separateAttachment(messageChain)
-    ).map(msg => {
-      switch (subscriber.chatType) {
-        case 'group':
-          return this.sendToGroup(subscriber.chatID.toString(), msg);
-        case 'private':
-          return this.sendToUser(subscriber.chatID.toString(), msg);
-        case 'temp': // currently unable to open session, awaiting OneBot v12
-          return this.sendToUser(subscriber.chatID.qq.toString(), msg);
-      }
-    }))
+    ).map(this.getSender(subscriber)))
     .then(response => {
       if (response === undefined) return;
       logger.info(`pushing data to ${JSON.stringify(subscriber.chatID)} was successful, response: ${response}`);
     })
     .catch(reason => {
-      logger.error(Message.ellipseBase64(`error pushing data to ${JSON.stringify(subscriber.chatID)}, reason: ${reason}`));
+      logger.error(`error pushing data to ${JSON.stringify(subscriber.chatID)}, reason: ${reason}`);
       if (!noErrors) throw reason instanceof Error ? reason : Error(reason);
     });
 
   private initBot = () => {
-    this.app = new App({
-      type: 'onebot',
-      server: `ws://${this.botInfo.host}:${this.botInfo.port}`,
-      selfId: this.botInfo.bot_id.toString(),
-      token: this.botInfo.access_token,
-      axiosConfig: {
-        maxContentLength: Infinity,
-      },
-      processMessage: msg => msg.trim(),
-    });
+    this.app = new App();
+    this.app.plugin(onebot, this.config);
 
     this.app.on('friend-request', async session => {
       const userString = `${session.username}(${session.userId})`;
-      let groupId: string;
-      let groupString: string;
-      if (session.username in this.tempSenders) groupId = this.tempSenders[session.userId as unknown as number].toString();
       logger.debug(`detected new friend request event: ${userString}`);
-      return session.bot.getGroupList().then(groupList => {
-        if (groupList.some(groupItem => {
-          const test = groupItem.groupId === groupId;
-          if (test) groupString = `${groupItem.groupName}(${groupId})`;
-          return test;
-        })) {
-          return session.bot.handleFriendRequest(session.messageId, true)
-            .then(() => { logger.info(`accepted friend request from ${userString} (from group ${groupString})`); })
-            .catch(error => { logger.error(`error accepting friend request from ${userString}, error: ${error}`); });
+      try {
+        const isTemp = session.username in this.tempSenders;
+        const {guildId, guildName} = isTemp ?
+          await session.bot.getGuild(this.tempSenders[session.userId].toString()) :
+            (await session.bot.getGuildList()).find(async ({guildId}) => {
+              try {
+                return await this.bot.getGuildMember(guildId, session.userId);
+              } catch {}
+            });
+        try {
+          const groupString = `${guildName}(${guildId})`;
+          await session.bot.handleFriendRequest(session.messageId, true);
+          logger.info(`accepted friend request from ${userString} (${
+            isTemp ? 'from' : 'found in'
+          } group ${groupString})`);
+        } catch (error) {
+          logger.error(`error accepting friend request from ${userString}, error: ${error}`);
         }
-        chainPromises(groupList.map(groupItem =>
-          (done: boolean) => Promise.resolve(done ||
-            this.bot.getGroupMember(groupItem.groupId, session.userId).then(() => {
-              groupString = `${groupItem.groupName}(${groupItem.groupId})`;
-              return session.bot.handleFriendRequest(session.messageId, true)
-                .then(() => { logger.info(`accepted friend request from ${userString} (found in group ${groupString})`); })
-                .catch(error => { logger.error(`error accepting friend request from ${userString}, error: ${error}`); })
-                .then(() => true);
-            }).catch(() => false)
-          )
-        )).then(done => {
-          if (done) return;
-          logger.warn(`received friend request from ${userString} (stranger)`);
-          logger.warn('please manually accept this friend request');
-        });
-      });
+      } catch {
+        logger.warn(`received friend request from ${userString} (stranger)`);
+        logger.warn('please manually accept this friend request');
+      }
     });
 
-    this.app.on('group-request', async session => {
+    this.app.on('guild-request', async session => {
       const userString = `${session.username}(${session.userId})`;
-      const groupString = `${session.groupName}(${session.groupId})`;
+      const groupString = `${session.guildName}(${session.guildId})`;
       logger.debug(`detected group invitation event: ${groupString}}`);
-      return session.bot.getFriendList().then(friendList => {
+      const friendList = await session.bot.getFriendList();
         if (friendList.some(friendItem => friendItem.userId = session.userId)) {
-          return session.bot.handleGroupRequest(session.messageId, true)
-            .then(() => { logger.info(`accepted group invitation from ${userString} (friend)`); })
-            .catch(error => { logger.error(`error accepting group invitation from ${userString}, error: ${error}`); });
+          try {
+            session.bot.handleGuildRequest(session.messageId, true);
+            logger.info(`accepted group invitation from ${userString} (friend)`);
+          } catch (error) {
+            logger.error(`error accepting group invitation from ${userString}, error: ${error}`);
+          }
         }
         logger.warn(`received group invitation from ${userString} (stranger)`);
         logger.warn('please manually accept this group invitation');
-      });
     });
 
-    this.app.middleware(async (session: CQSession) => {
+    this.app.middleware(async (session: Session) => {
       const chat = await this.getChat(session);
+      let userString = `${session.username}(${session.userId})`;
+      if (chat.chatType === 'temp') {
+        const group = await session.bot.getGuild(chat.chatID.group.toString());
+        userString += ` (from group ${group.guildName}(${group.guildId}))`;
+      }
       const cmdObj = parseCmd(session.content);
-      const reply = async msg => {
-        const userString = `${session.username}(${session.userId})`;
-        return (chat.chatType === ChatType.Group ? this.sendToGroup : this.sendToUser)(chat.chatID.toString(), msg)
-          .catch(error => { logger.error(`error replying to message from ${userString}, error: ${error}`); });
-      };
+      const reply = (msg: string) => this.getSender(chat)(msg).catch(error => {
+        if (chat.chatType === 'temp') {
+          return logger.info(`ignored error while replying to ${userString}`);
+        }
+        logger.error(`error replying to message from ${userString}, error: ${error}`);
+      });
       switch (cmdObj.cmd) {
-        case 'twitterpic_view':
-        case 'twitterpic_get':
+        case 'twipic_view':
           view(chat, cmdObj.args, reply);
           break;
-        case 'twitterpic_resendlast':
+        case 'twipic_resendlast':
           resendLast(chat, cmdObj.args, reply);
           break;
-        case 'twitterpic_query':
-        case 'twitterpic_gettimeline':
+        case 'twipic_query':
           query(chat, cmdObj.args, reply);
           break;
-        case 'twitterpic_sub':
-        case 'twitterpic_subscribe':
+        case 'twipic_sub':
           this.botInfo.sub(chat, cmdObj.args, reply);
           break;
-        case 'twitterpic_unsub':
-        case 'twitterpic_unsubscribe':
+        case 'twipic_unsub':
           this.botInfo.unsub(chat, cmdObj.args, reply);
           break;
-        case 'twitterpic_unsuball':
-        case 'bye':
+        case 'twipic_unsuball':
           this.botInfo.unsubAll(chat, cmdObj.args, reply);
           break;
-        case 'ping':
-        case 'twitterpic':
+        case 'twipic_listsub':
           this.botInfo.list(chat, cmdObj.args, reply);
           break;
         case 'help':
-          if (cmdObj.args.length === 0) {
+          if (cmdObj.args[0] === 'twipic') {
             reply(`推特媒体推文搬运机器人:
-/twitterpic - 查询当前聊天中的媒体推文订阅
-/twitterpic_sub[scribe]〈链接|用户名〉- 订阅 Twitter 媒体推文搬运
-/twitterpic_unsub[scribe]〈链接|用户名〉- 退订 Twitter 媒体推文搬运
-/twitterpic_view〈链接|表达式〉[{force|refresh}={on|off}] - 查看推文(可选强制重新载入)
-/twitterpic_resendlast〈用户名〉- 强制重发该用户最后一条媒体推文
-/twitterpic_query〈链接|用户名〉[参数列表...] - 查询时间线(详见 /help twitterpic_query)\
-${chat.chatType === ChatType.Temp ?
+/twipic_listsub - 查询当前聊天中的媒体推文订阅
+/twipic_sub〈链接|用户名〉- 订阅 Twitter 媒体推文搬运
+/twipic_unsub〈链接|用户名〉- 退订 Twitter 媒体推文搬运
+/twipic_view〈链接|表达式〉[{force|refresh}={on|off}] - 查看推文(可选强制重新载入)
+/twipic_resendlast〈用户名〉- 强制重发该用户最后一条媒体推文
+/twipic_query〈链接|用户名〉[参数列表...] - 查询时间线(详见 /help twipic_query)\
+${chat.chatType === 'temp' ?
     '\n(当前游客模式下无法使用订阅功能,请先添加本账号为好友。)' : ''
 }`);
-          } else if (cmdObj.args[0] === 'twitterpic_query') {
+          } else if (cmdObj.args[0] === 'twipic_query') {
             reply(`查询时间线中的媒体推文:
-/twitterpic_query〈链接|用户名〉[〈参数 1〉=〈值 1〉〈参数 2〉=〈值 2〉...]
+/twipic_query〈链接|用户名〉[〈参数 1〉=〈值 1〉〈参数 2〉=〈值 2〉...]
 
 参数列表(方框内全部为可选,留空则为默认):
     count:查询数量上限(类型:非零整数,最大值正负 50)[默认值:10]
@@ -251,7 +266,7 @@ ${chat.chatType === ChatType.Temp ?
 推荐的日期格式:2012-12-22 12:22 UTC+2 (日期和时间均为可选,可分别添加)
 count 为正时,从新向旧查询;为负时,从旧向新查询
 count 与 since/until 并用时,取二者中实际查询结果较少者
-例子:/twitterpic_query RiccaTachibana count=5 since="2019-12-30\
+例子:/twipic_query RiccaTachibana count=5 since="2019-12-30\
  UTC+9" until="2020-01-06 UTC+8" norts=on
     从起始时间点(含)到结束时间点(不含)从新到旧获取最多 5 条媒体推文,\
 其中不包含原生转推(实际上用户只发了 1 条)`)
@@ -266,7 +281,7 @@ count 与 since/until 并用时,取二者中实际查询结果较少者
     try {
       await this.app.start();
     } catch (err) {
-      logger.error(`error connecting to bot provider at ${this.app.options.server}, will retry in 2.5s...`);
+      logger.error(`error connecting to bot provider at ${this.config.endpoint}, will retry in 2.5s...`);
       await sleep(2500);
       await this.listen('retry connecting...');
     }
@@ -275,7 +290,7 @@ count 与 since/until 并用时,取二者中实际查询结果较少者
   public connect = async () => {
     this.initBot();
     await this.listen();
-    this.bot = this.app.getBot('onebot');
+    this.bot = this.app.bots.find(bot => bot.selfId === this.config.selfId) as OneBotBot;
   };
 
   constructor(opt: IQQProps) {

+ 17 - 11
src/model.d.ts

@@ -1,25 +1,30 @@
-declare const enum ChatType {
-  Private = 'private',
-  Group = 'group',
-  Temp = 'temp'
+type ChatType = 'private' | 'group' | 'temp' | 'guild';
+
+interface IChatBase {
+  chatType: ChatType;
 }
 
-interface IPrivateChat {
+interface IPrivateChat extends IChatBase {
   chatID: number;
-  chatType: ChatType.Private;
+  chatType: 'private';
 }
 
-interface IGroupChat {
+interface IGroupChat extends IChatBase {
   chatID: number;
-  chatType: ChatType.Group;
+  chatType: 'group';
 }
 
-interface ITempChat {
+interface ITempChat extends IChatBase {
   chatID: {qq: number, group: number, toString: () => string};
-  chatType: ChatType.Temp;
+  chatType: 'temp';
+}
+
+interface IGuildChat extends IChatBase {
+  chatID: string;
+  chatType: 'guild';
 }
 
-type IChat = IPrivateChat | IGroupChat | ITempChat;
+type IChat = IPrivateChat | IGroupChat | ITempChat | IGuildChat;
 
 interface ILock {
   workon: number;
@@ -28,6 +33,7 @@ interface ILock {
     [key: string]:
     {
       offset: string,
+      id?: string,
       updatedAt: string,
       subscribers: IChat[],
     },

+ 258 - 156
src/twitter.ts

@@ -1,10 +1,9 @@
 import * as fs from 'fs';
 import * as path from 'path';
-import * as Twitter from 'twitter';
-import TwitterTypes from 'twitter-d';
+import * as Twitter from 'twitter-api-v2';
 
 import { getLogger } from './loggers';
-import QQBot from './koishi';
+import QQBot, { Message } from './koishi';
 import RedisSvc from './redis';
 import { chainPromises, BigNumOps } from './utils';
 import Webshot from './webshot';
@@ -17,13 +16,33 @@ interface IWorkerOption {
   webshotDelay: number;
   consumerKey: string;
   consumerSecret: string;
-  accessTokenKey: string;
-  accessTokenSecret: string;
+  accessTokenKey?: string;
+  accessTokenSecret?: string;
   mode: number;
   wsUrl: string;
   redis?: IRedisConfig;
 }
 
+export const parseLink = (link: string): string[] => {
+  let match =
+    /twitter.com\/([^\/?#]+)\/lists\/([^\/?#]+)/.exec(link) ||
+    /^([^\/?#]+)\/([^\/?#]+)$/.exec(link);
+  if (match) return [match[1], `/lists/${match[2]}`];
+  match =
+    /twitter.com\/([^\/?#]+)\/status\/(\d+)/.exec(link);
+  if (match) return [match[1], `/status/${match[2]}`];
+  match =
+    /twitter.com\/([^\/?#]+)/.exec(link) ||
+    /^([^\/?#]+)$/.exec(link);
+  if (match) return [match[1]];
+  return;
+}
+
+export const linkBuilder = (userName: string, more = ''): string => {
+  if (!userName) return;
+  return `https://twitter.com/${userName}${more}`;
+}
+
 export class ScreenNameNormalizer {
 
   // tslint:disable-next-line: variable-name
@@ -32,17 +51,19 @@ export class ScreenNameNormalizer {
   public static normalize = (username: string) => username.toLowerCase().replace(/^@/, '');
 
   public static async normalizeLive(username: string) {
+    username = this.normalize(username);
     if (this._queryUser) {
       return await this._queryUser(username)
-        .catch((err: {code: number, message: string}[]) => {
-          if (err[0].code !== 50) {
-            logger.warn(`error looking up user: ${err[0].message}`);
+        .then(userNameId => userNameId.split(':')[0])
+        .catch((err: Twitter.InlineErrorV2) => {
+          if (err.title === 'Not Found Error') {
+            logger.warn(`error looking up user: ${showApiError(err)}`);
             return username;
           }
           return null;
         });
     }
-    return this.normalize(username);
+    return username;
   }
 }
 
@@ -99,19 +120,53 @@ const retryOnError = <T, U>(
   doWork().then(resolve).catch(error => retry(error, 1));
 });
 
-export type FullUser = TwitterTypes.FullUser;
-export type Entities = TwitterTypes.Entities;
-export type ExtendedEntities = TwitterTypes.ExtendedEntities;
-export type MediaEntity = TwitterTypes.MediaEntity;
+const showApiError = (err: Partial<Twitter.InlineErrorV2 & Twitter.ErrorV2 & Error>) =>
+  err.errors && err.errors[0].message || err.detail || err.stack || JSON.stringify(err);
 
-export interface Tweet extends TwitterTypes.Status {
-  user: FullUser;
-  retweeted_status?: Tweet;
-}
+const toMutableConst = <T>(o: T) => {
+  // credits: https://stackoverflow.com/a/60493166
+  type DeepMutableArrays<T> =
+    (T extends object ? { [K in keyof T]: DeepMutableArrays<T[K]> } : T) extends infer O ?
+    O extends ReadonlyArray<any> ? { -readonly [K in keyof O]: O[K] } : O : never;
+  return o as DeepMutableArrays<T>
+};
+
+const v2SingleParams = toMutableConst({
+  expansions: ['attachments.media_keys', 'author_id', 'referenced_tweets.id'],
+  'tweet.fields': ['created_at', 'entities'],
+  'media.fields': ['url', 'variants', 'alt_text'],
+  'user.fields': ['id', 'name', 'username']
+} as const);
+
+type PickRequired<T, K extends keyof T> = Pick<Required<T>, K> & T;
+
+export type TweetObject = PickRequired<
+  Twitter.TweetV2SingleResult['data'],
+  typeof v2SingleParams['tweet.fields'][number]
+>;
+
+export type UserObject = PickRequired<
+  Twitter.TweetV2SingleResult['includes']['users'][number],
+  typeof v2SingleParams['user.fields'][number]
+>;
+
+export type MediaObject =
+  Twitter.TweetV2SingleResult['includes']['media'][number] & (
+    {type: 'video' | 'animated_gif', variants: Twitter.MediaVariantsV2[]} |
+    {type: 'photo', url: string}
+  );
+
+export interface Tweet extends Twitter.TweetV2SingleResult {
+  data: TweetObject,
+  includes: {
+    media: MediaObject[],
+    users: UserObject[],
+  }
+};
 
 export default class {
 
-  private client: Twitter;
+  private client: Twitter.TwitterApiReadOnly;
   private lock: ILock;
   private lockfile: string;
   private workInterval: number;
@@ -123,12 +178,10 @@ export default class {
   private redis: RedisSvc;
 
   constructor(opt: IWorkerOption) {
-    this.client = new Twitter({
-      consumer_key: opt.consumerKey,
-      consumer_secret: opt.consumerSecret,
-      access_token_key: opt.accessTokenKey,
-      access_token_secret: opt.accessTokenSecret,
-    });
+    this.client = new Twitter.TwitterApi({
+      appKey: opt.consumerKey,
+      appSecret: opt.consumerSecret,
+    }).readOnly;
     this.lockfile = opt.lockfile;
     this.lock = opt.lock;
     this.workInterval = opt.workInterval;
@@ -145,19 +198,20 @@ export default class {
           count: 1 - Number(match[1]),
           noreps: {on: true, off: false}[match[3].replace(/.*,noreps=([^,]*).*/, '$1')],
           norts: {on: true, off: false}[match[3].replace(/.*,norts=([^,]*).*/, '$1')],
-        }).then(tweets => tweets.slice(-1)[0].id_str);
+        }).then(tweets => tweets.slice(-1)[0].data.id);
       (match ? query() : Promise.resolve(idOrQuery))
         .then((id: string) => this.getTweet(
           id,
           this.sendTweets({sourceInfo: `tweet ${id}`, reportOnSkip: true, force: forceRefresh}, receiver),
           forceRefresh
         ))
-        .catch((err: {code: number, message: string}[]) => {
-          if (err[0]?.code === 34)
+        .catch((err: Twitter.InlineErrorV2) => {
+          if (err.title !== 'Not Found Error') {
+            logger.warn(`error retrieving tweet: ${showApiError(err)}`);
+            this.bot.sendTo(receiver, `获取推文时出现错误:${showApiError(err)}`);
+          }
+          if (err.resource_type === 'user') {
             return this.bot.sendTo(receiver, `找不到用户 ${match[2].replace(/^@?(.*)$/, '@$1')}。`);
-          if (err[0].code !== 144) {
-            logger.warn(`error retrieving tweet: ${err[0].message}`);
-            this.bot.sendTo(receiver, `获取推文时出现错误:${err[0].message}`);
           }
           this.bot.sendTo(receiver, '找不到请求的推文,它可能已被删除。');
         });
@@ -173,21 +227,21 @@ export default class {
         norts: {on: true, off: false}[norts],
       })
         .then(tweets => chainPromises(
-          tweets.map(tweet => () => this.bot.sendTo(receiver, `\
-编号:${tweet.id_str}
-时间:${tweet.created_at}
-媒体:${tweet.extended_entities ? '有' : '无'}
-正文:\n${tweet.full_text.replace(/^([\s\S\n]{50})[\s\S\n]+?( https:\/\/t.co\/.*)?$/, '$1…$2')}`
+          tweets.map(({data}) => () => this.bot.sendTo(receiver, `\
+编号:${data.id}
+时间:${data.created_at}
+媒体:${(data.attachments || {}).media_keys ? '有' : '无'}
+正文:\n${data.text.replace(/^([\s\S\n]{50})[\s\S\n]+?( https:\/\/t.co\/.*)?$/, '$1…$2')}`
           ))
             .concat(() => this.bot.sendTo(receiver, tweets.length ?
-              '时间线查询完毕,使用 /twitterpic_view <编号> 查看媒体推文详细内容。' :
+              '时间线查询完毕,使用 /twipic_view <编号> 查看媒体推文详细内容。' :
               '时间线查询完毕,没有找到符合条件的媒体推文。'
             ))
         ))
-        .catch((err: {code: number, message: string}[]) => {
-          if (err[0]?.code !== 34) {
-            logger.warn(`error retrieving timeline: ${err[0]?.message || err}`);
-            return this.bot.sendTo(receiver, `获取时间线时出现错误:${err[0]?.message || err}`);
+        .catch((err: Twitter.InlineErrorV2) => {
+          if (err.title !== 'Not Found Error') {
+            logger.warn(`error retrieving timeline: ${showApiError(err)}`);
+            return this.bot.sendTo(receiver, `获取时间线时出现错误:${showApiError(err)}`);
           }
           this.bot.sendTo(receiver, `找不到用户 ${username.replace(/^@?(.*)$/, '@$1')}。`);
         });
@@ -195,15 +249,25 @@ export default class {
   }
 
   public launch = () => {
-    this.webshot = new Webshot(
-      this.wsUrl,
-      this.mode,
-      () => setTimeout(this.work, this.workInterval * 1000)
-    );
+    this.client.appLogin().then(client => {
+      this.client = client.readOnly;
+      this.webshot = new Webshot(
+        this.wsUrl,
+        this.mode,
+        () => setTimeout(this.work, this.workInterval * 1000)
+      );
+    });
   };
 
-  public queryUser = (username: string) => this.client.get('users/show', {screen_name: username})
-    .then((user: FullUser) => user.screen_name);
+  public queryUser = (username: string) => {
+    const thread = this.lock.threads[linkBuilder(username)];
+    if (thread && thread.id) return Promise.resolve(`${username}:${thread.id}`);
+    return this.client.v2.userByUsername(username).then(({data: {username, id}, errors}) => {
+      if (errors && errors.length > 0) throw errors[0];
+      if (thread) thread.id = id;
+      return `${username}:${id}`;
+    })
+  }
 
   public queryTimelineReverse = (conf: ITimelineQueryConfig) => {
     if (!conf.since) return this.queryTimeline(conf);
@@ -230,70 +294,70 @@ export default class {
   };
 
   public queryTimeline = (
-    { username, count, since, until, noreps, norts }: ITimelineQueryConfig
+    {username, count, since, until, noreps, norts}: ITimelineQueryConfig
   ) => {
     username = username.replace(/^@?(.*)$/, '@$1');
-    logger.info(`querying timeline of ${username} with config: ${
-      JSON.stringify({
-        ...(count && {count}),
-        ...(since && {since}),
-        ...(until && {until}),
-        ...(noreps && {noreps}),
-        ...(norts && {norts}),
-      })}`);
-    const fetchTimeline = (
-      config = {
-        screen_name: username.slice(1),
-        trim_user: true,
-        exclude_replies: noreps ?? true,
-        include_rts: !(norts ?? false),
-        since_id: since,
-        max_id: until,
-        tweet_mode: 'extended',
-      },
-      tweets: Tweet[] = []
-    ): Promise<Tweet[]> => this.client.get('statuses/user_timeline', config)
-      .then((newTweets: Tweet[]) => {
-        if (newTweets.length) {
-          logger.debug(`fetched tweets: ${JSON.stringify(newTweets)}`);
-          config.max_id = BigNumOps.plus('-1', newTweets[newTweets.length - 1].id_str);
-          logger.info(`timeline query of ${username} yielded ${
-            newTweets.length
-          } new tweets, next query will start at offset ${config.max_id}`);
-          tweets.push(...newTweets.filter(tweet => tweet.extended_entities));
-        }
-        if (!newTweets.length || tweets.length >= count) {
+    return this.queryUser(username.slice(1)).then(userNameId => {
+      const getMore = (lastTweets: Tweet[] = []) => {
+        logger.info(`querying timeline of ${username} with config: ${
+          JSON.stringify({
+            ...(count && {count}),
+            ...(since && {since}),
+            ...(until && {until}),
+            ...(noreps && {noreps}),
+            ...(norts && {norts}),
+          })}`);
+        return this.get('userTimeline', userNameId.split(':')[1], {
+          expansions: ['attachments.media_keys', 'author_id'],
+          'tweet.fields': ['created_at'],
+          exclude: [
+            ...(noreps ?? true) ? ['replies' as const] : [],
+            ...(norts ?? false) ? ['retweets' as const] : [],
+          ],
+          max_results: Math.min(Math.max(count || 0, 20), 100),
+          ...(since && {since_id: since}),
+          ...(until && {until_id: until}),
+        }).then(newTweets => {
+          logger.info(`timeline query of ${username} yielded ${newTweets.length} new tweets`);
+          const tweets = lastTweets.concat(newTweets.filter(({data}) => (data.attachments || {}).media_keys));
+          if (tweets.length < count) {
+            until = BigNumOps.plus('-1', newTweets.slice(-1)[0].data.id);
+            logger.info(`starting next query at offset ${until}...`);
+            return getMore(tweets);
+          }
           logger.info(`timeline query of ${username} finished successfully, ${
             tweets.length
-          } tweets with extended entities have been fetched`);
+          } media tweets have been fetched`);
           return tweets.slice(0, count);
-        }
-        return fetchTimeline(config, tweets);
-      });
-    return fetchTimeline();
+        });
+      }
+      return getMore();
+    });
   };
 
   private workOnTweets = (
     tweets: Tweet[],
     sendTweets: (cacheId: string, msg: string, text: string, author: string) => void,
     refresh = false
-  ) => Promise.all(tweets.map(tweet =>
+  ) => Promise.all(tweets.map(({data, includes}) =>
     ((this.redis && !refresh) ?
-      this.redis.waitForProcess(`webshot/${tweet.id_str}`, this.webshotDelay * 4)
-        .then(() => this.redis.getContent(`webshot/${tweet.id_str}`)) :
+      this.redis.waitForProcess(`webshot/${data.id}`, this.webshotDelay * 4)
+        .then(() => this.redis.getContent(`webshot/${data.id}`)) :
       Promise.reject())
       .then(content => {
         if (content === null) throw Error();
-        logger.info(`retrieved cached webshot of tweet ${tweet.id_str} from redis database`);
+        logger.info(`retrieved cached webshot of tweet ${data.id} from redis database, message chain:`);
         const {msg, text, author} = JSON.parse(content) as {[key: string]: string};
-        let cacheId = tweet.id_str;
-        if (tweet.retweeted_status) cacheId += `,rt:${tweet.retweeted_status.id_str}`;
-        sendTweets(cacheId, msg, text, author);
+        let cacheId = data.id;
+        const retweetRef = (data.referenced_tweets || []).find(ref => ref.type === 'retweeted');
+        if (retweetRef) cacheId += `,rt:${retweetRef.id}`;
+        logger.info(JSON.stringify(Message.parseCQCode(msg)));
+        sendTweets(cacheId, Message.parseCQCode(msg), text, author);
         return null as Tweet;
       })
       .catch(() => {
-        this.redis.startProcess(`webshot/${tweet.id_str}`);
-        return tweet;
+        this.redis.startProcess(`webshot/${data.id}`);
+        return {data, includes} as Tweet;
       })
   )).then(tweets =>
     this.webshot(
@@ -304,8 +368,9 @@ export default class {
             if (!this.redis) return;
             const [twid, rtid] = cacheId.split(',rt:');
             logger.info(`caching webshot of tweet ${twid} to redis database`);
-            this.redis.cacheContent(`webshot/${twid}`, JSON.stringify({msg, text, author, rtid}))
-              .then(() => this.redis.finishProcess(`webshot/${twid}`));
+            this.redis.cacheContent(`webshot/${twid}`,
+              JSON.stringify({msg: Message.toCQCode(msg), text, author, rtid})
+            ).then(() => this.redis.finishProcess(`webshot/${twid}`));
           })
           .then(() => sendTweets(cacheId, msg, text, author));
       },
@@ -317,31 +382,30 @@ export default class {
     id: string,
     sender: (cacheId: string, msg: string, text: string, author: string) => void,
     refresh = false
-  ) => {
-    const endpoint = 'statuses/show';
-    const config = {
-      id,
-      tweet_mode: 'extended',
-    };
-    return ((this.redis && !refresh) ?
+  ) =>
+    ((this.redis && !refresh) ?
       this.redis.waitForProcess(`webshot/${id}`, this.webshotDelay * 4)
         .then(() => this.redis.getContent(`webshot/${id}`))
         .then(content => {
           if (content === null) throw Error();
           const {rtid} = JSON.parse(content);
-          return {id_str: id, retweeted_status: rtid ? {id_str: rtid} : undefined} as Tweet;
+          return {data: {id, ...rtid && {referenced_tweets: [{type: 'retweeted', id: rtid}]}}} as Tweet;
         }) :
-      Promise.reject())
-      .catch(() => this.client.get(endpoint, config))
+      Promise.reject()
+    )
+      .catch(() => this.client.v2.singleTweet(id, v2SingleParams))
       .then((tweet: Tweet) => {
-        if (tweet.id) {
+        if (tweet.data.text) {
           logger.debug(`api returned tweet ${JSON.stringify(tweet)} for query id=${id}`);
+          const retweetRef = (tweet.data.referenced_tweets || []).find(ref => ref.type === 'retweeted');
+          if (retweetRef) return this.client.v2.singleTweet(retweetRef.id, v2SingleParams)
+            .then(({includes: {media}}) => ({...tweet, includes: {...tweet.includes, media}}) as Tweet);
         } else {
-          logger.debug(`skipped querying api as this tweet has been cached`)
+          logger.debug(`skipped querying api as this tweet has been cached`);
         }
-        return this.workOnTweets([tweet], sender, refresh);
-      });
-  };
+        return tweet;
+      })
+      .then((tweet: Tweet) => this.workOnTweets([tweet], sender, refresh));
 
   private sendTweets = (
     config: {sourceInfo?: string, reportOnSkip?: boolean, force?: boolean}
@@ -382,6 +446,43 @@ export default class {
     });
   };
 
+  private get = <T extends 'userTimeline' | 'listTweets'>(
+    type: T, targetId: string, params: Parameters<typeof this.client.v2[T]>[1]
+  ) => {
+    const {since_id, max_results} = (params as Twitter.TweetV2UserTimelineParams);
+    const getMore = (res: Twitter.TweetUserTimelineV2Paginator | Twitter.TweetV2ListTweetsPaginator) => {
+      if (res.errors && res.errors.length > 0) {
+        const [err] = res.errors;
+        if (!res.data) throw err;
+        if (err.title === 'Authorization Error') {
+          logger.warn(`non-fatal error while querying ${type} with id ${targetId}, error: ${err.detail}`);
+        }
+      }
+      if (!res.meta.next_token ||                                               // at last page
+        BigNumOps.compare(res.tweets.slice(-1)[0].id, since_id || '0') !== 1 || // at specified boundary
+        !since_id && res.meta.result_count >= max_results                       // at specified max count
+      ) return res;
+      return res.fetchNext().then<typeof res>(getMore);
+    };
+    if (type === 'listTweets') delete (params as any).since_id;
+    return this.client.v2[type](targetId, params).then(getMore)
+      .then(({includes, tweets}) => tweets.map((tweet): Tweet =>
+        ({
+          data: tweet as TweetObject,
+          includes: {
+            media: includes.medias(tweet) as MediaObject[],
+            users: [includes.author(tweet)]
+          }
+        })
+      ))
+      .then(tweets => Promise.all(tweets.map(tweet => {
+        const retweetRef = (tweet.data.referenced_tweets || []).find(ref => ref.type === 'retweeted');
+        if (retweetRef) return this.client.v2.singleTweet(retweetRef.id, v2SingleParams)
+          .then(({includes: {media}}) => ({...tweet, includes: {...tweet.includes, media}}) as Tweet);
+        return tweet;
+      })));
+  };
+
   public work = () => {
     const lock = this.lock;
     if (this.workInterval < 1) this.workInterval = 1;
@@ -406,62 +507,57 @@ export default class {
     const currentFeed = lock.feed[lock.workon];
     logger.debug(`pulling feed ${currentFeed}`);
 
-    const promise = new Promise(resolve => {
+    const promise = new Promise<Tweet[]>(resolve => {
+      let job = Promise.resolve();
+      let id = lock.threads[currentFeed].id;
+      let endpoint: Parameters<typeof this.get>[0];
+
       let match = /https:\/\/twitter.com\/([^\/]+)\/lists\/([^\/]+)/.exec(currentFeed);
-      let config: {[key: string]: any};
-      let endpoint: string;
       if (match) {
+        endpoint = 'listTweets';
         if (match[1] === 'i') {
-          config = {
-            list_id: match[2],
-            tweet_mode: 'extended',
-          };
-        } else {
-          config = {
+          id = match[2];
+        } else if (id === undefined) {
+          job = job.then(() => this.client.v1.list({
             owner_screen_name: match[1],
             slug: match[2],
-            tweet_mode: 'extended',
-          };
+          })).then(({id_str}) => {
+            lock.threads[currentFeed].id = id = id_str;
+          });
         }
-        endpoint = 'lists/statuses';
       } else {
         match = /https:\/\/twitter.com\/([^\/]+)/.exec(currentFeed);
         if (match) {
-          config = {
-            screen_name: match[1],
-            exclude_replies: false,
-            tweet_mode: 'extended',
-          };
-          endpoint = 'statuses/user_timeline';
+          endpoint = 'userTimeline';
+          if (id === undefined) {
+            job = job.then(() => this.queryUser(
+              match[1].replace(/^@?(.*)$/, '$1')
+            )).then(userNameId => {
+              lock.threads[currentFeed].id = id = userNameId.split(':')[1];
+            });
+          }
         }
       }
 
-      if (endpoint) {
-        const offset = lock.threads[currentFeed].offset;
-        config.include_rts = false;
-        if (offset as unknown as number > 0) config.since_id = offset;
-        if (offset as unknown as number < -1) config.max_id = offset.slice(1);
-        const getMore = (lastTweets: Tweet[] = []) => this.client.get(
-          endpoint, config, (error: {[key: string]: any}[], tweets: Tweet[]
-        ) => {
-          if (error) {
-            if (error instanceof Array && error.length > 0 && error[0].code === 34) {
-              logger.warn(`error on fetching tweets for ${currentFeed}: ${JSON.stringify(error)}`);
-              lock.threads[currentFeed].subscribers.forEach(subscriber => {
-                logger.info(`sending notfound message of ${currentFeed} to ${JSON.stringify(subscriber)}`);
-                this.bot.sendTo(subscriber, `链接 ${currentFeed} 指向的用户或列表不存在,请退订。`).catch();
-              });
-            } else {
-              logger.error(`unhandled error on fetching tweets for ${currentFeed}: ${JSON.stringify(error)}`);
-            }
-          }
-          if (!(tweets instanceof Array) || tweets.length === 0) return resolve(lastTweets);
-          if (offset as unknown as number <= 0) return resolve(lastTweets.concat(tweets));
-          config.max_id = BigNumOps.plus(tweets.slice(-1)[0].id_str, '-1');
-          getMore(lastTweets.concat(tweets));
-        });
-        getMore();
-      }
+      const offset = lock.threads[currentFeed].offset;
+      job.then(() => this.get(endpoint, id, {
+        ...v2SingleParams,
+        max_results: 20,
+        exclude: ['retweets'],
+        ...(offset as unknown as number > 0) && {since_id: offset},
+        ...(offset as unknown as number < -1) && {until_id: offset.slice(1)},
+      })).catch((err: Twitter.InlineErrorV2) => {
+        if (err.title === 'Not Found Error') {
+          logger.warn(`error on fetching tweets for ${currentFeed}: ${showApiError(err)}`);
+          lock.threads[currentFeed].subscribers.forEach(subscriber => {
+            logger.info(`sending notfound message of ${currentFeed} to ${JSON.stringify(subscriber)}`);
+            this.bot.sendTo(subscriber, `链接 ${currentFeed} 指向的用户或列表不存在,请退订。`).catch();
+          });
+        } else {
+          logger.error(`unhandled error on fetching tweets for ${currentFeed}: ${showApiError(err)}`);
+        }
+        return [] as Tweet[];
+      }).then(resolve);
     });
 
     promise.then((tweets: Tweet[]) => {
@@ -478,12 +574,18 @@ export default class {
         return;
       }
 
-      const topOfFeed = tweets[0].id_str;
+      const currentUser = tweets[0].includes.users.find(user => user.id === currentThread.id);
+      if (currentUser.username !== parseLink(currentFeed)[1]) {
+        lock.feed[lock.workon] = linkBuilder(currentUser.username);
+      }
+
+      const topOfFeed = tweets[0].data.id;
       logger.info(`current offset: ${currentThread.offset}, current top of feed: ${topOfFeed}`);
-      const bottomOfFeed = tweets[tweets.length - 1].id_str;
+      const bottomOfFeed = tweets.slice(-1)[0].data.id;
       const updateOffset = () => setOffset(topOfFeed);
-      tweets = tweets.filter(twi => twi.extended_entities);
+      tweets = tweets.filter(({data}) => (data.attachments || {}).media_keys);
       logger.info(`found ${tweets.length} tweets with extended entities`);
+
       if (currentThread.offset === '-1') { updateOffset(); return; }
       if (currentThread.offset as unknown as number <= 0) {
         if (tweets.length === 0) {

+ 66 - 77
src/webshot.ts

@@ -12,21 +12,16 @@ import * as temp from 'temp';
 
 import { getLogger } from './loggers';
 import { Message } from './koishi';
-import { MediaEntity, Tweet } from './twitter';
+import { MediaObject, Tweet } from './twitter';
 import { chainPromises, M3u8 } from './utils';
 
 const xmlEntities = new XmlEntities();
 
-const ZHType = (type: string) => new class extends String {
-  public type = super.toString();
-  public toString = () => `[${super.toString()}]`;
-}(type);
-
 const typeInZH = {
-  photo: ZHType('图片'),
-  video: ZHType('视频'),
-  animated_gif: ZHType('GIF'),
-};
+  photo: '图片',
+  video: '视频',
+  animated_gif: 'GIF',
+} as const;
 
 const logger = getLogger('webshot');
 
@@ -154,11 +149,13 @@ class Webshot extends CallableInstance<[Tweet[], (...args) => void, number], Pro
             // hide header, "more options" button, like and retweet count
             .then(() => page.addStyleTag({
               content: 'header,#layers{display:none!important}article{background-color:transparent!important}' +
-                '[data-testid="caret"],[role="group"],[data-testid="tweet"] [class*=" "]+:last-child>*+[class*=" "]~div{display:none}',
+              '[data-testid="caret"],[role="group"],[dir] div>a:nth-last-child(3)~span,' +
+              '[data-testid="tweet"] [class*=" "]+:last-child>*+[class*=" "]+[role="group"]~div{display:none!important}',
             }))
             .then(() => page.addStyleTag({
-              content: '*{font-family:-apple-system,".Helvetica Neue DeskInterface",Hiragino Sans,Hiragino Sans GB,sans-serif!important}' +
-                '*{-webkit-font-smoothing:antialiased!important}',
+              content: '*{font-family:-apple-system,".Helvetica Neue DeskInterface",' +
+              'Hiragino Sans,Hiragino Sans GB,sans-serif!important}' +
+              '*{-webkit-font-smoothing:antialiased!important;-webkit-locale:"ja"}',
             }))
             // remove listeners
             .then(() => page.evaluate(() => {
@@ -173,7 +170,7 @@ class Webshot extends CallableInstance<[Tweet[], (...args) => void, number], Pro
             }))
             // find main tweet
             .then(() => page.waitForSelector(
-              'xpath=//section/*/*/div[.//article[not(.//time[not(ancestor::div[@aria-labelledby])])]]',
+              'xpath=//section/*/*/div[.//article//a[@aria-describedby]/time]',
               {state: 'attached', timeout: getTimeout()}
             ) as Promise<puppeteer.ElementHandle<HTMLDivElement>>)
             // hide comments
@@ -203,7 +200,7 @@ class Webshot extends CallableInstance<[Tweet[], (...args) => void, number], Pro
               }).then(() => page.route('**/*', route => route.abort().catch(() => {/* ignore */}))
               ).then(() => page.screenshot({fullPage: true})).then(screenshot => {
                 sharpToFile(sharp(screenshot).jpeg({ quality: 90 })).then(fileUri => {
-                  logger.warn(`saved debug screenshot to ${fileUri.substring(7)}`);
+                  logger.warn(`saved debug screenshot to ${fileUri.slice(7)}`);
                 });
               }).then(() => null);
             })
@@ -291,30 +288,38 @@ class Webshot extends CallableInstance<[Tweet[], (...args) => void, number], Pro
     callback: (cacheId: string, msgs: string, text: string, author: string) => void,
     webshotDelay: number
   ): Promise<void> {
-    const promises = tweets.map((twi, index) => {
+    const promises = tweets.map(({data, includes: {media, users: [user]}}, index) => {
       let promise = promisify(setTimeout)(webshotDelay / 4 * index).then(() => {
-        logger.info(`working on ${twi.user.screen_name}/${twi.id_str}`);
+        logger.info(`working on ${user.username}/${data.id}`);
       });
-      const originTwi = twi.retweeted_status || twi;
       let messageChain = '';
       let truncatedAt: string;
 
       // text processing
-      let author = `${twi.user.name} (@${twi.user.screen_name}):\n`;
-      author += `${new Date(twi.created_at)}\n`;
-      if (twi.retweeted_status) author += `RT @${twi.retweeted_status.user.screen_name}: `;
+      let author = `${user.name} (@${user.username}):\n`;
+      author += `${new Date(data.created_at)}\n`;
+      let text = data.text;
 
-      let text = originTwi.full_text;
+      const rtTweet = (data.referenced_tweets || []).find(refTweet => refTweet.type === 'retweeted');
+      if (rtTweet) {
+        const match = /^(RT @.+?: )(.*)/.exec(text);
+        author += match[1];
+        text = match[2];
+      }
+
+      const urls = data.entities && data.entities.urls || [];
 
       promise = promise.then(() => {
-        if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
-          originTwi.entities.urls.forEach(url => {
+        if (urls.length) {
+          urls.forEach(url => {
             text = text.replace(new RegExp(url.url, 'gm'), url.expanded_url);
           });
         }
-        if (originTwi.extended_entities) {
-          originTwi.extended_entities.media.forEach(media => {
-            text = text.replace(new RegExp(media.url, 'gm'), this.mode === 1 ? typeInZH[media.type] : '');
+        if (media) {
+          media.forEach(entity => {
+            const mediaUrl = urls.find((url: any) => url.media_key);
+            if (!mediaUrl) return;
+            text = text.replace(new RegExp(mediaUrl.expanded_url, 'gm'), this.mode === 1 ? `[${typeInZH[entity.type]}]` : '');
           });
         }
         if (this.mode > 0) messageChain += (author + xmlEntities.decode(text));
@@ -322,7 +327,7 @@ class Webshot extends CallableInstance<[Tweet[], (...args) => void, number], Pro
 
       // invoke webshot
       if (this.mode === 0) {
-        const url = `https://mobile.twitter.com/${twi.user.screen_name}/status/${twi.id_str}`;
+        const url = `https://mobile.twitter.com/${user.username}/status/${data.id}`;
 
         promise = promise.then(() => this.renderWebshot(url, 1920, webshotDelay,
 
@@ -353,32 +358,27 @@ class Webshot extends CallableInstance<[Tweet[], (...args) => void, number], Pro
             const cardMediaDiv = div.querySelector('div[data-testid^="card.layout"][data-testid$=".media"]');
             const cardMedia = cardMediaDiv?.querySelector('img, video');
             if (!cardMedia) return {};
-            let match: RegExpExecArray;
+            let match: string[];
             if (cardMedia.tagName === 'IMG' && typeof cardMedia.getAttribute('src') === 'string') {
               match = /^(.*\/card_img\/(\d+)\/.+\?format=.*)&name=/.exec(cardMedia.getAttribute('src'));
             }
             if (cardMedia.tagName === 'VIDEO' && typeof cardMedia.getAttribute('poster') === 'string') {
               match = /^(.*\/amplify_video_thumb\/(\d+)\/img\/.*$)/.exec(cardMedia.getAttribute('poster'));
+              if (!match) match = [, cardMedia.getAttribute('poster'), '.*'];
             }
             if (!match) return {};
-            const [media_url_https, id_str] = match.slice(1);
+            const [url, id] = match.slice(1);
             return {
               type: cardMedia.tagName,
               entityBase: {
-                media_url: media_url_https.replace(/^https/, 'http'),
-                media_url_https,
-                url: '',
-                display_url: '',
-                expanded_url: '',
-                id: Number(id_str),
-                id_str,
-                sizes: undefined,
+                url,
+                media_key: `${{IMG: 3, VIDEO: 7}[cardMedia.tagName]}_${id}`,
               }
             };
           }).then(({type, entityBase}) => {
             if (!type) return;
-            const media = (originTwi.extended_entities ||= {}).media ||= [];
-            if (media.some(entity => entity.id_str === entityBase.id_str)) return;
+            media ||= [];
+            if (media.some(entity => entity.media_key === entityBase.media_key)) return;
             if (type === 'IMG') media.push({
               ...entityBase,
               type: 'photo',
@@ -387,13 +387,12 @@ class Webshot extends CallableInstance<[Tweet[], (...args) => void, number], Pro
               id_str => (window['__scrapedVideoUrls'] as string[])?.find(videoUrl =>
                 new RegExp(`.*/amplify_video/${id_str}/pl/[^/]*\\.m3u8(?:\\?|$)`).exec(videoUrl)
               ),
-              entityBase.id_str
+              entityBase.media_key.slice(2)
             ).then(streamlistUrl =>
               axiosGet(streamlistUrl, 'text')
                 .then(M3u8.parseStreamlist)
                 .then(playlists => playlists.sort((pl1, pl2) => pl2.bandwidth - pl1.bandwidth)[0])
-                .then(({bandwidth, playlistPath, resolution}) => {
-                  const [width, height] = /(.*)x(.*)/.exec(resolution).slice(1).map(Number);
+                .then(({bandwidth, playlistPath}) => {
                   const playlistUrl = new URL(playlistPath, streamlistUrl);
                   return axiosGet(playlistUrl.href, 'text')
                     .then(playlist => M3u8.parsePlaylist(playlist))
@@ -405,20 +404,18 @@ class Webshot extends CallableInstance<[Tweet[], (...args) => void, number], Pro
                         })
                       ))
                       .then(() => ({
-                        duration_millis: duration * 1000,
-                        aspect_ratio: [width, height],
                         variants: [{
-                          bitrate: bandwidth,
+                          bit_rate: bandwidth,
                           content_type: {mp4: 'video/mp4', ts: 'video/mp2t'}[ext],
                           url: `file://${mediaTempFilePath}`,
                         }]
-                      }) as MediaEntity['video_info'])
+                      }) as MediaObject)
                     });
                 })
               ).then(videoInfo => media.push({
                 ...entityBase,
                 type: 'video',
-                video_info: videoInfo,
+                ...videoInfo,
               })).catch(error => {
                 logger.error(`error while fetching scraped video, error: ${error}`);
                 logger.warn('unable to fetch scraped video, ignoring...');
@@ -437,18 +434,18 @@ class Webshot extends CallableInstance<[Tweet[], (...args) => void, number], Pro
       // tslint:disable-next-line: curly
       // eslint-disable-next-line curly
       if (1 - this.mode % 2) promise = promise.then(() => {
-        if (originTwi.extended_entities) {
-          return chainPromises(originTwi.extended_entities.media.map(media => () => {
+        if (media) {
+          return chainPromises(media.map(entity => () => {
             let url: string;
-            if (media.type === 'photo') {
-              url = media.media_url_https.replace(/\.([a-z]+)$/, '?format=$1') + '&name=orig';
+            if (entity.type === 'photo') {
+              url = entity.url.replace(/\.([a-z]+)$/, '?format=$1') + '&name=orig';
             } else {
-              url = media.video_info.variants
-                .filter(variant => variant.bitrate !== undefined)
-                .sort((var1, var2) => var2.bitrate - var1.bitrate)
+              url = entity.variants
+                .filter(variant => variant.bit_rate !== undefined)
+                .sort((var1, var2) => var2.bit_rate - var1.bit_rate)
                 .map(variant => variant.url)[0]; // largest video
             }
-            const altMessage = `\n[失败的${typeInZH[media.type as keyof typeof typeInZH].type}:${url}]`;
+            const altMessage = `\n[失败的${typeInZH[entity.type]}:${url}]`;
             return this.fetchMedia(url)
               .catch(error => {
                 logger.warn('unable to fetch media, sending plain text instead...');
@@ -459,37 +456,29 @@ class Webshot extends CallableInstance<[Tweet[], (...args) => void, number], Pro
         }
       });
       // append URLs, if any
-      if (this.mode === 0) {
-        if (originTwi.entities && originTwi.entities.urls && originTwi.entities.urls.length) {
-          promise = promise.then(() => {
-            const urls = originTwi.entities.urls
-              .filter(urlObj => urlObj.indices[0] < originTwi.display_text_range[1])
-              .map(urlObj => `\n\ud83d\udd17 ${urlObj.expanded_url}`);
-            if (urls.length) {
-              messageChain += urls.join('');
-            }
-          });
-        }
-      }
+      // if (this.mode === 0 && urls.length) {
+      //   promise = promise.then(() => {
+      //     messageChain += urls.map(urlObj => `\n\ud83d\udd17 ${urlObj.expanded_url}`).join('');
+      //   });
+      // }
       // refer to earlier tweets if thread is truncated
       promise = promise.then(() => {
         if (truncatedAt) {
-          messageChain += `\n回复此命令查看对话串中更早的推文:\n/twitter_view ${truncatedAt}`;
+          messageChain += `\n回复此命令查看对话串中更早的推文:\n/twi_view ${truncatedAt}`;
         }
       });
       // refer to quoted tweet, if any
-      if (originTwi.is_quote_status) {
+      const quotedTweet = (data.referenced_tweets || []).find(refTweet => refTweet.type === 'quoted');
+      if (quotedTweet) {
         promise = promise.then(() => {
-          const match = /\/status\/(\d+)/.exec(originTwi.quoted_status_permalink?.expanded);
-          const blockQuoteIdStr = match ? match[1] : originTwi.quoted_status?.id_str;
-          if (blockQuoteIdStr) messageChain += `\n回复此命令查看引用的推文:\n/twitter_view ${blockQuoteIdStr}`;
+          messageChain += `\n回复此命令查看引用的推文:\n/twi_view ${quotedTweet.id}`;
         });
       }
       return promise.then(() => {
-        logger.info(`done working on ${twi.user.screen_name}/${twi.id_str}, message chain:`);
-        logger.info(JSON.stringify(Message.ellipseBase64(messageChain)));
-        let cacheId = twi.id_str;
-        if (twi.retweeted_status) cacheId += `,rt:${twi.retweeted_status.id_str}`;
+        logger.info(`done working on ${user.username}/${data.id}, message chain:`);
+        logger.info(JSON.stringify(messageChain));
+        let cacheId = data.id;
+        if (rtTweet) cacheId += `,rt:${rtTweet.id}`;
         callback(cacheId, messageChain, xmlEntities.decode(text), author);
       });
     });