Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Webhook call failed. Error: UNAVAILABLE, State: URL_UNREACHABLE, Reason: UNREACHABLE_5xx, HTTP statu

I am using Dialogue flow inline editor. I have created cloud function to create an event but its not working and I am receiving following error in diagnostic info. Please help me to Resolve this issue.

Webhook call failed. Error: UNAVAILABLE, State: URL_UNREACHABLE, Reason: UNREACHABLE_5xx, HTTP status code: 500

My code in ndex.js file is as below:

 
  1.  'use strict';
  2.  
  3.  const functions = require('firebase-functions');
  4.  const {google} = require('googleapis');
  5.  const {WebhookClient} = require('dialogflow-fulfillment');
  6.  
  7.  // Enter your calendar ID below and service account JSON below
  8.  const calendarId = "My CalenderId";
  9.  const serviceAccount = {
  10.  My account details
  11. }; // Starts with {"type": "service_account",...
  12.  
  13.  // Set up Google Calendar Service account credentials
  14.  const serviceAccountAuth = new google.auth.JWT({
  15.    email: serviceAccount.client_email,
  16.    key: serviceAccount.private_key,
  17.    scopes: 'https://www.googleapis.com/auth/calendar'
  18.  });
  19.  
  20.  const calendar = google.calendar('v3');
  21.  process.env.DEBUG = 'dialogflow:*'; // enables lib debugging statements
  22.  
  23.  const timeZone = 'America/Los_Angeles';
  24.  const timeZoneOffset = '-07:00';
  25.  
  26.  exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  27.    const agent = new WebhookClient({ request, response });
  28.    console.log("Parameters", agent.parameters);
  29.    const Person_name = agent.parameters.person;
  30.    const phone = agent.parameters.phone;
  31.    function makeAppointment (agent) {
  32.      // Calculate appointment start and end datetimes (end = +1hr from start)
  33.      //console.log("Parameters", agent.parameters.date);
  34.      const dateTimeStart = new Date(Date.parse(agent.parameters.date.split('T')[0] + 'T' + agent.parameters.time.split('T')[1].split('-')[0] + timeZoneOffset));
  35.      const dateTimeEnd = new Date(new Date(dateTimeStart).setHours(dateTimeStart.getHours() + 1));
  36.      const appointmentTimeString = dateTimeStart.toLocaleString(
  37.        'en-US',
  38.        { month: 'long', day: 'numeric', hour: 'numeric', timeZone: timeZone }
  39.      );
  40.    
  41.  
  42.      // Check the availibility of the time, and make an appointment if there is time on the calendar
  43.      return createCalendarEvent(dateTimeStart, dateTimeEnd, Person_name, phone).then(() => {
  44.      function confirmAppointment() {
  45.             agent.add(`Ok, let me see if we can fit you in. ${appointmentTimeString} is fine!`);
  46.           }
  47.         confirmAppointment();
  48.      }).catch(() => {
  49.        agent.add(`I'm sorry, there are no slots available for ${appointmentTimeString}.`);
  50.      });
  51.    }
  52.  
  53.    let intentMap = new Map();
  54.    intentMap.set('Schedule Appointment', makeAppointment);
  55.    agent.handleRequest(intentMap);
  56.  });
  57.  function createCalendarEvent(dateTimeStart, dateTimeEnd, Person_name, phone) {
  58.     const new_event = {
  59.         summary: Person_name + ' Appointment',
  60.             description: 'with ' + Person_name +' - '+ phone.toString(), // Convert phone to string
  61.             start: { dateTime: dateTimeStart },
  62.             end: { dateTime: dateTimeEnd }
  63.     };
  64.   return new Promise((resolve, reject) => {
  65.     calendar.events.list({
  66.       auth: serviceAccountAuth, // List events for time period
  67.       calendarId: calendarId,
  68.       timeMin: dateTimeStart.toISOString(),
  69.       timeMax: dateTimeEnd.toISOString()
  70.     }, (err, calendarResponse) => {
  71.       // Check if there is an event already on the Calendar
  72.       if (err || calendarResponse.data.items.length > 0) {
  73.         reject(err || new Error('Requested time conflicts with another appointment'));
  74.       } else {
  75.         // Create event for the requested time period
  76.     calendar.events.insert({
  77.           auth: serviceAccountAuth,
  78.           calendarId: calendarId,
  79.           resource: new_event
  80.         }, (err, new_event) => {
  81.           if (err) {
  82.             console.error("Error creating event:", err);
  83.           } else {
  84.             console.log("Event created successfully:", new_event.id);
  85.           }
  86.         });                
  87.       }
  88.     });
  89.   });
  90. }
1 1 1,226
1 REPLY 1

Hi @NamitaDesai,

Welcome to Google Cloud Community!

You're getting a "UNAVAILABLE" error because your Cloud Function can't reach Google Calendar. Here's how to fix it:

  1. Check Network: Make sure your Cloud Function has internet access and no firewalls are blocking Google APIs.
  2. Verify Credentials: Double-check your service account details and ensure it has permission to access Google Calendar (scope: https://www.googleapis.com/auth/calendar).
  3. Debug Your Code: Use logging and error messages to pinpoint issues during authentication or API calls.
  4. Test Manually: Try making a direct API call from your machine to isolate the problem.

Here are additional tips:

  • Implement error handling in your code for a better user experience.
  • Consider using async/await for cleaner asynchronous handling.
  • Maintain good code formatting for readability.
Top Solution Authors