mirai.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. import { closeSync, createReadStream, writeSync } from 'fs';
  2. import { promisify } from 'util';
  3. import axios from 'axios';
  4. import Mirai, { MessageType } from 'mirai-ts';
  5. import MiraiMessage from 'mirai-ts/dist/message';
  6. import * as temp from 'temp';
  7. import { parseCmd, query, view } from './command';
  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. 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 imgFilePath: string;
  83. if (img.imageId !== '') return Promise.resolve();
  84. else 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. imgFilePath = tempFile.path;
  97. } catch (error) {
  98. logger.error(error);
  99. }
  100. } else imgFilePath = img.path;
  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', createReadStream(imgFilePath))
  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).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 = 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);
  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);
  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 'twitterpic_view':
  167. case 'twitterpic_get':
  168. view(chat, cmdObj.args, msg.reply);
  169. break;
  170. case 'twitterpic_query':
  171. case 'twitterpic_gettimeline':
  172. query(chat, cmdObj.args, msg.reply);
  173. break;
  174. case 'twitterpic_sub':
  175. case 'twitterpic_subscribe':
  176. this.botInfo.sub(chat, cmdObj.args, msg.reply);
  177. break;
  178. case 'twitterpic_unsub':
  179. case 'twitterpic_unsubscribe':
  180. this.botInfo.unsub(chat, cmdObj.args, msg.reply);
  181. break;
  182. case 'ping':
  183. case 'twitterpic':
  184. this.botInfo.list(chat, cmdObj.args, msg.reply);
  185. break;
  186. case 'help':
  187. if (cmdObj.args.length === 0) {
  188. msg.reply(`推特媒体推文搬运机器人:
  189. /twitterpic - 查询当前聊天中的媒体推文订阅
  190. /twitterpic_subscribe〈链接|用户名〉- 订阅 Twitter 媒体推文搬运
  191. /twitterpic_unsubscribe〈链接|用户名〉- 退订 Twitter 媒体推文搬运
  192. /twitterpic_view〈链接〉- 查看推文(无关是否包含媒体)
  193. /twitterpic_query〈链接|用户名〉[参数列表...] - 查询时间线(详见 /help twitterpic_query)\
  194. ${chat.chatType === ChatType.Temp ?
  195. '\n(当前游客模式下无法使用订阅功能,请先添加本账号为好友。)' : ''
  196. }`);
  197. } else if (cmdObj.args[0] === 'twitterpic_query') {
  198. msg.reply(`查询时间线中的媒体推文:
  199. /twitterpic_query〈链接|用户名〉[〈参数 1〉=〈值 1〉〈参数 2〉=〈值 2〉...]
  200. 参数列表(方框内全部为可选,留空则为默认):
  201. count:查询数量上限(类型:非零整数,最大值正负 50)[默认值:10]
  202. since:查询起始点(类型:正整数或日期)[默认值:(空,无限过去)]
  203. until:查询结束点(类型:正整数或日期)[默认值:(空,当前时刻)]
  204. noreps 忽略回复推文(类型:on/off)[默认值:on(是)]
  205. norts:忽略原生转推(类型:on/off)[默认值:off(否)]`)
  206. .then(() => msg.reply(`\
  207. 起始点和结束点为正整数时取推特推文编号作为比较基准,否则会尝试作为日期读取。
  208. 推荐的日期格式:2012-12-22 12:22 UTC+2 (日期和时间均为可选,可分别添加)
  209. count 为正时,从新向旧查询;为负时,从旧向新查询
  210. count 与 since/until 并用时,取二者中实际查询结果较少者
  211. 例子:/twitterpic_query RiccaTachibana count=5 since="2019-12-30\
  212. UTC+9" until="2020-01-06 UTC+8" norts=on
  213. 从起始时间点(含)到结束时间点(不含)从新到旧获取最多 5 条媒体推文,\
  214. 其中不包含原生转推(实际上用户只发了 1 条)`)
  215. );
  216. }
  217. }
  218. });
  219. };
  220. /**
  221. * @todo doesn't work if connection is dropped after connection
  222. */
  223. private listen = (logMsg?: string) => {
  224. if (logMsg !== '') {
  225. logger.warn(logMsg ?? 'Listening...');
  226. }
  227. axios.get(`http://${this.botInfo.host}:${this.botInfo.port}/about`)
  228. .then(async () => {
  229. if (logMsg !== '') {
  230. this.bot.listen();
  231. await this.login();
  232. }
  233. setTimeout(() => this.listen(''), 5000);
  234. })
  235. .catch(() => {
  236. logger.error(`Error connecting to bot provider at ${this.botInfo.host}:${this.botInfo.port}`);
  237. setTimeout(() => this.listen('Retry listening...'), 2500);
  238. });
  239. };
  240. private login = async (logMsg?: string) => {
  241. logger.warn(logMsg ?? 'Logging in...');
  242. await this.bot.link(this.botInfo.bot_id)
  243. .then(() => logger.warn(`Logged in as ${this.botInfo.bot_id}`))
  244. .catch(() => {
  245. logger.error(`Cannot log in. Do you have a bot logged in as ${this.botInfo.bot_id}?`);
  246. return promisify(setTimeout)(2500).then(() => this.login('Retry logging in...'));
  247. });
  248. };
  249. public connect = () => {
  250. this.initBot();
  251. this.listen();
  252. };
  253. constructor(opt: IQQProps) {
  254. logger.warn(`Initialized mirai-ts for ${opt.host}:${opt.port} with access_token ${opt.access_token}`);
  255. this.botInfo = opt;
  256. }
  257. }