通过Twit w / Node.js发布Twitter线程

问题描述 投票:0回答:1

我正在使用Node和npm Twit模块向Twitter发布推文。它正在工作......有点儿。

我能够成功发布一条没有任何问题的推文。但是,当我尝试将一串推文发布在一起时(如Twitter上的一个帖子),推文无法正确显示。这是我的代码的相关位。

基本上,我可以发布初始推文没有问题(函数中的“第一个”参数)。然后,我获得该推文的唯一ID(再次,没有问题),并尝试循环一个字符串数组(“后续”参数)并发布对该推文的回复。这是代码:

const tweet = (first, subsequent) => { 
  bot.post('statuses/update', { status: `${first}` }, (err,data, response) => {
    if (err) {
      console.log(err);
    } else {
      console.log(`${data.text} tweeted!`);

   /// Find the tweet and then subtweet it!
      var options = { screen_name: 'DoDContractBot', count: 1 };
      bot.get('statuses/user_timeline', options , function(err, data) {
        if (err) throw err;

        let tweetId = data[0].id_str;
        for(let i = 1; i < subsequent.length; i++){
          let status = subsequent[i];
          bot.post('statuses/update', { status, in_reply_to_status_id: tweetId }, (err, data, response) => {
            if(err) throw err;
            console.log(`${subsequent[i]} was posted!`);
          })
        }

      });
    }
  });
};

无论出于何种原因,这些推文都没有出现在Twitter上的同一个帖子下。这就是它的样子:(这里应该还有两个“子网”。这些推文“发布”但与原文分开):

enter image description here

有没有其他人与Twitter API有类似的问题?知道怎么更优雅地通过Twit做一个线程?谢谢!

javascript node.js npm twitter
1个回答
1
投票

我想出了该怎么做。

正如Andy Piper所说,我需要回复特定的推文ID,而不是线程中的原始推文ID。所以我通过将twit模块包装在promise包装器中来重构我的代码,并使用带有async / await的for循环。像这样:

const Twit = require('twit');
const config = require('./config');
const util = require("util");
const bot = new Twit(config);

// Wrapping my code in a promise wrapper...
let post_promise = require('util').promisify( // Wrap post function w/ promisify to allow for sequential posting.
  (options, data, cb) => bot.post(
    options,
    data,
    (err, ...results) => cb(err, results)
  )
);

// Async/await for the results of the previous post, get the id...
const tweet_crafter = async (array, id) => { 
  for(let i = 1; i < array.length; i++){
    let content = await post_promise('statuses/update', { status: array[i], in_reply_to_status_id: id });
    id = content[0].id_str;
  };
};

const tweet = (first, subsequent) => { 
  post_promise('statuses/update', { status: `${first}` })
    .then((top_tweet) => {
        console.log(`${top_tweet[0].text} tweeted!`);
        let starting_id = top_tweet[0].id_str; // Get top-line tweet ID...
        tweet_crafter(subsequent, starting_id);
    })
    .catch(err => console.log(err));
};

module.exports = tweet;
© www.soinside.com 2019 - 2024. All rights reserved.