NodeJS交互式推特机器人问题

大家好,我正在尝试创build一个交互式的Twitter机器人,可以根据用户需求提取和发布推文。 这是我迄今写的代码…

console.log("The bot is starting..."); var Twit = require('twit'); var config = require('./config') var prompt = require('prompt'); prompt.start() var T = new Twit(config); console.log("Bot is ready to roll!"); var tweet_terms = ""; var tweet_count = 0; var tweet_command = 0; console.log("Choose a command...\n1. Get tweets \n2. Post tweet"); prompt.get(['command'], function(err, result) { tweet_command = result.command if (tweet_command == 1) { console.log("You've chosen to get tweets."); console.log("Enter in terms you want to search for seperated by commas, \ \nand also enter in the amount of tweets you want to receive back."); prompt.get(['terms', 'count'], function(err, result) { tweet_terms = result.terms; tweet_count = result.count; }); } }); var params = { q: tweet_terms, count: tweet_count } T.get('search/tweets', params, gotData); function gotData(err, data, response) { var tweets = data.statuses; for (var i = 0; i < tweets.length; i++) { console.log(tweets[i].text); } } 

我试图要求用户input要search的条件以及要收集的推文数量。 但是,即使提示用户input,我的程序也停止运行。 这是程序如何执行..

The bot is starting... Bot is ready to roll! Choose a command... 1. Get tweets 2. Post tweet prompt: command: C:\Users\Kevin\Desktop\MERN Tutorials\Twit Twitter Bot\bot.js:42 for (var i = 0; i < tweets.length; i++) {

它看起来像我的gotData函数是造成这个问题,但我不明白为什么我的程序正在以这种方式执行..我的提示甚至不允许用户input。

TypeError: Cannot read property 'length' of undefined at gotData (C:\Users\X\Desktop\MERN Tutorials\Twit Twitter Bot\bot.js:42:31)

我不明白为什么这个函数甚至是在用户input被处理之前被调用的。我是NodeJS的新手,我很困惑为什么这样做。

任何帮助将不胜感激,谢谢。

这一行:

 T.get('search/tweets', params, gotData); 

在应用程序运行后立即被调用。 完成后,运行一些console.log() ,看起来是提供了对提示的响应。 直到用户input了他们的select(否则你怎么能知道这些参数?)之前你不会想要运行它。

在最后一个提示的callback中移动get调用:

 prompt.get(['command'], function(err, result) { tweet_command = result.command if (tweet_command == 1) { console.log("You've chosen to get tweets."); console.log("Enter in terms you want to search for seperated by commas, \ \nand also enter in the amount of tweets you want to receive back."); prompt.get(['terms', 'count'], function(err, result) { tweet_terms = result.terms; tweet_count = result.count; T.get('search/tweets', params, gotData); // ^ here! }); } else { // post a tweet code goes here } }); 

现在,虽然这有效,但并不是特别灵活。 你可能可能重写这个整洁的东西一点清洁,这样你就可以从用户检索所有的input,然后作为parameter passing给一个处理函数。