mirai.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  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. const axios_1 = require("axios");
  13. const crypto = require("crypto");
  14. const mirai_ts_1 = require("mirai-ts");
  15. const message_1 = require("mirai-ts/dist/message");
  16. const helper_1 = require("./helper");
  17. const loggers_1 = require("./loggers");
  18. const logger = loggers_1.getLogger('qqbot');
  19. const ChatTypeMap = {
  20. GroupMessage: "group" /* Group */,
  21. FriendMessage: "private" /* Private */,
  22. TempMessage: "temp" /* Temp */,
  23. };
  24. exports.MiraiMessage = message_1.default;
  25. class default_1 {
  26. constructor(opt) {
  27. this.revokeList = new Set();
  28. this.sendTo = (subscriber, msg, timeout) => {
  29. const msgId = `${new Date().getTime()}${crypto.randomBytes(8).toString('hex')}`;
  30. timeout = Math.floor(timeout);
  31. return new Promise((resolve, reject) => {
  32. if (timeout === 0 || timeout < -1 || timeout > 0xFFFFFFFF) {
  33. reject(`Error: timeout must be between 1 - ${0xFFFFFFFF} ms`);
  34. }
  35. (() => {
  36. switch (subscriber.chatType) {
  37. case 'group':
  38. return this.bot.api.sendGroupMessage(msg, subscriber.chatID);
  39. case 'private':
  40. return this.bot.api.sendFriendMessage(msg, subscriber.chatID);
  41. }
  42. })().then(response => {
  43. if (this.revokeList.has(msgId)) {
  44. this.bot.api.recall(response.messageId)
  45. .then(() => logger.info(`overdue message to ${subscriber.chatID} recalled`))
  46. .catch(() => logger.info(`error recalling overdue message to ${subscriber.chatID}`))
  47. .finally(() => this.revokeList.delete(msgId));
  48. }
  49. resolve(response);
  50. }).catch(reject);
  51. setTimeout(() => {
  52. this.revokeList.add(msgId);
  53. reject('Error: timed out, requesting termination');
  54. }, timeout);
  55. })
  56. .then(response => {
  57. logger.info(`pushing data to ${subscriber.chatID} was successful, response:`);
  58. logger.info(response);
  59. })
  60. .catch(reason => {
  61. logger.error(`error pushing data to ${subscriber.chatID}, reason: ${reason}`);
  62. throw Error(reason);
  63. });
  64. };
  65. this.initBot = () => {
  66. this.bot = new mirai_ts_1.default({
  67. authKey: this.botInfo.access_token,
  68. enableWebsocket: false,
  69. host: this.botInfo.host,
  70. port: this.botInfo.port,
  71. });
  72. this.bot.on('message', (msg) => {
  73. const chat = {
  74. chatType: ChatTypeMap[msg.type],
  75. chatID: 0,
  76. };
  77. if (msg.type === 'FriendMessage') {
  78. chat.chatID = msg.sender.id;
  79. }
  80. else if (msg.type === 'GroupMessage') {
  81. chat.chatID = msg.sender.group.id;
  82. }
  83. const cmdObj = helper_1.default(msg.plain);
  84. switch (cmdObj.cmd) {
  85. case 'twitter_sub':
  86. case 'twitter_subscribe':
  87. msg.reply(this.botInfo.sub(chat, cmdObj.args));
  88. break;
  89. case 'twitter_unsub':
  90. case 'twitter_unsubscribe':
  91. msg.reply(this.botInfo.unsub(chat, cmdObj.args));
  92. break;
  93. case 'ping':
  94. case 'twitter':
  95. msg.reply(this.botInfo.list(chat, cmdObj.args));
  96. break;
  97. case 'help':
  98. msg.reply(`推特搬运机器人:
  99. /twitter - 查询当前聊天中的订阅
  100. /twitter_subscribe [链接] - 订阅 Twitter 搬运
  101. /twitter_unsubscribe [链接] - 退订 Twitter 搬运`);
  102. }
  103. });
  104. };
  105. // TODO doesn't work if connection is dropped after connection
  106. this.listen = (logMsg) => {
  107. if (logMsg !== '') {
  108. logger.warn((logMsg !== null && logMsg !== void 0 ? logMsg : 'Listening...'));
  109. }
  110. axios_1.default.get(`http://${this.botInfo.host}:${this.botInfo.port}/about`)
  111. .then(() => __awaiter(this, void 0, void 0, function* () {
  112. if (logMsg !== '') {
  113. this.bot.listen();
  114. yield this.login();
  115. }
  116. setTimeout(() => this.listen(''), 5000);
  117. }))
  118. .catch(() => {
  119. logger.error(`Error connecting to bot provider at ${this.botInfo.host}:${this.botInfo.port}`);
  120. setTimeout(() => this.listen('Retry listening...'), 2500);
  121. });
  122. };
  123. this.login = (logMsg) => __awaiter(this, void 0, void 0, function* () {
  124. logger.warn((logMsg !== null && logMsg !== void 0 ? logMsg : 'Logging in...'));
  125. yield this.bot.login(this.botInfo.bot_id)
  126. .then(() => logger.warn(`Logged in as ${this.botInfo.bot_id}`))
  127. .catch(() => {
  128. logger.error(`Cannot log in. Do you have a bot logged in as ${this.botInfo.bot_id}?`);
  129. setTimeout(() => this.login('Retry logging in...'), 2500);
  130. });
  131. });
  132. this.connect = () => {
  133. this.initBot();
  134. this.listen();
  135. };
  136. logger.warn(`Initialized mirai-ts for ${opt.host}:${opt.port} with access_token ${opt.access_token}`);
  137. this.botInfo = opt;
  138. }
  139. }
  140. exports.default = default_1;