简体   繁体   English

使用 Node.js 通过 Twit 发布 Twitter 线程

[英]Posting Twitter Thread via Twit w/ Node.js

I'm using Node and the npm Twit module to post tweets to Twitter.我正在使用 Node 和 npm Twit 模块将推文发布到 Twitter。 It's working....sort of.它的工作......有点。

I'm able to successfully post a single tweet wihtout any problems.我能够成功发布一条推文而没有任何问题。 However, when I attempt to post a string of tweets together (like a thread on Twitter) the tweets don't display correctly.但是,当我尝试将一系列推文发布在一起(如 Twitter 上的一个线程)时,推文无法正确显示。 Here's the relevant bit of my code.这是我的代码的相关部分。

Essentially, I can post the initial tweet no problem (the "first" argument in the function).本质上,我可以毫无问题地发布初始推文(函数中的“第一个”参数)。 I then get that tweet's unique ID (again, no problem) and attempt to loop through an array of strings (the "subsequent" argument) and post replys to that tweet.然后,我获取该推文的唯一 ID(再次,没问题)并尝试遍历字符串数组(“后续”参数)并发布对该推文的回复。 Here's the code:这是代码:

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!`);
          })
        }

      });
    }
  });
};

For whatever reason, the tweets aren't showing up under the same thread on Twitter.无论出于何种原因,这些推文并未显示在 Twitter 的同一线程下。 Here's what it looks like: (there should be two more 'subtweets' here. Those tweets "post" but are separated from the original):这是它的样子:(这里应该还有两个“子推文”。这些推文“发布”但与原始推文分开):

在此处输入图片说明

Has anyone else had similar problems with the Twitter API?有没有其他人在 Twitter API 上遇到过类似的问题? Any idea how to more gracefully do a thread via Twit?知道如何通过 Twit 更优雅地做一个线程吗? Thanks!谢谢!

Using twit-thread使用twit-thread

Twit Thread is a Node.js module written in Typescript that add utility functions to Twit Twitter API Wrapper and help you implement threads in your twitter bot. 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();

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

I figured out what to do.我想出了该怎么做。

As Andy Piper mentioned, I needed to respond to the specific tweet id, rather than the original tweet id in the thread.正如 Andy Piper 所提到的,我需要响应特定的推文 ID,而不是线程中的原始推文 ID。 So I refactored my code by wrapping the twit module in a promise wrapper, and used a for loop with async/await.因此,我通过将 twit 模块包装在承诺包装器中来重构我的代码,并使用带有 async/await 的 for 循环。 Like this:像这样:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM