koishi.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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, resendLast } 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 'twitterpic_view':
  182. case 'twitterpic_get':
  183. view(chat, cmdObj.args, reply);
  184. break;
  185. case 'twitterpic_resendlast':
  186. resendLast(chat, cmdObj.args, reply);
  187. break;
  188. case 'twitterpic_query':
  189. case 'twitterpic_gettimeline':
  190. query(chat, cmdObj.args, reply);
  191. break;
  192. case 'twitterpic_sub':
  193. case 'twitterpic_subscribe':
  194. this.botInfo.sub(chat, cmdObj.args, reply);
  195. break;
  196. case 'twitterpic_unsub':
  197. case 'twitterpic_unsubscribe':
  198. this.botInfo.unsub(chat, cmdObj.args, reply);
  199. break;
  200. case 'twitterpic_unsuball':
  201. case 'bye':
  202. this.botInfo.unsubAll(chat, cmdObj.args, reply);
  203. break;
  204. case 'ping':
  205. case 'twitterpic':
  206. this.botInfo.list(chat, cmdObj.args, reply);
  207. break;
  208. case 'help':
  209. if (cmdObj.args.length === 0) {
  210. reply(`推特媒体推文搬运机器人:
  211. /twitterpic - 查询当前聊天中的媒体推文订阅
  212. /twitterpic_sub[scribe]〈链接|用户名〉- 订阅 Twitter 媒体推文搬运
  213. /twitterpic_unsub[scribe]〈链接|用户名〉- 退订 Twitter 媒体推文搬运
  214. /twitterpic_view〈链接|表达式〉[{force|refresh}={on|off}] - 查看推文(可选强制重新载入)
  215. /twitterpic_resendlast〈用户名〉- 强制重发该用户最后一条媒体推文
  216. /twitterpic_query〈链接|用户名〉[参数列表...] - 查询时间线(详见 /help twitterpic_query)\
  217. ${chat.chatType === ChatType.Temp ?
  218. '\n(当前游客模式下无法使用订阅功能,请先添加本账号为好友。)' : ''
  219. }`);
  220. } else if (cmdObj.args[0] === 'twitterpic_query') {
  221. reply(`查询时间线中的媒体推文:
  222. /twitterpic_query〈链接|用户名〉[〈参数 1〉=〈值 1〉〈参数 2〉=〈值 2〉...]
  223. 参数列表(方框内全部为可选,留空则为默认):
  224. count:查询数量上限(类型:非零整数,最大值正负 50)[默认值:10]
  225. since:查询起始点(类型:正整数或日期)[默认值:(空,无限过去)]
  226. until:查询结束点(类型:正整数或日期)[默认值:(空,当前时刻)]
  227. noreps 忽略回复推文(类型:on/off)[默认值:on(是)]
  228. norts:忽略原生转推(类型:on/off)[默认值:off(否)]`)
  229. .then(() => reply(`\
  230. 起始点和结束点为正整数时取推特推文编号作为比较基准,否则会尝试作为日期读取。
  231. 推荐的日期格式:2012-12-22 12:22 UTC+2 (日期和时间均为可选,可分别添加)
  232. count 为正时,从新向旧查询;为负时,从旧向新查询
  233. count 与 since/until 并用时,取二者中实际查询结果较少者
  234. 例子:/twitterpic_query RiccaTachibana count=5 since="2019-12-30\
  235. UTC+9" until="2020-01-06 UTC+8" norts=on
  236. 从起始时间点(含)到结束时间点(不含)从新到旧获取最多 5 条媒体推文,\
  237. 其中不包含原生转推(实际上用户只发了 1 条)`)
  238. );
  239. }
  240. }
  241. }, true);
  242. };
  243. private listen = async (logMsg = 'connecting to bot provider...'): Promise<void> => {
  244. logger.warn(logMsg);
  245. try {
  246. await this.app.start();
  247. } catch (err) {
  248. logger.error(`error connecting to bot provider at ${this.app.options.server}, will retry in 2.5s...`);
  249. await sleep(2500);
  250. await this.listen('retry connecting...');
  251. }
  252. };
  253. public connect = async () => {
  254. this.initBot();
  255. await this.listen();
  256. this.bot = this.app.getBot('onebot');
  257. };
  258. constructor(opt: IQQProps) {
  259. logger.warn(`Initialized koishi on ${opt.host}:${opt.port} with access_token ${opt.access_token}`);
  260. this.botInfo = opt;
  261. }
  262. }