Node.js-如何将MP4上传到Twitter



我目前正在学习如何使用Node.js制作Twitter机器人,但我不知道如何将mp4上传到Twitter。

我在谷歌和YouTube上搜索过如何做到这一点,但它似乎要么给了我更多的错误,要么似乎不需要我来做这件事

现在,我是Node.js的新手,所以如果我似乎误解了基本的东西,请原谅我。

这是我当前的代码:

const Twit = require('twit'),
fs = require('fs'),
path = require('path'),
config = require(path.join( __dirname, 'config.js') );


async function main() {
const T = new Twit( config );
T.post('statuses/update', {
status: 'File time lezgo',
media: "./media/congrats.mp4"
}, function( err, data, response ) {
console.log( data )
} );
}
console.log("Starting the bot...");
setInterval(main, 5000)

如果有人对如何做到这一点有解释,或者如果我错过了什么,请告诉我,就像我说的那样,我是Node.js和Twitter API的新手。

我认为你不能直接将媒体附加到你的推文中,你必须首先上传媒体,并在statuses/update端点中使用返回的media_id

以下示例取自twit-lib本身(尽管有点清理(

let b64content = fs.readFileSync('/path/to/media', {
encoding: 'base64'
})
// first we must post the media to Twitter
T.post('media/upload', {
media_data: b64content
}, (err, data, response) => {
if (err) {
console.error(err);
}
// now we can assign alt text to the media, for use by screen readers and
// other text-based presentations and interpreters
let mediaIdStr = data.media_id_string
let altText = "This is an ALT text"
let meta_params = {
media_id: mediaIdStr,
alt_text: {
text: altText
}
}
T.post('media/metadata/create', meta_params, (err, data, response) => {
if (!err) {
// now we can reference the media and post a tweet (media will attach to the tweet)
let params = {
status: 'File time lezgo',
media_ids: [mediaIdStr]
}
T.post('statuses/update', params, (err, data, response) => {
console.log(data)
})
}
})
})

这可以通过使用async/await来进一步清理,但目前这应该可以在中工作

更新

对于.mp4类型的文件,您必须使用postMediaChunked方法

let filePath = '/absolute/path/to/file.mp4'
T.postMediaChunked({
file_path: filePath
}, (err, data, response) => {
if (err) {
cosnole.error(err);
}
let mediaIdStr = data.media_id_string;
let params = {
status: 'File time lezgo',
media_ids: [mediaIdStr]
}
T.post('statuses/update', params, (err, data, response) => {
console.log(data)
})
})

最新更新