koishi.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. const plugin_adapter_onebot_1 = require("@koishijs/plugin-adapter-onebot");
  15. const command_1 = require("./command");
  16. const loggers_1 = require("./loggers");
  17. const logger = (0, loggers_1.getLogger)('qqbot');
  18. const batchExec = (executer, ...[chat, args, reply]) => {
  19. let combinedMsg = '';
  20. let promise = Promise.resolve();
  21. args.forEach(arg => {
  22. promise = promise.then(() => new Promise(resolve => {
  23. executer(chat, [arg], (msg) => {
  24. combinedMsg += msg + '\n';
  25. resolve();
  26. });
  27. }));
  28. });
  29. promise.then(() => {
  30. if (combinedMsg)
  31. reply(combinedMsg.slice(0, -1));
  32. });
  33. };
  34. exports.Message = {
  35. Image: koishi_1.segment.image,
  36. Video: koishi_1.segment.video,
  37. Voice: koishi_1.segment.audio,
  38. separateAttachment: (msg) => {
  39. const attachments = [];
  40. const message = msg.replace(/<(video|record) .*?\/>/g, code => {
  41. attachments.push(code);
  42. return '';
  43. });
  44. return { message, attachments };
  45. },
  46. parseCQCode: (cqStr) => plugin_adapter_onebot_1.CQCode.parse(cqStr).map(seg => {
  47. if (typeof seg.attrs.file === 'string') {
  48. seg.attrs.url = seg.attrs.file;
  49. delete seg.attrs.file;
  50. }
  51. return seg;
  52. }).join(''),
  53. toCQCode: (segStr) => koishi_1.segment.parse(segStr).map(seg => {
  54. if (typeof seg.attrs.url === 'string') {
  55. seg.attrs.file = seg.attrs.url;
  56. delete seg.attrs.url;
  57. }
  58. return (0, plugin_adapter_onebot_1.CQCode)(seg.type, seg.attrs);
  59. }).join(''),
  60. };
  61. class default_1 {
  62. constructor(opt) {
  63. this.messageQueues = {};
  64. this.tempSenders = {};
  65. this.next = (type, id) => {
  66. const queue = this.messageQueues[`${type}:${id}`];
  67. if (queue && queue.length) {
  68. queue[0]().then(() => {
  69. queue.shift();
  70. if (!queue.length)
  71. delete this.messageQueues[`${type}:${id}`];
  72. else
  73. this.next(type, id);
  74. });
  75. }
  76. };
  77. this.enqueue = (type, id, resolver) => {
  78. var _a, _b;
  79. let wasEmpty = false;
  80. const queue = (_a = this.messageQueues)[_b = `${type}:${id}`] || (_a[_b] = (() => { wasEmpty = true; return []; })());
  81. queue.push(() => (0, koishi_1.sleep)(200).then(resolver));
  82. logger.debug(`no. of message currently queued for ${type}:${id}: ${queue.length}`);
  83. if (wasEmpty)
  84. this.next(type, id);
  85. };
  86. this.getSender = ({ chatID, chatType }) => (msg) => (chatType === 'guild' ? this.sendToChannel :
  87. chatType === 'group' ? this.sendToGroup :
  88. this.sendToUser)(chatID.toString(), msg);
  89. this.getChat = (session) => __awaiter(this, void 0, void 0, function* () {
  90. if (session.type !== 'message')
  91. return null;
  92. if (session.subsubtype === 'guild') {
  93. return {
  94. chatID: `${session.onebot.guild_id}:${session.onebot.channel_id}`,
  95. chatType: 'guild',
  96. };
  97. }
  98. switch (session.subtype) {
  99. case 'private':
  100. const { group_id: groupId } = session.onebot.sender;
  101. if (groupId) {
  102. const friendList = yield session.bot.getFriendList();
  103. if (!friendList.some(friendItem => friendItem.userId === session.userId)) {
  104. this.tempSenders[session.userId] = groupId;
  105. return {
  106. chatID: {
  107. qq: Number(session.userId),
  108. group: Number(groupId),
  109. toString: () => session.userId,
  110. },
  111. chatType: 'temp',
  112. };
  113. }
  114. }
  115. return {
  116. chatID: Number(session.userId),
  117. chatType: 'private',
  118. };
  119. case 'group':
  120. return {
  121. chatID: Number(session.guildId),
  122. chatType: 'group',
  123. };
  124. }
  125. });
  126. this.sendToChannel = (guildChannel, message) => new Promise((resolve, reject) => {
  127. const [guildID, channelID] = guildChannel.split(':');
  128. this.enqueue('guild', guildChannel, () => this.bot.guildBot.sendMessage(channelID, message, guildID)
  129. .then(([response]) => resolve(response)).catch(reject));
  130. });
  131. this.sendToGroup = (groupID, message) => new Promise((resolve, reject) => {
  132. this.enqueue('group', groupID, () => this.bot.sendMessage(groupID, message)
  133. .then(([response]) => resolve(response)).catch(reject));
  134. });
  135. this.sendToUser = (userID, message) => new Promise((resolve, reject) => {
  136. this.enqueue('private', userID, () => this.bot.sendPrivateMessage(userID, message)
  137. .then(([response]) => resolve(response)).catch(reject));
  138. });
  139. this.sendTo = (subscriber, messageChain, noErrors = false) => Promise.all((splitted => [splitted.message, ...splitted.attachments])(exports.Message.separateAttachment(messageChain)).map(this.getSender(subscriber)))
  140. .then(response => {
  141. if (response === undefined)
  142. return;
  143. logger.info(`pushing data to ${JSON.stringify(subscriber.chatID)} was successful, response: ${response}`);
  144. })
  145. .catch(reason => {
  146. logger.error(`error pushing data to ${JSON.stringify(subscriber.chatID)}, reason: ${reason}`);
  147. if (!noErrors)
  148. throw reason instanceof Error ? reason : Error(reason);
  149. });
  150. this.initBot = () => {
  151. this.app = new koishi_1.App();
  152. this.app.plugin(plugin_adapter_onebot_1.default, this.config);
  153. this.app.on('friend-request', (session) => __awaiter(this, void 0, void 0, function* () {
  154. const userString = `${session.username}(${session.userId})`;
  155. logger.debug(`detected new friend request event: ${userString}`);
  156. try {
  157. const isTemp = session.username in this.tempSenders;
  158. const { guildId, guildName } = isTemp ?
  159. yield session.bot.getGuild(this.tempSenders[session.userId].toString()) :
  160. (yield session.bot.getGuildList()).find(({ guildId }) => __awaiter(this, void 0, void 0, function* () {
  161. try {
  162. return yield this.bot.getGuildMember(guildId, session.userId);
  163. }
  164. catch (_b) { }
  165. }));
  166. try {
  167. const groupString = `${guildName}(${guildId})`;
  168. yield session.bot.handleFriendRequest(session.messageId, true);
  169. logger.info(`accepted friend request from ${userString} (${isTemp ? 'from' : 'found in'} group ${groupString})`);
  170. }
  171. catch (error) {
  172. logger.error(`error accepting friend request from ${userString}, error: ${error}`);
  173. }
  174. }
  175. catch (_a) {
  176. logger.warn(`received friend request from ${userString} (stranger)`);
  177. logger.warn('please manually accept this friend request');
  178. }
  179. }));
  180. this.app.on('guild-request', (session) => __awaiter(this, void 0, void 0, function* () {
  181. const userString = `${session.username}(${session.userId})`;
  182. const groupString = `${session.guildName}(${session.guildId})`;
  183. logger.debug(`detected group invitation event: ${groupString}}`);
  184. const friendList = yield session.bot.getFriendList();
  185. if (friendList.some(friendItem => friendItem.userId = session.userId)) {
  186. try {
  187. session.bot.handleGuildRequest(session.messageId, true);
  188. logger.info(`accepted group invitation from ${userString} (friend)`);
  189. }
  190. catch (error) {
  191. logger.error(`error accepting group invitation from ${userString}, error: ${error}`);
  192. }
  193. }
  194. logger.warn(`received group invitation from ${userString} (stranger)`);
  195. logger.warn('please manually accept this group invitation');
  196. }));
  197. this.app.middleware((session) => __awaiter(this, void 0, void 0, function* () {
  198. const chat = yield this.getChat(session);
  199. let userString = `${session.username}(${session.userId})`;
  200. if (chat.chatType === 'temp') {
  201. const group = yield session.bot.getGuild(chat.chatID.group.toString());
  202. userString += ` (from group ${group.guildName}(${group.guildId}))`;
  203. }
  204. const cmdObj = (0, command_1.parseCmd)(session.content);
  205. const reply = (msg) => this.getSender(chat)(msg).catch(error => {
  206. if (chat.chatType === 'temp') {
  207. return logger.info(`ignored error while replying to ${userString}`);
  208. }
  209. logger.error(`error replying to message from ${userString}, error: ${error}`);
  210. });
  211. switch (cmdObj.cmd) {
  212. case 'twipic_view':
  213. (0, command_1.view)(chat, cmdObj.args, reply);
  214. break;
  215. case 'twipic_resendlast':
  216. (0, command_1.resendLast)(chat, cmdObj.args, reply);
  217. break;
  218. case 'twipic_query':
  219. (0, command_1.query)(chat, cmdObj.args, reply);
  220. break;
  221. case 'twipic_sub':
  222. batchExec(this.botInfo.sub, chat, cmdObj.args, reply);
  223. break;
  224. case 'twipic_unsub':
  225. batchExec(this.botInfo.unsub, chat, cmdObj.args, reply);
  226. break;
  227. case 'twipic_unsuball':
  228. this.botInfo.unsubAll(chat, cmdObj.args, reply);
  229. break;
  230. case 'twipic_listsub':
  231. this.botInfo.list(chat, cmdObj.args, reply);
  232. break;
  233. case 'help':
  234. if (cmdObj.args[0] === 'twipic') {
  235. reply(`推特媒体推文搬运机器人:
  236. /twipic_listsub - 查询当前聊天中的媒体推文订阅
  237. /twipic_sub〈链接|用户名〉[〈链接|用户名〉...] - 订阅一个或多个媒体推文搬运
  238. /twipic_unsub〈链接|用户名〉[〈链接|用户名〉...] - 退订一个或多个媒体推文搬运
  239. /twipic_unsuball - 退订当前聊天中全部的媒体推文搬运
  240. /twipic_view〈链接|表达式〉[{force|refresh}={on|off}] - 查看推文(可选强制重新载入)
  241. /twipic_resendlast〈用户名〉- 强制重发该用户最后一条媒体推文
  242. /twipic_query〈链接|用户名〉[参数列表...] - 查询时间线(详见 /help twipic_query)\
  243. ${chat.chatType === 'temp' ?
  244. '\n(当前游客模式下无法使用订阅功能,请先添加本账号为好友。)' : ''}`);
  245. }
  246. else if (cmdObj.args[0] === 'twipic_query') {
  247. reply(`查询时间线中的媒体推文:
  248. /twipic_query〈链接|用户名〉[〈参数 1〉=〈值 1〉〈参数 2〉=〈值 2〉...]
  249. 参数列表(方框内全部为可选,留空则为默认):
  250. count:查询数量上限(类型:非零整数,最大值正负 50)[默认值:10]
  251. since:查询起始点(类型:正整数或日期)[默认值:(空,无限过去)]
  252. until:查询结束点(类型:正整数或日期)[默认值:(空,当前时刻)]
  253. noreps 忽略回复推文(类型:on/off)[默认值:on(是)]
  254. norts:忽略原生转推(类型:on/off)[默认值:off(否)]`)
  255. .then(() => reply(`\
  256. 起始点和结束点为正整数时取推特推文编号作为比较基准,否则会尝试作为日期读取。
  257. 推荐的日期格式:2012-12-22 12:22 UTC+2 (日期和时间均为可选,可分别添加)
  258. count 为正时,从新向旧查询;为负时,从旧向新查询
  259. count 与 since/until 并用时,取二者中实际查询结果较少者
  260. 例子:/twipic_query RiccaTachibana count=5 since="2019-12-30\
  261. UTC+9" until="2020-01-06 UTC+8" norts=on
  262. 从起始时间点(含)到结束时间点(不含)从新到旧获取最多 5 条媒体推文,\
  263. 其中不包含原生转推(实际上用户只发了 1 条)`));
  264. }
  265. }
  266. }), true);
  267. };
  268. this.listen = (logMsg = 'connecting to bot provider...') => __awaiter(this, void 0, void 0, function* () {
  269. logger.warn(logMsg);
  270. try {
  271. yield this.app.start();
  272. }
  273. catch (err) {
  274. logger.error(`error connecting to bot provider at ${this.config.endpoint}, will retry in 2.5s...`);
  275. yield (0, koishi_1.sleep)(2500);
  276. yield this.listen('retry connecting...');
  277. }
  278. });
  279. this.connect = () => __awaiter(this, void 0, void 0, function* () {
  280. this.initBot();
  281. yield this.listen();
  282. this.bot = this.app.bots.find(bot => bot.selfId === this.config.selfId);
  283. });
  284. logger.warn(`Initialized koishi on ${opt.host}:${opt.port} with access_token ${opt.access_token}`);
  285. this.botInfo = opt;
  286. }
  287. get config() {
  288. return {
  289. protocol: 'ws',
  290. endpoint: `ws://${this.botInfo.host}:${this.botInfo.port}`,
  291. selfId: this.botInfo.bot_id.toString(),
  292. token: this.botInfo.access_token,
  293. };
  294. }
  295. ;
  296. }
  297. exports.default = default_1;