将 Dialogflow 与 Google Chat 集成

1. 准备工作

在此 Codelab 中,您将学习如何将 Dialogflow 与 Google Workspace API 相连接,以创建功能完善的预约安排工具,该工具可与 Google 日历搭配使用,并在 Google Chat 中提供动态回复。

如果您没有上一个 Codelab 中的设置,或者对 Dialogflow 和实现充满信心,可以从此处下载起始代码和代理配置

https://github.com/googleworkspace/appointment-scheduler-codelab

前提条件

在继续操作之前,您需要完成以下 Codelab:

  1. 使用 Dialogflow 构建预约安排程序
  2. 将 Dialogflow 与 Actions on Google 集成
  3. 了解 Dialogflow 中的实体
  4. 通过将 Dialogflow 与日历集成,了解 fulfillment 的原理

您还需要了解 Dialogflow 的基本概念和结构,您可以从使用 Dialogflow 构建聊天机器人开发者在线课程中的以下视频中获取这些内容。

学习内容

  • 如何部署和配置 Google Chat 聊天应用
  • 如何在 Google Chat 中构建显示卡片
  • 如何在 Dialogflow fulfillment 中构建自定义载荷

构建内容

  • Dialogflow、Google Chat 和日历之间的集成
  • (可选)集成 Google 地图以获得更丰富的卡片

5b4ca104638f9e8d.png

所需条件

  • 用于登录 Dialogflow 控制台的网络浏览器和电子邮件地址
  • Google Workspace 网域中已启用 Google 日历和 Google Chat

2. 启用和配置 Google Chat

我们将从您在之前的 Codelab 中创建的 Dialogflow 代理开始。

  1. Dialogflow 控制台中,点击 d7d792687e597dd5.png
  2. 常规标签页中,滚动到项目 ID,然后点击 Google Cloudf2bffd4fcdb84fa9.png

34be16fcd4c5aeff.png

  1. 在 Google Cloud Console 中,点击导航菜单 ☰ > API 和服务 >
  2. 搜索“Google Chat API”,然后点击启用,以便在您的 Google Cloud 云项目中使用该 API。
  3. 现在,我们将配置您的聊天应用,请前往相应 API 的配置页面。请注意,每个 GCP 项目最多只能有一个 Chat 应用。
  1. 您应该会看到 Dialogflow 字段填充配置选项。
  2. 将“头像网址”字段更改为以下汽车图片:**https://fonts.gstatic.com/s/i/googlematerialicons/directions_car/v5/black-48dp/1x/gm_directions_car_black_48dp.png**
  3. 如需让 Chat 应用同时支持私信和聊天室,请选择可以直接向应用发送消息应用可在包含多位用户的聊天室中使用

点击保存并退出 Cloud 控制台。

3. 其他 Dialogflow 集成

Google Chat 默认处于启用状态,但如果您希望机器人服务于多个平台,可以前往 Dialogflow 控制台中的集成页面启用这些平台。

4. 在 Google Chat 中测试

现在,您的 Chat 应用已配置完毕,接下来我们将其添加到 Chat 聊天室并进行测试。打开 Google Chat 并创建一个测试聊天室。

  1. 在聊天室的右上角,点击下拉菜单,然后选择添加联系人和应用
  2. 搜索 AppointmentScheduler 并将该应用添加到聊天室。
  3. 现在,您只需在对话框中输入 @AppointmentScheduler,即可与您已在 Google 中构建的应用互动。

在此平台上使用之前 Codelab 中的相同输入对其进行测试:

  1. 用户:“@AppointmentScheduler Set an appointment for vehicle registration at 2 PM tomorrow.”
  2. 聊天应用:“Ok, let me see if we can fit you in. April 24, 2 PM is fine!"

接下来,我们将使用 Google Chat 中的自定义功能来添加更丰富的回答。

5. 自定义 Google Chat 卡片

借助 Google Chat,您可以让您的应用向用户返回基本的文本响应或卡片响应,后者允许您构建包含图片、按钮等不同 widget 的更丰富的界面。现在,您已将 Dialogflow 代理连接到 Google Chat 聊天应用,只需以正确的格式返回 JSON,即可在履单代码中在 Google 中显示。我们来看一些 JSON 示例。

基本文本响应如下所示:

 {
  "text": "Your pizza delivery is here!"
}

7e1cd3efb4fe9d1f.png

包含微件的卡片响应示例如下所示:

{
  "cards": [
    {
      "sections": [
        {
          "widgets": [
            {
              "image": { "imageUrl": "https://..." }
            },
            {
              "buttons": [
                {
                  "textButton": {
                    "text": "OPEN IN GOOGLE MAPS",
                    "onClick": {
                      "openLink": {
                        "url": "https://..."
                      }
                    }
                  }
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}

72ac1b2903ed60b6.png

如需详细了解卡片,请参阅消息格式文档。在下一部分中,我们将向聊天应用添加卡片。

6. 自定义载荷和聊天卡片

借助 Dialogflow 中的自定义载荷 ,您可以发送平台专属的富响应消息。我们将在其中添加 Hangouts Chat JSON 卡片,以便代理将这些卡片返回给用户。

我们先为欢迎 intent 添加一张基本卡片。在 Dialogflow 控制台中,前往“默认欢迎意图”,然后向下滚动到“响应”部分。

9624208f0d266afd.png

点击 Google Chat,取消选中使用默认标签页中的响应作为第一个响应,然后依次点击 ADD RESPONSES > Custom Payload

您将看到一个 JSON 框架。

bb064f7ec1237fd3.png

复制并粘贴以下代码。我们已设置一张包含 TextParagraph widget 的卡片。

{
 "hangouts": {
   "header": {
     "title": "Appointment Scheduler"
   },
   "sections": [
     {
       "widgets": [
         {
           "textParagraph": {
             "text": "Welcome, I am the scheduler agent. Please request an appointment type and time."
           }
         }
       ]
     }
   ]
 }
}

点击保存,然后前往测试 Chat 聊天室,看看此卡片是否已呈现。在 Chat 聊天室中,输入“@AppointmentScheduler hello”。

91af6321f3a26e19.png

接下来,我们将在履单代码中添加自定义载荷,以便使用代码动态生成内容。

7. 在履单中添加卡片

现在,我们将创建一个包含多个 widget 的卡片,以显示预约安排。我们来添加一个名为 getGoogleChatCard 的函数,用于呈现输入内容:appointmentTypedatetime

将以下函数添加到 index.js 中代码的底部。

function getGoogleChatCard(appointmentType, date, time) {
   const cardHeader = {
     title: 'Appointment Confirmation',
     subtitle: appointmentType,
     imageUrl: ICON_IMAGE_URL,
     imageStyle: 'IMAGE',
   };
    const dateWidget = {
     keyValue: {
       content: 'Date',
       bottomLabel: date,
     },
   };
    const timeWidget = {
     keyValue: {
       content: 'Time',
       bottomLabel: time,
     },
   };

    const buttonWidget = {
     buttons: [
       {
         textButton: {
           text: 'View Appointment',
           onClick: {
             openLink: {
               url: CALENDAR_URL,
             },
           },
         },
       },
     ],
   };
    const infoSection = {widgets: [dateWidget, timeWidget,
     buttonWidget]};
    return {
     'hangouts': {
       'name': 'Confirmation Card',
       'header': cardHeader,
       'sections': [infoSection],
     },
   };
 }

此卡片包含键值对和按钮 widget。然后,这些 widget 会按顺序排列在 section 中,而 card 则包含要呈现的部分列表。

现在,我们将在创建日历活动时调用此函数。在 createCalendarEvent 函数中,将内容替换为以下代码并部署该函数。

return createCalendarEvent(dateTimeStart, dateTimeEnd, appointmentType).then(() => {
   agent.add(`Ok, let me see if we can fit you in. ${appointmentTimeString} is fine!.`);

   const dateString = dateTimeStart.toLocaleString(
     'en-US',
       {month: 'long', day: 'numeric'},
   );
   const dateParts = appointmentTimeString.split(',');
   const json = getGoogleChatCard(appointmentType, dateParts[0], dateParts[1]);
   const payload = new Payload(
       'hangouts',
       json,
       {rawPayload: true, sendAsMessage: true},
   );
   agent.add(payload);

 }).catch(() => {
   agent.add(`I'm sorry, there are no slots available for ${appointmentTimeString}.`);
 });
}

当代理在 Google Chat 中做出响应时,会知道返回上面构建的卡片。通过调度请求进行测试。

8. (可选)添加 Google 地图图片 widget

如果您想让回答卡片更直观,可以添加由 Maps Static API 生成的预约地点的静态地图。您可以使用该 API 通过网址参数构建 Google 地图图片。然后,我们可以在卡片的图片 widget 中使用该图片。

5b4ca104638f9e8d.png

  1. 在 Google Cloud 控制台中启用 Maps Static API,就像您启用日历和 Google Chat API 一样。
  2. 在控制台的 API 和服务页面中,为您的项目创建并保存 API 密钥。如需详细了解如何检索 API 密钥以及与 Maps 相关的 API 密钥最佳实践,请点击此处c0238236d3c709c5.png
  3. 将 API 密钥和以下常量复制到 index.js 文件顶部
const API_KEY = 'YOUR_API_KEY';
const MAP_IMAGE_URL = 'https://maps.googleapis.com/maps/api/staticmap?center=Googleplex&zoom=14&size=200x200&key=' + API_KEY;
const ICON_IMAGE_URL = 'https://fonts.gstatic.com/s/i/googlematerialicons/calendar_today/v5/black-48dp/1x/gm_calendar_today_black_48dp.png';
const CALENDAR_URL = 'YOUR_CALENDAR_URL';
  1. 接下来,在 getGoogleChatCard 函数中添加图片 widget
  const mapImageWidget = {
    'image': {
      'imageUrl': MAP_IMAGE_URL,
      'onClick': {
        'openLink': {
          'url': MAP_IMAGE_URL,
        },
      },
    },
  };
  1. mapImageWidget 添加到 infoSection 变量中的 widget 列表,然后保存并部署。
  2. 在 Chat 聊天室中测试您的 Chat 应用,您应该会看到基于您今天添加的代码的富媒体响应!

9. 清理

如果您计划完成其他 Dialogflow Codelab,请暂时跳过此部分,稍后再回来查看。

删除 Dialogflow 代理

  1. 点击现有代理旁边的 dc4ac6f9c0ae94e9.png

520c1c6bb9f46ea6.png

  1. 常规标签页中,滚动到底部,然后点击删除此代理
  2. 在对话框中键入 Delete,然后点击删除

10. 恭喜

您在 Dialogflow 中创建了一个聊天机器人,并将其与日历和 Google Chat 集成,现在您是 Google Workspace Pro 了!

了解详情

如需了解详情,请查看 Dialogflow GitHub 页面上的代码示例。