将 DialogflowChatbot 与 PostgreSQL 数据库连接

Posted

技术标签:

【中文标题】将 DialogflowChatbot 与 PostgreSQL 数据库连接【英文标题】:Connect DialogflowChatbot with PostgreSQL database 【发布时间】:2019-05-08 07:42:59 【问题描述】:

我想将 Dialogflow 中的自定义聊天机器人与 PostgreSQL 数据库连接起来。场景是用户将他/她的查询提交给机器人,然后它将 SQL 查询提交给数据库。我知道应该使用 Webhook/Fulfillment and Integration,但问题是如何

直到现在,我都尝试在 Fulfillment/Inside Editor 中通过放置...

const pg = require('pg');
const connectionString = process.env.DATABASE_URL || 'postgres://un:pass@localhost:5432/postgres';
const client = new pg.Client(connectionString);
client.connect();
const query = client.query('CREATE TABLE items(id SERIAL PRIMARY KEY, text VARCHAR(40) not null, complete BOOLEAN)');
    query.on('end', () =>  client.end(); );

...进入 index.js。此外,在尝试使用 Google Assistant 时,我总是会收到 Webhook 错误,但没有任何指示性解释:

textPayload: "MalformedResponse: Webhook error (206)"  

我不想将机器人连接到其他中间网站;聊天机器人应该能够自己进行查询和检查数据库。

有人对我有什么建议吗? 谢谢!

日志摘录如下:

7:10:03.013 PM
dialogflowFirebaseFulfillment
Ignoring exception from a finished function
7:10:02.995 PM
dialogflowFirebaseFulfillment
Function execution took 10 ms, finished with status code: 200
7:10:02.986 PM
dialogflowFirebaseFulfillment
Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions
7:10:02.986 PM
dialogflowFirebaseFulfillment
Function execution started
7:09:49.540 PM
dialogflowFirebaseFulfillment
Ignoring exception from a finished function
7:09:48.543 PM
dialogflowFirebaseFulfillment
Function execution took 865 ms, finished with status code: 200
7:09:47.678 PM
dialogflowFirebaseFulfillment
Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions
7:09:47.678 PM
dialogflowFirebaseFulfillment
Function execution started
7:09:12.659 PM
dialogflowFirebaseFulfillment
Warning, estimating Firebase Config based on GCLOUD_PROJECT. Initializing firebase-admin may fail
7:08:41.442 PM
dialogflowFirebaseFulfillment
Warning, estimating Firebase Config based on GCLOUD_PROJECT. Initializing firebase-admin may fail
7:04:51.279 PM
dialogflowFirebaseFulfillment
Ignoring exception from a finished function
7:04:51.238 PM
dialogflowFirebaseFulfillment
Function execution took 896 ms, finished with status code: 200
7:04:50.343 PM
dialogflowFirebaseFulfillment
Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions
7:04:50.343 PM
dialogflowFirebaseFulfillment
Function execution started
7:04:33.195 PM
dialogflowFirebaseFulfillment
Warning, estimating Firebase Config based on GCLOUD_PROJECT. Initializing firebase-admin may fail

【问题讨论】:

嗨,你的 package.json 中包含 pg 了吗? 此外,您将无法连接到在 localhost:5432 上运行的 postgres 的本地实例。您必须使用托管的 postgres 服务。 我确实将 pg 添加到依赖项中,仍然一样。是的,我确实在 localhost:5432 使用它。 :( 谢谢。您认为使用其他数据库会更好/可以在本地设置? 您可以在 ElephantSQL 上设置 postgres 或在 mlab 上设置 MongoDB 并在全球范围内使用它! 如果您使用的是内联编辑器,您能否通过单击部署附近的履行页面上的查看执行日志来发布日志截图 【参考方案1】:

我最近写了一篇关于将 MongoDB 与 Dialogflow here 连接起来的文章。

正如我之前所说,您将无法连接到在 localhost:5432 上运行的 Postgres 的本地实例(localhost:8080 上的 mysql 也不行)。 您必须使用 托管 Postgres 服务,例如 ElephantSQL(也适用于除 Firebase/Firestore 之外的其他数据库。)

现在朝着你的答案前进, 首先,认真对待这条日志消息很重要:

未配置结算帐号。外部网络无法访问并且 名额受到严格限制。配置结算帐户以删除这些 限制

要解决这个问题,非常重要您使用计费帐户,例如,firebase 的 Blaze 计划来访问外部网络(在您的情况下是作为服务托管的数据库)请参阅 @987654323 @。

代码

'use strict';

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

const pg = require('pg');
const connectionString = process.env.DATABASE_URL || 'postgres://fsdgubow:K4R2HEcfFeYHPY1iLYvwums3oWezZFJy@stampy.db.elephantsql.com:5432/fsdgubow';
const client = new pg.Client(connectionString);
client.connect();
//const query = client.query('CREATE TABLE items(id SERIAL PRIMARY KEY, text VARCHAR(40) not null, complete BOOLEAN)');

);

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

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

  function welcome(agent) 

     const text = 'INSERT INTO items(text, complete) VALUES($1, $2) RETURNING *'
     const values = ['some item text', '1' ]

    // insert demo in your items database
    client.query(text, values)
      .then(res => 
        console.log(res.rows[0])
        //see log for output
      )
     .catch(e => console.error(e.stack))

    // sample query returning current time...
     return client.query('SELECT NOW() as now')
           .then((res) =>  
               console.log(res.rows[0]);
               agent.add(`Welcome to my agent! Time is  $res.rows[0].now!`);
           )
           .catch(e => console.error(e.stack))

  

  function fallback(agent) 
    agent.add(`I didn't understand`);
    agent.add(`I'm sorry, can you try again?`);


  // Run the proper function handler based on the matched Dialogflow intent name
  let intentMap = new Map();
  intentMap.set('welcome', welcome);
  intentMap.set('Default Fallback Intent', fallback);
  // intentMap.set('your intent name here', yourFunctionHandler);
  // intentMap.set('your intent name here', googleAssistantHandler);
  agent.handleRequest(intentMap);

);

ElephantSQL 控制台

Firebase 日志

Google 助理

我在这里使用 ElephantSQL 进行演示。 寻找更多queries。确保在它们之前放置 return 以成功执行并避免 "MalformedResponse: Webhook error (206)"!

希望能解答您的所有疑问。祝你好运!

【讨论】:

亲爱的 sai.raj。我一试就做。现在我有很多工作要做。谢谢。 嗨,当我在 dialogflow 上部署时,它给了我一些错误,例如:详细的堆栈跟踪:错误:找不到模块 'pg' 试试npm install pg --save 我无法通过对话框流中的内联编辑器安装此功能,您能给我更多指导吗? @blueman010112 在您的内联编辑器的 package.json 文件中添加 pg ref

以上是关于将 DialogflowChatbot 与 PostgreSQL 数据库连接的主要内容,如果未能解决你的问题,请参考以下文章

与IOS配合使用的POS系统

将 USB POS 打印机与 Android 平板电脑上的应用程序集成

master_pos_wait函数与MySQL主从切换

Dialogflow Chatbot 负载/性能测试

快排,堆排与归并排序

报错与解决 | ValueError: pos_label=‘pos‘ is not a valid label