大家好,我正在尝试创建一个交互式 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);
}
}
我试图要求用户输入要搜索的术语以及要收集的推文数量。然而,我的程序甚至在提示用户输入之前就停止了。这是程序的执行方式..
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函数导致了这个问题,但我不明白为什么我的程序以这种方式执行。我的提示符甚至不允许用户输入。
TypeError: Cannot read property 'length' of undefined at gotData (C:\Users\X\Desktop\MERN Tutorials\Twit Twitter Bot\bot.js:42:31)
我不明白为什么在处理用户输入之前会调用这个函数。我是 NodeJS 的新手,并且很困惑为什么它会这样。
任何帮助将不胜感激,谢谢。
最佳答案
这一行:
T.get('search/tweets', params, gotData);
在应用程序运行后立即被调用。完成后,您运行一堆 console.log()
,它们似乎提供了对提示的响应。在用户输入他们的选择之后你不会想运行它(否则你怎么知道参数?)。
将 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
}
});
现在,虽然这可行,但并不是特别灵活。您可能可以将整个事情重写得更干净一些,以便您可以检索用户的所有输入,然后将它们作为参数传递给单个处理程序函数。
关于javascript - NodeJS 交互式 Twitter 机器人问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42033355/