mirai.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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 { parseCmd, view } from './command';
  7. import { getLogger } from './loggers';
  8. const logger = getLogger('qqbot');
  9. interface IQQProps {
  10. access_token: string;
  11. host: string;
  12. port: number;
  13. bot_id: number;
  14. list(chat: IChat, args: string[], replyfn: (msg: string) => any): void;
  15. sub(chat: IChat, args: string[], replyfn: (msg: string) => any): void;
  16. unsub(chat: IChat, args: string[], replyfn: (msg: string) => any): void;
  17. }
  18. export type MessageChain = MessageType.MessageChain;
  19. export const Message = MiraiMessage;
  20. export default class {
  21. private botInfo: IQQProps;
  22. public bot: Mirai;
  23. private getChat = async (msg: MessageType.ChatMessage): Promise<IChat> => {
  24. switch (msg.type) {
  25. case 'FriendMessage':
  26. return {
  27. chatID: msg.sender.id,
  28. chatType: ChatType.Private,
  29. };
  30. case 'GroupMessage':
  31. return {
  32. chatID: msg.sender.group.id,
  33. chatType: ChatType.Group,
  34. };
  35. case 'TempMessage':
  36. const friendList: [{
  37. id: number,
  38. nickname: string,
  39. remark: string,
  40. }] = await this.bot.api.friendList();
  41. // already befriended
  42. if (friendList.some(friendItem => friendItem.id === msg.sender.id)) {
  43. return {
  44. chatID: msg.sender.id,
  45. chatType: ChatType.Private,
  46. };
  47. }
  48. return {
  49. chatID: {
  50. qq: msg.sender.id,
  51. group: msg.sender.group.id,
  52. },
  53. chatType: ChatType.Temp,
  54. };
  55. }
  56. }
  57. public sendTo = (subscriber: IChat, msg: string | MessageChain) =>
  58. (() => {
  59. switch (subscriber.chatType) {
  60. case 'group':
  61. return this.bot.api.sendGroupMessage(msg, subscriber.chatID);
  62. case 'private':
  63. return this.bot.api.sendFriendMessage(msg, subscriber.chatID);
  64. // currently disabled
  65. case 'temp':
  66. return this.bot.api.sendTempMessage(msg, subscriber.chatID.qq, subscriber.chatID.group);
  67. }
  68. })()
  69. .then(response => {
  70. logger.info(`pushing data to ${JSON.stringify(subscriber.chatID)} was successful, response:`);
  71. logger.info(response);
  72. })
  73. .catch(reason => {
  74. logger.error(`error pushing data to ${JSON.stringify(subscriber.chatID)}, reason: ${reason}`);
  75. throw Error(reason);
  76. })
  77. public uploadPic = (img: MessageType.Image, timeout = -1) => {
  78. if (timeout) timeout = Math.floor(timeout);
  79. if (timeout === 0 || timeout < -1) {
  80. return Promise.reject('Error: timeout must be greater than 0ms');
  81. }
  82. let imgFile: string;
  83. if (img.imageId !== '') return Promise.resolve();
  84. if (img.url !== '') {
  85. if (img.url.split(':')[0] !== 'data') {
  86. return Promise.reject('Error: URL must be of protocol "data"');
  87. }
  88. if (img.url.split(',')[0].split(';')[1] !== 'base64') {
  89. return Promise.reject('Error: data URL must be of encoding "base64"');
  90. }
  91. temp.track();
  92. try {
  93. const tempFile = temp.openSync();
  94. writeSync(tempFile.fd, Buffer.from(img.url.split(',')[1], 'base64'));
  95. closeSync(tempFile.fd);
  96. imgFile = tempFile.path;
  97. } catch (error) {
  98. logger.error(error);
  99. }
  100. }
  101. try {
  102. this.bot.axios.defaults.timeout = timeout === -1 ? 0 : timeout;
  103. logger.info(`uploading ${JSON.stringify(
  104. Message.Image(img.imageId, `${img.url.split(',')[0]},[...]`, img.path)
  105. )}...`);
  106. return this.bot.api.uploadImage('group', imgFile || img.path)
  107. .then(response => { // workaround for https://github.com/mamoe/mirai/issues/194
  108. logger.info(`uploading ${img.path} as group image was successful, response:`);
  109. logger.info(JSON.stringify(response));
  110. img.url = '';
  111. img.path = (response.path as string).split(/[/\\]/).slice(-1)[0];
  112. })
  113. .catch(reason => {
  114. logger.error(`error uploading ${img.path}, reason: ${reason}`);
  115. throw Error(reason);
  116. });
  117. } finally {
  118. temp.cleanup();
  119. this.bot.axios.defaults.timeout = 0;
  120. }
  121. }
  122. private initBot = () => {
  123. this.bot = new Mirai({
  124. authKey: this.botInfo.access_token,
  125. enableWebsocket: false,
  126. host: this.botInfo.host,
  127. port: this.botInfo.port,
  128. });
  129. this.bot.axios.defaults.maxContentLength = this.bot.axios.defaults.maxBodyLength = Infinity;
  130. this.bot.on('NewFriendRequestEvent', evt => {
  131. logger.debug(`detected new friend request event: ${JSON.stringify(evt)}`);
  132. this.bot.api.groupList()
  133. .then((groupList: [{
  134. id: number,
  135. name: string,
  136. permission: 'OWNER' | 'ADMINISTRATOR' | 'MEMBER',
  137. }]) => {
  138. if (groupList.some(groupItem => groupItem.id === evt.groupId)) {
  139. evt.respond(0); // allow
  140. return logger.info(`accepted friend request from ${evt.fromId} (from group ${evt.groupId})`);
  141. }
  142. logger.warn(`received friend request from ${evt.fromId} (from group ${evt.groupId})`);
  143. logger.warn('please manually accept this friend request');
  144. });
  145. });
  146. this.bot.on('BotInvitedJoinGroupRequestEvent', evt => {
  147. logger.debug(`detected group invitation event: ${JSON.stringify(evt)}`);
  148. this.bot.api.friendList()
  149. .then((friendList: [{
  150. id: number,
  151. nickname: string,
  152. remark: string,
  153. }]) => {
  154. if (friendList.some(friendItem => friendItem.id = evt.fromId)) {
  155. evt.respond(0); // allow
  156. return logger.info(`accepted group invitation from ${evt.fromId} (friend)`);
  157. }
  158. logger.warn(`received group invitation from ${evt.fromId} (unknown)`);
  159. logger.warn('please manually accept this group invitation');
  160. });
  161. });
  162. this.bot.on('message', async msg => {
  163. const chat = await this.getChat(msg);
  164. const cmdObj = parseCmd(msg.plain);
  165. switch (cmdObj.cmd) {
  166. case 'twitterfleets_view':
  167. case 'twitterfleets_get':
  168. view(chat, cmdObj.args, msg.reply);
  169. break;
  170. case 'twitterfleets_sub':
  171. case 'twitterfleets_subscribe':
  172. this.botInfo.sub(chat, cmdObj.args, msg.reply);
  173. break;
  174. case 'twitterfleets_unsub':
  175. case 'twitterfleets_unsubscribe':
  176. this.botInfo.unsub(chat, cmdObj.args, msg.reply);
  177. break;
  178. case 'ping':
  179. case 'twitterfleets':
  180. this.botInfo.list(chat, cmdObj.args, msg.reply);
  181. break;
  182. case 'help':
  183. msg.reply(`推特故事搬运机器人:
  184. /twitterfleets - 查询当前聊天中的推特故事订阅
  185. /twitterfleets_view〈链接〉- 查看该用户当前可见的所有 Fleets
  186. /twitterfleets_subscribe [链接] - 订阅 Twitter Fleets 搬运
  187. /twitterfleets_unsubscribe [链接] - 退订 Twitter Fleets 搬运`);
  188. }
  189. });
  190. }
  191. // TODO doesn't work if connection is dropped after connection
  192. private listen = (logMsg?: string) => {
  193. if (logMsg !== '') {
  194. logger.warn(logMsg ?? 'Listening...');
  195. }
  196. axios.get(`http://${this.botInfo.host}:${this.botInfo.port}/about`)
  197. .then(async () => {
  198. if (logMsg !== '') {
  199. this.bot.listen();
  200. await this.login();
  201. }
  202. setTimeout(() => this.listen(''), 5000);
  203. })
  204. .catch(() => {
  205. logger.error(`Error connecting to bot provider at ${this.botInfo.host}:${this.botInfo.port}`);
  206. setTimeout(() => this.listen('Retry listening...'), 2500);
  207. });
  208. }
  209. private login = async (logMsg?: string) => {
  210. logger.warn(logMsg ?? 'Logging in...');
  211. await this.bot.link(this.botInfo.bot_id)
  212. .then(() => logger.warn(`Logged in as ${this.botInfo.bot_id}`))
  213. .catch(() => {
  214. logger.error(`Cannot log in. Do you have a bot logged in as ${this.botInfo.bot_id}?`);
  215. setTimeout(() => this.login('Retry logging in...'), 2500);
  216. });
  217. }
  218. public connect = () => {
  219. this.initBot();
  220. this.listen();
  221. }
  222. constructor(opt: IQQProps) {
  223. logger.warn(`Initialized mirai-ts for ${opt.host}:${opt.port} with access_token ${opt.access_token}`);
  224. this.botInfo = opt;
  225. }
  226. }