Невозможно добавить участников в календарь Google, используя диалоговое окно, используя node.js в онлайн-редакторе Firebase. - PullRequest
0 голосов
/ 06 февраля 2020

Первый пост от эксперта по неразработке. Я изучал библиотеки и онлайн-ресурсы о том, как использовать Dialogflow Fulfillment для интеграции с API Календаря Google. Я могу установить время начала и окончания, сводку, описание, местоположение в Календаре Google, но не могу успешно добавить участников. Я перепробовал много вариантов формата участников. Вот код, который я использую, я удалил закрытый ключ по соображениям безопасности. Одна заметка, когда я использовал квадратные скобки, как предлагали некоторые сайты, я всегда получал ответ, что время уже занято.

'use strict';

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

 // Enter your calendar ID below and service account JSON below
 const calendarId = 'piec3rnlo2v2p2cemgjdjfctmg@group.calendar.google.com';
 const serviceAccount = {
  "type": "service_account",
  "project_id": "whatduewhen2020v1-kgwjyd",
  "private_key_id": "2a2dead3e050ef295cfef9c2c27bd2ac7d2b7471",
  "private_key": "-----BEGIN PRIVATE KEY-----,
  "client_email": "google-calendar@whatduewhen2020v1-kgwjyd.iam.gserviceaccount.com",
  "client_id": "114290887729963225819",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/google-calendar%40whatduewhen2020v1-kgwjyd.iam.gserviceaccount.com"
}; // Starts with {"type": "service_account",...

 // Set up Google Calendar Service account credentials
 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:*'; // enables lib debugging statements

 const timeZone = 'America/Toronto';
 const timeZoneOffset = '-05:00';

 exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
   const agent = new WebhookClient({ request, response });
   console.log("Parameters", agent.parameters);
   const appointment_type = agent.parameters.AppointmentType;
   const attendee_email = agent.parameters.email;
   const attendee_phone = agent.parameters.phone_number;
   const attendee_firstname = agent.parameters.given_name;
   const attendee_lastname = agent.parameters.last_name;
   function makeAppointment (agent) {
     // Calculate appointment start and end datetimes (end = +1hr from start)
     //console.log("Parameters", agent.parameters.date);
     const dateTimeStart = new Date(Date.parse(agent.parameters.date.split('T')[0] + 'T' + agent.parameters.time.split('T')[1].split('-')[0] + timeZoneOffset));
     const dateTimeEnd = new Date(new Date(dateTimeStart).setHours(dateTimeStart.getHours() + 1));
     const appointmentTimeString = dateTimeStart.toLocaleString(
       'en-US',
       { month: 'long', day: 'numeric', hour: 'numeric', timeZone: timeZone }
     );

     // Check the availibility of the time, and make an appointment if there is time on the calendar
     return createCalendarEvent(dateTimeStart, dateTimeEnd, appointment_type, attendee_email, attendee_phone, attendee_firstname, attendee_lastname).then(() => {
       agent.add(`Excellent, it looks like ${appointmentTimeString} is available and we have reserved the time for you!.`);
     }).catch(() => {
       agent.add(`I'm so sorry, it looks like we're already booked on ${appointmentTimeString} is there an alternate day or time you are available?`);
     });
   }

   let intentMap = new Map();
   intentMap.set('Schedule Appointment', makeAppointment);
   agent.handleRequest(intentMap);
 });



 function createCalendarEvent (dateTimeStart, dateTimeEnd, appointment_type, attendee_email, attendee_phone, attendee_firstname, attendee_lastname) {
   return new Promise((resolve, reject) => {
     calendar.events.list({
       auth: serviceAccountAuth, // List events for time period
       calendarId: calendarId,
       timeMin: dateTimeStart.toISOString(),
       timeMax: dateTimeEnd.toISOString()
     }, (err, calendarResponse) => {
       // Check if there is a event already on the Calendar
       if (err || calendarResponse.data.items.length > 0) {
         reject(err || new Error('Requested time conflicts with another appointment'));
       } else {
         // Create event for the requested time period
         calendar.events.insert({ auth: serviceAccountAuth,
           calendarId: calendarId,
           resource: {summary: ' Membership Discussion' + ' ' + attendee_email + ' ' + attendee_phone ,
             description: ' Membership Discussion' + ' ' + attendee_email + ' ' + attendee_phone,
             location: 'Call ' + attendee_firstname + ' ' + attendee_lastname + ' at ' + attendee_phone,
             start: {dateTime: dateTimeStart},
             end: {dateTime: dateTimeEnd},
             attendees: { email: 'new@example.com'} },
         }, (err, event) => {
           err ? reject(err) : resolve(event);
         }
         );
       }
     });
   });
 }
...