问题部署到Heroku的
问题描述:
所以这是我的基本Twitter的机器人,它使用节点查找搜索字词与@引用,然后找到与之相关GIF动画:问题部署到Heroku的
//Dependencies
const Twitter = require('twitter');
const http = require('http');
const config = require('./config.js');
const giphyApiKey = (process.env.apiKey || config.giphy.apiKey);
let searchString = "";
let giphyQueryUrl;
//Initialize twitter client
const client = new Twitter({
consumer_key: (process.env.consumer_key || config.twitter.consumer_key),
consumer_secret: (process.env.consumer_secret || config.twitter.consumer_secret),
access_token_key: (process.env.access_token_key || config.twitter.access_token_key),
access_token_secret: (process.env.access_token_secret || config.twitter.access_token_secret)
});
process.on('unhandledRejection', (reason,promise) => {
console.log('Unhandled Rejection at:', promise, 'reason:', reason);
})
//This stream checks for statuses containing '@[USERNAME]' references, strips out the relevant seach data and feeds
//that search data to the queryGiphy function
client.stream('statuses/filter', {track: '@[USERNAME]'}, (stream) => {
stream.on('data', (tweet) => {
searchString =
tweet.text.substring(tweet.text.indexOf("@[USERNAME]")+"@[USERNAME]".length + 1,tweet.text.length);
giphyQueryUrl = "http://api.giphy.com/v1/gifs/search?q="+searchString+"&api_key="+ giphyApiKey +"&limit=5&rating=g";
let replyString = '@' + tweet.user.screen_name + ' ';
let giphyUrl = queryGiphy(replyString,giphyQueryUrl);
})
})
//This function will query the Giphy API using the node http module and when it finds a match, posts that to twitter
//using the gifUrlToPost function
function queryGiphy(replyString,queryUrl) {
http.get(queryUrl, res => {
res.setEncoding("utf8");
let body = '';
res.on("data", data => {
body += data;
});
res.on("end",() => {
body = JSON.parse(body);
if(postToTwitter(replyString + body.data[0].url)) {
return true;
} else {
return false;
}
});
res.on("error", error => {
console.log("Error: " + error);
})
});
}
//This simply posts the url of the gif passed to it
function postToTwitter(body) {
client.post('statuses/update', {status: body})
.then(tweet => {
return true;
})
.catch(error => {
throw error;
});
}
我的问题是,当我这个部署heroku,我不断收到一个超时错误,没有地方连接$ PORT来为heroku动态分配一个端口。现在,我明白了这一点的本质,我之前已经将小型Web服务器部署到了heroku,并了解如何设置环境变量,以便它可以动态分配端口号,以便使用Twitter设置流并查询Giphy。但我在我的代码中做什么?在这种情况下,我不明白在哪里可以做到这一点?
答
你有app.js文件或bin文件,如果你有那么
app.set('port',(process.env.PORT||5000));
app.listen(app.get('port'),function(){
})
,或者您需要在您的根目录中创建一个Procfile,推动代码的Heroku的git
你可能看完这篇文章获得进一步的澄清 https://devcenter.heroku.com/articles/procfile
我并不清楚你的问题的性质,如果你能更具体或解释一点,我会很乐意帮助 –
所以它的本质是,每一个版本一个我已经看到部署到heroku的节点应用程序有一个根“应用程序”进程,它被分配一个端口用于与外部世界进行通信,如下例所示。我刚刚使用节点作为运行时环境,没有创建服务器,所以我不明白我必须为$ PORT建立连接。我写了一个procfile for heroku,它有web:node index.js $ PORT,但似乎没有修复它 –
没问题,所以你只需要提供一个节点文件?这是你的问题吗? –