mirai.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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. exports.Message = message_1.default;
  23. class default_1 {
  24. constructor(opt) {
  25. this.getChat = (msg) => {
  26. switch (msg.type) {
  27. case 'FriendMessage':
  28. return {
  29. chatID: msg.sender.id,
  30. chatType: "private" /* Private */,
  31. };
  32. case 'GroupMessage':
  33. return {
  34. chatID: msg.sender.group.id,
  35. chatType: "group" /* Group */,
  36. };
  37. case 'TempMessage':
  38. this.bot.api.friendList()
  39. .then((friendList) => {
  40. // already befriended
  41. if (friendList.some(friendItem => friendItem.id = msg.sender.id)) {
  42. return {
  43. chatID: msg.sender.id,
  44. chatType: "private" /* Private */,
  45. };
  46. }
  47. return {
  48. chatID: {
  49. qq: msg.sender.id,
  50. group: msg.sender.group.id,
  51. },
  52. chatType: "temp" /* Temp */,
  53. };
  54. });
  55. }
  56. };
  57. this.sendTo = (subscriber, msg) => (() => {
  58. switch (subscriber.chatType) {
  59. case 'group':
  60. return this.bot.api.sendGroupMessage(msg, subscriber.chatID);
  61. case 'private':
  62. return this.bot.api.sendFriendMessage(msg, subscriber.chatID);
  63. // currently disabled
  64. case 'temp':
  65. return this.bot.api.sendTempMessage(msg, subscriber.chatID.qq, subscriber.chatID.group);
  66. }
  67. })()
  68. .then(response => {
  69. logger.info(`pushing data to ${JSON.stringify(subscriber.chatID)} was successful, response:`);
  70. logger.info(response);
  71. })
  72. .catch(reason => {
  73. logger.error(`error pushing data to ${JSON.stringify(subscriber.chatID)}, reason: ${reason}`);
  74. throw Error(reason);
  75. });
  76. this.uploadPic = (img, timeout = -1) => {
  77. if (timeout)
  78. timeout = Math.floor(timeout);
  79. if (timeout === 0 || timeout < -1) {
  80. return Promise.reject('Error: timeout must be greater than 0ms');
  81. }
  82. let imgFile;
  83. if (img.imageId !== '')
  84. return Promise.resolve();
  85. if (img.url !== '') {
  86. if (img.url.split(':')[0] !== 'data') {
  87. return Promise.reject('Error: URL must be of protocol "data"');
  88. }
  89. if (img.url.split(',')[0].split(';')[1] !== 'base64') {
  90. return Promise.reject('Error: data URL must be of encoding "base64"');
  91. }
  92. temp.track();
  93. try {
  94. const tempFile = temp.openSync();
  95. fs_1.writeSync(tempFile.fd, Buffer.from(img.url.split(',')[1], 'base64'));
  96. fs_1.closeSync(tempFile.fd);
  97. imgFile = tempFile.path;
  98. }
  99. catch (error) {
  100. logger.error(error);
  101. }
  102. }
  103. try {
  104. this.bot.axios.defaults.timeout = timeout === -1 ? 0 : timeout;
  105. logger.info(`uploading ${JSON.stringify(exports.Message.Image(img.imageId, `${img.url.split(',')[0]},[...]`, img.path))}...`);
  106. return this.bot.api.uploadImage('group', imgFile || img.path)
  107. .then(response => {
  108. logger.info(`uploading ${img.path} as group image was successful, response:`);
  109. logger.info(JSON.stringify(response));
  110. img.url = '';
  111. img.path = response.path.split(/[/\\]/).slice(-1)[0];
  112. })
  113. .catch(reason => {
  114. logger.error(`error uploading ${img.path}, reason: ${reason}`);
  115. throw Error(reason);
  116. });
  117. }
  118. finally {
  119. temp.cleanup();
  120. this.bot.axios.defaults.timeout = 0;
  121. }
  122. };
  123. this.initBot = () => {
  124. this.bot = new mirai_ts_1.default({
  125. authKey: this.botInfo.access_token,
  126. enableWebsocket: false,
  127. host: this.botInfo.host,
  128. port: this.botInfo.port,
  129. });
  130. this.bot.axios.defaults.maxContentLength = Infinity;
  131. this.bot.on('NewFriendRequestEvent', evt => {
  132. logger.debug(`detected new friend request event: ${JSON.stringify(evt)}`);
  133. this.bot.api.groupList()
  134. .then((groupList) => {
  135. if (groupList.some(groupItem => groupItem.id === evt.groupId)) {
  136. evt.respond('allow');
  137. return logger.info(`accepted friend request from ${evt.fromId} (from group ${evt.groupId})`);
  138. }
  139. logger.warn(`received friend request from ${evt.fromId} (from group ${evt.groupId})`);
  140. logger.warn('please manually accept this friend request');
  141. });
  142. });
  143. this.bot.on('BotInvitedJoinGroupRequestEvent', evt => {
  144. logger.debug(`detected group invitation event: ${JSON.stringify(evt)}`);
  145. this.bot.api.friendList()
  146. .then((friendList) => {
  147. if (friendList.some(friendItem => friendItem.id = evt.fromId)) {
  148. evt.respond('allow');
  149. return logger.info(`accepted group invitation from ${evt.fromId} (friend)`);
  150. }
  151. logger.warn(`received group invitation from ${evt.fromId} (unknown)`);
  152. logger.warn('please manually accept this group invitation');
  153. });
  154. });
  155. this.bot.on('message', msg => {
  156. const chat = this.getChat(msg);
  157. const cmdObj = helper_1.default(msg.plain);
  158. switch (cmdObj.cmd) {
  159. case 'twitter_view':
  160. case 'twitter_get':
  161. command_1.view(chat, cmdObj.args, msg.reply);
  162. break;
  163. case 'twitter_sub':
  164. case 'twitter_subscribe':
  165. this.botInfo.sub(chat, cmdObj.args, msg.reply);
  166. break;
  167. case 'twitter_unsub':
  168. case 'twitter_unsubscribe':
  169. this.botInfo.unsub(chat, cmdObj.args, msg.reply);
  170. break;
  171. case 'ping':
  172. case 'twitter':
  173. this.botInfo.list(chat, cmdObj.args, msg.reply);
  174. break;
  175. case 'help':
  176. msg.reply(`推特搬运机器人:
  177. /twitter - 查询当前聊天中的订阅
  178. /twitter_subscribe [链接] - 订阅 Twitter 搬运
  179. /twitter_unsubscribe [链接] - 退订 Twitter 搬运
  180. /twitter_view [链接] - 查看推文
  181. ${chat.chatType === "temp" /* Temp */ &&
  182. '(当前游客模式下无法使用订阅功能,请先添加本账号为好友。)'}`);
  183. }
  184. });
  185. };
  186. // TODO doesn't work if connection is dropped after connection
  187. this.listen = (logMsg) => {
  188. if (logMsg !== '') {
  189. logger.warn(logMsg !== null && logMsg !== void 0 ? logMsg : 'Listening...');
  190. }
  191. axios_1.default.get(`http://${this.botInfo.host}:${this.botInfo.port}/about`)
  192. .then(() => __awaiter(this, void 0, void 0, function* () {
  193. if (logMsg !== '') {
  194. this.bot.listen();
  195. yield this.login();
  196. }
  197. setTimeout(() => this.listen(''), 5000);
  198. }))
  199. .catch(() => {
  200. logger.error(`Error connecting to bot provider at ${this.botInfo.host}:${this.botInfo.port}`);
  201. setTimeout(() => this.listen('Retry listening...'), 2500);
  202. });
  203. };
  204. this.login = (logMsg) => __awaiter(this, void 0, void 0, function* () {
  205. logger.warn(logMsg !== null && logMsg !== void 0 ? logMsg : 'Logging in...');
  206. yield this.bot.link(this.botInfo.bot_id)
  207. .then(() => logger.warn(`Logged in as ${this.botInfo.bot_id}`))
  208. .catch(() => {
  209. logger.error(`Cannot log in. Do you have a bot logged in as ${this.botInfo.bot_id}?`);
  210. setTimeout(() => this.login('Retry logging in...'), 2500);
  211. });
  212. });
  213. this.connect = () => {
  214. this.initBot();
  215. this.listen();
  216. };
  217. logger.warn(`Initialized mirai-ts for ${opt.host}:${opt.port} with access_token ${opt.access_token}`);
  218. this.botInfo = opt;
  219. }
  220. }
  221. exports.default = default_1;