Skip to content

Instantly share code, notes, and snippets.

@devmaufh
Created August 12, 2018 17:30
Show Gist options
  • Save devmaufh/24d466c57ece8527727d729d5a0ddee5 to your computer and use it in GitHub Desktop.
Save devmaufh/24d466c57ece8527727d729d5a0ddee5 to your computer and use it in GitHub Desktop.
This code call Watson assistant and send the response to facebook
//Sorry for my lousy English
var bodyParser=require('body-parser');
var request=require('request');
var express = require('express');var watson = require('watson-developer-cloud');
var assistant = new watson.AssistantV1({
username: 'Paste Assistan api username here',
password: 'paste Assistan api password here',
version: '2018-07-10'
});
var app = express();
app.use(bodyParser.json());
const APP_TOKEN='Paste your Facebook token here';
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.get('/webhook',function(req,res){
if(req.query['hub.verify_token']=='Paste your Facebook Token Here '){
res.send(req.query['hub.challenge']);
}else{
res.send('You cant access here ): ');
}
});
//valida eventos
app.post('/webhook',function(req,res){
var data=req.body;
if(data.object=='page'){
data.entry.forEach(function(pageEntry){
pageEntry.messaging.forEach(function(messagingEvent){
if(messagingEvent.message){
reciveMessage(messagingEvent);
}
});
});
res.sendStatus(200);
}//end if
});
////////////////////
//recive mensaje
function reciveMessage(event){//this function recive message an
var senderID=event.sender.id;
var messageText=event.message.text;
//console.log(senderID);
//console.log(messageText);
sendTextToWatson(senderID,messageText);
}
function sendTextToWatson(senderId,inputText) { //This function call to Assitan api en get the answer :v
var finalMessage='';
assistant.message({
workspace_id: 'Pase your workspace id here',
input: { 'text': inputText }
}, function (err, response) {
if (err){
finalMessage=err;
//console.log('error:', err);
}
else{
finalMessage=response.output.text[0];
//console.log(JSON.stringify(response, null, 2));
console.log("sendTextToWatson "+finalMessage);
}
sendMessageText(senderId,finalMessage);
});
}
function sendMessageText(recipientId,message){ //this function format the message
var messageData={
recipient:{
id:recipientId
},
message:{
text:message
}
};
callSendApi(messageData);
}
function callSendApi(messageData){ //This function send text message to facebook
request({
uri:'https://graph.facebook.com/v2.6/me/messages',
qs:{access_token:APP_TOKEN},
method:'POST',
json:messageData
},function(error,response,data){
if(error){
console.log('Error enviando msg');
}else{
console.log('Mensaje exitoso');
}
});
}
////////
var host = (process.env.VCAP_APP_HOST || 'localhost');
var port = (process.env.VCAP_APP_PORT || 3000);
app.listen(port, host);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment