// Copyright 2018 Google LLC. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import * as functions from 'firebase-functions' import { DialogflowApp } from 'actions-on-google' import * as Translate from '@google-cloud/translate' const translate = new Translate({ projectId: functions.config().firebase.projectId, }) const actionMap = new Map() actionMap.set('translate.text', translateText) const languages = { 'French': 'fr', 'Russian': 'ru', 'Spanish': 'es', 'Japanese': 'ja', 'Chinese': 'zh', 'Dutch': 'nl', 'English': 'en', 'German': 'de', 'Italian': 'it', 'Korean': 'ko' } export const fulfill = functions.https.onRequest((request, response) => { const app = new DialogflowApp({request, response}) app.handleRequest(actionMap) }) function translateText(app) { let text = app.getArgument('text') let langTo = app.getArgument('lang-to') let langFrom = app.getArgument('lang-from') console.log(app.getContext('translate-text')) if (!text) { const arg = app.getContextArgument('translate-text', 'lastText') if (arg) { text = arg.value } } if (!langTo) { const arg = app.getContextArgument('translate-text', 'lastLangTo') if (arg) { langTo = arg.value } } if (!langFrom) { const arg = app.getContextArgument('translate-text', 'lastLangFrom') if (arg) { langFrom = arg.value } if (!langFrom) { langFrom = 'English' } } app.setContext('translate-text', 2, { lastText: text, lastLangTo: langTo, lastLangFrom: langFrom }) console.log(`text: ${text}`) console.log(`lang-to: ${langTo}`) console.log(`lang-from: ${langFrom}`) if (!text) { ask(app, "What would you like to translate?") } else if (!langTo) { ask(app, "What language would you like to translate to?") } else { const options = { to: languages[langTo] } if (langFrom) { options['from'] = languages[langFrom] } translate.translate(text, options) .then(results => { const translation = results[0] console.log(`translation: ${translation}`) tell(app, translation) }) .catch(error => { console.error(error) const message = "Sorry, I couldn't translate that." tell(app, message) }) } } // Warning! I'm using private APIs below to gain access to the data field // in the Dialogflow response. function tell(app, speech) { const res = app.buildResponse_(speech, false) res.data.slack = { text: speech } app.doResponse_(res, 200) } function ask(app, question) { const res = app.buildResponse_(question, true) res.data.slack = { text: question } app.doResponse_(res, 200) }