執行要求 (Dialogflow)

執行要求邏輯可以使用在每個要求中收到的語言代碼字串,以便為使用者提供回應。本指南將說明如何在 Cloud Function 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 檔案中,宣告 i18n 節點和時刻程式庫的依附元件:

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