koishi.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. import * as getPort from 'get-port';
  2. import { App, Bot, segment, Session } from 'koishi';
  3. import 'koishi-adapter-onebot';
  4. import { parseCmd, query, view } from './command';
  5. import { getLogger } from './loggers';
  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. export const message = segment;
  17. export const ellipseBase64InMessage = (msg: string) => msg.replace(/(?<=\[CQ:.*base64:\/\/).*?(,|\])/, '...$1');
  18. export default class {
  19. private botInfo: IQQProps;
  20. private app: App;
  21. public bot: Bot;
  22. private getChat = async (session: Session): Promise<IChat> => {
  23. switch (session.subtype) {
  24. case 'private':
  25. if (session.groupId) { // temp message
  26. const friendList = await session.bot.getFriendList();
  27. if (!friendList.some(friendItem => friendItem.userId === session.userId)) {
  28. return {
  29. chatID: {
  30. qq: Number(session.userId),
  31. group: Number(session.groupId),
  32. },
  33. chatType: ChatType.Temp,
  34. };
  35. }
  36. }
  37. return { // already befriended
  38. chatID: Number(session.userId),
  39. chatType: ChatType.Private,
  40. };
  41. case 'group':
  42. return {
  43. chatID: Number(session.groupId),
  44. chatType: ChatType.Group,
  45. };
  46. }
  47. };
  48. public sendTo = (subscriber: IChat, msg: string) => (() => {
  49. switch (subscriber.chatType) {
  50. case 'group':
  51. return this.bot.sendMessage(subscriber.chatID.toString(), msg);
  52. case 'private':
  53. return this.bot.sendPrivateMessage(subscriber.chatID.toString(), msg);
  54. case 'temp': // currently unable to open session, awaiting OneBot v12
  55. return this.bot.sendPrivateMessage(subscriber.chatID.qq.toString(), msg);
  56. }
  57. })()
  58. .then(response => {
  59. logger.info(`pushing data to ${JSON.stringify(subscriber.chatID)} was successful, response:`);
  60. logger.info(response);
  61. })
  62. .catch(reason => {
  63. logger.error(`error pushing data to ${JSON.stringify(subscriber.chatID)}, reason: ${reason}`);
  64. throw Error(reason);
  65. });
  66. private initBot = async () => {
  67. const port = await getPort();
  68. this.app = new App({
  69. type: 'onebot',
  70. port,
  71. server: `http://${this.botInfo.host}:${this.botInfo.port}`,
  72. selfId: this.botInfo.bot_id.toString(),
  73. token: this.botInfo.access_token,
  74. onebot: {
  75. quickOperation: 100,
  76. },
  77. axiosConfig: {
  78. maxContentLength: Infinity,
  79. },
  80. processMessage: msg => msg.trim(),
  81. });
  82. this.app.on('friend-request', async session => {
  83. const userString = `${session.username}(${session.userId})`;
  84. const groupString = `${session.groupName}(${session.groupId})`;
  85. logger.debug(`detected new friend request event: ${userString}`);
  86. return session.bot.getGroupList().then(groupList => {
  87. if (groupList.some(groupItem => groupItem.groupId === session.groupId)) {
  88. session.bot.handleFriendRequest(session.messageId, true);
  89. return logger.info(`accepted friend request from ${userString} (from group ${groupString})`);
  90. }
  91. logger.warn(`received friend request from ${userString} (from group ${groupString})`);
  92. logger.warn('please manually accept this friend request');
  93. });
  94. });
  95. this.app.on('group-request', async session => {
  96. const userString = `${session.username}(${session.userId})`;
  97. const groupString = `${session.groupName}(${session.groupId})`;
  98. logger.debug(`detected group invitation event: ${groupString}}`);
  99. return session.bot.getFriendList().then(friendList => {
  100. if (friendList.some(friendItem => friendItem.userId = session.userId)) {
  101. session.bot.handleGroupRequest(session.messageId, true);
  102. return logger.info(`accepted group invitation from ${userString} (friend)`);
  103. }
  104. logger.warn(`received group invitation from ${userString} (stranger)`);
  105. logger.warn('please manually accept this group invitation');
  106. });
  107. });
  108. this.app.middleware(async session => {
  109. const chat = await this.getChat(session);
  110. const cmdObj = parseCmd(session.content);
  111. const reply = async msg => session.send(msg);
  112. switch (cmdObj.cmd) {
  113. case 'twitter_view':
  114. case 'twitter_get':
  115. view(chat, cmdObj.args, reply);
  116. break;
  117. case 'twitter_query':
  118. case 'twitter_gettimeline':
  119. query(chat, cmdObj.args, reply);
  120. break;
  121. case 'twitter_sub':
  122. case 'twitter_subscribe':
  123. this.botInfo.sub(chat, cmdObj.args, reply);
  124. break;
  125. case 'twitter_unsub':
  126. case 'twitter_unsubscribe':
  127. this.botInfo.unsub(chat, cmdObj.args, reply);
  128. break;
  129. case 'ping':
  130. case 'twitter':
  131. this.botInfo.list(chat, cmdObj.args, reply);
  132. break;
  133. case 'help':
  134. if (cmdObj.args.length === 0) {
  135. reply(`推特搬运机器人:
  136. /twitter - 查询当前聊天中的推文订阅
  137. /twitter_subscribe〈链接|用户名〉- 订阅 Twitter 推文搬运
  138. /twitter_unsubscribe〈链接|用户名〉- 退订 Twitter 推文搬运
  139. /twitter_view〈链接〉- 查看推文
  140. /twitter_query〈链接|用户名〉[参数列表...] - 查询时间线(详见 /help twitter_query)\
  141. ${chat.chatType === ChatType.Temp ?
  142. '\n(当前游客模式下无法使用订阅功能,请先添加本账号为好友。)' : ''
  143. }`);
  144. } else if (cmdObj.args[0] === 'twitter_query') {
  145. reply(`查询时间线中的推文:
  146. /twitter_query〈链接|用户名〉[〈参数 1〉=〈值 1〉〈参数 2〉=〈值 2〉...]
  147. 参数列表(方框内全部为可选,留空则为默认):
  148. count:查询数量上限(类型:非零整数,最大值正负 50)[默认值:10]
  149. since:查询起始点(类型:正整数或日期)[默认值:(空,无限过去)]
  150. until:查询结束点(类型:正整数或日期)[默认值:(空,当前时刻)]
  151. noreps 忽略回复推文(类型:on/off)[默认值:on(是)]
  152. norts:忽略原生转推(类型:on/off)[默认值:off(否)]`)
  153. .then(() => reply(`\
  154. 起始点和结束点为正整数时取推特推文编号作为比较基准,否则会尝试作为日期读取。
  155. 推荐的日期格式:2012-12-22 12:22 UTC+2 (日期和时间均为可选,可分别添加)
  156. count 为正时,从新向旧查询;为负时,从旧向新查询
  157. count 与 since/until 并用时,取二者中实际查询结果较少者
  158. 例子:/twitter_query RiccaTachibana count=5 since="2019-12-30\
  159. UTC+9" until="2020-01-06 UTC+8" norts=on
  160. 从起始时间点(含)到结束时间点(不含)从新到旧获取最多 5 条推文,\
  161. 其中不包含原生转推(实际上用户只发了 1 条)`)
  162. );
  163. }
  164. }
  165. });
  166. };
  167. public connect = async () => {
  168. await this.initBot();
  169. await this.app.start();
  170. this.bot = this.app.getBot('onebot');
  171. };
  172. constructor(opt: IQQProps) {
  173. logger.warn(`Initialized koishi on ${opt.host}:${opt.port} with access_token ${opt.access_token}`);
  174. this.botInfo = opt;
  175. }
  176. }