koishi.ts 10 KB

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