首页 > 解决方案 > 通过带有 Node.js 的 Twit 发布 Twitter 线程

问题描述

我正在使用 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 更优雅地做一个线程吗?谢谢!

标签: javascriptnode.jsnpmtwitter

解决方案


使用推特线程

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


推荐阅读