koishi.ts 8.0 KB

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