twitter.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. "use strict";
  2. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  4. return new (P || (P = Promise))(function (resolve, reject) {
  5. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  6. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  7. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  8. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9. });
  10. };
  11. Object.defineProperty(exports, "__esModule", { value: true });
  12. exports.sendTimeline = exports.sendTweet = exports.ScreenNameNormalizer = exports.linkBuilder = exports.parseLink = void 0;
  13. const fs = require("fs");
  14. const path = require("path");
  15. const Twitter = require("twitter-api-v2");
  16. const loggers_1 = require("./loggers");
  17. const koishi_1 = require("./koishi");
  18. const redis_1 = require("./redis");
  19. const utils_1 = require("./utils");
  20. const webshot_1 = require("./webshot");
  21. const parseLink = (link) => {
  22. let match = /twitter.com\/([^\/?#]+)\/lists\/([^\/?#]+)/.exec(link) ||
  23. /^([^\/?#]+)\/([^\/?#]+)$/.exec(link);
  24. if (match)
  25. return [match[1], `/lists/${match[2]}`];
  26. match =
  27. /twitter.com\/([^\/?#]+)\/status\/(\d+)/.exec(link);
  28. if (match)
  29. return [match[1], `/status/${match[2]}`];
  30. match =
  31. /twitter.com\/([^\/?#]+)/.exec(link) ||
  32. /^([^\/?#]+)$/.exec(link);
  33. if (match)
  34. return [match[1]];
  35. return;
  36. };
  37. exports.parseLink = parseLink;
  38. const linkBuilder = (userName, more = '') => {
  39. if (!userName)
  40. return;
  41. return `https://twitter.com/${userName}${more}`;
  42. };
  43. exports.linkBuilder = linkBuilder;
  44. class ScreenNameNormalizer {
  45. static normalizeLive(username) {
  46. return __awaiter(this, void 0, void 0, function* () {
  47. if (this._queryUser) {
  48. return yield this._queryUser(username)
  49. .then(userNameId => userNameId.split(':')[0])
  50. .catch((err) => {
  51. if (err.title === 'Not Found Error') {
  52. logger.warn(`error looking up user: ${showApiError(err)}`);
  53. return username;
  54. }
  55. return null;
  56. });
  57. }
  58. return this.normalize(username);
  59. });
  60. }
  61. }
  62. exports.ScreenNameNormalizer = ScreenNameNormalizer;
  63. ScreenNameNormalizer.normalize = (username) => username.toLowerCase().replace(/^@/, '');
  64. let sendTweet = (id, receiver, forceRefresh) => {
  65. throw Error();
  66. };
  67. exports.sendTweet = sendTweet;
  68. let sendTimeline = (conf, receiver) => {
  69. throw Error();
  70. };
  71. exports.sendTimeline = sendTimeline;
  72. const TWITTER_EPOCH = 1288834974657;
  73. const snowflake = (epoch) => Number.isNaN(epoch) ? undefined :
  74. utils_1.BigNumOps.lShift(String(epoch - 1 - TWITTER_EPOCH), 22);
  75. const logger = (0, loggers_1.getLogger)('twitter');
  76. const maxTrials = 3;
  77. const retryInterval = 1500;
  78. const ordinal = (n) => {
  79. switch ((Math.trunc(n / 10) % 10 === 1) ? 0 : n % 10) {
  80. case 1:
  81. return `${n}st`;
  82. case 2:
  83. return `${n}nd`;
  84. case 3:
  85. return `${n}rd`;
  86. default:
  87. return `${n}th`;
  88. }
  89. };
  90. const retryOnError = (doWork, onRetry) => new Promise(resolve => {
  91. const retry = (reason, count) => {
  92. setTimeout(() => {
  93. let terminate = false;
  94. onRetry(reason, count, defaultValue => { terminate = true; resolve(defaultValue); });
  95. if (!terminate)
  96. doWork().then(resolve).catch(error => retry(error, count + 1));
  97. }, retryInterval);
  98. };
  99. doWork().then(resolve).catch(error => retry(error, 1));
  100. });
  101. const showApiError = (err) => err.errors && err.errors[0].message || err.detail || err.stack || JSON.stringify(err);
  102. const toMutableConst = (o) => {
  103. return o;
  104. };
  105. const v2SingleParams = toMutableConst({
  106. expansions: ['attachments.media_keys', 'author_id', 'referenced_tweets.id'],
  107. 'tweet.fields': ['created_at', 'entities'],
  108. 'media.fields': ['url', 'variants', 'alt_text'],
  109. 'user.fields': ['id', 'name', 'username']
  110. });
  111. ;
  112. class default_1 {
  113. constructor(opt) {
  114. this.launch = () => {
  115. this.client.appLogin().then(client => {
  116. this.client = client.readOnly;
  117. this.webshot = new webshot_1.default(this.wsUrl, this.mode, () => setTimeout(this.work, this.workInterval * 1000));
  118. });
  119. };
  120. this.queryUser = (username) => {
  121. const thread = this.lock.threads[(0, exports.linkBuilder)(username)];
  122. if (thread && thread.id)
  123. return Promise.resolve(`${username}:${thread.id}`);
  124. return this.client.v2.userByUsername(username).then(({ data: { username, id }, errors }) => {
  125. if (errors && errors.length > 0)
  126. throw errors[0];
  127. if (thread)
  128. thread.id = id;
  129. return `${username}:${id}`;
  130. });
  131. };
  132. this.queryTimelineReverse = (conf) => {
  133. if (!conf.since)
  134. return this.queryTimeline(conf);
  135. const count = conf.count;
  136. const maxID = conf.until;
  137. conf.count = undefined;
  138. const until = () => utils_1.BigNumOps.min(maxID, utils_1.BigNumOps.plus(conf.since, String(7 * 24 * 3600 * 1000 * Math.pow(2, 22))));
  139. conf.until = until();
  140. const promise = (tweets) => this.queryTimeline(conf).then(newTweets => {
  141. tweets = newTweets.concat(tweets);
  142. conf.since = conf.until;
  143. conf.until = until();
  144. if (tweets.length >= count ||
  145. utils_1.BigNumOps.compare(conf.since, conf.until) >= 0) {
  146. return tweets.slice(-count);
  147. }
  148. return promise(tweets);
  149. });
  150. return promise([]);
  151. };
  152. this.queryTimeline = ({ username, count, since, until, noreps, norts }) => {
  153. username = username.replace(/^@?(.*)$/, '@$1');
  154. logger.info(`querying timeline of ${username} with config: ${JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (count && { count })), (since && { since })), (until && { until })), (noreps && { noreps })), (norts && { norts })))}`);
  155. return this.queryUser(username.slice(1)).then(userNameId => this.get('userTimeline', userNameId.split(':')[1], Object.assign(Object.assign(Object.assign({ expansions: ['attachments.media_keys', 'author_id'], 'tweet.fields': ['created_at'], exclude: [
  156. ...(noreps !== null && noreps !== void 0 ? noreps : true) ? ['replies'] : [],
  157. ...(norts !== null && norts !== void 0 ? norts : false) ? ['retweets'] : [],
  158. ] }, (count && { max_results: Math.min(Math.max(count, 5), 100) })), (since && { since_id: since })), (until && { until_id: until }))).then(tweets => tweets.slice(0, count)));
  159. };
  160. this.workOnTweets = (tweets, sendTweets, refresh = false) => Promise.all(tweets.map(({ data, includes }) => ((this.redis && !refresh) ?
  161. this.redis.waitForProcess(`webshot/${data.id}`, this.webshotDelay * 4)
  162. .then(() => this.redis.getContent(`webshot/${data.id}`)) :
  163. Promise.reject())
  164. .then(content => {
  165. if (content === null)
  166. throw Error();
  167. logger.info(`retrieved cached webshot of tweet ${data.id} from redis database, message chain:`);
  168. const { msg, text, author } = JSON.parse(content);
  169. let cacheId = data.id;
  170. const retweetRef = (data.referenced_tweets || []).find(ref => ref.type === 'retweeted');
  171. if (retweetRef)
  172. cacheId += `,rt:${retweetRef.id}`;
  173. logger.info(JSON.stringify(koishi_1.Message.parseCQCode(msg)));
  174. sendTweets(cacheId, koishi_1.Message.parseCQCode(msg), text, author);
  175. return null;
  176. })
  177. .catch(() => {
  178. this.redis.startProcess(`webshot/${data.id}`);
  179. return { data, includes };
  180. }))).then(tweets => this.webshot(tweets.filter(t => t), (cacheId, msg, text, author) => {
  181. Promise.resolve()
  182. .then(() => {
  183. if (!this.redis)
  184. return;
  185. const [twid, rtid] = cacheId.split(',rt:');
  186. logger.info(`caching webshot of tweet ${twid} to redis database`);
  187. this.redis.cacheContent(`webshot/${twid}`, JSON.stringify({ msg: koishi_1.Message.toCQCode(msg), text, author, rtid })).then(() => this.redis.finishProcess(`webshot/${twid}`));
  188. })
  189. .then(() => sendTweets(cacheId, msg, text, author));
  190. }, this.webshotDelay));
  191. this.getTweet = (id, sender, refresh = false) => ((this.redis && !refresh) ?
  192. this.redis.waitForProcess(`webshot/${id}`, this.webshotDelay * 4)
  193. .then(() => this.redis.getContent(`webshot/${id}`))
  194. .then(content => {
  195. if (content === null)
  196. throw Error();
  197. const { rtid } = JSON.parse(content);
  198. return { data: Object.assign({ id }, rtid && { referenced_tweets: [{ type: 'retweeted', id: rtid }] }) };
  199. }) :
  200. Promise.reject())
  201. .catch(() => this.client.v2.singleTweet(id, v2SingleParams))
  202. .then((tweet) => {
  203. if (tweet.data.text) {
  204. logger.debug(`api returned tweet ${JSON.stringify(tweet)} for query id=${id}`);
  205. const retweetRef = (tweet.data.referenced_tweets || []).find(ref => ref.type === 'retweeted');
  206. if (retweetRef)
  207. return this.client.v2.singleTweet(retweetRef.id, v2SingleParams)
  208. .then(({ includes: { media } }) => (Object.assign(Object.assign({}, tweet), { includes: Object.assign(Object.assign({}, tweet.includes), { media }) })));
  209. }
  210. else {
  211. logger.debug(`skipped querying api as this tweet has been cached`);
  212. }
  213. return tweet;
  214. })
  215. .then((tweet) => this.workOnTweets([tweet], sender, refresh));
  216. this.sendTweets = (config = { reportOnSkip: false, force: false }, ...to) => (id, msg, text, author) => {
  217. to.forEach(subscriber => {
  218. const [twid, rtid] = id.split(',rt:');
  219. const { sourceInfo: source, reportOnSkip, force } = config;
  220. const targetStr = JSON.stringify(subscriber);
  221. const send = () => retryOnError(() => this.bot.sendTo(subscriber, msg), (_, count, terminate) => {
  222. if (count <= maxTrials) {
  223. logger.warn(`retry sending to ${subscriber.chatID} for the ${ordinal(count)} time...`);
  224. }
  225. else {
  226. logger.warn(`${count - 1} consecutive failures while sending message chain, trying plain text instead...`);
  227. terminate(this.bot.sendTo(subscriber, author + text, true));
  228. }
  229. }).then(() => {
  230. if (this.redis) {
  231. logger.info(`caching push status of tweet ${rtid ? `${rtid} (RTed as ${twid})` : twid} for ${targetStr}...`);
  232. return this.redis.cacheForChat(rtid || twid, subscriber);
  233. }
  234. });
  235. ((this.redis && !force) ? this.redis.isCachedForChat(rtid || twid, subscriber) : Promise.resolve(false))
  236. .then(isCached => {
  237. if (isCached) {
  238. logger.info(`skipped subscriber ${targetStr} as tweet ${rtid ? `${rtid} (or its RT)` : twid} has been sent already`);
  239. if (!reportOnSkip)
  240. return;
  241. text = `[最近发送过的推文:${rtid || twid}]`;
  242. msg = author + text;
  243. }
  244. logger.info(`pushing data${source ? ` of ${source}` : ''} to ${targetStr}`);
  245. return send();
  246. });
  247. });
  248. };
  249. this.get = (type, targetId, params) => {
  250. const { since_id, max_results } = params;
  251. const getMore = (res) => {
  252. if (res.errors && res.errors.length > 0) {
  253. const [err] = res.errors;
  254. if (!res.data)
  255. throw err;
  256. if (err.title === 'Authorization Error') {
  257. logger.warn(`non-fatal error while querying ${type} with id ${targetId}, error: ${err.detail}`);
  258. }
  259. }
  260. if (!res.meta.next_token ||
  261. utils_1.BigNumOps.compare(res.tweets.slice(-1)[0].id, since_id || '0') !== 1 ||
  262. !since_id && res.meta.result_count >= max_results)
  263. return res;
  264. return res.fetchNext().then(getMore);
  265. };
  266. if (type === 'listTweets')
  267. delete params.since_id;
  268. return this.client.v2[type](targetId, params).then(getMore)
  269. .then(({ includes, tweets }) => tweets.map((tweet) => ({
  270. data: tweet,
  271. includes: {
  272. media: includes.medias(tweet),
  273. users: [includes.author(tweet)]
  274. }
  275. })))
  276. .then(tweets => Promise.all(tweets.map(tweet => {
  277. const retweetRef = (tweet.data.referenced_tweets || []).find(ref => ref.type === 'retweeted');
  278. if (retweetRef)
  279. return this.client.v2.singleTweet(retweetRef.id, v2SingleParams)
  280. .then(({ includes: { media } }) => (Object.assign(Object.assign({}, tweet), { includes: Object.assign(Object.assign({}, tweet.includes), { media }) })));
  281. return tweet;
  282. })));
  283. };
  284. this.work = () => {
  285. const lock = this.lock;
  286. if (this.workInterval < 1)
  287. this.workInterval = 1;
  288. if (lock.feed.length === 0) {
  289. setTimeout(() => {
  290. this.work();
  291. }, this.workInterval * 1000);
  292. return;
  293. }
  294. if (lock.workon >= lock.feed.length)
  295. lock.workon = 0;
  296. if (!lock.threads[lock.feed[lock.workon]] ||
  297. !lock.threads[lock.feed[lock.workon]].subscribers ||
  298. lock.threads[lock.feed[lock.workon]].subscribers.length === 0) {
  299. logger.warn(`nobody subscribes thread ${lock.feed[lock.workon]}, removing from feed`);
  300. delete lock.threads[lock.feed[lock.workon]];
  301. lock.feed.splice(lock.workon, 1);
  302. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  303. this.work();
  304. return;
  305. }
  306. const currentFeed = lock.feed[lock.workon];
  307. logger.debug(`pulling feed ${currentFeed}`);
  308. const promise = new Promise(resolve => {
  309. let job = Promise.resolve();
  310. let id = lock.threads[currentFeed].id;
  311. let endpoint;
  312. let match = /https:\/\/twitter.com\/([^\/]+)\/lists\/([^\/]+)/.exec(currentFeed);
  313. if (match) {
  314. endpoint = 'listTweets';
  315. if (match[1] === 'i') {
  316. id = match[2];
  317. }
  318. else if (id === undefined) {
  319. job = job.then(() => this.client.v1.list({
  320. owner_screen_name: match[1],
  321. slug: match[2],
  322. })).then(({ id_str }) => {
  323. lock.threads[currentFeed].id = id = id_str;
  324. });
  325. }
  326. }
  327. else {
  328. match = /https:\/\/twitter.com\/([^\/]+)/.exec(currentFeed);
  329. if (match) {
  330. endpoint = 'userTimeline';
  331. if (id === undefined) {
  332. job = job.then(() => this.queryUser(match[1].replace(/^@?(.*)$/, '$1'))).then(userNameId => {
  333. lock.threads[currentFeed].id = id = userNameId.split(':')[1];
  334. });
  335. }
  336. }
  337. }
  338. const offset = lock.threads[currentFeed].offset;
  339. job.then(() => this.get(endpoint, id, Object.assign(Object.assign(Object.assign({}, v2SingleParams), { max_results: 20 }), (offset > 0) && { since_id: offset }))).catch((err) => {
  340. if (err.title === 'Not Found Error') {
  341. logger.warn(`error on fetching tweets for ${currentFeed}: ${showApiError(err)}`);
  342. lock.threads[currentFeed].subscribers.forEach(subscriber => {
  343. logger.info(`sending notfound message of ${currentFeed} to ${JSON.stringify(subscriber)}`);
  344. this.bot.sendTo(subscriber, `链接 ${currentFeed} 指向的用户或列表不存在,请退订。`).catch();
  345. });
  346. }
  347. else {
  348. logger.error(`unhandled error on fetching tweets for ${currentFeed}: ${showApiError(err)}`);
  349. }
  350. return [];
  351. }).then(resolve);
  352. });
  353. promise.then((tweets) => {
  354. logger.debug(`api returned ${JSON.stringify(tweets)} for feed ${currentFeed}`);
  355. const currentThread = lock.threads[currentFeed];
  356. const updateDate = () => currentThread.updatedAt = new Date().toString();
  357. if (tweets.length === 0) {
  358. updateDate();
  359. return;
  360. }
  361. const topOfFeed = tweets[0].data.id;
  362. const updateOffset = () => currentThread.offset = topOfFeed;
  363. if (currentThread.offset === '-1') {
  364. updateOffset();
  365. return;
  366. }
  367. if (currentThread.offset === '0')
  368. tweets.splice(1);
  369. return this.workOnTweets(tweets, this.sendTweets({ sourceInfo: `thread ${currentFeed}` }, ...currentThread.subscribers))
  370. .then(updateDate).then(updateOffset);
  371. })
  372. .then(() => {
  373. lock.workon++;
  374. let timeout = this.workInterval * 1000 / lock.feed.length;
  375. if (timeout < 1000)
  376. timeout = 1000;
  377. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  378. setTimeout(() => {
  379. this.work();
  380. }, timeout);
  381. });
  382. };
  383. this.client = new Twitter.TwitterApi({
  384. appKey: opt.consumerKey,
  385. appSecret: opt.consumerSecret,
  386. }).readOnly;
  387. this.lockfile = opt.lockfile;
  388. this.lock = opt.lock;
  389. this.workInterval = opt.workInterval;
  390. this.bot = opt.bot;
  391. this.webshotDelay = opt.webshotDelay;
  392. this.mode = opt.mode;
  393. this.wsUrl = opt.wsUrl;
  394. if (opt.redis)
  395. this.redis = new redis_1.default(opt.redis);
  396. ScreenNameNormalizer._queryUser = this.queryUser;
  397. exports.sendTweet = (idOrQuery, receiver, forceRefresh) => {
  398. const match = /^last(|-\d+)@([^\/?#,]+)((?:,no.*?=[^,]*)*)$/.exec(idOrQuery);
  399. const query = () => this.queryTimeline({
  400. username: match[2],
  401. count: 1 - Number(match[1]),
  402. noreps: { on: true, off: false }[match[3].replace(/.*,noreps=([^,]*).*/, '$1')],
  403. norts: { on: true, off: false }[match[3].replace(/.*,norts=([^,]*).*/, '$1')],
  404. }).then(tweets => tweets.slice(-1)[0].data.id);
  405. (match ? query() : Promise.resolve(idOrQuery))
  406. .then((id) => this.getTweet(id, this.sendTweets({ sourceInfo: `tweet ${id}`, reportOnSkip: true, force: forceRefresh }, receiver), forceRefresh))
  407. .catch((err) => {
  408. if (err.title !== 'Not Found Error') {
  409. logger.warn(`error retrieving tweet: ${showApiError(err)}`);
  410. this.bot.sendTo(receiver, `获取推文时出现错误:${showApiError(err)}`);
  411. }
  412. if (err.resource_type === 'user') {
  413. return this.bot.sendTo(receiver, `找不到用户 ${match[2].replace(/^@?(.*)$/, '@$1')}。`);
  414. }
  415. this.bot.sendTo(receiver, '找不到请求的推文,它可能已被删除。');
  416. });
  417. };
  418. exports.sendTimeline = ({ username, count, since, until, noreps, norts }, receiver) => {
  419. const countNum = Number(count) || 10;
  420. (countNum > 0 ? this.queryTimeline : this.queryTimelineReverse)({
  421. username,
  422. count: Math.abs(countNum),
  423. since: utils_1.BigNumOps.parse(since) || snowflake(new Date(since).getTime()),
  424. until: utils_1.BigNumOps.parse(until) || snowflake(new Date(until).getTime()),
  425. noreps: { on: true, off: false }[noreps],
  426. norts: { on: true, off: false }[norts],
  427. })
  428. .then(tweets => (0, utils_1.chainPromises)(tweets.map(({ data }) => () => this.bot.sendTo(receiver, `\
  429. 编号:${data.id}
  430. 时间:${data.created_at}
  431. 媒体:${(data.attachments || {}).media_keys ? '有' : '无'}
  432. 正文:\n${data.text.replace(/^([\s\S\n]{50})[\s\S\n]+?( https:\/\/t.co\/.*)?$/, '$1…$2')}`))
  433. .concat(() => this.bot.sendTo(receiver, tweets.length ?
  434. '时间线查询完毕,使用 /twi_view <编号> 查看推文详细内容。' :
  435. '时间线查询完毕,没有找到符合条件的推文。'))))
  436. .catch((err) => {
  437. if (err.title !== 'Not Found Error') {
  438. logger.warn(`error retrieving timeline: ${showApiError(err)}`);
  439. return this.bot.sendTo(receiver, `获取时间线时出现错误:${showApiError(err)}`);
  440. }
  441. this.bot.sendTo(receiver, `找不到用户 ${username.replace(/^@?(.*)$/, '@$1')}。`);
  442. });
  443. };
  444. }
  445. }
  446. exports.default = default_1;