koishi.ts 9.9 KB

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