koishi.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. import { App, Bot, segment, Session, sleep } from 'koishi';
  2. import 'koishi-adapter-onebot';
  3. import { parseCmd, view } from './command';
  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[], replyfn: (msg: string) => any): void;
  12. sub(chat: IChat, args: string[], replyfn: (msg: string) => any): void;
  13. unsub(chat: IChat, args: string[], replyfn: (msg: string) => any): void;
  14. }
  15. const cqUrlFix = (factory: segment.Factory<string | ArrayBuffer | Buffer>) =>
  16. (...args: Parameters<typeof factory>) =>
  17. factory(...args).replace(/(?<=\[CQ:.*)url=(?=(base64|file|https?):\/\/)/, 'file=');
  18. export const Message = {
  19. Image: cqUrlFix(segment.image),
  20. Video: cqUrlFix(segment.video),
  21. Voice: cqUrlFix(segment.audio),
  22. ellipseBase64: (msg: string) => msg.replace(/(?<=\[CQ:.*base64:\/\/).*?(,|\])/g, '...$1'),
  23. separateAttachment: (msg: string) => {
  24. const attachments: string[] = [];
  25. const message = msg.replace(/\[CQ:(video|record),.*?\]/g, code => {
  26. attachments.push(code);
  27. return '';
  28. });
  29. return {message, attachments};
  30. },
  31. };
  32. export default class {
  33. private botInfo: IQQProps;
  34. private app: App;
  35. public bot: Bot;
  36. private messageQueues: {[key: string]: (() => Promise<void>)[]} = {};
  37. private next = (type: 'private' | 'group', id: string) => {
  38. const queue = this.messageQueues[`${type}:${id}`];
  39. if (queue && queue.length) {
  40. queue[0]().then(() => {
  41. queue.shift();
  42. if (!queue.length) delete this.messageQueues[`${type}:${id}`];
  43. else this.next(type, id);
  44. });
  45. }
  46. };
  47. private enqueue = (type: 'private' | 'group', id: string, resolver: () => Promise<void>) => {
  48. let wasEmpty = false;
  49. const queue = this.messageQueues[`${type}:${id}`] ||= (() => { wasEmpty = true; return []; })();
  50. queue.push(() => sleep(200).then(resolver));
  51. logger.debug(`no. of message currently queued for ${type}:${id}: ${queue.length}`);
  52. if (wasEmpty) this.next(type, id);
  53. };
  54. private getChat = async (session: Session): Promise<IChat> => {
  55. switch (session.subtype) {
  56. case 'private':
  57. if (session.groupId) { // temp message
  58. const friendList = await session.bot.getFriendList();
  59. if (!friendList.some(friendItem => friendItem.userId === session.userId)) {
  60. return {
  61. chatID: {
  62. qq: Number(session.userId),
  63. group: Number(session.groupId),
  64. },
  65. chatType: ChatType.Temp,
  66. };
  67. }
  68. }
  69. return { // already befriended
  70. chatID: Number(session.userId),
  71. chatType: ChatType.Private,
  72. };
  73. case 'group':
  74. return {
  75. chatID: Number(session.groupId),
  76. chatType: ChatType.Group,
  77. };
  78. }
  79. };
  80. private sendToGroup = (groupID: string, message: string) => new Promise<string>(resolve => {
  81. this.enqueue('group', groupID, () => this.bot.sendMessage(groupID, message).then(resolve));
  82. });
  83. private sendToUser = (userID: string, message: string) => new Promise<string>(resolve => {
  84. this.enqueue('private', userID, () => this.bot.sendPrivateMessage(userID, message).then(resolve));
  85. });
  86. public sendTo = (subscriber: IChat, messageChain: string) => Promise.all(
  87. (splitted => [splitted.message, ...splitted.attachments])(
  88. Message.separateAttachment(messageChain)
  89. ).map(msg => {
  90. switch (subscriber.chatType) {
  91. case 'group':
  92. return this.sendToGroup(subscriber.chatID.toString(), msg);
  93. case 'private':
  94. return this.sendToUser(subscriber.chatID.toString(), msg);
  95. case 'temp': // currently unable to open session, awaiting OneBot v12
  96. return this.sendToUser(subscriber.chatID.qq.toString(), msg);
  97. }
  98. }))
  99. .then(response => {
  100. if (response === undefined) return;
  101. logger.info(`pushing data to ${JSON.stringify(subscriber.chatID)} was successful, response: ${response}`);
  102. })
  103. .catch(reason => {
  104. reason = Message.ellipseBase64(reason);
  105. logger.error(`error pushing data to ${JSON.stringify(subscriber.chatID)}, reason: ${reason}`);
  106. throw Error(reason);
  107. });
  108. private initBot = () => {
  109. this.app = new App({
  110. type: 'onebot',
  111. server: `ws://${this.botInfo.host}:${this.botInfo.port}`,
  112. selfId: this.botInfo.bot_id.toString(),
  113. token: this.botInfo.access_token,
  114. axiosConfig: {
  115. maxContentLength: Infinity,
  116. },
  117. processMessage: msg => msg.trim(),
  118. });
  119. this.app.on('friend-request', async session => {
  120. const userString = `${session.username}(${session.userId})`;
  121. const groupString = `${session.groupName}(${session.groupId})`;
  122. logger.debug(`detected new friend request event: ${userString}`);
  123. return session.bot.getGroupList().then(groupList => {
  124. if (groupList.some(groupItem => groupItem.groupId === session.groupId)) {
  125. session.bot.handleFriendRequest(session.messageId, true);
  126. return logger.info(`accepted friend request from ${userString} (from group ${groupString})`);
  127. }
  128. logger.warn(`received friend request from ${userString} (from group ${groupString})`);
  129. logger.warn('please manually accept this friend request');
  130. });
  131. });
  132. this.app.on('group-request', async session => {
  133. const userString = `${session.username}(${session.userId})`;
  134. const groupString = `${session.groupName}(${session.groupId})`;
  135. logger.debug(`detected group invitation event: ${groupString}}`);
  136. return session.bot.getFriendList().then(friendList => {
  137. if (friendList.some(friendItem => friendItem.userId = session.userId)) {
  138. session.bot.handleGroupRequest(session.messageId, true);
  139. return logger.info(`accepted group invitation from ${userString} (friend)`);
  140. }
  141. logger.warn(`received group invitation from ${userString} (stranger)`);
  142. logger.warn('please manually accept this group invitation');
  143. });
  144. });
  145. this.app.middleware(async session => {
  146. const chat = await this.getChat(session);
  147. const cmdObj = parseCmd(session.content);
  148. const reply = async msg => session.sendQueued(msg);
  149. switch (cmdObj.cmd) {
  150. case 'igstory_view':
  151. case 'igstory_get':
  152. view(chat, cmdObj.args, reply);
  153. break;
  154. case 'igstory_sub':
  155. case 'igstory_subscribe':
  156. this.botInfo.sub(chat, cmdObj.args, reply);
  157. break;
  158. case 'igstory_unsub':
  159. case 'igstory_unsubscribe':
  160. this.botInfo.unsub(chat, cmdObj.args, reply);
  161. break;
  162. case 'ping':
  163. case 'igstory':
  164. this.botInfo.list(chat, cmdObj.args, reply);
  165. break;
  166. case 'help':
  167. if (cmdObj.args.length === 0) {
  168. reply(`Instagram 故事搬运机器人:
  169. /igstory - 查询当前聊天中的 Instagram Stories 动态订阅
  170. /igstory_subscribe〈链接|用户名〉- 订阅 Instagram Stories 搬运
  171. /igstory_unsubscribe〈链接|用户名〉- 退订 Instagram Stories 媒体搬运
  172. /igstory_view〈链接〉- 查看该用户所有 Stories
  173. ${chat.chatType === ChatType.Temp ?
  174. '\n(当前游客模式下无法使用订阅功能,请先添加本账号为好友。)' : ''
  175. }`);
  176. }
  177. }
  178. }, true);
  179. };
  180. private listen = async (logMsg = 'connecting to bot provider...'): Promise<void> => {
  181. logger.warn(logMsg);
  182. try {
  183. await this.app.start();
  184. } catch (err) {
  185. logger.error(`error connecting to bot provider at ${this.app.options.server}, will retry in 2.5s...`);
  186. await sleep(2500);
  187. await this.listen('retry connecting...');
  188. }
  189. };
  190. public connect = async () => {
  191. this.initBot();
  192. await this.listen();
  193. this.bot = this.app.getBot('onebot');
  194. };
  195. constructor(opt: IQQProps) {
  196. logger.warn(`Initialized koishi on ${opt.host}:${opt.port} with access_token ${opt.access_token}`);
  197. this.botInfo = opt;
  198. }
  199. }