command.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. /* eslint-disable @typescript-eslint/no-unsafe-return */
  2. /* eslint-disable @typescript-eslint/member-delimiter-style */
  3. /* eslint-disable prefer-arrow/prefer-arrow-functions */
  4. import * as fs from 'fs';
  5. import * as path from 'path';
  6. import { relativeDate } from './datetime';
  7. import { getLogger } from './loggers';
  8. import { sendTimeline, sendTweet, ScreenNameNormalizer as normalizer } from './twitter';
  9. import { BigNumOps } from './utils';
  10. const logger = getLogger('command');
  11. function parseCmd(message: string): {
  12. cmd: string;
  13. args: string[];
  14. } {
  15. message = message.trim();
  16. message = message.replace('\\\\', '\\0x5c');
  17. message = message.replace('\\\"', '\\0x22');
  18. message = message.replace('\\\'', '\\0x27');
  19. const strs = message.match(/'[\s\S]*?'|(?:\S+=)?"[\s\S]*?"|\S+/mg);
  20. const cmd = strs?.length ? strs[0].length ? strs[0].substring(0, 1) === '/' ? strs[0].substring(1) : '' : '' : '';
  21. const args = (strs ?? []).slice(1).map(arg => {
  22. arg = arg.replace(/^(\S+=)?["']+(?!.*=)|["']+$/g, '$1');
  23. arg = arg.replace('\\0x27', '\\\'');
  24. arg = arg.replace('\\0x22', '\\\"');
  25. arg = arg.replace('\\0x5c', '\\\\');
  26. return arg;
  27. });
  28. return {
  29. cmd,
  30. args,
  31. };
  32. }
  33. function parseLink(link: string): string[] {
  34. let match =
  35. /twitter.com\/([^\/?#]+)\/lists\/([^\/?#]+)/.exec(link) ||
  36. /^([^\/?#]+)\/([^\/?#]+)$/.exec(link);
  37. if (match) return [match[1], `/lists/${match[2]}`];
  38. match =
  39. /twitter.com\/([^\/?#]+)\/status\/(\d+)/.exec(link);
  40. if (match) return [match[1], `/status/${match[2]}`];
  41. match =
  42. /twitter.com\/([^\/?#]+)/.exec(link) ||
  43. /^([^\/?#]+)$/.exec(link);
  44. if (match) return [match[1]];
  45. return;
  46. }
  47. function linkBuilder(userName: string, more = ''): string {
  48. if (!userName) return;
  49. return `https://twitter.com/${userName}${more}`;
  50. }
  51. function linkFinder(checkedMatch: string[], chat: IChat, lock: ILock): [string, number] {
  52. const normalizedLink =
  53. linkBuilder(normalizer.normalize(checkedMatch[0]), checkedMatch[1]?.toLowerCase());
  54. const link = Object.keys(lock.threads).find(realLink =>
  55. normalizedLink === realLink.replace(/\/@/, '/').toLowerCase()
  56. );
  57. if (!link) return [null, -1];
  58. const index = lock.threads[link].subscribers.findIndex(({chatID, chatType}) =>
  59. chat.chatID === chatID && chat.chatType === chatType
  60. );
  61. return [link, index];
  62. }
  63. function sub(chat: IChat, args: string[], reply: (msg: string) => any,
  64. lock: ILock, lockfile: string
  65. ): void {
  66. if (chat.chatType === ChatType.Temp) {
  67. return reply('请先添加机器人为好友。');
  68. }
  69. if (args.length === 0) {
  70. return reply('找不到要订阅媒体推文的链接。');
  71. }
  72. const match = parseLink(args[0]);
  73. if (!match) {
  74. return reply(`订阅链接格式错误:
  75. 示例:
  76. https://twitter.com/Saito_Shuka
  77. https://twitter.com/rikakomoe/lists/lovelive
  78. https://twitter.com/TomoyoKurosawa/status/1294613494860361729`);
  79. }
  80. let offset = '0';
  81. if (match[1]) {
  82. const matchStatus = /\/status\/(\d+)/.exec(match[1]);
  83. if (matchStatus) {
  84. offset = BigNumOps.plus(matchStatus[1], '-1');
  85. delete match[1];
  86. }
  87. }
  88. const subscribeTo = (link: string, config: {addNew?: boolean, msg?: string} = {}) => {
  89. const {addNew = false, msg = `已为此聊天订阅 ${link} 的媒体推文`} = config;
  90. if (addNew) {
  91. lock.feed.push(link);
  92. lock.threads[link] = {
  93. offset,
  94. subscribers: [],
  95. updatedAt: '',
  96. };
  97. }
  98. lock.threads[link].subscribers.push(chat);
  99. logger.warn(`chat ${JSON.stringify(chat)} has subscribed ${link}`);
  100. fs.writeFileSync(path.resolve(lockfile), JSON.stringify(lock));
  101. reply(msg);
  102. };
  103. const [realLink, index] = linkFinder(match, chat, lock);
  104. if (index > -1) return reply('此聊天已订阅此链接。');
  105. if (realLink) return subscribeTo(realLink);
  106. const [rawUserName, more] = match;
  107. if (rawUserName.toLowerCase() === 'i' && /lists\/(\d+)/.exec(more)) {
  108. return subscribeTo(linkBuilder('i', more), {addNew: true});
  109. }
  110. normalizer.normalizeLive(rawUserName).then(userName => {
  111. if (!userName) return reply(`找不到用户 ${rawUserName.replace(/^@?(.*)$/, '@$1')}。`);
  112. const link = linkBuilder(userName, more);
  113. const msg = (offset === '0') ?
  114. undefined :
  115. `已为此聊天订阅 ${link} 的媒体动态并回溯到此动态 ID(含)之后的第一条媒体动态。
  116. (参见:https://blog.twitter.com/engineering/en_us/a/2010/announcing-snowflake.html)`;
  117. subscribeTo(link, {addNew: true, msg});
  118. });
  119. }
  120. function unsub(chat: IChat, args: string[], reply: (msg: string) => any,
  121. lock: ILock, lockfile: string
  122. ): void {
  123. if (chat.chatType === ChatType.Temp) {
  124. return reply('请先添加机器人为好友。');
  125. }
  126. if (args.length === 0) {
  127. return reply('找不到要退订媒体推文的链接。');
  128. }
  129. const match = parseLink(args[0]);
  130. if (!match) {
  131. return reply('链接格式有误。');
  132. }
  133. const [link, index] = linkFinder(match, chat, lock);
  134. if (index === -1) return list(chat, args, msg => reply('您没有订阅此链接的媒体推文。\n' + msg), lock);
  135. else {
  136. lock.threads[link].subscribers.splice(index, 1);
  137. fs.writeFileSync(path.resolve(lockfile), JSON.stringify(lock));
  138. logger.warn(`chat ${JSON.stringify(chat)} has unsubscribed ${link}`);
  139. return reply(`已为此聊天退订 ${link} 的媒体推文`);
  140. }
  141. }
  142. function list(chat: IChat, _: string[], reply: (msg: string) => any, lock: ILock): void {
  143. if (chat.chatType === ChatType.Temp) {
  144. return reply('请先添加机器人为好友。');
  145. }
  146. const links = [];
  147. Object.keys(lock.threads).forEach(key => {
  148. if (lock.threads[key].subscribers.find(({chatID, chatType}) =>
  149. chat.chatID === chatID && chat.chatType === chatType
  150. )) links.push(`${key} ${relativeDate(lock.threads[key].updatedAt)}`);
  151. });
  152. return reply('此聊天中订阅媒体推文的链接:\n' + links.join('\n'));
  153. }
  154. function view(chat: IChat, args: string[], reply: (msg: string) => any): void {
  155. if (args.length === 0) {
  156. return reply('找不到要查看的链接。');
  157. }
  158. const match = /^(?:.*twitter.com\/[^\/?#]+\/status\/)?(\d+)/.exec(args[0]);
  159. if (!match) {
  160. return reply('链接格式有误。');
  161. }
  162. try {
  163. sendTweet(match[1], chat);
  164. } catch (e) {
  165. reply('推特机器人尚未加载完毕,请稍后重试。');
  166. }
  167. }
  168. function query(chat: IChat, args: string[], reply: (msg: string) => any): void {
  169. if (args.length === 0) {
  170. return reply('找不到要查询的用户。');
  171. }
  172. const match =
  173. /twitter.com\/([^\/?#]+)/.exec(args[0]) ||
  174. /^([^\/?#]+)$/.exec(args[0]);
  175. if (!match) {
  176. return reply('链接格式有误。');
  177. }
  178. const conf: {
  179. username: string,
  180. count?: string,
  181. since?: string,
  182. until?: string,
  183. noreps: string,
  184. norts: string,
  185. } = {username: match[1], noreps: 'on', norts: 'off'};
  186. const confZH: Record<Exclude<keyof typeof conf, 'username'>, string> = {
  187. count: '数量上限',
  188. since: '起始点',
  189. until: '结束点',
  190. noreps: '忽略回复推文(on/off)',
  191. norts: '忽略原生转推(on/off)',
  192. };
  193. for (const arg of args.slice(1)) {
  194. const optMatch = /^(count|since|until|noreps|norts)=(.*)/.exec(arg);
  195. if (!optMatch) return reply(`未定义的查询参数:${arg}。`);
  196. const optKey = optMatch[1] as keyof typeof confZH;
  197. if (optMatch.length === 1) return reply(`查询${confZH[optKey]}参数格式有误。`);
  198. conf[optKey] = optMatch[2];
  199. if (optMatch[2] === '') return reply(`查询${confZH[optKey]}参数值不可为空。`);
  200. }
  201. if (conf.count !== undefined && !Number(conf.count) || Math.abs(Number(conf.count)) > 50) {
  202. return reply('查询数量上限参数为零、非数值或超出取值范围。');
  203. }
  204. try {
  205. sendTimeline(conf, chat);
  206. } catch (e) {
  207. logger.error(`error querying timeline, error: ${e}`);
  208. reply('推特机器人尚未加载完毕,请稍后重试。');
  209. }
  210. }
  211. export { parseCmd, sub, list, unsub, view, query };