koishi.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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(() => queue.shift()).then(() => {
  41. if (!queue.length)
  42. delete this.messageQueues[`${type}:${id}`];
  43. else
  44. this.next(type, id);
  45. });
  46. }
  47. };
  48. this.enqueue = (type, id, resolver) => {
  49. var _a, _b;
  50. const queue = (_a = this.messageQueues)[_b = `${type}:${id}`] || (_a[_b] = []);
  51. queue.push(() => koishi_1.sleep(200).then(resolver));
  52. logger.debug(`no. of message currently queued for ${type}:${id}: ${queue.length}`);
  53. if (queue.length === 1)
  54. this.next(type, id);
  55. };
  56. this.getChat = (session) => __awaiter(this, void 0, void 0, function* () {
  57. switch (session.subtype) {
  58. case 'private':
  59. if (session.groupId) {
  60. const friendList = yield session.bot.getFriendList();
  61. if (!friendList.some(friendItem => friendItem.userId === session.userId)) {
  62. return {
  63. chatID: {
  64. qq: Number(session.userId),
  65. group: Number(session.groupId),
  66. },
  67. chatType: "temp",
  68. };
  69. }
  70. }
  71. return {
  72. chatID: Number(session.userId),
  73. chatType: "private",
  74. };
  75. case 'group':
  76. return {
  77. chatID: Number(session.groupId),
  78. chatType: "group",
  79. };
  80. }
  81. });
  82. this.sendToGroup = (groupID, message) => new Promise(resolve => {
  83. this.enqueue('group', groupID, () => this.bot.sendMessage(groupID, message).then(resolve));
  84. });
  85. this.sendToUser = (userID, message) => new Promise(resolve => {
  86. this.enqueue('private', userID, () => this.bot.sendPrivateMessage(userID, message).then(resolve));
  87. });
  88. this.sendTo = (subscriber, messageChain) => utils_1.chainPromises((splitted => [splitted.message, ...splitted.attachments])(exports.Message.separateAttachment(messageChain)).map(msg => {
  89. switch (subscriber.chatType) {
  90. case 'group':
  91. return this.sendToGroup(subscriber.chatID.toString(), msg);
  92. case 'private':
  93. return this.sendToUser(subscriber.chatID.toString(), msg);
  94. case 'temp':
  95. return this.sendToUser(subscriber.chatID.qq.toString(), msg);
  96. }
  97. }))
  98. .then(response => {
  99. if (response === undefined)
  100. return;
  101. logger.info(`pushing data to ${JSON.stringify(subscriber.chatID)} was successful, response: ${response}`);
  102. })
  103. .catch(reason => {
  104. reason = exports.Message.ellipseBase64(reason);
  105. logger.error(`error pushing data to ${JSON.stringify(subscriber.chatID)}, reason: ${reason}`);
  106. throw Error(reason);
  107. });
  108. this.initBot = () => {
  109. this.app = new koishi_1.App({
  110. type: 'onebot',
  111. server: `ws://${this.botInfo.host}:${this.botInfo.port}`,
  112. selfId: this.botInfo.bot_id.toString(),
  113. token: this.botInfo.access_token,
  114. axiosConfig: {
  115. maxContentLength: Infinity,
  116. },
  117. processMessage: msg => msg.trim(),
  118. });
  119. this.app.on('friend-request', (session) => __awaiter(this, void 0, void 0, function* () {
  120. const userString = `${session.username}(${session.userId})`;
  121. const groupString = `${session.groupName}(${session.groupId})`;
  122. logger.debug(`detected new friend request event: ${userString}`);
  123. return session.bot.getGroupList().then(groupList => {
  124. if (groupList.some(groupItem => groupItem.groupId === session.groupId)) {
  125. session.bot.handleFriendRequest(session.messageId, true);
  126. return logger.info(`accepted friend request from ${userString} (from group ${groupString})`);
  127. }
  128. logger.warn(`received friend request from ${userString} (from group ${groupString})`);
  129. logger.warn('please manually accept this friend request');
  130. });
  131. }));
  132. this.app.on('group-request', (session) => __awaiter(this, void 0, void 0, function* () {
  133. const userString = `${session.username}(${session.userId})`;
  134. const groupString = `${session.groupName}(${session.groupId})`;
  135. logger.debug(`detected group invitation event: ${groupString}}`);
  136. return session.bot.getFriendList().then(friendList => {
  137. if (friendList.some(friendItem => friendItem.userId = session.userId)) {
  138. session.bot.handleGroupRequest(session.messageId, true);
  139. return logger.info(`accepted group invitation from ${userString} (friend)`);
  140. }
  141. logger.warn(`received group invitation from ${userString} (stranger)`);
  142. logger.warn('please manually accept this group invitation');
  143. });
  144. }));
  145. this.app.middleware((session) => __awaiter(this, void 0, void 0, function* () {
  146. const chat = yield this.getChat(session);
  147. const cmdObj = command_1.parseCmd(session.content);
  148. const reply = (msg) => __awaiter(this, void 0, void 0, function* () { return session.sendQueued(msg); });
  149. switch (cmdObj.cmd) {
  150. case 'twitter_view':
  151. case 'twitter_get':
  152. command_1.view(chat, cmdObj.args, reply);
  153. break;
  154. case 'twitter_query':
  155. case 'twitter_gettimeline':
  156. command_1.query(chat, cmdObj.args, reply);
  157. break;
  158. case 'twitter_sub':
  159. case 'twitter_subscribe':
  160. this.botInfo.sub(chat, cmdObj.args, reply);
  161. break;
  162. case 'twitter_unsub':
  163. case 'twitter_unsubscribe':
  164. this.botInfo.unsub(chat, cmdObj.args, reply);
  165. break;
  166. case 'ping':
  167. case 'twitter':
  168. this.botInfo.list(chat, cmdObj.args, reply);
  169. break;
  170. case 'help':
  171. if (cmdObj.args.length === 0) {
  172. reply(`推特搬运机器人:
  173. /twitter - 查询当前聊天中的推文订阅
  174. /twitter_subscribe〈链接|用户名〉- 订阅 Twitter 推文搬运
  175. /twitter_unsubscribe〈链接|用户名〉- 退订 Twitter 推文搬运
  176. /twitter_view〈链接〉- 查看推文
  177. /twitter_query〈链接|用户名〉[参数列表...] - 查询时间线(详见 /help twitter_query)\
  178. ${chat.chatType === "temp" ?
  179. '\n(当前游客模式下无法使用订阅功能,请先添加本账号为好友。)' : ''}`);
  180. }
  181. else if (cmdObj.args[0] === 'twitter_query') {
  182. reply(`查询时间线中的推文:
  183. /twitter_query〈链接|用户名〉[〈参数 1〉=〈值 1〉〈参数 2〉=〈值 2〉...]
  184. 参数列表(方框内全部为可选,留空则为默认):
  185. count:查询数量上限(类型:非零整数,最大值正负 50)[默认值:10]
  186. since:查询起始点(类型:正整数或日期)[默认值:(空,无限过去)]
  187. until:查询结束点(类型:正整数或日期)[默认值:(空,当前时刻)]
  188. noreps 忽略回复推文(类型:on/off)[默认值:on(是)]
  189. norts:忽略原生转推(类型:on/off)[默认值:off(否)]`)
  190. .then(() => reply(`\
  191. 起始点和结束点为正整数时取推特推文编号作为比较基准,否则会尝试作为日期读取。
  192. 推荐的日期格式:2012-12-22 12:22 UTC+2 (日期和时间均为可选,可分别添加)
  193. count 为正时,从新向旧查询;为负时,从旧向新查询
  194. count 与 since/until 并用时,取二者中实际查询结果较少者
  195. 例子:/twitter_query RiccaTachibana count=5 since="2019-12-30\
  196. UTC+9" until="2020-01-06 UTC+8" norts=on
  197. 从起始时间点(含)到结束时间点(不含)从新到旧获取最多 5 条推文,\
  198. 其中不包含原生转推(实际上用户只发了 1 条)`));
  199. }
  200. }
  201. }), true);
  202. };
  203. this.listen = (logMsg = 'connecting to bot provider...') => __awaiter(this, void 0, void 0, function* () {
  204. logger.warn(logMsg);
  205. try {
  206. yield this.app.start();
  207. }
  208. catch (err) {
  209. logger.error(`error connecting to bot provider at ${this.app.options.server}, will retry in 2.5s...`);
  210. yield koishi_1.sleep(2500);
  211. yield this.listen('retry connecting...');
  212. }
  213. });
  214. this.connect = () => __awaiter(this, void 0, void 0, function* () {
  215. this.initBot();
  216. yield this.listen();
  217. this.bot = this.app.getBot('onebot');
  218. });
  219. logger.warn(`Initialized koishi on ${opt.host}:${opt.port} with access_token ${opt.access_token}`);
  220. this.botInfo = opt;
  221. }
  222. }
  223. exports.default = default_1;