mirai.ts 3.6 KB

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