mirai.js 9.9 KB

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