twitter.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. import * as emojiStrip from 'emoji-strip';
  2. import * as fs from 'fs';
  3. import * as path from 'path';
  4. import * as Twitter from 'twitter';
  5. import TwitterTypes from 'twitter-d';
  6. import { XmlEntities } from 'html-entities';
  7. import QQBot from './koishi';
  8. import { getLogger } from './loggers';
  9. import { BigNumOps, chainPromises } from './utils';
  10. import Wiki from './wiki';
  11. interface IWorkerOption {
  12. lock: ILock;
  13. lockfile: string;
  14. bot: QQBot,
  15. workInterval: number;
  16. wikiSessionCookie: string;
  17. consumerKey: string;
  18. consumerSecret: string;
  19. accessTokenKey: string;
  20. accessTokenSecret: string;
  21. }
  22. export interface ITimelineQueryConfig {
  23. username: string;
  24. count?: number;
  25. since?: string;
  26. until?: string;
  27. noreps?: boolean;
  28. norts?: boolean;
  29. }
  30. export const keywordMap = {
  31. 'ガチャ予告': '卡池',
  32. '一日一回無料ガチャ': '卡池',
  33. 'イベント開催決定': '活动',
  34. 'タワー.*追加': '新塔',
  35. '(生放送|配信)予告': '生放',
  36. 'メンテナンス予告': '维护',
  37. '(育成応援|お仕事).*開催': '工作',
  38. '新曲一部公開': '新曲',
  39. 'キャラクター紹介': '组合',
  40. '今後のアップデート情報': '计划',
  41. '(?<!今後の)アップデート情報': '改修',
  42. };
  43. export const recurringKeywords = [
  44. '(育成応援|お仕事).*開催', 'イベント開催決定', '無料ガチャ',
  45. 'アップデート情報', 'キャラクター紹介',
  46. '(生放送|配信)予告', 'メンテナンス予告'
  47. ];
  48. const xmlEntities = new XmlEntities();
  49. export const processTweetBody = (tweet: Tweet) => {
  50. const urls = tweet.entities.urls ? tweet.entities.urls.map(url => url.expanded_url) : [];
  51. const [title, body] = emojiStrip(xmlEntities.decode(tweet.full_text))
  52. .replace(/(?<=\n|^)(.*)(?:\: |:)(https?:\/\/.*?)(?=\s|$)/g, '[$2 $1]')
  53. .replace(/https?:\/\/.*?(?=\s|$)/g, () => urls.length ? urls.splice(0, 1)[0] : '')
  54. .replace(/(?<=\n|^)[\/]\n/g, '')
  55. .replace(/((?<=\s)#.*?\s+)+$/g, '')
  56. .trim()
  57. .match(/(.*?)\n\n(.*)/s).slice(1);
  58. const date = new Date(tweet.created_at);
  59. const formatedDate = [[date.getFullYear(), 4], [date.getMonth(), 2], [date.getDate(), 2]]
  60. .map(([value, padLength]) => value.toString().padStart(padLength, '0'))
  61. .join('');
  62. const pageTitle = title.replace(/[【】\/]/g, '') + `${recurringKeywords.some(
  63. keyword => new RegExp(keyword).exec(title)
  64. ) ? `-${formatedDate}` : ''}`;
  65. return {title, body, pageTitle, date: formatedDate};
  66. };
  67. export const parseAction = (action: WikiEditResult) => {
  68. if (!action || !Object.keys(action)) return '(无)';
  69. return `\n
  70. 标题:${action.title}
  71. 操作:${action.new ? '新建' : '更新'}
  72. 媒体:${action.mediafiles.map((fileName, index) => `\n ${index + 1}. ${fileName}`).join('') || '(无)'}
  73. 链接:${action.pageid ? `https://wiki.biligame.com/idolypride/index.php?curid=${action.pageid}` : '(无)'}
  74. `;
  75. }
  76. const TWITTER_EPOCH = 1288834974657;
  77. export const snowflake = (epoch: number) => Number.isNaN(epoch) ? undefined :
  78. BigNumOps.lShift(String(epoch - 1 - TWITTER_EPOCH), 22);
  79. const logger = getLogger('twitter');
  80. export type FullUser = TwitterTypes.FullUser;
  81. export type Entities = TwitterTypes.Entities;
  82. export type ExtendedEntities = TwitterTypes.ExtendedEntities;
  83. export type MediaEntity = TwitterTypes.MediaEntity;
  84. interface ITweet extends TwitterTypes.Status {
  85. user: FullUser;
  86. retweeted_status?: Tweet;
  87. }
  88. export type Tweet = ITweet;
  89. export type Tweets = ITweet[];
  90. export default class {
  91. private client: Twitter;
  92. private bot: QQBot;
  93. private publisher: Wiki;
  94. private lock: ILock;
  95. private lockfile: string;
  96. private workInterval: number;
  97. private wikiSessionCookie: string;
  98. constructor(opt: IWorkerOption) {
  99. this.client = new Twitter({
  100. consumer_key: opt.consumerKey,
  101. consumer_secret: opt.consumerSecret,
  102. access_token_key: opt.accessTokenKey,
  103. access_token_secret: opt.accessTokenSecret,
  104. });
  105. this.bot = opt.bot;
  106. this.publisher = new Wiki(opt.lock);
  107. this.lockfile = opt.lockfile;
  108. this.lock = opt.lock;
  109. this.workInterval = opt.workInterval;
  110. this.wikiSessionCookie = opt.wikiSessionCookie;
  111. }
  112. public launch = () => {
  113. this.publisher.login(this.wikiSessionCookie).then(() => {
  114. setTimeout(this.work, this.workInterval * 1000)
  115. });
  116. }
  117. public work = () => {
  118. const lock = this.lock;
  119. if (this.workInterval < 1) this.workInterval = 1;
  120. const currentFeed = 'https://twitter.com/idolypride';
  121. logger.debug(`pulling feed ${currentFeed}`);
  122. const promise = new Promise(resolve => {
  123. let config: {[key: string]: any};
  124. let endpoint: string;
  125. const match = /https:\/\/twitter.com\/([^\/]+)/.exec(currentFeed);
  126. if (match) {
  127. config = {
  128. screen_name: match[1],
  129. exclude_replies: false,
  130. tweet_mode: 'extended',
  131. };
  132. endpoint = 'statuses/user_timeline';
  133. }
  134. if (endpoint) {
  135. const offset = lock.offset;
  136. if (offset as unknown as number > 0) config.since_id = offset;
  137. const getMore = (lastTweets: Tweets = []) => this.client.get(
  138. endpoint, config, (error: {[key: string]: any}[], tweets: Tweets
  139. ) => {
  140. if (error) {
  141. if (error instanceof Array && error.length > 0 && error[0].code === 34) {
  142. logger.warn(`error on fetching tweets for ${currentFeed}: ${JSON.stringify(error)}`);
  143. lock.subscribers.forEach(subscriber => {
  144. logger.info(`sending notfound message of ${currentFeed} to ${JSON.stringify(subscriber)}`);
  145. this.bot.sendTo(subscriber, `错误:链接 ${currentFeed} 指向的用户或列表不存在。`).catch();
  146. });
  147. } else {
  148. logger.error(`unhandled error on fetching tweets for ${currentFeed}: ${JSON.stringify(error)}`);
  149. }
  150. }
  151. if (!(tweets instanceof Array) || tweets.length === 0) return resolve(lastTweets);
  152. if (offset as unknown as number <= 0) return resolve(lastTweets.concat(tweets));
  153. config.max_id = BigNumOps.plus(tweets.slice(-1)[0].id_str, '-1');
  154. getMore(lastTweets.concat(tweets));
  155. });
  156. getMore();
  157. }
  158. });
  159. promise.then((tweets: Tweets) => {
  160. logger.debug(`api returned ${JSON.stringify(tweets)} for feed ${currentFeed}`);
  161. const updateDate = () => lock.updatedAt = new Date().toString();
  162. if (tweets.length === 0) { updateDate(); return; }
  163. const topOfFeed = tweets[0].id_str;
  164. const updateOffset = () => lock.offset = topOfFeed;
  165. if (lock.offset === '-1') { updateOffset(); return; }
  166. if (lock.offset === '0') tweets.splice(1);
  167. return chainPromises(tweets.reverse().map(tweet => () => {
  168. const match = /(.*?)\n\n(.*)/s.exec(tweet.full_text);
  169. if (!match) return Promise.resolve({});
  170. for (const keyword in keywordMap) {
  171. if (new RegExp(keyword).exec(match[1])) {
  172. const tweetUrl = `${currentFeed}/status/${tweet.id_str}`;
  173. logger.info(`working on ${tweetUrl}`);
  174. return this.publisher.post(tweet, keywordMap[keyword])
  175. .then(action => {
  176. if (action.result === 'Success') {
  177. this.lock.lastActions.push(action);
  178. logger.info(`successfully posted content of ${tweetUrl} to bwiki, link:`);
  179. logger.info(`https://wiki.biligame.com/idolypride/index.php?curid=${action.pageid}`)
  180. const message = `已更新如下页面:${parseAction(action)}`;
  181. return Promise.all(
  182. this.lock.subscribers.map(subscriber => this.bot.sendTo(subscriber, message))
  183. );
  184. }
  185. })
  186. .then(updateDate).then(updateOffset);
  187. }
  188. }
  189. }));
  190. })
  191. .then(() => {
  192. let timeout = this.workInterval * 1000;
  193. if (timeout < 1000) timeout = 1000;
  194. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  195. setTimeout(() => {
  196. this.work();
  197. }, timeout);
  198. });
  199. };
  200. }