koishi.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. "use strict";
  2. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  4. return new (P || (P = Promise))(function (resolve, reject) {
  5. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  6. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  7. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  8. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9. });
  10. };
  11. Object.defineProperty(exports, "__esModule", { value: true });
  12. exports.Message = void 0;
  13. const koishi_1 = require("koishi");
  14. require("koishi-adapter-onebot");
  15. const command_1 = require("./command");
  16. const loggers_1 = require("./loggers");
  17. const utils_1 = require("./utils");
  18. const logger = loggers_1.getLogger('qqbot');
  19. const cqUrlFix = (factory) => (...args) => factory(...args).replace(/(?<=\[CQ:.*)url=(?=(base64|file|https?):\/\/)/, 'file=');
  20. exports.Message = {
  21. Image: cqUrlFix(koishi_1.segment.image),
  22. Video: cqUrlFix(koishi_1.segment.video),
  23. Voice: cqUrlFix(koishi_1.segment.audio),
  24. ellipseBase64: (msg) => msg.replace(/(?<=\[CQ:.*base64:\/\/).*?(,|\])/g, '...$1'),
  25. separateAttachment: (msg) => {
  26. const attachments = [];
  27. const message = msg.replace(/\[CQ:(video|record),.*?\]/g, code => {
  28. attachments.push(code);
  29. return '';
  30. });
  31. return { message, attachments };
  32. },
  33. };
  34. class default_1 {
  35. constructor(opt) {
  36. this.messageQueues = {};
  37. this.next = (type, id) => {
  38. const queue = this.messageQueues[`${type}:${id}`];
  39. if (queue && queue.length) {
  40. queue[0]().then(() => {
  41. queue.shift();
  42. if (!queue.length)
  43. delete this.messageQueues[`${type}:${id}`];
  44. else
  45. this.next(type, id);
  46. });
  47. }
  48. };
  49. this.enqueue = (type, id, resolver) => {
  50. var _a, _b;
  51. let wasEmpty = false;
  52. const queue = (_a = this.messageQueues)[_b = `${type}:${id}`] || (_a[_b] = (() => { wasEmpty = true; return []; })());
  53. queue.push(() => koishi_1.sleep(200).then(resolver));
  54. logger.debug(`no. of message currently queued for ${type}:${id}: ${queue.length}`);
  55. if (wasEmpty)
  56. this.next(type, id);
  57. };
  58. this.getChat = (session) => __awaiter(this, void 0, void 0, function* () {
  59. switch (session.subtype) {
  60. case 'private':
  61. if (session.groupId) {
  62. const friendList = yield session.bot.getFriendList();
  63. if (!friendList.some(friendItem => friendItem.userId === session.userId)) {
  64. return {
  65. chatID: {
  66. qq: Number(session.userId),
  67. group: Number(session.groupId),
  68. },
  69. chatType: "temp",
  70. };
  71. }
  72. }
  73. return {
  74. chatID: Number(session.userId),
  75. chatType: "private",
  76. };
  77. case 'group':
  78. return {
  79. chatID: Number(session.groupId),
  80. chatType: "group",
  81. };
  82. }
  83. });
  84. this.sendToGroup = (groupID, message) => new Promise(resolve => {
  85. this.enqueue('group', groupID, () => this.bot.sendMessage(groupID, message).then(resolve));
  86. });
  87. this.sendToUser = (userID, message) => new Promise(resolve => {
  88. this.enqueue('private', userID, () => this.bot.sendPrivateMessage(userID, message).then(resolve));
  89. });
  90. this.sendTo = (subscriber, messageChain) => utils_1.chainPromises((splitted => [splitted.message, ...splitted.attachments])(exports.Message.separateAttachment(messageChain)).map(msg => {
  91. switch (subscriber.chatType) {
  92. case 'group':
  93. return this.sendToGroup(subscriber.chatID.toString(), msg);
  94. case 'private':
  95. return this.sendToUser(subscriber.chatID.toString(), msg);
  96. case 'temp':
  97. return this.sendToUser(subscriber.chatID.qq.toString(), msg);
  98. }
  99. }))
  100. .then(response => {
  101. if (response === undefined)
  102. return;
  103. logger.info(`pushing data to ${JSON.stringify(subscriber.chatID)} was successful, response: ${response}`);
  104. })
  105. .catch(reason => {
  106. reason = exports.Message.ellipseBase64(reason);
  107. logger.error(`error pushing data to ${JSON.stringify(subscriber.chatID)}, reason: ${reason}`);
  108. throw Error(reason);
  109. });
  110. this.initBot = () => {
  111. this.app = new koishi_1.App({
  112. type: 'onebot',
  113. server: `ws://${this.botInfo.host}:${this.botInfo.port}`,
  114. selfId: this.botInfo.bot_id.toString(),
  115. token: this.botInfo.access_token,
  116. axiosConfig: {
  117. maxContentLength: Infinity,
  118. },
  119. processMessage: msg => msg.trim(),
  120. });
  121. this.app.on('friend-request', (session) => __awaiter(this, void 0, void 0, function* () {
  122. const userString = `${session.username}(${session.userId})`;
  123. const groupString = `${session.groupName}(${session.groupId})`;
  124. logger.debug(`detected new friend request event: ${userString}`);
  125. return session.bot.getGroupList().then(groupList => {
  126. if (groupList.some(groupItem => groupItem.groupId === session.groupId)) {
  127. session.bot.handleFriendRequest(session.messageId, true);
  128. return logger.info(`accepted friend request from ${userString} (from group ${groupString})`);
  129. }
  130. logger.warn(`received friend request from ${userString} (from group ${groupString})`);
  131. logger.warn('please manually accept this friend request');
  132. });
  133. }));
  134. this.app.on('group-request', (session) => __awaiter(this, void 0, void 0, function* () {
  135. const userString = `${session.username}(${session.userId})`;
  136. const groupString = `${session.groupName}(${session.groupId})`;
  137. logger.debug(`detected group invitation event: ${groupString}}`);
  138. return session.bot.getFriendList().then(friendList => {
  139. if (friendList.some(friendItem => friendItem.userId = session.userId)) {
  140. session.bot.handleGroupRequest(session.messageId, true);
  141. return logger.info(`accepted group invitation from ${userString} (friend)`);
  142. }
  143. logger.warn(`received group invitation from ${userString} (stranger)`);
  144. logger.warn('please manually accept this group invitation');
  145. });
  146. }));
  147. this.app.middleware((session) => __awaiter(this, void 0, void 0, function* () {
  148. const chat = yield this.getChat(session);
  149. const cmdObj = command_1.parseCmd(session.content);
  150. const reply = (msg) => __awaiter(this, void 0, void 0, function* () { return session.sendQueued(msg); });
  151. switch (cmdObj.cmd) {
  152. case 'instagram_view':
  153. case 'instagram_get':
  154. command_1.view(chat, cmdObj.args, reply);
  155. break;
  156. case 'instagram_sub':
  157. case 'instagram_subscribe':
  158. this.botInfo.sub(chat, cmdObj.args, reply);
  159. break;
  160. case 'instagram_unsub':
  161. case 'instagram_unsubscribe':
  162. this.botInfo.unsub(chat, cmdObj.args, reply);
  163. break;
  164. case 'ping':
  165. case 'instagram':
  166. this.botInfo.list(chat, cmdObj.args, reply);
  167. break;
  168. case 'help':
  169. if (cmdObj.args.length === 0) {
  170. reply(`Instagram 搬运机器人:
  171. /instagram - 查询当前聊天中的 Instagram 动态订阅
  172. /instagram_subscribe〈链接|用户名〉- 订阅 Instagram 媒体搬运
  173. /instagram_unsubscribe〈链接|用户名〉- 退订 Instagram 媒体搬运
  174. /instagram_view〈链接〉- 查看媒体
  175. ${chat.chatType === "temp" ?
  176. '\n(当前游客模式下无法使用订阅功能,请先添加本账号为好友。)' : ''}`);
  177. }
  178. }
  179. }), true);
  180. };
  181. this.listen = (logMsg = 'connecting to bot provider...') => __awaiter(this, void 0, void 0, function* () {
  182. logger.warn(logMsg);
  183. try {
  184. yield this.app.start();
  185. }
  186. catch (err) {
  187. logger.error(`error connecting to bot provider at ${this.app.options.server}, will retry in 2.5s...`);
  188. yield koishi_1.sleep(2500);
  189. yield this.listen('retry connecting...');
  190. }
  191. });
  192. this.connect = () => __awaiter(this, void 0, void 0, function* () {
  193. this.initBot();
  194. yield this.listen();
  195. this.bot = this.app.getBot('onebot');
  196. });
  197. logger.warn(`Initialized koishi on ${opt.host}:${opt.port} with access_token ${opt.access_token}`);
  198. this.botInfo = opt;
  199. }
  200. }
  201. exports.default = default_1;