如何在facebook Messenger中显示个性化的"欢迎信息"?

Eug*_*hel 4 facebook facebook-graph-api facebook-messenger

我想展示'欢迎信息',如'嗨罗伯特,欢迎来到我的申请'.所以我需要发送:

  1. " https://graph.facebook.com/v2.6/USER_ID?fields=first_name,last_name,profile_pic,locale,timezone,gender&access_token=PAGE_ACCESS_TOKEN "

  2. 使用第一个请求中的"first_name",发送" https://graph.facebook.com/v2.6/PAGE_ID/thread_settings?access_token=PAGE_ACCESS_TOKEN "请求以设置"欢迎消息".

但是,我需要在第一次请求之前知道user_id.

我的问题:

  1. 创建"欢迎信息"的步骤是什么?
  2. 当用户打开facebook messenger窗口时,如何显示"欢迎信息"?

我查看了https://developers.facebook.com/docs/messenger-platform文档,我仍然有疑问.

Noc*_*cka 6

所以你可以用一个"开始"按钮来做这个.仅当用户首次向机器人发送消息时,此按钮才会出现.

使用此命令可以设置按钮:

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"      
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,按下按钮,您的Webhook会收到"回发"

这是你得到的回调:

{
  "sender":{
    "id":"USER_ID"
  },
  "recipient":{
    "id":"PAGE_ID"
  },
  "timestamp":1458692752478,
  "postback":{
    "payload":"USER_DEFINED_PAYLOAD"
  }
}  
Run Code Online (Sandbox Code Playgroud)

所以这是你可以获得用户ID的地方

现在您可以为此编写一个函数.我看起来像这样:

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");
       }
Run Code Online (Sandbox Code Playgroud)

我的startsConv()看起来像这样

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 ? ")
          }
      });
}
Run Code Online (Sandbox Code Playgroud)