mirai.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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 axios_1 = require("axios");
  14. const fs_1 = require("fs");
  15. const mirai_ts_1 = require("mirai-ts");
  16. const message_1 = require("mirai-ts/dist/message");
  17. const temp = require("temp");
  18. const command_1 = require("./command");
  19. const loggers_1 = require("./loggers");
  20. const logger = loggers_1.getLogger('qqbot');
  21. exports.Message = message_1.default;
  22. class default_1 {
  23. constructor(opt) {
  24. this.getChat = (msg) => __awaiter(this, void 0, void 0, function* () {
  25. switch (msg.type) {
  26. case 'FriendMessage':
  27. return {
  28. chatID: msg.sender.id,
  29. chatType: "private" /* Private */,
  30. };
  31. case 'GroupMessage':
  32. return {
  33. chatID: msg.sender.group.id,
  34. chatType: "group" /* Group */,
  35. };
  36. case 'TempMessage':
  37. const friendList = yield this.bot.api.friendList();
  38. // already befriended
  39. if (friendList.some(friendItem => friendItem.id === msg.sender.id)) {
  40. return {
  41. chatID: msg.sender.id,
  42. chatType: "private" /* Private */,
  43. };
  44. }
  45. return {
  46. chatID: {
  47. qq: msg.sender.id,
  48. group: msg.sender.group.id,
  49. },
  50. chatType: "temp" /* Temp */,
  51. };
  52. }
  53. });
  54. this.sendTo = (subscriber, msg) => {
  55. const chain = [];
  56. const voices = [];
  57. return (() => {
  58. if (typeof msg !== 'string') {
  59. msg.forEach(singleMsg => (singleMsg.type === 'Voice' ? voices : chain).push(singleMsg));
  60. msg = chain;
  61. }
  62. switch (subscriber.chatType) {
  63. case 'group':
  64. return this.bot.api.sendGroupMessage(msg, subscriber.chatID);
  65. case 'private':
  66. return this.bot.api.sendFriendMessage(msg, subscriber.chatID);
  67. // currently disabled
  68. case 'temp':
  69. return this.bot.api.sendTempMessage(msg, subscriber.chatID.qq, subscriber.chatID.group);
  70. }
  71. })()
  72. .then(response => {
  73. logger.info(`pushing data to ${JSON.stringify(subscriber.chatID)} was successful, response:`);
  74. logger.info(response);
  75. })
  76. .then(() => {
  77. if (voices.length && subscriber.chatType === 'group') {
  78. voices.forEach((voice, index) => this.bot.api.sendGroupMessage([voice], subscriber.chatID)
  79. .then(voiceResponse => {
  80. logger.info(`pushing voice #${index} to ${JSON.stringify(subscriber.chatID)} was successful, response:`);
  81. logger.info(voiceResponse);
  82. }));
  83. }
  84. })
  85. .catch(reason => {
  86. logger.error(`error pushing data to ${JSON.stringify(subscriber.chatID)}, reason: ${reason}`);
  87. throw Error(reason);
  88. });
  89. };
  90. this.upload = (mediaMsg, timeout = -1) => {
  91. const idKeyName = `${mediaMsg.type.toLowerCase()}Id`;
  92. if (timeout)
  93. timeout = Math.floor(timeout);
  94. if (timeout === 0 || timeout < -1) {
  95. return Promise.reject('Error: timeout must be greater than 0ms');
  96. }
  97. let file;
  98. if (mediaMsg[idKeyName] !== '')
  99. return Promise.resolve();
  100. if (mediaMsg.url !== '') {
  101. if (mediaMsg.url.split(':')[0] !== 'data') {
  102. return Promise.reject('Error: URL must be of protocol "data"');
  103. }
  104. if (mediaMsg.url.split(',')[0].split(';')[1] !== 'base64') {
  105. return Promise.reject('Error: data URL must be of encoding "base64"');
  106. }
  107. temp.track();
  108. try {
  109. const tempFile = temp.openSync();
  110. fs_1.writeSync(tempFile.fd, Buffer.from(mediaMsg.url.split(',')[1], 'base64'));
  111. fs_1.closeSync(tempFile.fd);
  112. file = tempFile.path;
  113. }
  114. catch (error) {
  115. logger.error(error);
  116. }
  117. }
  118. try {
  119. this.bot.axios.defaults.timeout = timeout === -1 ? 0 : timeout;
  120. logger.info(`uploading ${JSON.stringify(exports.Message[mediaMsg.type](mediaMsg[idKeyName], `${mediaMsg.url.split(',')[0]},[...]`, mediaMsg.path))}...`);
  121. return this.bot.api[`upload${mediaMsg.type}`]('group', file || mediaMsg.path)
  122. .then(response => {
  123. logger.info(`uploading ${mediaMsg.path} as group ${mediaMsg.type.toLowerCase()} was successful, response:`);
  124. logger.info(JSON.stringify(response));
  125. if (mediaMsg.type === 'Voice')
  126. mediaMsg[idKeyName] = response[idKeyName];
  127. mediaMsg.url = '';
  128. mediaMsg.path = response.path.split(/[/\\]/).slice(-1)[0];
  129. })
  130. .catch(reason => {
  131. logger.error(`error uploading ${mediaMsg.path}, reason: ${reason}`);
  132. throw Error(reason);
  133. });
  134. }
  135. finally {
  136. temp.cleanup();
  137. this.bot.axios.defaults.timeout = 0;
  138. }
  139. };
  140. this.initBot = () => {
  141. this.bot = new mirai_ts_1.default({
  142. authKey: this.botInfo.access_token,
  143. enableWebsocket: false,
  144. host: this.botInfo.host,
  145. port: this.botInfo.port,
  146. });
  147. this.bot.axios.defaults.maxContentLength = this.bot.axios.defaults.maxBodyLength = Infinity;
  148. this.bot.on('NewFriendRequestEvent', evt => {
  149. logger.debug(`detected new friend request event: ${JSON.stringify(evt)}`);
  150. this.bot.api.groupList()
  151. .then((groupList) => {
  152. if (groupList.some(groupItem => groupItem.id === evt.groupId)) {
  153. evt.respond(0);
  154. return logger.info(`accepted friend request from ${evt.fromId} (from group ${evt.groupId})`);
  155. }
  156. logger.warn(`received friend request from ${evt.fromId} (from group ${evt.groupId})`);
  157. logger.warn('please manually accept this friend request');
  158. });
  159. });
  160. this.bot.on('BotInvitedJoinGroupRequestEvent', evt => {
  161. logger.debug(`detected group invitation event: ${JSON.stringify(evt)}`);
  162. this.bot.api.friendList()
  163. .then((friendList) => {
  164. if (friendList.some(friendItem => friendItem.id = evt.fromId)) {
  165. evt.respond(0);
  166. return logger.info(`accepted group invitation from ${evt.fromId} (friend)`);
  167. }
  168. logger.warn(`received group invitation from ${evt.fromId} (unknown)`);
  169. logger.warn('please manually accept this group invitation');
  170. });
  171. });
  172. this.bot.on('message', (msg) => __awaiter(this, void 0, void 0, function* () {
  173. const chat = yield this.getChat(msg);
  174. const cmdObj = command_1.parseCmd(msg.plain);
  175. switch (cmdObj.cmd) {
  176. case 'twitter_view':
  177. case 'twitter_get':
  178. command_1.view(chat, cmdObj.args, msg.reply);
  179. break;
  180. case 'twitter_query':
  181. case 'twitter_gettimeline':
  182. command_1.query(chat, cmdObj.args, msg.reply);
  183. break;
  184. case 'twitter_sub':
  185. case 'twitter_subscribe':
  186. this.botInfo.sub(chat, cmdObj.args, msg.reply);
  187. break;
  188. case 'twitter_unsub':
  189. case 'twitter_unsubscribe':
  190. this.botInfo.unsub(chat, cmdObj.args, msg.reply);
  191. break;
  192. case 'ping':
  193. case 'twitter':
  194. this.botInfo.list(chat, cmdObj.args, msg.reply);
  195. break;
  196. case 'help':
  197. if (cmdObj.args.length === 0) {
  198. msg.reply(`推特搬运机器人:
  199. /twitter - 查询当前聊天中的推文订阅
  200. /twitter_subscribe〈链接|用户名〉- 订阅 Twitter 推文搬运
  201. /twitter_unsubscribe〈链接|用户名〉- 退订 Twitter 推文搬运
  202. /twitter_view〈链接〉- 查看推文
  203. /twitter_query〈链接|用户名〉[参数列表...] - 查询时间线(详见 /help twitter_query)\
  204. ${chat.chatType === "temp" /* Temp */ ?
  205. '\n(当前游客模式下无法使用订阅功能,请先添加本账号为好友。)' : ''}`);
  206. }
  207. else if (cmdObj.args[0] === 'twitter_query') {
  208. msg.reply(`查询时间线中的推文:
  209. /twitter_query〈链接|用户名〉[〈参数 1〉=〈值 1〉〈参数 2〉=〈值 2〉...]
  210. 参数列表(方框内全部为可选,留空则为默认):
  211. count:查询数量上限(类型:非零整数,最大值正负 50)[默认值:10]
  212. since:查询起始点(类型:正整数或日期)[默认值:(空,无限过去)]
  213. until:查询结束点(类型:正整数或日期)[默认值:(空,当前时刻)]
  214. noreps 忽略回复推文(类型:on/off)[默认值:on(是)]
  215. norts:忽略原生转推(类型:on/off)[默认值:off(否)]`)
  216. .then(() => msg.reply(`\
  217. 起始点和结束点为正整数时取推特推文编号作为比较基准,否则会尝试作为日期读取。
  218. 推荐的日期格式:2012-12-22 12:22 UTC+2 (日期和时间均为可选,可分别添加)
  219. count 为正时,从新向旧查询;为负时,从旧向新查询
  220. count 与 since/until 并用时,取二者中实际查询结果较少者
  221. 例子:/twitter_query RiccaTachibana count=5 since="2019-12-30\
  222. UTC+9" until="2020-01-06 UTC+8" norts=on
  223. 从起始时间点(含)到结束时间点(不含)从新到旧获取最多 5 条推文,\
  224. 其中不包含原生转推(实际上用户只发了 1 条)`));
  225. }
  226. }
  227. }));
  228. };
  229. // TODO doesn't work if connection is dropped after connection
  230. this.listen = (logMsg) => {
  231. if (logMsg !== '') {
  232. logger.warn(logMsg !== null && logMsg !== void 0 ? logMsg : 'Listening...');
  233. }
  234. axios_1.default.get(`http://${this.botInfo.host}:${this.botInfo.port}/about`)
  235. .then(() => __awaiter(this, void 0, void 0, function* () {
  236. if (logMsg !== '') {
  237. this.bot.listen();
  238. yield this.login();
  239. }
  240. setTimeout(() => this.listen(''), 5000);
  241. }))
  242. .catch(() => {
  243. logger.error(`Error connecting to bot provider at ${this.botInfo.host}:${this.botInfo.port}`);
  244. setTimeout(() => this.listen('Retry listening...'), 2500);
  245. });
  246. };
  247. this.login = (logMsg) => __awaiter(this, void 0, void 0, function* () {
  248. logger.warn(logMsg !== null && logMsg !== void 0 ? logMsg : 'Logging in...');
  249. yield this.bot.link(this.botInfo.bot_id)
  250. .then(() => logger.warn(`Logged in as ${this.botInfo.bot_id}`))
  251. .catch(() => {
  252. logger.error(`Cannot log in. Do you have a bot logged in as ${this.botInfo.bot_id}?`);
  253. setTimeout(() => this.login('Retry logging in...'), 2500);
  254. });
  255. });
  256. this.connect = () => {
  257. this.initBot();
  258. this.listen();
  259. };
  260. logger.warn(`Initialized mirai-ts for ${opt.host}:${opt.port} with access_token ${opt.access_token}`);
  261. this.botInfo = opt;
  262. }
  263. }
  264. exports.default = default_1;