瀏覽代碼

migrate to koishi.js v4 to support guilds

Mike L 2 年之前
父節點
當前提交
6a40ab44e1
共有 10 個文件被更改,包括 259 次插入209 次删除
  1. 4 4
      dist/command.js
  2. 97 76
      dist/koishi.js
  3. 6 5
      dist/twitter.js
  4. 3 3
      dist/webshot.js
  5. 10 8
      package.json
  6. 4 4
      src/command.ts
  7. 108 89
      src/koishi.ts
  8. 16 11
      src/model.d.ts
  9. 8 6
      src/twitter.ts
  10. 3 3
      src/webshot.ts

+ 4 - 4
dist/command.js

@@ -38,7 +38,7 @@ function linkFinder(checkedMatch, chat, lock) {
     return [link, index];
 }
 function sub(chat, args, reply, lock, lockfile) {
-    if (chat.chatType === "temp") {
+    if (chat.chatType === 'temp') {
         return reply('请先添加机器人为好友。');
     }
     if (args.length === 0) {
@@ -97,7 +97,7 @@ 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 }]) => {
@@ -112,7 +112,7 @@ 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) {
@@ -134,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 = [];

+ 97 - 76
dist/koishi.js

@@ -11,25 +11,37 @@ 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,71 +68,79 @@ 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') {
+                const channel = session.onebot.channel_id;
+                const guild = session.onebot.guild_id;
+                return {
+                    chatID: {
+                        channel,
+                        guild,
+                        toString: () => `${guild}:${channel}`,
+                    },
+                    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;
@@ -128,11 +148,11 @@ class default_1 {
                 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;
+                return session.bot.getGuildList().then(groupList => {
+                    if (groupList.some(({ guildName, guildId }) => {
+                        const test = guildId.toString() === groupId;
                         if (test)
-                            groupString = `${groupItem.groupName}(${groupId})`;
+                            groupString = `${guildName}(${guildId})`;
                         return test;
                     })) {
                         return session.bot.handleFriendRequest(session.messageId, true)
@@ -140,8 +160,8 @@ class default_1 {
                             .catch(error => { logger.error(`error accepting friend request from ${userString}, error: ${error}`); });
                     }
                     (0, utils_1.chainPromises)(groupList.map(groupItem => (done) => Promise.resolve(done ||
-                        this.bot.getGroupMember(groupItem.groupId, session.userId).then(() => {
-                            groupString = `${groupItem.groupName}(${groupItem.groupId})`;
+                        this.bot.getGuildMember(groupItem.guildId, session.userId).then(() => {
+                            groupString = `${groupItem.guildName}(${groupItem.guildName})`;
                             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}`); })
@@ -154,13 +174,13 @@ class default_1 {
                     });
                 });
             }));
-            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)
+                        return session.bot.handleGuildRequest(session.messageId, true)
                             .then(() => { logger.info(`accepted group invitation from ${userString} (friend)`); })
                             .catch(error => { logger.error(`error accepting group invitation from ${userString}, error: ${error}`); });
                     }
@@ -171,54 +191,46 @@ class default_1 {
             this.app.middleware((session) => __awaiter(this, void 0, void 0, function* () {
                 const chat = yield this.getChat(session);
                 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 => {
+                    logger.error(`error replying to message from ${session.username}(${session.userId}), error: ${error}`);
                 });
                 switch (cmdObj.cmd) {
-                    case 'twitter_view':
-                    case 'twitter_get':
+                    case 'twi_view':
                         (0, command_1.view)(chat, cmdObj.args, reply);
                         break;
-                    case 'twitter_resendlast':
+                    case 'twi_resendlast':
                         (0, command_1.resendLast)(chat, cmdObj.args, reply);
                         break;
-                    case 'twitter_query':
-                    case 'twitter_gettimeline':
+                    case 'twi_query':
                         (0, command_1.query)(chat, cmdObj.args, reply);
                         break;
-                    case 'twitter_sub':
-                    case 'twitter_subscribe':
+                    case 'twi_sub':
                         this.botInfo.sub(chat, cmdObj.args, reply);
                         break;
-                    case 'twitter_unsub':
-                    case 'twitter_unsubscribe':
+                    case 'twi_unsub':
                         this.botInfo.unsub(chat, cmdObj.args, reply);
                         break;
-                    case 'twitter_unsuball':
-                    case 'bye':
+                    case 'twi_unsuball':
                         this.botInfo.unsubAll(chat, cmdObj.args, reply);
                         break;
-                    case 'ping':
-                    case 'twitter':
+                    case 'twi_listsub':
                         this.botInfo.list(chat, cmdObj.args, reply);
                         break;
                     case 'help':
-                        if (cmdObj.args.length === 0) {
+                        if (cmdObj.args[0] === 'twi') {
                             reply(`推特搬运机器人:
-/twitter - 查询当前聊天中的推文订阅
-/twitter_sub[scribe]〈链接|用户名〉- 订阅 Twitter 推文搬运
-/twitter_unsub[scribe]〈链接|用户名〉- 退订 Twitter 推文搬运
-/twitter_view〈链接|表达式〉[{force|refresh}={on|off}] - 查看推文(可选强制重新载入)
-/twitter_resendlast〈用户名〉- 强制重发该用户最后一条推文
-/twitter_query〈链接|用户名〉[参数列表...] - 查询时间线(详见 /help twitter_query)\
-${chat.chatType === "temp" ?
+/twi_listsub - 查询当前聊天中的推文订阅
+/twi_sub〈链接|用户名〉- 订阅 Twitter 推文搬运
+/twi_unsub〈链接|用户名〉- 退订 Twitter 推文搬运
+/twi_view〈链接|表达式〉[{force|refresh}={on|off}] - 查看推文(可选强制重新载入)
+/twi_resendlast〈用户名〉- 强制重发该用户最后一条推文
+/twi_query〈链接|用户名〉[参数列表...] - 查询时间线(详见 /help twi_query)\
+${chat.chatType === 'temp' ?
                                 '\n(当前游客模式下无法使用订阅功能,请先添加本账号为好友。)' : ''}`);
                         }
-                        else if (cmdObj.args[0] === 'twitter_query') {
+                        else if (cmdObj.args[0] === 'twi_query') {
                             reply(`查询时间线中的推文:
-/twitter_query〈链接|用户名〉[〈参数 1〉=〈值 1〉〈参数 2〉=〈值 2〉...]
+/twi_query〈链接|用户名〉[〈参数 1〉=〈值 1〉〈参数 2〉=〈值 2〉...]
 
 参数列表(方框内全部为可选,留空则为默认):
     count:查询数量上限(类型:非零整数,最大值正负 50)[默认值:10]
@@ -231,7 +243,7 @@ ${chat.chatType === "temp" ?
 推荐的日期格式:2012-12-22 12:22 UTC+2 (日期和时间均为可选,可分别添加)
 count 为正时,从新向旧查询;为负时,从旧向新查询
 count 与 since/until 并用时,取二者中实际查询结果较少者
-例子:/twitter_query RiccaTachibana count=5 since="2019-12-30\
+例子:/twi_query RiccaTachibana count=5 since="2019-12-30\
  UTC+9" until="2020-01-06 UTC+8" norts=on
     从起始时间点(含)到结束时间点(不含)从新到旧获取最多 5 条推文,\
 其中不包含原生转推(实际上用户只发了 1 条)`));
@@ -245,7 +257,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 +265,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;

+ 6 - 5
dist/twitter.js

@@ -14,6 +14,7 @@ const fs = require("fs");
 const path = require("path");
 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");
@@ -163,13 +164,14 @@ class default_1 {
             .then(content => {
             if (content === null)
                 throw Error();
-            logger.info(`retrieved cached webshot of tweet ${data.id} 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 = data.id;
             const retweetRef = (data.referenced_tweets || []).find(ref => ref.type === 'retweeted');
             if (retweetRef)
                 cacheId += `,rt:${retweetRef.id}`;
-            sendTweets(cacheId, msg, text, author);
+            logger.info(JSON.stringify(koishi_1.Message.parseCQCode(msg)));
+            sendTweets(cacheId, koishi_1.Message.parseCQCode(msg), text, author);
             return null;
         })
             .catch(() => {
@@ -182,8 +184,7 @@ 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));
@@ -412,7 +413,7 @@ class default_1 {
 媒体:${(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 ?
-                '时间线查询完毕,使用 /twitter_view <编号> 查看推文详细内容。' :
+                '时间线查询完毕,使用 /twi_view <编号> 查看推文详细内容。' :
                 '时间线查询完毕,没有找到符合条件的推文。'))))
                 .catch((err) => {
                 if (err.title !== 'Not Found Error') {

+ 3 - 3
dist/webshot.js

@@ -403,18 +403,18 @@ class Webshot extends CallableInstance {
                 });
             promise = promise.then(() => {
                 if (truncatedAt) {
-                    messageChain += `\n回复此命令查看对话串中更早的推文:\n/twitter_view ${truncatedAt}`;
+                    messageChain += `\n回复此命令查看对话串中更早的推文:\n/twi_view ${truncatedAt}`;
                 }
             });
             const quotedTweet = (data.referenced_tweets || []).find(refTweet => refTweet.type === 'quoted');
             if (quotedTweet) {
                 promise = promise.then(() => {
-                    messageChain += `\n回复此命令查看引用的推文:\n/twitter_view ${quotedTweet.id}`;
+                    messageChain += `\n回复此命令查看引用的推文:\n/twi_view ${quotedTweet.id}`;
                 });
             }
             return promise.then(() => {
                 logger.info(`done working on ${user.username}/${data.id}, message chain:`);
-                logger.info(JSON.stringify(koishi_1.Message.ellipseBase64(messageChain)));
+                logger.info(JSON.stringify(messageChain));
                 let cacheId = data.id;
                 if (rtTweet)
                     cacheId += `,rt:${rtTweet.id}`;

+ 10 - 8
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,11 +30,14 @@
     "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",
@@ -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",

+ 4 - 4
src/command.ts

@@ -50,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) {
@@ -108,7 +108,7 @@ 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}]) => {
@@ -126,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) {
@@ -147,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 = [];

+ 108 - 89
src/koishi.ts

@@ -1,6 +1,5 @@
-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';
@@ -8,8 +7,6 @@ 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 +18,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 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 +75,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,76 +83,88 @@ 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') {
+      const channel = session.onebot.channel_id;
+      const guild = session.onebot.guild_id;
+      return {
+        chatID: {
+          channel,
+          guild,
+          toString: () => `${guild}:${channel}`,
+        },
+        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})`;
@@ -145,10 +172,10 @@ export default class {
       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 session.bot.getGuildList().then(groupList => {
+        if (groupList.some(({guildName, guildId}) => {
+          const test = guildId.toString() === groupId;
+          if (test) groupString = `${guildName}(${guildId})`;
           return test;
         })) {
           return session.bot.handleFriendRequest(session.messageId, true)
@@ -157,8 +184,8 @@ export default class {
         }
         chainPromises(groupList.map(groupItem =>
           (done: boolean) => Promise.resolve(done ||
-            this.bot.getGroupMember(groupItem.groupId, session.userId).then(() => {
-              groupString = `${groupItem.groupName}(${groupItem.groupId})`;
+            this.bot.getGuildMember(groupItem.guildId, session.userId).then(() => {
+              groupString = `${groupItem.guildName}(${groupItem.guildName})`;
               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}`); })
@@ -173,13 +200,13 @@ export default class {
       });
     });
 
-    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 => {
         if (friendList.some(friendItem => friendItem.userId = session.userId)) {
-          return session.bot.handleGroupRequest(session.messageId, true)
+          return session.bot.handleGuildRequest(session.messageId, true)
             .then(() => { logger.info(`accepted group invitation from ${userString} (friend)`); })
             .catch(error => { logger.error(`error accepting group invitation from ${userString}, error: ${error}`); });
         }
@@ -188,57 +215,49 @@ export default class {
       });
     });
 
-    this.app.middleware(async (session: CQSession) => {
+    this.app.middleware(async (session: Session) => {
       const chat = await this.getChat(session);
       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 => {
+        logger.error(`error replying to message from ${session.username}(${session.userId}), error: ${error}`);
+      });
       switch (cmdObj.cmd) {
-        case 'twitter_view':
-        case 'twitter_get':
+        case 'twi_view':
           view(chat, cmdObj.args, reply);
           break;
-        case 'twitter_resendlast':
+        case 'twi_resendlast':
           resendLast(chat, cmdObj.args, reply);
           break;
-        case 'twitter_query':
-        case 'twitter_gettimeline':
+        case 'twi_query':
           query(chat, cmdObj.args, reply);
           break;
-        case 'twitter_sub':
-        case 'twitter_subscribe':
+        case 'twi_sub':
           this.botInfo.sub(chat, cmdObj.args, reply);
           break;
-        case 'twitter_unsub':
-        case 'twitter_unsubscribe':
+        case 'twi_unsub':
           this.botInfo.unsub(chat, cmdObj.args, reply);
           break;
-        case 'twitter_unsuball':
-        case 'bye':
+        case 'twi_unsuball':
           this.botInfo.unsubAll(chat, cmdObj.args, reply);
           break;
-        case 'ping':
-        case 'twitter':
+        case 'twi_listsub':
           this.botInfo.list(chat, cmdObj.args, reply);
           break;
         case 'help':
-          if (cmdObj.args.length === 0) {
+          if (cmdObj.args[0] === 'twi') {
             reply(`推特搬运机器人:
-/twitter - 查询当前聊天中的推文订阅
-/twitter_sub[scribe]〈链接|用户名〉- 订阅 Twitter 推文搬运
-/twitter_unsub[scribe]〈链接|用户名〉- 退订 Twitter 推文搬运
-/twitter_view〈链接|表达式〉[{force|refresh}={on|off}] - 查看推文(可选强制重新载入)
-/twitter_resendlast〈用户名〉- 强制重发该用户最后一条推文
-/twitter_query〈链接|用户名〉[参数列表...] - 查询时间线(详见 /help twitter_query)\
-${chat.chatType === ChatType.Temp ?
+/twi_listsub - 查询当前聊天中的推文订阅
+/twi_sub〈链接|用户名〉- 订阅 Twitter 推文搬运
+/twi_unsub〈链接|用户名〉- 退订 Twitter 推文搬运
+/twi_view〈链接|表达式〉[{force|refresh}={on|off}] - 查看推文(可选强制重新载入)
+/twi_resendlast〈用户名〉- 强制重发该用户最后一条推文
+/twi_query〈链接|用户名〉[参数列表...] - 查询时间线(详见 /help twi_query)\
+${chat.chatType === 'temp' ?
     '\n(当前游客模式下无法使用订阅功能,请先添加本账号为好友。)' : ''
 }`);
-          } else if (cmdObj.args[0] === 'twitter_query') {
+          } else if (cmdObj.args[0] === 'twi_query') {
             reply(`查询时间线中的推文:
-/twitter_query〈链接|用户名〉[〈参数 1〉=〈值 1〉〈参数 2〉=〈值 2〉...]
+/twi_query〈链接|用户名〉[〈参数 1〉=〈值 1〉〈参数 2〉=〈值 2〉...]
 
 参数列表(方框内全部为可选,留空则为默认):
     count:查询数量上限(类型:非零整数,最大值正负 50)[默认值:10]
@@ -251,7 +270,7 @@ ${chat.chatType === ChatType.Temp ?
 推荐的日期格式:2012-12-22 12:22 UTC+2 (日期和时间均为可选,可分别添加)
 count 为正时,从新向旧查询;为负时,从旧向新查询
 count 与 since/until 并用时,取二者中实际查询结果较少者
-例子:/twitter_query RiccaTachibana count=5 since="2019-12-30\
+例子:/twi_query RiccaTachibana count=5 since="2019-12-30\
  UTC+9" until="2020-01-06 UTC+8" norts=on
     从起始时间点(含)到结束时间点(不含)从新到旧获取最多 5 条推文,\
 其中不包含原生转推(实际上用户只发了 1 条)`)
@@ -266,7 +285,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 +294,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) {

+ 16 - 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: {channel: string, guild: string, toString: () => string};
+  chatType: 'guild';
 }
 
-type IChat = IPrivateChat | IGroupChat | ITempChat;
+type IChat = IPrivateChat | IGroupChat | ITempChat | IGuildChat;
 
 interface ILock {
   workon: number;

+ 8 - 6
src/twitter.ts

@@ -3,7 +3,7 @@ import * as path from 'path';
 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';
@@ -233,7 +233,7 @@ export default class {
 正文:\n${data.text.replace(/^([\s\S\n]{50})[\s\S\n]+?( https:\/\/t.co\/.*)?$/, '$1…$2')}`
           ))
             .concat(() => this.bot.sendTo(receiver, tweets.length ?
-              '时间线查询完毕,使用 /twitter_view <编号> 查看推文详细内容。' :
+              '时间线查询完毕,使用 /twi_view <编号> 查看推文详细内容。' :
               '时间线查询完毕,没有找到符合条件的推文。'
             ))
         ))
@@ -330,12 +330,13 @@ export default class {
       Promise.reject())
       .then(content => {
         if (content === null) throw Error();
-        logger.info(`retrieved cached webshot of tweet ${data.id} 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 = data.id;
         const retweetRef = (data.referenced_tweets || []).find(ref => ref.type === 'retweeted');
         if (retweetRef) cacheId += `,rt:${retweetRef.id}`;
-        sendTweets(cacheId, msg, text, author);
+        logger.info(JSON.stringify(Message.parseCQCode(msg)));
+        sendTweets(cacheId, Message.parseCQCode(msg), text, author);
         return null as Tweet;
       })
       .catch(() => {
@@ -351,8 +352,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));
       },

+ 3 - 3
src/webshot.ts

@@ -464,19 +464,19 @@ class Webshot extends CallableInstance<[Tweet[], (...args) => void, number], Pro
       // 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
       const quotedTweet = (data.referenced_tweets || []).find(refTweet => refTweet.type === 'quoted');
       if (quotedTweet) {
         promise = promise.then(() => {
-          messageChain += `\n回复此命令查看引用的推文:\n/twitter_view ${quotedTweet.id}`;
+          messageChain += `\n回复此命令查看引用的推文:\n/twi_view ${quotedTweet.id}`;
         });
       }
       return promise.then(() => {
         logger.info(`done working on ${user.username}/${data.id}, message chain:`);
-        logger.info(JSON.stringify(Message.ellipseBase64(messageChain)));
+        logger.info(JSON.stringify(messageChain));
         let cacheId = data.id;
         if (rtTweet) cacheId += `,rt:${rtTweet.id}`;
         callback(cacheId, messageChain, xmlEntities.decode(text), author);