mirai.js 7.6 KB

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