koishi.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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 = (0, 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.tempSenders = {};
  38. this.next = (type, id) => {
  39. const queue = this.messageQueues[`${type}:${id}`];
  40. if (queue && queue.length) {
  41. queue[0]().then(() => {
  42. queue.shift();
  43. if (!queue.length)
  44. delete this.messageQueues[`${type}:${id}`];
  45. else
  46. this.next(type, id);
  47. });
  48. }
  49. };
  50. this.enqueue = (type, id, resolver, delay) => {
  51. var _a, _b;
  52. let wasEmpty = false;
  53. const queue = (_a = this.messageQueues)[_b = `${type}:${id}`] || (_a[_b] = (() => { wasEmpty = true; return []; })());
  54. queue.push(() => (0, koishi_1.sleep)(wasEmpty ? Math.random() * 3000 + 600 : delay).then(resolver));
  55. logger.debug(`no. of message currently queued for ${type}:${id}: ${queue.length}`);
  56. if (wasEmpty)
  57. this.next(type, id);
  58. };
  59. this.getChat = (session) => __awaiter(this, void 0, void 0, function* () {
  60. switch (session.subtype) {
  61. case 'private':
  62. if (session.sender.groupId) {
  63. const friendList = yield session.bot.getFriendList();
  64. if (!friendList.some(friendItem => friendItem.userId === session.userId)) {
  65. this.tempSenders[session.userId] = session.sender.groupId;
  66. return {
  67. chatID: {
  68. qq: Number(session.userId),
  69. group: Number(session.sender.groupId),
  70. toString: () => session.userId,
  71. },
  72. chatType: "temp",
  73. };
  74. }
  75. }
  76. return {
  77. chatID: Number(session.userId),
  78. chatType: "private",
  79. };
  80. case 'group':
  81. return {
  82. chatID: Number(session.groupId),
  83. chatType: "group",
  84. };
  85. }
  86. });
  87. this.sendToGroup = (groupID, message, delay = 0) => new Promise((resolve, reject) => {
  88. this.enqueue('group', groupID, () => this.bot.sendMessage(groupID, message).then(resolve).catch(reject), delay);
  89. });
  90. this.sendToUser = (userID, message, delay = 0) => new Promise((resolve, reject) => {
  91. this.enqueue('private', userID, () => this.bot.sendPrivateMessage(userID, message).then(resolve).catch(reject), delay);
  92. });
  93. this.sendTo = (subscriber, messageChain, noErrors = false) => Promise.all((splitted => [splitted.message, ...splitted.attachments])(exports.Message.separateAttachment(messageChain)).map((msg, index) => {
  94. const delay = (/\[CQ:/.exec(msg) ? Math.random() * 25600 : 0) +
  95. (index === 0 ? Math.random() * 16000 : 0) +
  96. Math.random() * 3000 + 600;
  97. switch (subscriber.chatType) {
  98. case 'group':
  99. return this.sendToGroup(subscriber.chatID.toString(), msg, delay);
  100. case 'private':
  101. return this.sendToUser(subscriber.chatID.toString(), msg, delay);
  102. case 'temp':
  103. return this.sendToUser(subscriber.chatID.qq.toString(), msg, delay);
  104. }
  105. }))
  106. .then(response => {
  107. if (response === undefined)
  108. return;
  109. logger.info(`pushing data to ${JSON.stringify(subscriber.chatID)} was successful, response: ${response}`);
  110. })
  111. .catch(reason => {
  112. logger.error(exports.Message.ellipseBase64(`error pushing data to ${JSON.stringify(subscriber.chatID)}, reason: ${reason}`));
  113. if (!noErrors)
  114. throw reason instanceof Error ? reason : Error(reason);
  115. });
  116. this.initBot = () => {
  117. this.app = new koishi_1.App({
  118. type: 'onebot',
  119. server: `ws://${this.botInfo.host}:${this.botInfo.port}`,
  120. selfId: this.botInfo.bot_id.toString(),
  121. token: this.botInfo.access_token,
  122. axiosConfig: {
  123. maxContentLength: Infinity,
  124. },
  125. processMessage: msg => msg.trim(),
  126. });
  127. this.app.on('friend-request', (session) => __awaiter(this, void 0, void 0, function* () {
  128. const userString = `${session.username}(${session.userId})`;
  129. let groupId;
  130. let groupString;
  131. if (session.username in this.tempSenders)
  132. groupId = this.tempSenders[session.userId].toString();
  133. logger.debug(`detected new friend request event: ${userString}`);
  134. return session.bot.getGroupList().then(groupList => {
  135. if (groupList.some(groupItem => {
  136. const test = groupItem.groupId === groupId;
  137. if (test)
  138. groupString = `${groupItem.groupName}(${groupId})`;
  139. return test;
  140. })) {
  141. return session.bot.handleFriendRequest(session.messageId, true)
  142. .then(() => { logger.info(`accepted friend request from ${userString} (from group ${groupString})`); })
  143. .catch(error => { logger.error(`error accepting friend request from ${userString}, error: ${error}`); });
  144. }
  145. (0, utils_1.chainPromises)(groupList.map(groupItem => (done) => Promise.resolve(done ||
  146. this.bot.getGroupMember(groupItem.groupId, session.userId).then(() => {
  147. groupString = `${groupItem.groupName}(${groupItem.groupId})`;
  148. return session.bot.handleFriendRequest(session.messageId, true)
  149. .then(() => { logger.info(`accepted friend request from ${userString} (found in group ${groupString})`); })
  150. .catch(error => { logger.error(`error accepting friend request from ${userString}, error: ${error}`); })
  151. .then(() => true);
  152. }).catch(() => false)))).then(done => {
  153. if (done)
  154. return;
  155. logger.warn(`received friend request from ${userString} (stranger)`);
  156. logger.warn('please manually accept this friend request');
  157. });
  158. });
  159. }));
  160. this.app.on('group-request', (session) => __awaiter(this, void 0, void 0, function* () {
  161. const userString = `${session.username}(${session.userId})`;
  162. const groupString = `${session.groupName}(${session.groupId})`;
  163. logger.debug(`detected group invitation event: ${groupString}}`);
  164. return session.bot.getFriendList().then(friendList => {
  165. if (friendList.some(friendItem => friendItem.userId = session.userId)) {
  166. return session.bot.handleGroupRequest(session.messageId, true)
  167. .then(() => { logger.info(`accepted group invitation from ${userString} (friend)`); })
  168. .catch(error => { logger.error(`error accepting group invitation from ${userString}, error: ${error}`); });
  169. }
  170. logger.warn(`received group invitation from ${userString} (stranger)`);
  171. logger.warn('please manually accept this group invitation');
  172. });
  173. }));
  174. this.app.middleware((session) => __awaiter(this, void 0, void 0, function* () {
  175. const chat = yield this.getChat(session);
  176. const cmdObj = (0, command_1.parseCmd)(session.content);
  177. const reply = (msg) => __awaiter(this, void 0, void 0, function* () {
  178. const userString = `${session.username}(${session.userId})`;
  179. return (chat.chatType === "group" ? this.sendToGroup : this.sendToUser)(chat.chatID.toString(), msg)
  180. .catch(error => { logger.error(`error replying to message from ${userString}, error: ${error}`); });
  181. });
  182. switch (cmdObj.cmd) {
  183. case 'igstory_view':
  184. case 'igstory_get':
  185. (0, command_1.view)(chat, cmdObj.args, reply);
  186. break;
  187. case 'igstory_query':
  188. case 'igstory_gettimeline':
  189. (0, command_1.query)(chat, cmdObj.args, reply);
  190. break;
  191. case 'igstory_sub':
  192. case 'igstory_subscribe':
  193. this.botInfo.sub(chat, cmdObj.args, reply);
  194. break;
  195. case 'igstory_unsub':
  196. case 'igstory_unsubscribe':
  197. this.botInfo.unsub(chat, cmdObj.args, reply);
  198. break;
  199. case 'igstory_unsuball':
  200. case 'bye':
  201. this.botInfo.unsubAll(chat, cmdObj.args, reply);
  202. break;
  203. case 'ping':
  204. case 'igstory':
  205. this.botInfo.list(chat, cmdObj.args, reply);
  206. break;
  207. case 'help':
  208. if (cmdObj.args.length === 0) {
  209. reply(`Instagram 限时动态搬运机器人:
  210. /igstory - 查询当前聊天中的 Instagram Stories 动态订阅
  211. /igstory_query〈链接|用户名〉- 列出该用户当前可用的 Stories 时间线
  212. /igstory_sub[scribe]〈链接|用户名〉- 订阅 Instagram Stories 搬运
  213. /igstory_unsub[scribe]〈链接|用户名〉- 退订 Instagram Stories 搬运
  214. /igstory_view〈链接|用户名〉[skip=〈跳过条数〉] [count=〈最大条数(默认:10)〉] - 查看该用户全部或指定范围的 Stories\
  215. ${chat.chatType === "temp" ?
  216. '\n(当前游客模式下无法使用订阅功能,请先添加本账号为好友。)' : ''}`);
  217. }
  218. }
  219. }), true);
  220. };
  221. this.listen = (logMsg = 'connecting to bot provider...') => __awaiter(this, void 0, void 0, function* () {
  222. logger.warn(logMsg);
  223. try {
  224. yield this.app.start();
  225. }
  226. catch (err) {
  227. logger.error(`error connecting to bot provider at ${this.app.options.server}, will retry in 2.5s...`);
  228. yield (0, koishi_1.sleep)(2500);
  229. yield this.listen('retry connecting...');
  230. }
  231. });
  232. this.connect = () => __awaiter(this, void 0, void 0, function* () {
  233. this.initBot();
  234. yield this.listen();
  235. this.bot = this.app.getBot('onebot');
  236. });
  237. logger.warn(`Initialized koishi on ${opt.host}:${opt.port} with access_token ${opt.access_token}`);
  238. this.botInfo = opt;
  239. }
  240. }
  241. exports.default = default_1;