mirai.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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 = this.bot.axios.defaults.maxBodyLength = 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 'twitterfleets_view':
  158. case 'twitterfleets_get':
  159. command_1.view(chat, cmdObj.args, msg.reply);
  160. break;
  161. case 'twitterfleets_sub':
  162. case 'twitterfleets_subscribe':
  163. this.botInfo.sub(chat, cmdObj.args, msg.reply);
  164. break;
  165. case 'twitterfleets_unsub':
  166. case 'twitterfleets_unsubscribe':
  167. this.botInfo.unsub(chat, cmdObj.args, msg.reply);
  168. break;
  169. case 'ping':
  170. case 'twitterfleets':
  171. this.botInfo.list(chat, cmdObj.args, msg.reply);
  172. break;
  173. case 'help':
  174. if (cmdObj.args.length === 0) {
  175. msg.reply(`推特故事搬运机器人:
  176. /twitterfleets - 查询当前聊天中的推特故事订阅
  177. /twitterfleets_view〈链接〉- 查看该用户当前可见的所有 Fleets
  178. /twitterfleets_subscribe [链接] - 订阅 Twitter Fleets 搬运
  179. /twitterfleets_unsubscribe [链接] - 退订 Twitter Fleets 搬运`);
  180. }
  181. }
  182. }));
  183. };
  184. this.listen = (logMsg) => {
  185. if (logMsg !== '') {
  186. logger.warn(logMsg !== null && logMsg !== void 0 ? logMsg : 'Listening...');
  187. }
  188. axios_1.default.get(`http://${this.botInfo.host}:${this.botInfo.port}/about`)
  189. .then(() => __awaiter(this, void 0, void 0, function* () {
  190. if (logMsg !== '') {
  191. this.bot.listen();
  192. yield this.login();
  193. }
  194. setTimeout(() => this.listen(''), 5000);
  195. }))
  196. .catch(() => {
  197. logger.error(`Error connecting to bot provider at ${this.botInfo.host}:${this.botInfo.port}`);
  198. setTimeout(() => this.listen('Retry listening...'), 2500);
  199. });
  200. };
  201. this.login = (logMsg) => __awaiter(this, void 0, void 0, function* () {
  202. logger.warn(logMsg !== null && logMsg !== void 0 ? logMsg : 'Logging in...');
  203. yield this.bot.link(this.botInfo.bot_id)
  204. .then(() => logger.warn(`Logged in as ${this.botInfo.bot_id}`))
  205. .catch(() => {
  206. logger.error(`Cannot log in. Do you have a bot logged in as ${this.botInfo.bot_id}?`);
  207. return util_1.promisify(setTimeout)(2500).then(() => this.login('Retry logging in...'));
  208. });
  209. });
  210. this.connect = () => {
  211. this.initBot();
  212. this.listen();
  213. };
  214. logger.warn(`Initialized mirai-ts for ${opt.host}:${opt.port} with access_token ${opt.access_token}`);
  215. this.botInfo = opt;
  216. }
  217. }
  218. exports.default = default_1;