Fulfillment (Dialogflow)

您的执行方式逻辑可以使用它在每个请求中收到的语言区域字符串来满足用户响应需求。本指南介绍了如何使用 Cloud Functions for Firebase 中的某些第三方本地化库来返回本地化响应。

本地化库

下面是一些有用的库,可帮助您针对特定语言区域生成自定义响应:

  • 通用:I18n-node(我们的示例代码段使用此库)
  • 通用:format.js
  • 时区/时间本地化:moment.js(我们的示例代码段使用此库)
  • 货币/币种:numeral.js

创建本地化响应

本部分介绍如何创建包含本地化字符串的本地化字符串资源文件,以及如何在 Cloud Functions for Firebase 执行方式中使用这些资源文件。

如需创建本地化响应,请执行以下操作:

  1. package.jsonindex.js 文件所在的目录中,为本地化的字符串文件创建一个 locales 目录。我们将此目录称为 <project-dir>/functions/locales
  2. 创建一个资源文件,其中包含您要支持的每个语言区域的本地化字符串。例如,如果要为 en-USen-GBde-DE 语言区域提供本地化的欢迎和日期消息,这些文件可能如下所示:

    <project-dir>/functions/locales/en-US.json

    {
       "WELCOME_BASIC": "Hello, welcome!",
       "DATE": "The date is %s"
    }
    

    <project-dir>/functions/locales/en-GB.json

    {
       "WELCOME_BASIC": "Hello, welcome!",
       "DATE": "The date is %s"
    }
    

    <project-dir>/functions/locales/de-DE.json

    {
       "WELCOME_BASIC": "Hallo und willkommen!",
       "DATE": "Das Datum ist %s"
    }
    
  3. package.json 文件中,将 i18n 节点和时刻库声明为依赖项:

    {
     ...
     "dependencies": {
       "actions-on-google": "^2.7.0",
       "firebase-admin": "^7.2.1",
       "firebase-functions": "^2.2.1",
       "i18n": "^0.8.3",
       "moment": "^2.22.1"
     }
    }
    
  4. index.js 文件中,声明国际化节点和时刻库的依赖项:

    const i18n = require('i18n');
    const moment = require('moment');

  5. index.js 文件中,使用受支持的语言区域配置 i18n 节点:

    i18n.configure({
      locales: ['en-US', 'en-GB', 'de-DE'],
      directory: __dirname + '/locales',
      defaultLocale: 'en-US'
    });

  6. 使用客户端库属性中的 conv.user.locale 设置库的语言区域。

    app.middleware((conv) => {
      i18n.setLocale(conv.user.locale);
      moment.locale(conv.user.locale);
    });

  7. 如需返回本地化响应,请使用 i18n 返回的本地化字符串调用 ask()。此代码段还包含一个使用利用时刻返回本地化日期的函数:

    app.intent('Default Welcome Intent', (conv) => { // must not be async for i18n
      conv.ask(i18n.__('WELCOME_BASIC'));
    });
    
    app.intent('date', (conv) => { // must not be async for i18n
      conv.ask(i18n.__('DATE', moment().format('LL')));
    });

下面是一个完整的 index.js 文件示例:

'use strict';
const {dialogflow} = require('actions-on-google');
const functions = require('firebase-functions');
const i18n = require('i18n');
const moment = require('moment');

i18n.configure({
  locales: ['en-US', 'en-GB', 'de-DE'],
  directory: __dirname + '/locales',
  defaultLocale: 'en-US'
});

const app = dialogflow({debug: true});

app.middleware((conv) => {
  i18n.setLocale(conv.user.locale);
  moment.locale(conv.user.locale);
});

app.intent('Default Welcome Intent', (conv) => { // must not be async for i18n
  conv.ask(i18n.__('WELCOME_BASIC'));
});

app.intent('date', (conv) => { // must not be async for i18n
  conv.ask(i18n.__('DATE', moment().format('LL')));
});

exports.demoAction = functions.https.onRequest(app);