mirai.ts 4.2 KB

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