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 fs_1 = require("fs");
  14. const util_1 = require("util");
  15. const axios_1 = require("axios");
  16. const mirai_ts_1 = require("mirai-ts");
  17. const message_1 = require("mirai-ts/dist/message");
  18. const temp = require("temp");
  19. const command_1 = require("./command");
  20. const loggers_1 = require("./loggers");
  21. const logger = loggers_1.getLogger('qqbot');
  22. exports.Message = message_1.default;
  23. class default_1 {
  24. constructor(opt) {
  25. this.getChat = (msg) => __awaiter(this, void 0, void 0, function* () {
  26. switch (msg.type) {
  27. case 'FriendMessage':
  28. return {
  29. chatID: msg.sender.id,
  30. chatType: "private",
  31. };
  32. case 'GroupMessage':
  33. return {
  34. chatID: msg.sender.group.id,
  35. chatType: "group",
  36. };
  37. case 'TempMessage':
  38. const friendList = yield this.bot.api.friendList();
  39. if (friendList.some(friendItem => friendItem.id === msg.sender.id)) {
  40. return {
  41. chatID: msg.sender.id,
  42. chatType: "private",
  43. };
  44. }
  45. return {
  46. chatID: {
  47. qq: msg.sender.id,
  48. group: msg.sender.group.id,
  49. },
  50. chatType: "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. case 'temp':
  61. return this.bot.api.sendTempMessage(msg, subscriber.chatID.qq, subscriber.chatID.group);
  62. }
  63. })()
  64. .then(response => {
  65. logger.info(`pushing data to ${JSON.stringify(subscriber.chatID)} was successful, response:`);
  66. logger.info(response);
  67. })
  68. .catch(reason => {
  69. logger.error(`error pushing data to ${JSON.stringify(subscriber.chatID)}, reason: ${reason}`);
  70. throw Error(reason);
  71. });
  72. this.uploadPic = (img, timeout = -1) => {
  73. if (timeout)
  74. timeout = Math.floor(timeout);
  75. if (timeout === 0 || timeout < -1) {
  76. return Promise.reject('Error: timeout must be greater than 0ms');
  77. }
  78. let imgFilePath;
  79. if (img.imageId !== '')
  80. return Promise.resolve();
  81. else if (img.url !== '') {
  82. if (img.url.split(':')[0] !== 'data') {
  83. return Promise.reject('Error: URL must be of protocol "data"');
  84. }
  85. if (img.url.split(',')[0].split(';')[1] !== 'base64') {
  86. return Promise.reject('Error: data URL must be of encoding "base64"');
  87. }
  88. temp.track();
  89. try {
  90. const tempFile = temp.openSync();
  91. fs_1.writeSync(tempFile.fd, Buffer.from(img.url.split(',')[1], 'base64'));
  92. fs_1.closeSync(tempFile.fd);
  93. imgFilePath = tempFile.path;
  94. }
  95. catch (error) {
  96. logger.error(error);
  97. }
  98. }
  99. else
  100. imgFilePath = img.path;
  101. try {
  102. this.bot.axios.defaults.timeout = timeout === -1 ? 0 : timeout;
  103. logger.info(`uploading ${JSON.stringify(exports.Message.Image(img.imageId, `${img.url.split(',')[0]},[...]`, img.path))}...`);
  104. return this.bot.api.uploadImage('group', fs_1.createReadStream(imgFilePath))
  105. .then(response => {
  106. logger.info(`uploading ${img.path} as group image was successful, response:`);
  107. logger.info(JSON.stringify(response));
  108. img.url = '';
  109. img.path = (response.path).split(/[/\\]/).slice(-1)[0];
  110. })
  111. .catch(reason => {
  112. logger.error(`error uploading ${img.path}, reason: ${reason}`);
  113. throw Error(reason);
  114. });
  115. }
  116. finally {
  117. temp.cleanup();
  118. this.bot.axios.defaults.timeout = 0;
  119. }
  120. };
  121. this.initBot = () => {
  122. this.bot = new mirai_ts_1.default({
  123. authKey: this.botInfo.access_token,
  124. enableWebsocket: false,
  125. host: this.botInfo.host,
  126. port: this.botInfo.port,
  127. });
  128. this.bot.axios.defaults.maxContentLength = Infinity;
  129. this.bot.on('NewFriendRequestEvent', evt => {
  130. logger.debug(`detected new friend request event: ${JSON.stringify(evt)}`);
  131. this.bot.api.groupList()
  132. .then((groupList) => {
  133. if (groupList.some(groupItem => groupItem.id === evt.groupId)) {
  134. evt.respond(0);
  135. return logger.info(`accepted friend request from ${evt.fromId} (from group ${evt.groupId})`);
  136. }
  137. logger.warn(`received friend request from ${evt.fromId} (from group ${evt.groupId})`);
  138. logger.warn('please manually accept this friend request');
  139. });
  140. });
  141. this.bot.on('BotInvitedJoinGroupRequestEvent', evt => {
  142. logger.debug(`detected group invitation event: ${JSON.stringify(evt)}`);
  143. this.bot.api.friendList()
  144. .then((friendList) => {
  145. if (friendList.some(friendItem => friendItem.id = evt.fromId)) {
  146. evt.respond(0);
  147. return logger.info(`accepted group invitation from ${evt.fromId} (friend)`);
  148. }
  149. logger.warn(`received group invitation from ${evt.fromId} (unknown)`);
  150. logger.warn('please manually accept this group invitation');
  151. });
  152. });
  153. this.bot.on('message', (msg) => __awaiter(this, void 0, void 0, function* () {
  154. const chat = yield this.getChat(msg);
  155. const cmdObj = command_1.parseCmd(msg.plain);
  156. switch (cmdObj.cmd) {
  157. case 'twitterpic_view':
  158. case 'twitterpic_get':
  159. command_1.view(chat, cmdObj.args, msg.reply);
  160. break;
  161. case 'twitterpic_query':
  162. case 'twitterpic_gettimeline':
  163. command_1.query(chat, cmdObj.args, msg.reply);
  164. break;
  165. case 'twitterpic_sub':
  166. case 'twitterpic_subscribe':
  167. this.botInfo.sub(chat, cmdObj.args, msg.reply);
  168. break;
  169. case 'twitterpic_unsub':
  170. case 'twitterpic_unsubscribe':
  171. this.botInfo.unsub(chat, cmdObj.args, msg.reply);
  172. break;
  173. case 'ping':
  174. case 'twitterpic':
  175. this.botInfo.list(chat, cmdObj.args, msg.reply);
  176. break;
  177. case 'help':
  178. if (cmdObj.args.length === 0) {
  179. msg.reply(`推特媒体推文搬运机器人:
  180. /twitterpic - 查询当前聊天中的媒体推文订阅
  181. /twitterpic_subscribe〈链接|用户名〉- 订阅 Twitter 媒体推文搬运
  182. /twitterpic_unsubscribe〈链接|用户名〉- 退订 Twitter 媒体推文搬运
  183. /twitterpic_view〈链接〉- 查看推文(无关是否包含媒体)
  184. /twitterpic_query〈链接|用户名〉[参数列表...] - 查询时间线(详见 /help twitterpic_query)\
  185. ${chat.chatType === "temp" ?
  186. '\n(当前游客模式下无法使用订阅功能,请先添加本账号为好友。)' : ''}`);
  187. }
  188. else if (cmdObj.args[0] === 'twitterpic_query') {
  189. msg.reply(`查询时间线中的媒体推文:
  190. /twitterpic_query〈链接|用户名〉[〈参数 1〉=〈值 1〉〈参数 2〉=〈值 2〉...]
  191. 参数列表(方框内全部为可选,留空则为默认):
  192. count:查询数量上限(类型:非零整数,最大值正负 50)[默认值:10]
  193. since:查询起始点(类型:正整数或日期)[默认值:(空,无限过去)]
  194. until:查询结束点(类型:正整数或日期)[默认值:(空,当前时刻)]
  195. noreps 忽略回复推文(类型:on/off)[默认值:on(是)]
  196. norts:忽略原生转推(类型:on/off)[默认值:off(否)]`)
  197. .then(() => msg.reply(`\
  198. 起始点和结束点为正整数时取推特推文编号作为比较基准,否则会尝试作为日期读取。
  199. 推荐的日期格式:2012-12-22 12:22 UTC+2 (日期和时间均为可选,可分别添加)
  200. count 为正时,从新向旧查询;为负时,从旧向新查询
  201. count 与 since/until 并用时,取二者中实际查询结果较少者
  202. 例子:/twitterpic_query RiccaTachibana count=5 since="2019-12-30\
  203. UTC+9" until="2020-01-06 UTC+8" norts=on
  204. 从起始时间点(含)到结束时间点(不含)从新到旧获取最多 5 条媒体推文,\
  205. 其中不包含原生转推(实际上用户只发了 1 条)`));
  206. }
  207. }
  208. }));
  209. };
  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. return util_1.promisify(setTimeout)(2500).then(() => this.login('Retry logging in...'));
  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;