Last active
September 19, 2016 05:25
-
-
Save sgaurav/8be5b90c279df0837747c16276d571e0 to your computer and use it in GitHub Desktop.
Sending personal responses through FB Messenger bot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.post('/webhook/', receiveMessage); | |
function receiveMessage(req, res, next){ | |
var message_instances = req.body.entry[0].messaging; | |
message_instances.forEach(function(instance){ | |
var sender = instance.sender.id; | |
if(instance.message && instance.message.text) { | |
fetchUserProfileAndReply(sender, conf.PROFILE_TOKEN); | |
} | |
}); | |
res.sendStatus(200); | |
} | |
function fetchUserProfileAndReply(sender, token){ | |
request({ | |
url: 'https://graph.facebook.com/v2.6/' + sender + '?access_token=' + token, | |
method: 'GET' | |
}, function (error, response) { | |
if(error) return; | |
response = JSON.parse(response.body); | |
msg_text = "Hey " + response.first_name + ", happy to have you here." | |
sendMessage(sender, msg_text); | |
sendMessage(sender, "I am test bot written to save my creator from felony charges"); | |
}); | |
} | |
function sendMessage(receiver, data){ | |
var payload = {}; | |
payload = data; | |
request({ | |
url: conf.FB_MESSAGE_URL, | |
method: 'POST', | |
qs: { | |
access_token: conf.PROFILE_TOKEN | |
}, | |
json: { | |
recipient: {id: receiver}, | |
message: payload | |
} | |
}, function (error, response) { | |
if(error) console.log(error); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment