在DialogFlow中访问Facebook Messenger Messenger.id [英] Accessing Facebook Messenger sender.id in DialogFlow

查看:91
本文介绍了在DialogFlow中访问Facebook Messenger Messenger.id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想访问Facebook用户个人资料API以了解用户名,以便将其首选项保存在各个文档中。但是有更新的地方,现在,要获得 sender.id 值,我必须使用中的 originalDetectIntentRequest.payload.data.sender 字段Dialogflow WebhookRequest 消息。但是这个消息在哪里呢?如何获得相关字段?


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

  //参见https://github.com/dialogflow/dialogflow-fulfillment-nodejs 
//以获取Dialogflow履行库文档,示例,并报告问题
'use strict';

const函数= require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card,Recommendation,Payload} = require('dialogflow-fulfillment');
const admin = require('firebase-admin');
var answers = [];
var score = {};

const {promisify} = require(’util’);
let graph = require(‘fbgraph’); // Facebook图形库

const fbGraph = {
get:promisify(graph.get)
};
让FACEBOOK_PAGE_TOKEN =‘héhéhé’;
graph.setAccessToken(FACEBOOK_PAGE_TOKEN); //<--您的Facebook页面令牌
graph.setVersion( 3.2);

//从Facebook获取配置文件
//用户必须已启动联系人才能使用发件人ID
//返回:facebook配置文件对象,如果有
异步函数getFacebookProfile(agent){
let ctx = agent.context.get('generic');
让fbSenderID = ctx吗? ctx.parameters.facebook_sender_id:未定义;
让有效负载;

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

if(fbSenderID){
try {有效载荷=等待fbGraph.get(fbSenderID); }
catch(err){console.warn(err); }
}

返回有效载荷;
}

admin.initializeApp({
凭据:admin.credential.applicationDefault(),
数据库URL:'ws://parisianelections-yjhpuf.firebaseio.com /'
});

process.env.DEBUG ='dialogflow:debug'; //启用lib调试语句

函数fallback(agent){
agent.add(ʻ我不了解FULLFILMENT`);
agent.add(很抱歉,您可以再试一次吗?FULLFILMENT`);
}

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

函数welcome(agent){
agent.add(`Salut!C'est Jacques。Et ouai,je suis revenu d'outre-tombe?`);
agent。 add(`J'étaismaire de la ville autrefois tu sais?`);
agent.add(`Si te dit je tepose quelquesquour pour savoir quel candidat pourrait te栏目?);
agent.add(ʻEt ques sont les gens qui partagent tesOpinions autour de toi!`);
agent.add(ʻOn y va?`);
agent.add(new Recommendationion( C'est parti!));
}



函数answerIntroductionHandler(agent){
agent.add('Super!Quel est votre arrondissement?(I,...,XIII,...)');
}

函数answerArrondissementHandler(agent){
const arrondissement = agent.parameters.text ;
/*admin.database().ref(\"data&q uot;)。s​​et({{
arrondissement:arrondissement
}); * /
agent.add(new Card({
title:'1/11 Faut-ilaccélérerl '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,
文本: dumétro?'
})
);
agent.add(new proposal( Oui)));
agent.add(new Suggestion( Non)));}

函数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',
文字:'le stationnement des deux-roues?'
})
);
agent.add(new proposal( Oui)));
agent.add(new proposal( Non)));

}

函数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',
文字:'les bus de Tourisme dans la capitale?'
})
);
agent.add(new proposal( Oui)));
agent.add(new proposal( Non)));

}

//根据匹配的Dialogflow目的名称运行适当的函数处理程序
let intentMap = new Map();
intentMap.set(默认欢迎意图,欢迎);
intentMap.set(默认后备意图,后备);
intentMap.set('answerIntroduction',answerIntroductionHandler);
intentMap.set('answerArrondissement',answerArrondissementHandler);
intentMap.set('answer1',answer1Handler);
intentMap.set('answer2',answer2Handler);


agent.handleRequest(intentMap);
});

我在部署它时遇到了问题。

解决方案

要访问Facebook用户ID,您需要跳入请求_

 严格使用; 

const函数= require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {卡,建议,有效载荷} = require('dialogflow-fulfillment');

process.env.DEBUG =‘dialogflow:debug’; //启用lib调试语句

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

函数welcome(agent){

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

代理。 add(`Salut!C'est Jacques。Et ouai,je suis revenu d'outre-tombe?`);
agent.add(`J'étaismaire de la ville autrefois tu sais?`);
agent.add(`姿势问题请注解squeir quel candidat pourrait te ??);
agent.add(ʻEt ques sont les gens qui partagent tes options autour de toi!` );
agent.add(ʻOn y va?`);
agent.add(new Suggestion( C'est parti!)));
}

//根据匹配的Dialogflow目的名称运行适当的函数处理程序
let intentMap = new Map();
intentMap.set (默认欢迎意图,欢迎);
agent.handleRequest(intentMap);
});



agent.request_.body.originalDetectIntentRequest.payload


保留包含的整个有效负载

  {
数据:{
时间戳:'1593326276255',
发件人:{id:'1783142XXXXX368'},
收件人:{id:'604xxxxxx287668'},
消息:{
文本:'hi',
mid:'m_yNJv_e2oA6bkkVpRgyRE4-O4kDj_NSPod_wOuRHPDL47RpMeDvKTcHOxvAQdLPn0whDjVrdvTjskEefR8XKGJw'
}
> b >希望我回答您的问题。


I'd like to access the Facebook User Profile API to learn the user's name so I can save its preferences in individual documents. Yet there where an update and now, to get the Facebook sender.id value, I have to use the originalDetectIntentRequest.payload.data.sender field from the Dialogflow WebhookRequest message. But where is this message? How can I get the related field?

So far my code look like the following:

// 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);
});

I had issues deploying it.

解决方案

To access the Facebook User's ID you need to dive in 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

Holds the whole payload that contains,

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

Hope i answred your question.

这篇关于在DialogFlow中访问Facebook Messenger Messenger.id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆