mirai.ts 5.9 KB

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