【问题标题】:connecting dialogflow to mysql database for inserting data into mysql tables将 dialogflow 连接到 mysql 数据库以将数据插入到 mysql 表中
【发布时间】:2019-06-20 11:43:18
【问题描述】:
// 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 mysql = require( 'mysql' );
const {WebhookClient} = require( 'dialogflow-fulfillment' );
const {Text, Card, Image, Suggestion, Payload} = require( 'dialogflow-fulfillment' );

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

const mysiteurl = 'https://en.wikipedia.org/wiki/Narendra_Modi';


exports.dialogflowFirebaseFulfillment = functions.https.onRequest( ( request, response ) =>{
  const agent = new WebhookClient( {request, response} );
  console.log( 'Dialogflow Request headers: ' + JSON.stringify( request.headers ) );
  console.log( 'Dialogflow Request body: ' + JSON.stringify( request.body ) );

  let action = request.body.result['action'];
 function welcome( agent ){
    agent.add( `Welcome to infohub personal assistant, my name is Isobel` );
    agent.add( new Card( {
        title: `mysite`,
        imageUrl: mysiteurl,
        text: `Did you know already mysite if not visit it now! `,
        buttonText: 'mysite',
        buttonUrl: mysiteurl
      } )
    );
    agent.add( `I can help you get information already contained in mysite` );
    agent.add( new Suggestion( `population` ) );
    agent.add( new Suggestion( `avgincome` ) );
    agent.add( new Suggestion( `thisyeargdp` ) );
  }


      //Call the callDBJokes method

function navigationdistance( agent ){
    // Get parameters from Dialogflow to convert
    const from = agent.parameters.from;
    const to = agent.parameters.to;
    console.log( `User requested to get info on  ${to} in ${from}` );


    if (action === 'get.data') {

        // Call the callDBJokes method
        callDB().then((output) => {
            // Return the results of the weather API to API.AI
            response.setHeader('Content-Type', 'application/json');
            response.send(JSON.stringify(output));
        }).catch((error) => {
            // If there is an error let the user know
            response.setHeader('Content-Type', 'application/json');
            response.send(JSON.stringify(error));
        });

    }


    // Sent the context to store the parameter information
    // and make sure the followup 
    agent.setContext( {
      name: 'navigationdistance',
      lifespan: 3,
      parameters: {from: from, to: to}
    } );

    // Compile and send response
    agent.add( ` ${to} in ${from} ` );

    agent.add( `Would you like to know something else?` );
    agent.add( new Suggestion( `population` ) );
    agent.add( new Suggestion( `avgincome` ) );
    agent.add( new Suggestion( `thisyeargdp` ) );
  }




  function fallback( agent ){
    agent.add( `I didnt get that, can you try again?` );
  }

  function callDB( to, from ){
    return new Promise( ( resolve, reject ) =>{

        try{

          var connection = mysql.createConnection( {
            host: "localhost",
            user: "root",
            password: "",
            database: "test"
          } );

          var sql = "INSERT INTO mocktable (from, to) VALUES ('$from', '$to')";
          connection.query( sql, function( error, results, fields ){
            if( !error ){

              let response = "The solution is: " + results[0];
              response = response.toString();
              let output = {'speech': response, 'displayText': response};
              console.log( output );
              resolve( output );

            } else{

              let output = {
                'speech': 'Error. Query Failed.',
                'displayText': 'Error. Query Failed.'
              };
              console.log( output );
              reject( output );

            }
          } );
          connection.end();

        } catch
          ( err ){
          let output = {
            'speech': 'try-cacth block error',
            'displayText': 'try-cacth block error'
          };
          console.log( output );
          reject( output );

        }

    });
  }



  let intentMap = new Map(); // Map functions to Dialogflow intent names
  intentMap.set( 'Default Welcome Intent', welcome );
  intentMap.set( 'get info about mycountry', navigationdistance );
  intentMap.set( 'Default Fallback Intent', fallback );
  agent.handleRequest( intentMap );
})
;

这是我用来将对话流连接到数据库的代码。我在 dialogflow 中使用内联编辑器并对其进行修改以将其连接到数据库。我无法连接到数据库。是否有任何其他方法可以将对话流连接到数据库。

  1. 我在 package.json 文件中有所有依赖项。
  2. 我在 MySQL 中创建了一个名为 test 的数据库。
  3. 我在 dialogflow 中创建了一些意图,并且我从这些意图中获得了默认响应。
  4. 我需要将响应中的详细信息插入到数据库中。

TIA,

【问题讨论】:

    标签: mysql node.js dialogflow-es webhooks


    【解决方案1】:

    看起来您正在本地计算机上运行 MySQL 数据库并尝试通过主机名“localhost”访问它。使用 Dialogflow 内置代码编辑器执行此操作存在一些问题:

    • Dialogflow 不会在您的本地计算机上运行该履行代码。它使用 Firebase Cloud Functions 运行它。
    • 由于代码没有在您的本地机器上运行,调用“localhost”会调用它正在运行的机器。其中,由于它是 Google 机器,因此没有运行 MySQL。 (当然没有那个帐户和密码的人!)
    • 但即使您确实为其指定了可公开访问的机器的名称,Firebase Cloud Functions 也限制访问 Google 云之外的机器。您可以通过升级到付费帐户(包括免费套餐)来获得访问权限。

    您有几种可能的方法来解决这个问题:

    • 您可以在运行 MySQL 的同一台机器(或任何具有安全、公共 URL 的机器)上运行您的实现代码,而不是使用内置编辑器。
      • 如果您没有公共 URL,可以使用 ngrok 或 serveo.net 等工具创建到本地服务器的隧道
    • 您可以使用Google Cloud SQL 服务,它可以是托管的 MySQL 实例。 (您可能仍需要为您的项目设置计费,但是有可用的积分可供开始使用,并且当您发布您的操作时,您有资格获得额外的积分。)
    • 您可以转到 Firebase Firestore 之类的东西,它是一个非 SQL 数据库,但更适合键值存储。 (但同样,可能需要设置结算。)

    【讨论】:

      【解决方案2】:

      如果我是你,我只会使用 Firestore 数据库。免费,而且无论如何都是 Google 产品! https://firebase.google.com/docs/firestore/quickstart

      【讨论】:

        猜你喜欢
        • 2012-08-15
        • 1970-01-01
        • 2022-01-01
        • 2016-02-14
        相关资源
        最近更新 更多