我正在尝试使用Messenger机器人制作简单的电影字幕。我已经完成了大部分工作,但仍停留在这一部分。
好的,这是消息流
User sends message -> e.g "hi" -> server makes a http request to my database and return the "hi" meaning. -> send the message back
好的,要处理所有这些,我有:
// handler receiving messages
app.post('/webhook', function (req, res) {
var events = req.body.entry[0].messaging;
for (i = 0; i < events.length; i++) {
var event = events[i];
if (event.message && event.message.text) {
if (hasWhiteSpace(event.message.text)) {
console.log("hi");
sendMessage(event.sender.id, {text: "Whitespace please try again"});
} else {
sendMessage(event.sender.id, {text: "wait..."});
var url = 'http://subtitlebuddy.com/api/res/index.php?word=' + event.message.text ;
console.log(url)
// Return new promise
return new Promise(function(resolve, reject) {
// Do async job
http.get(url, function(res){
var body = '';
res.on('data', function(chunk){
body += chunk;
});
res.on('end', function(){
var fbResponse = JSON.parse(body);
sendMessage(event.sender.id, {text: event.message.text + ": " + fbResponse.meaning});
//console.log("Got a response: ", fbResponse.meaning);
});
}).on('error', function(e){
console.log("Got an error: ", e);
});
})
}
}
}
res.sendStatus(200);
});
我的sendMessage()
函数:
// generic function sending messages
function sendMessage(recipientId, message) {
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token: process.env.PAGE_ACCESS_TOKEN},
method: 'POST',
json: {
recipient: {id: recipientId},
message: message,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
});
};
为了便于记录,我的网站subtitlebuddy.com很快,我在浏览器上尝试了它。但是,当用户发送不带空格的消息时,我应该得到的意思是我都会“等待” 10至12次。我不知道我在做什么错,
谢谢
编辑。这是我检查空白的方法:
function hasWhiteSpace(s) {
return /\s/g.test(s);
}