mirai.js 10 KB

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