NodeJS 交互式 Twitter Bot 问题



大家好,我正在尝试创建一个交互式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:UsersKevinDesktopMERN TutorialsTwit Twitter Botbot.js:42 for (var i = 0; i < tweets.length; i++) {

看起来我的gotData函数导致了这个问题,但我不明白为什么我的程序以这种方式执行。我的提示甚至不允许用户输入。

TypeError: Cannot read property 'length' of undefined at gotData (C:UsersXDesktopMERN TutorialsTwit Twitter Botbot.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
    }
});

现在,虽然这有效,但它并不是特别灵活。您可能会更干净地重写整个内容,以便您可以从用户那里检索所有输入,然后将它们作为参数传递给单个处理程序函数。

最新更新