Search code examples
facebookfacebook-graph-apifacebook-javascript-sdkfacebook-messengerdialogflow-es

Passing Thread Control Facebook messenger bot


I am trying the Handover Protocal for my bot but I am not able to get about passing thread control though I read the documentation still, I am confused

curl -X POST -H "Content-Type: application/json" -d '{
  "recipient":{"id":"<PSID>"},
  "target_app_id":123456789,
  "metadata":"String to pass to secondary receiver app" 
}' "https://graph.facebook.com/v2.6/me/pass_thread_control?access_token=<PAGE_ACCESS_TOKEN>"

Example pass_thread_control Event

{
  "sender":{
    "id":"<PSID>"
  },
  "recipient":{
    "id":"<PAGE_ID>"
  },
  "timestamp":1458692752478,
  "pass_thread_control":{
    "new_owner_app_id":"123456789",
    "metadata":"Additional content that the caller wants to set"
  }
}

I am trying to know what is PSID here and what can be target_app_id. can anyone help me with proper example.


Solution

  • It took me a bit to figure out, so I totally understand your frustration! There isn't adequate documentation when it comes to working with the handover protocol.

    My current use case is a bot that offers the option to speak to a representative if it's unable to understand the user. This is done through the use of a postback button, which means the handover is activated by the user. After the user clicks on the button, the following code is run:

    graph.setAccessToken(<YOUR_APP_ACCESS_TOKEN>);
    graph.setAppSecret(<YOUR_APP_SECRET>);
    graph.setVersion("2.12");
    
    graph.post(
        `me/pass_thread_control?access_token=${functions.config().messenger.token}`, 
        handoverMessage, 
        (err, res) => {
            if(err) {
                console.log('HANDOVER ERROR:', err);
                return;
            }                    
            console.log('HANDOVER SUCCESS:', res);
    });
    

    The handoverMessage variable is where you will place the psid and target_app_id:

    let handoverMessage = {
        "recipient": {
            "id": <PSID>
         },
         "target_app_id": <YOUR_TARGET_APP_ID>
    }
    

    Calling this code will handover the control of the conversation to whatever your target_app_id is.

    If you're wondering what 'graph' is, it is a node package called 'fbgraph' that I've found very useful when dealing with the facebook graph api. It's certainly not the only wrapper and there are likely better packages out there, but it has worked for me up to now.