twitter.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. const fs = require("fs");
  4. const path = require("path");
  5. const Twitter = require("twitter");
  6. const loggers_1 = require("./loggers");
  7. const mirai_1 = require("./mirai");
  8. const webshot_1 = require("./webshot");
  9. const logger = loggers_1.getLogger('twitter');
  10. class default_1 {
  11. constructor(opt) {
  12. this.launch = () => {
  13. this.webshot = new webshot_1.default(this.webshotOutDir, this.mode, () => setTimeout(this.work, this.workInterval * 1000));
  14. };
  15. this.work = () => {
  16. const lock = this.lock;
  17. if (this.workInterval < 1)
  18. this.workInterval = 1;
  19. if (lock.feed.length === 0) {
  20. setTimeout(() => {
  21. this.work();
  22. }, this.workInterval * 1000);
  23. return;
  24. }
  25. if (lock.workon >= lock.feed.length)
  26. lock.workon = 0;
  27. if (!lock.threads[lock.feed[lock.workon]] ||
  28. !lock.threads[lock.feed[lock.workon]].subscribers ||
  29. lock.threads[lock.feed[lock.workon]].subscribers.length === 0) {
  30. logger.warn(`nobody subscribes thread ${lock.feed[lock.workon]}, removing from feed`);
  31. delete lock.threads[lock.feed[lock.workon]];
  32. lock.feed.splice(lock.workon, 1);
  33. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  34. this.work();
  35. return;
  36. }
  37. const currentFeed = lock.feed[lock.workon];
  38. logger.debug(`pulling feed ${currentFeed}`);
  39. const promise = new Promise(resolve => {
  40. let match = currentFeed.match(/https:\/\/twitter.com\/([^\/]+)\/lists\/([^\/]+)/);
  41. let config;
  42. let endpoint;
  43. if (match) {
  44. config = {
  45. owner_screen_name: match[1],
  46. slug: match[2],
  47. tweet_mode: 'extended',
  48. };
  49. endpoint = 'lists/statuses';
  50. }
  51. else {
  52. match = currentFeed.match(/https:\/\/twitter.com\/([^\/]+)/);
  53. if (match) {
  54. config = {
  55. screen_name: match[1],
  56. exclude_replies: false,
  57. tweet_mode: 'extended',
  58. };
  59. endpoint = 'statuses/user_timeline';
  60. }
  61. }
  62. if (endpoint) {
  63. const offset = lock.threads[currentFeed].offset;
  64. if (offset > 0)
  65. config.since_id = offset;
  66. this.client.get(endpoint, config, (error, tweets, response) => {
  67. if (error) {
  68. if (error instanceof Array && error.length > 0 && error[0].code === 34) {
  69. logger.warn(`error on fetching tweets for ${currentFeed}: ${JSON.stringify(error)}`);
  70. lock.threads[currentFeed].subscribers.forEach(subscriber => {
  71. logger.info(`sending notfound message of ${currentFeed} to ${JSON.stringify(subscriber)}`);
  72. this.bot.sendTo(subscriber, `链接 ${currentFeed} 指向的用户或列表不存在,请退订。`).catch();
  73. });
  74. }
  75. else {
  76. logger.error(`unhandled error on fetching tweets for ${currentFeed}: ${JSON.stringify(error)}`);
  77. }
  78. resolve();
  79. }
  80. else
  81. resolve(tweets);
  82. });
  83. }
  84. });
  85. promise.then((tweets) => {
  86. logger.debug(`api returned ${JSON.stringify(tweets)} for feed ${currentFeed}`);
  87. const currentThread = lock.threads[currentFeed];
  88. const updateDate = () => currentThread.updatedAt = new Date().toString();
  89. if (!tweets || tweets.length === 0) {
  90. updateDate();
  91. return;
  92. }
  93. const topOfFeed = tweets[0].id_str;
  94. const updateOffset = () => currentThread.offset = topOfFeed;
  95. if (currentThread.offset === '-1') {
  96. updateOffset();
  97. return;
  98. }
  99. if (currentThread.offset === '0')
  100. tweets.splice(1);
  101. const maxCount = 3;
  102. let sendTimeout = 10000;
  103. const retryTimeout = 1500;
  104. const ordinal = (n) => {
  105. switch ((~~(n / 10) % 10 === 1) ? 0 : n % 10) {
  106. case 1:
  107. return `${n}st`;
  108. case 2:
  109. return `${n}nd`;
  110. case 3:
  111. return `${n}rd`;
  112. default:
  113. return `${n}th`;
  114. }
  115. };
  116. const sendTweets = (msg, text, author) => {
  117. currentThread.subscribers.forEach(subscriber => {
  118. logger.info(`pushing data of thread ${currentFeed} to ${JSON.stringify(subscriber)}`);
  119. const retry = (reason, count) => {
  120. if (count <= maxCount)
  121. sendTimeout *= (count + 2) / (count + 1);
  122. setTimeout(() => {
  123. msg.forEach((message, pos) => {
  124. if (count > maxCount && message.type === 'Image') {
  125. if (pos === 0) {
  126. logger.warn(`${count - 1} consecutive failures sending webshot, trying plain text instead...`);
  127. msg[pos] = mirai_1.Message.Plain(author + text);
  128. }
  129. else {
  130. msg[pos] = mirai_1.Message.Plain(`[失败的图片:${message.path}]`);
  131. }
  132. }
  133. });
  134. logger.warn(`retry sending to ${subscriber.chatID} for the ${ordinal(count)} time...`);
  135. this.bot.sendTo(subscriber, msg, sendTimeout).catch(error => retry(error, count + 1));
  136. }, retryTimeout);
  137. };
  138. this.bot.sendTo(subscriber, msg, sendTimeout).catch(error => retry(error, 1));
  139. });
  140. };
  141. return this.webshot(tweets, sendTweets, this.webshotDelay).then(updateDate).then(updateOffset);
  142. })
  143. .then(() => {
  144. lock.workon++;
  145. let timeout = this.workInterval * 1000 / lock.feed.length;
  146. if (timeout < 1000)
  147. timeout = 1000;
  148. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  149. setTimeout(() => {
  150. this.work();
  151. }, timeout);
  152. });
  153. };
  154. this.client = new Twitter({
  155. consumer_key: opt.consumer_key,
  156. consumer_secret: opt.consumer_secret,
  157. access_token_key: opt.access_token_key,
  158. access_token_secret: opt.access_token_secret,
  159. });
  160. this.lockfile = opt.lockfile;
  161. this.lock = opt.lock;
  162. this.workInterval = opt.workInterval;
  163. this.bot = opt.bot;
  164. this.webshotDelay = opt.webshotDelay;
  165. this.webshotOutDir = opt.webshotOutDir;
  166. this.mode = opt.mode;
  167. }
  168. }
  169. exports.default = default_1;