mirai.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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 helper_1 = require("./helper");
  19. const loggers_1 = require("./loggers");
  20. const logger = loggers_1.getLogger('qqbot');
  21. const ChatTypeMap = {
  22. GroupMessage: "group" /* Group */,
  23. FriendMessage: "private" /* Private */,
  24. TempMessage: "temp" /* Temp */,
  25. };
  26. exports.Message = message_1.default;
  27. class default_1 {
  28. constructor(opt) {
  29. this.sendTo = (subscriber, msg) => (() => {
  30. switch (subscriber.chatType) {
  31. case 'group':
  32. return this.bot.api.sendGroupMessage(msg, subscriber.chatID);
  33. case 'private':
  34. return this.bot.api.sendFriendMessage(msg, subscriber.chatID);
  35. }
  36. })()
  37. .then(response => {
  38. logger.info(`pushing data to ${subscriber.chatID} was successful, response:`);
  39. logger.info(response);
  40. })
  41. .catch(reason => {
  42. logger.error(`error pushing data to ${subscriber.chatID}, reason: ${reason}`);
  43. throw Error(reason);
  44. });
  45. this.uploadPic = (img, timeout = -1) => {
  46. if (timeout)
  47. timeout = Math.floor(timeout);
  48. if (timeout === 0 || timeout < -1) {
  49. return Promise.reject('Error: timeout must be greater than 0ms');
  50. }
  51. let imgFile;
  52. if (img.imageId !== '')
  53. return Promise.resolve();
  54. if (img.url !== '') {
  55. if (img.url.split(':')[0] !== 'data') {
  56. return Promise.reject('Error: URL must be of protocol "data"');
  57. }
  58. if (img.url.split(',')[0].split(';')[1] !== 'base64') {
  59. return Promise.reject('Error: data URL must be of encoding "base64"');
  60. }
  61. temp.track();
  62. try {
  63. const tempFile = temp.openSync();
  64. fs_1.writeSync(tempFile.fd, Buffer.from(img.url.split(',')[1], 'base64'));
  65. fs_1.closeSync(tempFile.fd);
  66. imgFile = tempFile.path;
  67. }
  68. catch (error) {
  69. logger.error(error);
  70. }
  71. }
  72. try {
  73. this.bot.axios.defaults.timeout = timeout === -1 ? 0 : timeout;
  74. logger.info(`uploading ${JSON.stringify(exports.Message.Image(img.imageId, `${img.url.split(',')[0]},[...]`, img.path))}...`);
  75. return this.bot.api.uploadImage('group', imgFile || img.path)
  76. .then(response => {
  77. logger.info(`uploading ${img.path} as group image was successful, response:`);
  78. logger.info(JSON.stringify(response));
  79. img.url = '';
  80. img.path = response.path.split(/[/\\]/).slice(-1)[0];
  81. })
  82. .catch(reason => {
  83. logger.error(`error uploading ${img.path}, reason: ${reason}`);
  84. throw Error(reason);
  85. });
  86. }
  87. finally {
  88. temp.cleanup();
  89. this.bot.axios.defaults.timeout = 0;
  90. }
  91. };
  92. this.initBot = () => {
  93. this.bot = new mirai_ts_1.default({
  94. authKey: this.botInfo.access_token,
  95. enableWebsocket: false,
  96. host: this.botInfo.host,
  97. port: this.botInfo.port,
  98. });
  99. this.bot.axios.defaults.maxContentLength = Infinity;
  100. this.bot.on('message', (msg) => {
  101. const chat = {
  102. chatType: ChatTypeMap[msg.type],
  103. chatID: 0,
  104. };
  105. if (msg.type === 'FriendMessage') {
  106. chat.chatID = msg.sender.id;
  107. }
  108. else if (msg.type === 'GroupMessage') {
  109. chat.chatID = msg.sender.group.id;
  110. }
  111. const cmdObj = helper_1.default(msg.plain);
  112. switch (cmdObj.cmd) {
  113. case 'twitter_sub':
  114. case 'twitter_subscribe':
  115. msg.reply(this.botInfo.sub(chat, cmdObj.args));
  116. break;
  117. case 'twitter_unsub':
  118. case 'twitter_unsubscribe':
  119. msg.reply(this.botInfo.unsub(chat, cmdObj.args));
  120. break;
  121. case 'ping':
  122. case 'twitter':
  123. msg.reply(this.botInfo.list(chat, cmdObj.args));
  124. break;
  125. case 'help':
  126. msg.reply(`推特搬运机器人:
  127. /twitter - 查询当前聊天中的订阅
  128. /twitter_subscribe [链接] - 订阅 Twitter 搬运
  129. /twitter_unsubscribe [链接] - 退订 Twitter 搬运`);
  130. }
  131. });
  132. };
  133. // TODO doesn't work if connection is dropped after connection
  134. this.listen = (logMsg) => {
  135. if (logMsg !== '') {
  136. logger.warn(logMsg !== null && logMsg !== void 0 ? logMsg : 'Listening...');
  137. }
  138. axios_1.default.get(`http://${this.botInfo.host}:${this.botInfo.port}/about`)
  139. .then(() => __awaiter(this, void 0, void 0, function* () {
  140. if (logMsg !== '') {
  141. this.bot.listen();
  142. yield this.login();
  143. }
  144. setTimeout(() => this.listen(''), 5000);
  145. }))
  146. .catch(() => {
  147. logger.error(`Error connecting to bot provider at ${this.botInfo.host}:${this.botInfo.port}`);
  148. setTimeout(() => this.listen('Retry listening...'), 2500);
  149. });
  150. };
  151. this.login = (logMsg) => __awaiter(this, void 0, void 0, function* () {
  152. logger.warn(logMsg !== null && logMsg !== void 0 ? logMsg : 'Logging in...');
  153. yield this.bot.login(this.botInfo.bot_id)
  154. .then(() => logger.warn(`Logged in as ${this.botInfo.bot_id}`))
  155. .catch(() => {
  156. logger.error(`Cannot log in. Do you have a bot logged in as ${this.botInfo.bot_id}?`);
  157. setTimeout(() => this.login('Retry logging in...'), 2500);
  158. });
  159. });
  160. this.connect = () => {
  161. this.initBot();
  162. this.listen();
  163. };
  164. logger.warn(`Initialized mirai-ts for ${opt.host}:${opt.port} with access_token ${opt.access_token}`);
  165. this.botInfo = opt;
  166. }
  167. }
  168. exports.default = default_1;