koishi.js 15 KB

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