twitter.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. .toLocaleDateString('en-CA', {timeZone: 'Asia/Tokyo'})
  60. .replace(/-/g, '');
  61. const pageTitle = title.replace(/[【】\/]/g, '') + `${recurringKeywords.some(
  62. keyword => new RegExp(keyword).exec(title)
  63. ) ? `-${date}` : ''}`;
  64. return {title, body, pageTitle, date};
  65. };
  66. export const parseAction = (action: WikiEditResult) => {
  67. if (!action || !Object.keys(action)) return '(无)';
  68. return `\n
  69. 标题:${action.title}
  70. 操作:${action.new ? '新建' : '更新'}
  71. 媒体:${action.mediafiles.map((fileName, index) => `\n ${index + 1}. ${fileName}`).join('') || '(无)'}
  72. 链接:${action.pageid ? `https://wiki.biligame.com/idolypride/index.php?curid=${action.pageid}` : '(无)'}
  73. `;
  74. }
  75. const TWITTER_EPOCH = 1288834974657;
  76. export const snowflake = (epoch: number) => Number.isNaN(epoch) ? undefined :
  77. BigNumOps.lShift(String(epoch - 1 - TWITTER_EPOCH), 22);
  78. const logger = getLogger('twitter');
  79. export type FullUser = TwitterTypes.FullUser;
  80. export type Entities = TwitterTypes.Entities;
  81. export type ExtendedEntities = TwitterTypes.ExtendedEntities;
  82. export type MediaEntity = TwitterTypes.MediaEntity;
  83. interface ITweet extends TwitterTypes.Status {
  84. user: FullUser;
  85. retweeted_status?: Tweet;
  86. }
  87. export type Tweet = ITweet;
  88. export type Tweets = ITweet[];
  89. export default class {
  90. private client: Twitter;
  91. private bot: QQBot;
  92. private publisher: Wiki;
  93. private lock: ILock;
  94. private lockfile: string;
  95. private workInterval: number;
  96. private wikiSessionCookie: string;
  97. constructor(opt: IWorkerOption) {
  98. this.client = new Twitter({
  99. consumer_key: opt.consumerKey,
  100. consumer_secret: opt.consumerSecret,
  101. access_token_key: opt.accessTokenKey,
  102. access_token_secret: opt.accessTokenSecret,
  103. });
  104. this.bot = opt.bot;
  105. this.publisher = new Wiki(opt.lock);
  106. this.lockfile = opt.lockfile;
  107. this.lock = opt.lock;
  108. this.workInterval = opt.workInterval;
  109. this.wikiSessionCookie = opt.wikiSessionCookie;
  110. }
  111. public launch = () => {
  112. this.publisher.login(this.wikiSessionCookie).then(() => {
  113. setTimeout(this.work, this.workInterval * 1000)
  114. });
  115. }
  116. public work = () => {
  117. const lock = this.lock;
  118. if (this.workInterval < 1) this.workInterval = 1;
  119. const currentFeed = 'https://twitter.com/idolypride';
  120. logger.debug(`pulling feed ${currentFeed}`);
  121. const promise = new Promise(resolve => {
  122. let config: {[key: string]: any};
  123. let endpoint: string;
  124. const match = /https:\/\/twitter.com\/([^\/]+)/.exec(currentFeed);
  125. if (match) {
  126. config = {
  127. screen_name: match[1],
  128. exclude_replies: true,
  129. include_rts: 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 updateOffset = (offset: string) => lock.offset = offset;
  164. if (lock.offset === '-1') { updateOffset(tweets[0].id_str); return; }
  165. if (lock.offset === '0') tweets.splice(1);
  166. return chainPromises(tweets.reverse().map(tweet => () => {
  167. const match = /(.*?)\n\n(.*)/s.exec(tweet.full_text);
  168. if (!match) return Promise.resolve({});
  169. for (const keyword in keywordMap) {
  170. if (new RegExp(keyword).exec(match[1])) {
  171. const tweetUrl = `${currentFeed}/status/${tweet.id_str}`;
  172. logger.info(`working on ${tweetUrl}`);
  173. return this.publisher.post(tweet, keywordMap[keyword])
  174. .then(action => {
  175. if (action.result === 'Success') {
  176. this.lock.lastActions.push(action);
  177. logger.info(`successfully posted content of ${tweetUrl} to bwiki, link:`);
  178. logger.info(`https://wiki.biligame.com/idolypride/index.php?curid=${action.pageid}`)
  179. const message = `已更新如下页面:${parseAction(action)}`;
  180. return Promise.all(
  181. this.lock.subscribers.map(subscriber => this.bot.sendTo(subscriber, message))
  182. );
  183. }
  184. }).then(updateDate).then(() => updateOffset(tweet.id_str));
  185. }
  186. }
  187. }));
  188. })
  189. .then(() => {
  190. let timeout = this.workInterval * 1000;
  191. if (timeout < 1000) timeout = 1000;
  192. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  193. setTimeout(() => {
  194. this.work();
  195. }, timeout);
  196. });
  197. };
  198. }