Google动作从Firebase发送Webhook错误406

时间:2019-04-11 22:34:50

标签: google-api action

我正在为我的论文使用Google api创建约会动作。我有js代码,但我停留在json文件中,因此无法在Firebase中启动代码。 Firebase返回Webhook错误406。

js代码如下:

    'use strict';

    const functions = require('firebase-functions');
    const {google} = require('googleapis');
    const {WebhookClient} = require('dialogflow-fulfillment');

// Enter your calendar ID and service account JSON below.
const calendarId = 'https://calendar.google.com/calendar/embed?src=qekai7gj2lmc84chq367cd0da4%40group.calendar.google.com&ctz=Europe%2FBerlin'; // Example: 6ujc6j6rgfk02cp02vg6h38cs0@group.calendar.google.com
const serviceAccount = {
  "type": "service_account",
  "project_id": "PROJECT ID",
  "private_key_id": "PRIVATE KEY",
 ...
}; 

// Set up credentials of Calendar API
const serviceAccountAuth = new google.auth.JWT({
  email: serviceAccount.client_email,
  key: serviceAccount.private_key,
  scopes: 'https://www.googleapis.com/auth/calendar'
});

const calendar = google.calendar('v3');
process.env.DEBUG = 'dialogflow:*'; // It enables lib debugging statements

const timeZone = 'Germany';  
const timeZoneOffset = '+02:00';        

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });

  function makeAppointment (agent) {
    // Use the Dialogflow's date and time parameters for Date instances, 'dateTimeStart' and 'dateTimeEnd',
    // which are used to specify the appointment's time.

    const dateTimeStart = convertParametersDate(agent.parameters.startdate, agent.parameters.starttime, agent.parameters.name);
    const dateTimeEnd = convertParametersDate(agent.parameters.startdate, agent.parameters.endtime, agent.parameters.name);
    const appointmentTimeString = getLocaleTimeString(dateTimeStart);
    const appointmentDateString = getLocaleDateString(dateTimeStart);

    // Check the availability of the time slot and set up an appointment if the time slot is available on the calendar
    return createCalendarEvent(...
    });
  }
    let intentMap = new Map();
  intentMap.set('Terminerstellung', makeAppointment);  // It maps the intent 'Termin' to the function 'makeAppointment()'
  agent.handleRequest(intentMap);

   function deleteAppointment (agent) {
    // Use the Dialogflow's date and time parameters for Date instances, 'dateTimeStart' and 'dateTimeEnd',
    // which are used to specify the appointment's time.    

    const dateTimeStart = convertParametersDate(agent.parameters.startdate, agent.parameters.starttime, agent.parameters.name);
    const dateTimeEnd = convertParametersDate(agent.parameters.enddate, agent.parameters.endtime, agent.parameters.name);
    const appointmentTimeString = getLocaleTimeString(dateTimeStart);
    const appointmentDateString = getLocaleDateString(dateTimeStart);

    // Check the availability of the time slot and set up an appointment if the time slot is available on the calendar
    return deleteCalendarEvent(dateTimeStart, dateTimeEnd).then(() => {
   ...
  }
}); 
  function deleteCalendarEvent (dateTimeStart, dateTimeEnd) {
    return new Promise((resolve, reject) => {
    calendar.events.list({  // List all events in the specified time period
      auth: serviceAccountAuth,
      calendarId: calendarId,
      timeMin: dateTimeStart.toISOString(),
      timeMax: dateTimeEnd.toISOString()
    }, (err, calendarResponse) => {
      // Check if there exists any event on the calendar given the specified the time period
      if (err || calendarResponse.data.items.length < 0) {
        reject(err || new Error('Zu der Zeit existiert noch kein Termin'));
      } else {
        // Delete event for the requested time period
        calendar.events.delete({ auth: serviceAccountAuth,
          calendarId: calendarId,
          resource: {summary: 'Terminentfernung',
            start: {dateTime: dateTimeStart},
            end: {dateTime: dateTimeEnd}}
         }, (err, event) => {
          err ? reject(err) : resolve(event);
       }
        );
      }
    });
  });
  }

function createCalendarEvent (dateTimeStart, dateTimeEnd) {
  return new Promise((resolve, reject) => {
    calendar.events.list({  // List all events in the specified time period
      auth: serviceAccountAuth,
      calendarId: calendarId,
      timeMin: dateTimeStart.toISOString(),
      timeMax: dateTimeEnd.toISOString()
    }, (err, calendarResponse) => {
      // Check if there exists any event on the calendar given the specified the time period
      if (err || calendarResponse.data.items.length > 0) {
        reject(err || new Error('...'));
      } else {
        // Create an event for the requested time period
        calendar.events.insert({ auth: serviceAccountAuth,
          calendarId: calendarId,
          resource: {summary: 'Terminerstellung',
            start: {dateTime: dateTimeStart},
            end: {dateTime: dateTimeEnd}}
        }, (err, event) => {
          err ? reject(err) : resolve(event);
        }
        );
      }
    });
  });
}

// A helper function that receives Dialogflow's 'date' and 'time' parameters and creates a Date instance.
function convertParametersDate(date, time){
  return new Date(Date.parse(date.split('T')[0] + 'T' + time.split('T')[1].split('-')[0] + timeZoneOffset));
}

// A helper function that adds the integer value of 'hoursToAdd' to the Date instance 'dateObj' and returns a new Data instance.
function addHours(dateObj, hoursToAdd){
  return new Date(new Date(dateObj).setHours(dateObj.getHours() + hoursToAdd));
}

// A helper function that converts the Date instance 'dateObj' into a string that represents this time in English.
function getLocaleTimeString(dateObj){
  return dateObj.toLocaleTimeString('de-GER', { hour: 'numeric', hour12: true, timeZone: timeZone });
}

// A helper function that converts the Date instance 'dateObj' into a string that represents this date in English. 
function getLocaleDateString(dateObj){
  return dateObj.toLocaleDateString('de-GER', { weekday: 'long', month: 'long', day: 'numeric', timeZone: timeZone });
}

我在google action教程中创建了它,但是Google仅显示了JSON文件的内容:

{
  "name": "DialogflowFirebaseWebhook",
  "description": "Firebase Webhook dependencies for a Dialogflow agent.",
  "version": "0.0.1",
  "private": true,
  "license": "Apache Version 2.0",
  "author": "a",
  "engines": {
    "node": "6"
  },
  "scripts": {
    "lint": "semistandard --fix \"**/*.js\"",
    "start": "firebase deploy --only functions",
    "deploy": "firebase deploy --only functions"
  },
  "dependencies": {
    "firebase-functions": "^2.0.2",
    "firebase-admin": "^5.13.1",
    "googleapis": "^27.0.0",
    "actions-on-google": "2.2.0",
    "dialogflow-fulfillment": "0.5.0"
  },

我添加了这些东西:

  "responseId": "c4b863dd-aafe-41ad-a115-91736b665cb9",
    "queryResult": {
    "queryText": "GOOGLE_ASSISTANT_WELCOME",
    "action": "input.welcome",
    "parameters": {},
    "allRequiredParamsPresent": true,
    "fulfillmentText": "",
    "fulfillmentMessages": [],
    "outputContexts": [
      {
        "name": "projects/$PROJECTID}/agent/sessions/${newagent-1-df43c}/contexts/google_assistant_welcome"
      },
      {
        "name": "projects/${PROJECTID}/agent/sessions/${newagent-1-df43c}/contexts/actions_capability_screen_output"
      },
      {
        "name": "projects/${PROJECTID}/agent/sessions/${newagent-1-df43c}/contexts/google_assistant_input_type_voice"
      },
      {
        "name": "projects/${PROJECTID}/agent/sessions/${newagent-1-df43c}/contexts/actions_capability_audio_output"
      },
      {
        "name": "projects/${PROJECTID}/agent/sessions/${newagent-1-df43c}/contexts/actions_capability_web_browser"
      },
      {
        "name": "projects/${PROJECTID}/agent/sessions/${newagent-1-df43c}/contexts/actions_capability_media_response_audio"
      }
    ],
    "intent": {
      "name": "projects/${PROJECTID}/agent/intents/8b006880-0af7-4ec9-a4c3-1cc503ea8260",
      "displayName": "Default Welcome Intent"
    },
    "intentDetectionConfidence": 1,
    "diagnosticInfo": {},
    "languageCode": "de-ger"
  },
      "originalDetectIntentRequest": {
    "source": "google",
    "version": "2",
    "payload": {
      "isInSandbox": true,
      "surface": {
        "capabilities": [
          {
            "name": "actions.capability.SCREEN_OUTPUT"
          },
          {
            "name": "actions.capability.AUDIO_OUTPUT"
          },
          {
            "name": "actions.capability.WEB_BROWSER"
          },
          {
            "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
          }
        ]
      },
      "inputs": [
        {
          "rawInputs": [
            {
              "query": "start project",
              "inputType": "VOICE"
            }
          ],
          "intent": "actions.intent.WELCOME"
        }
      ],
      "user": {
        "lastSeen": "2018-03-16T22:08:48Z",
        "permissions": [
          "UPDATE"
        ],
        "locale": "de-GER",
        "userId": "ABwppHEvwoXs18xBNzumk18p5h02bhRDp_riW0kTZKYdxB6-LfP3BJRjgPjHf1xqy1lxqS2uL8Z36gT6JLXSrSCZ"
      },
      "conversation": {
        "conversationId": "${SESSIONID}",
        "type": "NEW"
      },
      "availableSurfaces": [
        {
          "capabilities": [
            {
              "name": "actions.capability.SCREEN_OUTPUT"
            },
            {
              "name": "actions.capability.AUDIO_OUTPUT"
            }
          ]
        }
      ]
    }
  },
  "session": "projects/${PROJECTID}/agent/sessions/$PROJECTID}"
    }   

我希望在日历中创建约会或在日历中删除约会。 但是firebase甚至无法启动操作。 1.它显示一个webhook错误406 2.它显示:您不能在模拟器中使用标准的Google Assistant功能。如果您想尝试一下,请在手机或其他兼容设备上使用Google Assistant 3.它表明该动作没有反应...

0 个答案:

没有答案