mirai.js 12 KB

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