Taking actions with the AI chat

With the Alan AI Web Chat, you can help users take actions and complete tasks within your app through voice and text interactions. For that, you can:

In this tutorial, we will integrate our AI assistant with Google Calendar via the Google Calendar API and allow website users to schedule a meeting with the website owner using the Alan AI Web Chat.

What you will learn

  • How to complete tasks within your app with the Alan AI Web Chat

  • How to take actions in software on users’ queries with the Alan AI Web Chat

What you will need

To go through this tutorial, make sure you have completed the following tutorial: Building an AI chat for a website.

Step 1. Get an OAuth 2.0 Client ID for Google apps

First, we will perform the steps described in the previous tutorial to get the Google OAuth Client ID with the following scope:

  • Enabled API: Google Calendar API

  • Google API scopes:

    • https://www.googleapis.com/auth/calendar

    • https://www.googleapis.com/auth/calendar.events

Step 2. Get the Google calendar ID

We need to get an ID of the calendar in which events should be created.

With the account you used to create the Google Cloud project, create a new calendar or choose to use an existing one. Then, get the calendar ID:

  1. In the left pane of Google Calendar, hover over the calendar name and select Options > Settings and sharing.

  2. Scroll down the Integrate calendar section and copy the calendar ID.

../../../_images/integrating-calendar.png

Step 3. Capture user’s data with the AI chat

To the dialog script in Alan AI Studio, we will add code to capture the following user’s data: name, email address, date and time of the meeting.

Dialog script
intent(`I want to schedule a meeting`, async p => {
    p.play('I need some info from you to schedule a  meeting');

    // Capturing the user's name
    p.play('Please type in your name');
    let userName = await p.then(getName);

    // Capturing the user's email address
    p.play('Please type in your email address');
    let userEmail = await p.then(getEmail);

    // Capturing the date
    p.play('When would you like to meet?');
    let userDate = await p.then(getDate);

    // Capturing the time
    p.play('At what time?');
    let userTime = await p.then(getTime);
    let startTime = api.moment(userDate).add(userTime, 'seconds', p.timeZone);
    let endTime = api.moment(startTime).add(3600, 'seconds');

    p.play(`Great! Check your inbox, you should get an invitation soon`);
});

let getName = context((p) => {
    intent('$(USERNAME* .+)', p => {
        return p.resolve(p.USERNAME.value);
    });
});

let getEmail = context((p) => {
    const email = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|.(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    intent(`$(EMAIL* ${email.source})`, p => {
        return p.resolve(p.EMAIL.value);
    });

    fallback('Please provide a valid email');
 });

let getDate = context((p) => {
    intent('$(DATE)', p => {
        return p.resolve(p.DATE.moment);
    });

    fallback('Please provide a valid date');
});

let getTime = context((p) => {
    intent('$(TIME)', p => {
        return p.resolve(p.TIME.time);
    });

    fallback('Please provide valid time');
});

Here, when the user says: I want to schedule a meeting, Alan AI sequentially activates the getName, getEmail, getDate and getTme contexts to capture the required values and save them to variables. To this, we use the NAME, regEx, DATE and TIME slots.

After the date and time values are captured, we convert them to startTime and endTime values. We will need them later to create a calendar event.

Step 4. Create an event with user’s data

We can capture the data we need; next, we need to create an event in Google Calendar.

  1. To the dialog script, add the code to get a token for Google APIs with the client ID, client secret and refresh token we obtained in step 1.

    Dialog script
    // Getting a Google API token
    const getToken = async () => {
        const data = {
            "client_id": "YOUR-CLIENT-ID",
            "client_secret": "YOUR-CLIENT-SECRET",
            "refresh_token": "YOUR-REFRESH-TOKEN",
            "grant_type": "refresh_token"
        }
        try {
            const response = await api.axios({
                url: "https://www.googleapis.com/oauth2/v4/token",
                method: "POST",
                data: data});
            return response.data.access_token;
        } catch(error) {
            console.error(JSON.stringify(error));
        }
    }
    
  2. Next, we need to create an event. For this, we will add the createEvent() function that uses the event:insert method of the Google Calendar API. To send a POST request, we will use the built-in axios library.

    Dialog script
    // Create an event in Google Calendar
    let CALENDAR_ID = "YOUR-CALENDAR-ID'";
    
    const createEvent = async (name, email, start, end, timeZone) => {
        const token = await getToken();
        const summary = "Meeting: Alan Turing, Jr. and " + name
        const data = {
            start: {dateTime: start, timeZone: timeZone},
            end: {dateTime: end, timeZone: timeZone},
            summary: summary,
            attendees: [
                {
                    displayName: name,
                    email: email
                }
            ]
        }
        try {
            const response = await api.axios({
                url: `https://www.googleapis.com/calendar/v3/calendars/${CALENDAR_ID}/events`,
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    Authorization: `Bearer ${token}`,
                },
                params: {
                    'sendUpdates': 'all'
                },
                data: data});
            console.log(response.data);
        } catch(error) {
            console.error(JSON.stringify(error));
        }
    }
    

    Here, we first call the getToken() function to generate a new token using the refresh token we have. After that, we use the insert method to create a calendar event with the data passed to the function.

  3. Finally, we will update the I want to schedule a meeting intent to call the createEvent() function after all the required data is collected:

    Dialog script
    intent(`I want to schedule a meeting`, async p => {
        p.play('I need some info from you to schedule a call');
        p.play('Please type in your name');
        let userName = await p.then(getName);
        p.play('Please type in your email address');
        let userEmail = await p.then(getEmail);
        p.play('When would you like to meet?');
        let userDate = await p.then(getDate);
        p.play('At what time?');
        let userTime = await p.then(getTime);
        let startTime = api.moment(userDate).add(userTime, 'seconds', p.timeZone);
        let endTime = api.moment(startTime).add(3600, 'seconds');
    
        //Creating a calendar event
        createEvent(userName, userEmail, startTime, endTime, p.timeZone);
    
     p.play(`Great! Check your inbox, you should get an invitation soon`);
    

You can test how it works: in the Alan AI Web Chat type: I want to schedule a meeting, then provide a name, email address, date and time. Open the calendar and make sure a new event is added to it.