mirai.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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 ${img.path}...`);
  71. return this.bot.api.uploadImage('group', imgFile || img.path)
  72. .then(response => { // workaround for https://github.com/mamoe/mirai/issues/194
  73. logger.info(`uploading ${img.path} as group image was successful, response:`);
  74. logger.info(JSON.stringify(response));
  75. img.url = '';
  76. img.path = (response.path as string).split(/[/\\]/).slice(-1)[0];
  77. })
  78. .catch(reason => {
  79. logger.error(`error uploading ${img.path}, reason: ${reason}`);
  80. throw Error(reason);
  81. });
  82. } finally {
  83. temp.cleanup();
  84. this.bot.axios.defaults.timeout = 0;
  85. }
  86. }
  87. private initBot = () => {
  88. this.bot = new Mirai({
  89. authKey: this.botInfo.access_token,
  90. enableWebsocket: false,
  91. host: this.botInfo.host,
  92. port: this.botInfo.port,
  93. });
  94. this.bot.on('message', (msg) => {
  95. const chat: IChat = {
  96. chatType: ChatTypeMap[msg.type],
  97. chatID: 0,
  98. };
  99. if (msg.type === 'FriendMessage') {
  100. chat.chatID = msg.sender.id;
  101. } else if (msg.type === 'GroupMessage') {
  102. chat.chatID = msg.sender.group.id;
  103. }
  104. const cmdObj = command(msg.plain);
  105. switch (cmdObj.cmd) {
  106. case 'twitter_sub':
  107. case 'twitter_subscribe':
  108. msg.reply(this.botInfo.sub(chat, cmdObj.args));
  109. break;
  110. case 'twitter_unsub':
  111. case 'twitter_unsubscribe':
  112. msg.reply(this.botInfo.unsub(chat, cmdObj.args));
  113. break;
  114. case 'ping':
  115. case 'twitter':
  116. msg.reply(this.botInfo.list(chat, cmdObj.args));
  117. break;
  118. case 'help':
  119. msg.reply(`推特搬运机器人:
  120. /twitter - 查询当前聊天中的订阅
  121. /twitter_subscribe [链接] - 订阅 Twitter 搬运
  122. /twitter_unsubscribe [链接] - 退订 Twitter 搬运`);
  123. }
  124. });
  125. }
  126. // TODO doesn't work if connection is dropped after connection
  127. private listen = (logMsg?: string) => {
  128. if (logMsg !== '') {
  129. logger.warn(logMsg ?? 'Listening...');
  130. }
  131. axios.get(`http://${this.botInfo.host}:${this.botInfo.port}/about`)
  132. .then(async () => {
  133. if (logMsg !== '') {
  134. this.bot.listen();
  135. await this.login();
  136. }
  137. setTimeout(() => this.listen(''), 5000);
  138. })
  139. .catch(() => {
  140. logger.error(`Error connecting to bot provider at ${this.botInfo.host}:${this.botInfo.port}`);
  141. setTimeout(() => this.listen('Retry listening...'), 2500);
  142. });
  143. }
  144. private login = async (logMsg?: string) => {
  145. logger.warn(logMsg ?? 'Logging in...');
  146. await this.bot.login(this.botInfo.bot_id)
  147. .then(() => logger.warn(`Logged in as ${this.botInfo.bot_id}`))
  148. .catch(() => {
  149. logger.error(`Cannot log in. Do you have a bot logged in as ${this.botInfo.bot_id}?`);
  150. setTimeout(() => this.login('Retry logging in...'), 2500);
  151. });
  152. }
  153. public connect = () => {
  154. this.initBot();
  155. this.listen();
  156. }
  157. constructor(opt: IQQProps) {
  158. logger.warn(`Initialized mirai-ts for ${opt.host}:${opt.port} with access_token ${opt.access_token}`);
  159. this.botInfo = opt;
  160. }
  161. }