嗨我有一个机器人的错误,它会工作正常一点但会返回此错误..我想知道是否有一个修复它,如果这个错误是因为代码或因为API。
Users/x/Documents/AUTOBOT/bot.js:39
var mediaIdStr = data.media_id_string;
^
TypeError: Cannot read property 'media_id_string' of undefined
at /Users/x/Documents/AUTOBOT/bot.js:39:31
at responseHandler (/Users/x/Documents/AUTOBOT/node_modules/twit/lib/oarequest.js:362:14)
at passBackControl (/Users/x/Documents/AUTOBOT/node_modules/oauth/lib/oauth.js:374:13)
at IncomingMessage.<anonymous> (/Users/x/Documents/AUTOBOT/node_modules/oauth/lib/oauth.js:386:9)
at IncomingMessage.emit (events.js:165:20)
at endReadableNT (_stream_readable.js:1101:12)
at process._tickCallback (internal/process/next_tick.js:152:19)
一旦有人提到您将在代码中看到的关键字的帐户,该机器人将工作一点然后返回该错误。 这是脚本的代码..
var Twit = require('twit')
var fs = require('fs');
const dir = 'images' //Set your image folder here
var T = new Twit({
consumer_key: 'x',
consumer_secret: 'xx',
access_token: 'xx',
access_token_secret: 'xx',
timeout_ms: 60 * 1000, // optional HTTP request timeout to apply to all requests.
})
var files = fs.readdirSync(dir);
var stream = T.stream('statuses/filter', {
track: '@dogarchiver dog'
})
stream.on('tweet', function(tweet) {
var file = dir + "/" + files[Math.floor(Math.random() * files.length)];
var id = tweet['id_str'];
var name = tweet['user']['screen_name'];
var b64content = fs.readFileSync(file, {
encoding: 'base64'
})
// first we must post the media to Twitter
T.post('media/upload', {
media_data: b64content
}, function(err, data, response) {
// now we can assign alt text to the media, for use by screen readers and
// other text-based presentations and interpreters
var mediaIdStr = data.media_id_string;
var altText = ".."
var meta_params = {
media_id: mediaIdStr,
alt_text: {
text: altText
}
}
T.post('media/metadata/create', meta_params, function(err, data, response) {
// now we can reference the media and post a tweet (media will attach to the tweet)
var params = {
status: '@' + name,
media_ids: [mediaIdStr],
in_reply_to_status_id: id
}
T.post('statuses/update', params, function(err, data, response) {
console.log(data)
})
})
})
})
答案 0 :(得分:0)
发生错误,Twit
在回调中告诉您相关信息。你没有检查错误并假设,data
将始终是一个对象。如果出现错误,则不是。
因此,您需要检查是否发生了错误并在使用data
之前对其进行了适当处理。
function(err, data, response) {
if (err) {
console.warn("An error occurred while posting", err);
return;
}
// Here you can safely access `data`