我正在使用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的同一主题下。外观如下:(这里应该还有两个“ subtweets”。这些tweets是“ post”,但与原始消息分开):
还有其他人在Twitter API上遇到过类似问题吗?知道如何通过Twit更优雅地执行线程吗?谢谢!
最佳答案
我知道该怎么办。
正如安迪·派珀(Andy Piper)所述,我需要响应特定的tweet ID,而不是线程中的原始tweet 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;
关于javascript - 通过Twit w/Node.js发布Twitter线程,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54602481/