koishi.js 9.4 KB

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