koishi.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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.ellipseBase64InMessage = 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 logger = loggers_1.getLogger('qqbot');
  18. exports.message = koishi_1.segment;
  19. const ellipseBase64InMessage = (msg) => msg.replace(/(?<=\[CQ:.*base64:\/\/).*?(,|\])/, '...$1');
  20. exports.ellipseBase64InMessage = ellipseBase64InMessage;
  21. class default_1 {
  22. constructor(opt) {
  23. this.getChat = (session) => __awaiter(this, void 0, void 0, function* () {
  24. switch (session.subtype) {
  25. case 'private':
  26. if (session.groupId) {
  27. const friendList = yield session.bot.getFriendList();
  28. if (!friendList.some(friendItem => friendItem.userId === session.userId)) {
  29. return {
  30. chatID: {
  31. qq: Number(session.userId),
  32. group: Number(session.groupId),
  33. },
  34. chatType: "temp",
  35. };
  36. }
  37. }
  38. return {
  39. chatID: Number(session.userId),
  40. chatType: "private",
  41. };
  42. case 'group':
  43. return {
  44. chatID: Number(session.groupId),
  45. chatType: "group",
  46. };
  47. }
  48. });
  49. this.sendTo = (subscriber, msg) => (() => {
  50. switch (subscriber.chatType) {
  51. case 'group':
  52. return this.bot.sendMessage(subscriber.chatID.toString(), msg);
  53. case 'private':
  54. return this.bot.sendPrivateMessage(subscriber.chatID.toString(), msg);
  55. case 'temp':
  56. return this.bot.sendPrivateMessage(subscriber.chatID.qq.toString(), msg);
  57. }
  58. })()
  59. .then(response => {
  60. logger.info(`pushing data to ${JSON.stringify(subscriber.chatID)} was successful, response:`);
  61. logger.info(response);
  62. })
  63. .catch(reason => {
  64. logger.error(`error pushing data to ${JSON.stringify(subscriber.chatID)}, reason: ${reason}`);
  65. throw Error(reason);
  66. });
  67. this.initBot = () => {
  68. this.app = new koishi_1.App({
  69. type: 'onebot',
  70. server: `http://${this.botInfo.host}:${this.botInfo.port}`,
  71. selfId: this.botInfo.bot_id.toString(),
  72. token: this.botInfo.access_token,
  73. onebot: {
  74. quickOperation: 100,
  75. },
  76. axiosConfig: {
  77. maxContentLength: Infinity,
  78. },
  79. processMessage: msg => msg.trim(),
  80. });
  81. this.app.on('friend-request', (session) => __awaiter(this, void 0, void 0, function* () {
  82. const userString = `${session.username}(${session.userId})`;
  83. const groupString = `${session.groupName}(${session.groupId})`;
  84. logger.debug(`detected new friend request event: ${userString}`);
  85. return session.bot.getGroupList().then(groupList => {
  86. if (groupList.some(groupItem => groupItem.groupId === session.groupId)) {
  87. session.bot.handleFriendRequest(session.messageId, true);
  88. return logger.info(`accepted friend request from ${userString} (from group ${groupString})`);
  89. }
  90. logger.warn(`received friend request from ${userString} (from group ${groupString})`);
  91. logger.warn('please manually accept this friend request');
  92. });
  93. }));
  94. this.app.on('group-request', (session) => __awaiter(this, void 0, void 0, function* () {
  95. const userString = `${session.username}(${session.userId})`;
  96. const groupString = `${session.groupName}(${session.groupId})`;
  97. logger.debug(`detected group invitation event: ${groupString}}`);
  98. return session.bot.getFriendList().then(friendList => {
  99. if (friendList.some(friendItem => friendItem.userId = session.userId)) {
  100. session.bot.handleGroupRequest(session.messageId, true);
  101. return logger.info(`accepted group invitation from ${userString} (friend)`);
  102. }
  103. logger.warn(`received group invitation from ${userString} (stranger)`);
  104. logger.warn('please manually accept this group invitation');
  105. });
  106. }));
  107. this.app.middleware((session) => __awaiter(this, void 0, void 0, function* () {
  108. const chat = yield this.getChat(session);
  109. const cmdObj = command_1.parseCmd(session.content);
  110. const reply = (msg) => __awaiter(this, void 0, void 0, function* () { return session.send(msg); });
  111. switch (cmdObj.cmd) {
  112. case 'twitter_view':
  113. case 'twitter_get':
  114. command_1.view(chat, cmdObj.args, reply);
  115. break;
  116. case 'twitter_query':
  117. case 'twitter_gettimeline':
  118. command_1.query(chat, cmdObj.args, reply);
  119. break;
  120. case 'twitter_sub':
  121. case 'twitter_subscribe':
  122. this.botInfo.sub(chat, cmdObj.args, reply);
  123. break;
  124. case 'twitter_unsub':
  125. case 'twitter_unsubscribe':
  126. this.botInfo.unsub(chat, cmdObj.args, reply);
  127. break;
  128. case 'ping':
  129. case 'twitter':
  130. this.botInfo.list(chat, cmdObj.args, reply);
  131. break;
  132. case 'help':
  133. if (cmdObj.args.length === 0) {
  134. reply(`推特搬运机器人:
  135. /twitter - 查询当前聊天中的推文订阅
  136. /twitter_subscribe〈链接|用户名〉- 订阅 Twitter 推文搬运
  137. /twitter_unsubscribe〈链接|用户名〉- 退订 Twitter 推文搬运
  138. /twitter_view〈链接〉- 查看推文
  139. /twitter_query〈链接|用户名〉[参数列表...] - 查询时间线(详见 /help twitter_query)\
  140. ${chat.chatType === "temp" ?
  141. '\n(当前游客模式下无法使用订阅功能,请先添加本账号为好友。)' : ''}`);
  142. }
  143. else if (cmdObj.args[0] === 'twitter_query') {
  144. reply(`查询时间线中的推文:
  145. /twitter_query〈链接|用户名〉[〈参数 1〉=〈值 1〉〈参数 2〉=〈值 2〉...]
  146. 参数列表(方框内全部为可选,留空则为默认):
  147. count:查询数量上限(类型:非零整数,最大值正负 50)[默认值:10]
  148. since:查询起始点(类型:正整数或日期)[默认值:(空,无限过去)]
  149. until:查询结束点(类型:正整数或日期)[默认值:(空,当前时刻)]
  150. noreps 忽略回复推文(类型:on/off)[默认值:on(是)]
  151. norts:忽略原生转推(类型:on/off)[默认值:off(否)]`)
  152. .then(() => reply(`\
  153. 起始点和结束点为正整数时取推特推文编号作为比较基准,否则会尝试作为日期读取。
  154. 推荐的日期格式:2012-12-22 12:22 UTC+2 (日期和时间均为可选,可分别添加)
  155. count 为正时,从新向旧查询;为负时,从旧向新查询
  156. count 与 since/until 并用时,取二者中实际查询结果较少者
  157. 例子:/twitter_query RiccaTachibana count=5 since="2019-12-30\
  158. UTC+9" until="2020-01-06 UTC+8" norts=on
  159. 从起始时间点(含)到结束时间点(不含)从新到旧获取最多 5 条推文,\
  160. 其中不包含原生转推(实际上用户只发了 1 条)`));
  161. }
  162. }
  163. }));
  164. };
  165. this.connect = () => {
  166. this.initBot();
  167. this.app.start().then(() => this.bot = this.app.getBot('onebot'));
  168. };
  169. logger.warn(`Initialized koishi on ${opt.host}:${opt.port} with access_token ${opt.access_token}`);
  170. this.botInfo = opt;
  171. }
  172. }
  173. exports.default = default_1;