I would like to show 'welcome message' like 'Hi Robert, welcome to my application'. So I need to send:
"https://graph.facebook.com/v2.6/USER_ID?fields=first_name,last_name,profile_pic,locale,timezone,gender&access_token=PAGE_ACCESS_TOKEN"
using 'first_name' from 1st request, send "https://graph.facebook.com/v2.6/PAGE_ID/thread_settings?access_token=PAGE_ACCESS_TOKEN" request to set 'welcome message'.
However, I need to know user_id before first request.
My questions:
I reviewed https://developers.facebook.com/docs/messenger-platform document, and I have still questions.
So you can make this with a "get started" Button. This button is only there if the User Messages the bot for the first time.
With this command you can set the button:
curl -X POST -H "Content-Type: application/json" -d '{
"setting_type":"call_to_actions",
"thread_state":"new_thread",
"call_to_actions":[
{
"payload":"USER_DEFINED_PAYLOAD"
}
]
}' "https://graph.facebook.com/v2.6/me/thread_settings?access_token=PAGE_ACCESS_TOKEN"
As you can see if the Button is pressed your Webhook recieves a "postback"
this is the callback you get:
{
"sender":{
"id":"USER_ID"
},
"recipient":{
"id":"PAGE_ID"
},
"timestamp":1458692752478,
"postback":{
"payload":"USER_DEFINED_PAYLOAD"
}
}
So this is from where you can get User id
Now you can code a Function for this. My looks like this:
function receivedPostback(event) {
var senderID = event.sender.id;
var recipientID = event.recipient.id;
var timeOfPostback = event.timestamp;
// The 'payload' param is a developer-defined field which is set in a postback
// button for Structured Messages.
var payload = event.postback.payload;
console.log("Received postback for user %d and page %d with payload '%s' " +
"at %d", senderID, recipientID, payload, timeOfPostback);
if (payload) {
// When a postback is called, we'll send a message back to the sender to
// let them know it was successful
switch (payload) {
case 'USER_DEFINED_PAYLOAD':
startedConv(senderID);
break;
default:
sendTextMessage(senderID, "Postback called");
}
My startedConv() looks like this
function startedConv(recipientId){
var name;
request({
url: 'https://graph.facebook.com/v2.6/'+ recipientId +'?fields=first_name',
qs: {access_token: PAGE_ACCESS_TOKEN},
method: 'GET'
}, function(error, response, body) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}else{
name = JSON.parse(body);
sendTextMessage(recipientId, "Hello "+ name.first_name+", how can i help you ? ")
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With