从实时数据库获取 json 数据到 Dialogflow 内联编辑器(谷歌助手)

2024-04-22

编程初学者,我正在利用空闲时间从事一个与 Google Assistant 相关的项目,这是我第一次使用 Firebase 实时数据库,不知道如何从那里获取数据,代码下面是 Dialogflow 的内联编辑器中的内容,其中的类别 1、2 和 3 是有学分的学生。我做了一些更改,并将这三个类别(类别1、2和3)放入下面的数据库图片中,我想从代码中删除这三个类别并将其替换为实时数据库中的类别。

因为这是我第一次使用该数据库,所以我不知道如何使用 nodejs 从那里获取该数据。

   
      function categoryac(agent) {
        const categories =  {
          category1: {"Alex" : 25, "Jennifer" : 45, "Justin" : 35, "Peter" : 89},
          category2: {"Alex" : 95, "Jennifer" : 75, "Justin" : 85, "Peter" : 59},
          category3: {"Alex" : 67, "Jennifer" : 55, "Justin" : 45, "Peter" : 15},
        };
        const categoried = agent.parameters["categoried"];
        const categoryAmount = agent.parameters["categoryAmount"];        
        const category = category[categoried];
        const aggregate = category[categoryAmount];       
        agent.add(`${categoried}'s ${categoryAmount} is ${aggregate}`); 
      }

      let intentMap = new Map();
      intentMap.set('category', categoryac);
      agent.handleRequest(intentMap);
    });

更新 我使用了下面的代码,如下所示:

  

  function categoryac( agent ){
    const categoried = agent.parameters["categoried"];
    const categoryAmount = agent.parameters["categoryAmount"];
    var admin = require( 'firebase-admin' );
    admin.initializeApp( {
      credential: admin.credential.cert( {
        projectId: ' ',
        clientEmail: ' ',
        privateKey: ' '
      } ),
      dblink: 'www.*****.*****.com'
    } );
    var thing = admin.database();
    var  relating= thing.ref( `category/${categoried}/${categoryAmount}` );
    return relating.once( "value" ).then( snapshot =>{
      var aggregate = snapshot.value();
      agent.add( `${categoried}'s ${categoryAmount} is ${aggregate}` );
    } )
      .catch( fail =>{
        agent.add( 'uh oh, something went wrong.' );
        console.error( fail );
      } );
  }

  let intentMap = new Map();
  intentMap.set( 'category', categoryac );
  agent.handleRequest( intentMap );
} );
got error message : 'MalformedResponse Failed to parse Dialogflow response into AppResponse because of empty speech response.' error from log :
{
 insertId:  "v*****2"  
 labels: {
  channel:  "preview"   
  querystream:  "GOOGLE_USER"   
  source:  "JSON_RESPONSE_VALIDATION"   
 }
 logName:  "projects/****/logs/actions.googleapis.com%2Factions"  
 receiveTimestamp:  "2019-01-07T14:45:29.274840871Z"  
 resource: {
  labels: {
   action_id:  "actions.intent.TEXT"    
   project_id:  "******"    
   version_id:  ""    
  }
  type:  "assistant_action"   
 }
 severity:  "ERROR"  
 textPayload:  "MalformedResponse: Failed to parse Dialogflow response into AppResponse because of empty speech response"  
 timestamp:  "2019-01-07T14:45:29.266062732Z"  
 trace:  "projects/383182941858/traces/ABwppHFK_PehMj1XEs_Arng9VL7_zShy-EWvoziK0Ro6v74TaduNG1cJaRMnGAZMoLZhtILdG2hEBkDvJQ"  
}

这是日志中的错误:

Error: The default Firebase app already exists. This means you called initializeApp() more than once without providing an app name as the second argument. In most cases you only need to call initializeApp() once. But if you do want to initialize multiple apps, pass a second argument to initializeApp() to give each app a unique name. 
at FirebaseAppError.Error (native) 
at FirebaseAppError.FirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:39:28) 
at FirebaseAppError.PrefixedFirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:85:28) 
at new FirebaseAppError (/user_code/node_modules/firebase-admin/lib/utils/error.js:119:28) 
at FirebaseNamespaceInternals.initializeApp (/user_code/node_modules/firebase-admin/lib/firebase-namespace.js:68:23) 
at FirebaseNamespace.initializeApp (/user_code/node_modules/firebase-admin/lib/firebase-namespace.js:362:30) 
at categoryac (/user_code/index.js:34:11) 
at WebhookClient.handleRequest (/user_code/node_modules/dialogflow-fulfillment/src/dialogflow-fulfillment.js:303:44) 
at exports.dialogflowFirebaseFulfillment.functions.https.onRequest (/user_code/index.js:91:9) 
at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:57:9)

您需要学习几件事。

第一个是如何添加 Firebase 管理 SDK https://firebase.google.com/docs/admin/setup到你的项目。

您还需要学习如何检索数据 https://firebase.google.com/docs/database/admin/retrieve-data使用图书馆。 Firebase 使用基于引用路径的方法来获取数据,因此您需要确保正确构建路径。

最后,由于您是在履行处理程序内执行此操作,并且正在进行异步调用,因此需要确保返回 Promise。幸运的是,获取数据还涉及到返回一个Promise,所以你可以返回这个Promise。

该代码可能部分看起来像这样(未经测试):

  function personFacts(agent) {
    const personId = agent.parameters["personId"];
    const personMeasurement = agent.parameters["personMeasurement"];        

    var db = admin.database();
    var ref = db.ref(`person/${personId}/${personMeasurement}`);
    return ref.once("value")
      .then( snapshot => {
        var result = snapshot.val();
        agent.add(`${personId}'s ${personMeasurement} is ${result}`); 
      })
      .catch( err => {
        agent.add('uh oh, something went wrong.');
        console.error( err );
      });

  }

正如您所指出的,您需要使用一个密钥来初始化 Firebase 管理库,该密钥将允许您通过服务帐户进行访问。你可以生成密钥 https://firebase.google.com/docs/admin/setup#add_firebase_to_your_app并下载它,然后指向保存它的文件夹。 (看起来您刚刚内联了信息,这也有效。)

“响应格式错误”错误意味着未设置响应。这可能是由于多种原因造成的,但通常意味着您的程序崩溃或无法调用agent.add()因为某些原因。请查阅您运行的操作日志以获取更多信息。 (如果您使用的是 Dialogflow 内联编辑器,则可以通过以下方式访问日志https://console.firebase.google.com/ https://console.firebase.google.com/,选择您的项目,选择左侧的“函数”选项卡,然后选择“日志”选项卡。)

Update基于代码和错误消息。

正如错误消息所示,您调用了admin.initializeApp()不止一次。仅应在首次配置函数时执行此操作,而不是在每次调用函数时执行此操作。一旦初始化一次——就可以多次使用。

就您而言,这可以通过移动来完成require导入 firebase-admin 并调用admin.initializeApp()出于personFacts()函数并将它们都放在更靠近顶部的位置 - 可能就在另一个之后require() calls.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从实时数据库获取 json 数据到 Dialogflow 内联编辑器(谷歌助手) 的相关文章

随机推荐