koishi.js 14 KB

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