mirai.ts 8.2 KB

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