mirai.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. import axios from 'axios';
  2. import Mirai, { MessageType } from 'mirai-ts';
  3. import MiraiMessage from 'mirai-ts/dist/message';
  4. import * as temp from 'temp';
  5. import command from './helper';
  6. import { getLogger } from './loggers';
  7. const logger = getLogger('qqbot');
  8. interface IQQProps {
  9. access_token: string;
  10. host: string;
  11. port: number;
  12. bot_id: number;
  13. list(chat: IChat, args: string[]): string;
  14. sub(chat: IChat, args: string[]): string;
  15. unsub(chat: IChat, args: string[]): string;
  16. }
  17. const ChatTypeMap: Record<MessageType.ChatMessageType, ChatType> = {
  18. GroupMessage: ChatType.Group,
  19. FriendMessage: ChatType.Private,
  20. TempMessage: ChatType.Temp,
  21. };
  22. export type MessageChain = MessageType.MessageChain;
  23. export const Message = MiraiMessage;
  24. export default class {
  25. private botInfo: IQQProps;
  26. public bot: Mirai;
  27. public sendTo = (subscriber: IChat, msg: string | MessageChain) =>
  28. (() => {
  29. switch (subscriber.chatType) {
  30. case 'group':
  31. return this.bot.api.sendGroupMessage(msg, subscriber.chatID);
  32. case 'private':
  33. return this.bot.api.sendFriendMessage(msg, subscriber.chatID);
  34. }
  35. })()
  36. .then(response => {
  37. logger.info(`pushing data to ${subscriber.chatID} was successful, response:`);
  38. logger.info(response);
  39. })
  40. .catch(reason => {
  41. logger.error(`error pushing data to ${subscriber.chatID}, reason: ${reason}`);
  42. throw Error(reason);
  43. })
  44. public uploadPic = (img: MessageType.Image, timeout = -1) => {
  45. if (timeout) timeout = Math.floor(timeout);
  46. if (timeout === 0 || timeout < -1) {
  47. return Promise.reject('Error: timeout must be greater than 0ms');
  48. }
  49. let imgFile: string;
  50. if (img.imageId !== '') return Promise.resolve();
  51. if (img.url !== '') {
  52. if (img.url.split(':')[0] !== 'data') {
  53. return Promise.reject('Error: URL must be of protocol "data"');
  54. }
  55. if (img.url.split(',')[0].split(';')[1] !== 'base64') {
  56. return Promise.reject('Error: data URL must be of encoding "base64"');
  57. }
  58. temp.track();
  59. try {
  60. const tempFileStream = temp.createWriteStream();
  61. tempFileStream.write(img.url.split(',')[1], 'base64');
  62. tempFileStream.end();
  63. if (typeof(tempFileStream.path) === 'string') imgFile = tempFileStream.path;
  64. } catch (error) {
  65. logger.error(error);
  66. }
  67. }
  68. try {
  69. this.bot.axios.defaults.timeout = timeout === -1 ? 0 : timeout;
  70. logger.info(`uploading ${JSON.stringify(
  71. Message.Image(img.imageId, `${img.url.split(',')[0]},[...]`, img.path)
  72. )}...`);
  73. return this.bot.api.uploadImage('group', imgFile || img.path)
  74. .then(response => { // workaround for https://github.com/mamoe/mirai/issues/194
  75. logger.info(`uploading ${img.path} as group image was successful, response:`);
  76. logger.info(JSON.stringify(response));
  77. img.url = '';
  78. img.path = (response.path as string).split(/[/\\]/).slice(-1)[0];
  79. })
  80. .catch(reason => {
  81. logger.error(`error uploading ${img.path}, reason: ${reason}`);
  82. throw Error(reason);
  83. });
  84. } finally {
  85. temp.cleanup();
  86. this.bot.axios.defaults.timeout = 0;
  87. }
  88. }
  89. private initBot = () => {
  90. this.bot = new Mirai({
  91. authKey: this.botInfo.access_token,
  92. enableWebsocket: false,
  93. host: this.botInfo.host,
  94. port: this.botInfo.port,
  95. });
  96. this.bot.axios.defaults.maxContentLength = Infinity;
  97. this.bot.on('message', (msg) => {
  98. const chat: IChat = {
  99. chatType: ChatTypeMap[msg.type],
  100. chatID: 0,
  101. };
  102. if (msg.type === 'FriendMessage') {
  103. chat.chatID = msg.sender.id;
  104. } else if (msg.type === 'GroupMessage') {
  105. chat.chatID = msg.sender.group.id;
  106. }
  107. const cmdObj = command(msg.plain);
  108. switch (cmdObj.cmd) {
  109. case 'twitterpic_sub':
  110. case 'twitterpic_subscribe':
  111. msg.reply(this.botInfo.sub(chat, cmdObj.args));
  112. break;
  113. case 'twitterpic_unsub':
  114. case 'twitterpic_unsubscribe':
  115. msg.reply(this.botInfo.unsub(chat, cmdObj.args));
  116. break;
  117. case 'ping':
  118. case 'twitterpic':
  119. msg.reply(this.botInfo.list(chat, cmdObj.args));
  120. break;
  121. case 'help':
  122. msg.reply(`推特图片搬运机器人:
  123. /twitterpic - 查询当前聊天中的订阅
  124. /twitterpic_subscribe [链接] - 订阅 Twitter 图片搬运
  125. /twitterpic_unsubscribe [链接] - 退订 Twitter 图片搬运`);
  126. }
  127. });
  128. }
  129. // TODO doesn't work if connection is dropped after connection
  130. private listen = (logMsg?: string) => {
  131. if (logMsg !== '') {
  132. logger.warn(logMsg ?? 'Listening...');
  133. }
  134. axios.get(`http://${this.botInfo.host}:${this.botInfo.port}/about`)
  135. .then(async () => {
  136. if (logMsg !== '') {
  137. this.bot.listen();
  138. await this.login();
  139. }
  140. setTimeout(() => this.listen(''), 5000);
  141. })
  142. .catch(() => {
  143. logger.error(`Error connecting to bot provider at ${this.botInfo.host}:${this.botInfo.port}`);
  144. setTimeout(() => this.listen('Retry listening...'), 2500);
  145. });
  146. }
  147. private login = async (logMsg?: string) => {
  148. logger.warn(logMsg ?? 'Logging in...');
  149. await this.bot.login(this.botInfo.bot_id)
  150. .then(() => logger.warn(`Logged in as ${this.botInfo.bot_id}`))
  151. .catch(() => {
  152. logger.error(`Cannot log in. Do you have a bot logged in as ${this.botInfo.bot_id}?`);
  153. setTimeout(() => this.login('Retry logging in...'), 2500);
  154. });
  155. }
  156. public connect = () => {
  157. this.initBot();
  158. this.listen();
  159. }
  160. constructor(opt: IQQProps) {
  161. logger.warn(`Initialized mirai-ts for ${opt.host}:${opt.port} with access_token ${opt.access_token}`);
  162. this.botInfo = opt;
  163. }
  164. }