在 DialogFlow 中访问 Facebook Messenger sender.id

Accessing Facebook Messenger sender.id in DialogFlow

我想访问 Facebook 用户配置文件 API 以了解用户的姓名,以便将其首选项保存在各个文档中。但是 there where an update 现在,要获取 Facebook sender.id 值,我必须使用 Dialogflow WebhookRequest 消息中的 originalDetectIntentRequest.payload.data.sender 字段。但是这条消息在哪里?如何获取相关字段?

到目前为止,我的代码如下所示:

// See https://github.com/dialogflow/dialogflow-fulfillment-nodejs
// for Dialogflow fulfillment library docs, samples, and to report issues
'use strict';
 
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion, Payload} = require('dialogflow-fulfillment');
const admin = require('firebase-admin');
var answers = [];
var score = {};

const { promisify } = require('util');
let graph = require('fbgraph'); // facebook graph library

const fbGraph = {
  get: promisify(graph.get)
};
let FACEBOOK_PAGE_TOKEN = 'héhéhé';
graph.setAccessToken(FACEBOOK_PAGE_TOKEN);  // <--- your facebook page token
graph.setVersion("3.2");

// gets profile from facebook
// user must have initiated contact for sender id to be available
// returns: facebook profile object, if any
async function getFacebookProfile(agent) {
  let ctx = agent.context.get('generic');
  let fbSenderID = ctx ? ctx.parameters.facebook_sender_id : undefined;
  let payload;

  console.log('FACEBOOK SENDER ID: ' + fbSenderID);

  if ( fbSenderID ) {
    try { payload = await fbGraph.get(fbSenderID); }
    catch (err) { console.warn( err ); }
  }

  return payload;
}

admin.initializeApp({
    credential: admin.credential.applicationDefault(),
    databaseURL:'ws://parisianelections-yjhpuf.firebaseio.com/'
});
 
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

function fallback(agent) {
  agent.add(`I didn't understand FULLFILMENT`);
  agent.add(`I'm sorry, can you try again? FULLFILMENT`);
}
 
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });
 
  function welcome(agent) {
    agent.add(`Salut! C'est Jacques. Et ouai, je suis revenu d'outre-tombe?`);
    agent.add(`J'étais maire de la ville autrefois tu sais?`);
    agent.add(`Si ca te dit je te pose quelques questions pour savoir quel candidat pourrait te correspondre?`);
    agent.add(`Et quels sont les gens qui partagent tes opinions autour de toi!`);
    agent.add(`On y va?`);
    agent.add(new Suggestion("C'est parti!"));
  }
  
  
  
  function answerIntroductionHandler(agent){
    agent.add('Super! Quel est votre arrondissement? (I, ..., XIII, ...)');
  }
  
  function answerArrondissementHandler(agent){
    const arrondissement = agent.parameters.text;
    /*admin.database().ref("data").set({
        arrondissement: arrondissement
    });*/
    agent.add(new Card({
        title: '1/11 Faut-il accélérer l’automatisation ',
        imageUrl: 'http://www.leparisien.fr/resizer/mz-PnB5RECZ1q-z9GDRvlB_3jsg=/932x582/arc-anglerfish-eu-central-1-prod-leparisien.s3.amazonaws.com/public/RJPSM346RO4M5VIDDOS35APBII.jpg',
        text: 'du métro ?'
      })
    );
    agent.add(new Suggestion("Oui"));
    agent.add(new Suggestion("Non"));}
  
  function answer1Handler(agent){
    
    const answer = agent.parameters.Boolean;
    
    if(answer === 'true'){
      score.griveaux = (score.griveaux+1) || 1 ;
    }else{
    }
    
    answers.push(answer);
    
    agent.add(new Card({
        title: '2/11 Faut-il faire payer ',
        imageUrl: 'https://img.autoplus.fr/news/2017/06/28/1517769/c4d017960fb061c5e50cf2c4-1350-900.jpg?r',
        text: 'le stationnement des deux-roues ?'
      })
    );
    agent.add(new Suggestion("Oui"));
    agent.add(new Suggestion("Non"));
    
  }
  
  function answer2Handler(agent){
    const answer = agent.parameters.Boolean;
    answers.push(answer);
    
    if(answer === 'true'){
      score.villani = (score.villani+1) || 1;
    }else{
    }
    console.log(score);
    
    agent.add(new Card({
        title: '3/11 Faut-il interdire ',
        imageUrl: 'https://i.f1g.fr/media/eidos/767x431_crop/2019/12/11/XVM2caa28bc-1b79-11ea-a0e7-e9356c04d0c7.jpg',
        text: 'les bus de tourisme dans la capitale ?'
      })
    );
    agent.add(new Suggestion("Oui"));
    agent.add(new Suggestion("Non"));
   
  }

  // Run the proper function handler based on the matched Dialogflow intent name
  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', welcome);
  intentMap.set('Default Fallback Intent', fallback);
  intentMap.set('answerIntroduction', answerIntroductionHandler);
  intentMap.set('answerArrondissement', answerArrondissementHandler);
  intentMap.set('answer1', answer1Handler);
  intentMap.set('answer2', answer2Handler);


  agent.handleRequest(intentMap);
});

我在部署时遇到问题。

要访问 Facebook 用户 ID,您需要深入了解 request_

'use strict';

const functions = require('firebase-functions');
const { WebhookClient } = require('dialogflow-fulfillment');
const { Card, Suggestion, Payload } = require('dialogflow-fulfillment');

process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
    const agent = new WebhookClient({ request, response });

    function welcome(agent) {

        const senderID  = agent.request_.body.originalDetectIntentRequest.payload.data.sender.id

        agent.add(`Salut! C'est Jacques. Et ouai, je suis revenu d'outre-tombe?`);
        agent.add(`J'étais maire de la ville autrefois tu sais?`);
        agent.add(`Si ca te dit je te pose quelques questions pour savoir quel candidat pourrait te correspondre?`);
        agent.add(`Et quels sont les gens qui partagent tes opinions autour de toi!`);
        agent.add(`On y va?`);
        agent.add(new Suggestion("C'est parti!"));
    }

    // Run the proper function handler based on the matched Dialogflow intent name
    let intentMap = new Map();
    intentMap.set('Default Welcome Intent', welcome);
    agent.handleRequest(intentMap);
});

agent.request_.body.originalDetectIntentRequest.payload

持有包含的整个有效载荷,

{
  data: {
    timestamp: '1593326276255',
    sender: { id: '1783142XXXXX368' },
    recipient: { id: '604xxxxxx287668' },
    message: {
      text: 'hi',
      mid: 'm_yNJv_e2oA6bkkVpRgyRE4-O4kDj_NSPod_wOuRHPDL47RpMeDvKTcHOxvAQdLPn0whDjVrdvTjskEefR8XKGJw'
    }
  }
}

希望我回答了你的问题。