【问题标题】:Posting Twitter Thread via Twit w/ Node.js通过带有 Node.js 的 Twit 发布 Twitter 线程
【发布时间】:2019-07-03 06:57:41
【问题描述】:

我正在使用 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 上的同一线程下。这是它的样子:(这里应该还有两个“子推文”。那些推文“发布”但与原始推文分开):

还有其他人在使用 Twitter API 时遇到过类似的问题吗?知道如何通过 Twit 更优雅地做一个线程吗?谢谢!

【问题讨论】:

  • 不确定是否这么简单,但您的“后续”数组从索引 0 开始。但是,您的循环从索引 1 开始读取数组。
  • 这是故意的;相关数据从索引 1 开始。我认为 twitters API 有点可疑,但他们的文档真的很糟糕。
  • 您不需要使用时间线调用来查找推文 ID - 推文 ID 将从 statuses/update 调用中返回。线程中的每条推文都应该是in_reply_to 上一条推文,而不是第一个推文。如果您可以让我知道文档有什么特别不好的地方,我可以与团队一起改进这一点。

标签: javascript node.js npm twitter


【解决方案1】:

使用推特线程

Twit Thread 是一个用 Typescript 编写的 Node.js 模块,它向 Twit Twitter API Wrapper 添加实用功能并帮助您在 Twitter 机器人中实现线程。

const { TwitThread } = require("twit-thread");
// or import { TwitThread } from "twit-thread" in Typescript

const config = {
  consumer_key:         '...',
  consumer_secret:      '...',
  access_token:         '...',
  access_token_secret:  '...',
  timeout_ms:           60*1000,  // optional HTTP request timeout to apply to all requests.
  strictSSL:            true,     // optional - requires SSL certificates to be valid.
};

}
async function tweetThread() {
   const t = new TwitThread(config);

   await t.tweetThread([
     {text: "hello, message 1/3"}, 
     {text: "this is a thread 2/3"}, 
     {text: "bye 3/3"}
   ]);
}

tweetThread();

更多信息:https://www.npmjs.com/package/twit-thread

【讨论】:

    【解决方案2】:

    我知道该怎么做了。

    正如 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;
    

    【讨论】:

    • 以上内容适用于纯文本推文,但如果主要推文是媒体推文则无效。
    猜你喜欢
    • 2019-04-10
    • 2020-03-09
    • 2021-07-01
    • 2017-11-28
    • 2017-06-13
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    相关资源
    最近更新 更多