What are Cloud Functions?

Cloud Functions is a unique feature of Stackchat Studio whereby you can make some JavaScript code(of your choosing) to be available to your chatbot. Think of it as microservices for your chatbot.


Building a platform that allows businesses to better engage with their customers means ensuring that they have the right tools to deliver the best user experience for their customers. To that end, it is quite a daunting task to account for every single use case that a business might have. Which is why we have Cloud Functions - a tool to allow businesses to customise their chatbot to their heart's content.


Technically speaking, Cloud Functions is a collection of custom JavaScript code that a bot has access to at runtime. To explain Cloud Functions, I'll using an example. I will also be using the built-in editor so you can easily follow along.


Our scenario: We will be gathering user information and storing them in HubSpot. Once they consent to sign up for our newsletter, we will send them a welcome email.


Bolt ⚡️ - Our Chatbot

I have already made a bot that asks user for their contact information. If you already have a bot ready, you can skip this section.


To get started quickly, I will not be focusing on creating the bot. But I can help you get started. Paste the following CDML into the CDML Editor in Stackchat Studio.

bot:
  format: chat
  flows:
    - name: Welcome
      entry_flow: true
      flow_elements:
        - message_thread:
            name: Introduction
            entry_element: true
            messages:
              - text:
                  text: "Hello, \U0001F916!\n\nI'm Bolt ⚡"
              - user_input_group:
                  require_confirmation: false
                  items:
                    - text:
                        slot_name: name
                        label: name
                        prompt: What's your name?
              - text:
                  text: 'Great! Nice to meet you ${name}'
            continue_to: '_:Add to HubSpot'
        - message_thread:
            name: Check for Signup
            quick_nav:
              prompt: Would you like to sign up for our newsletter?
              choices:
                - display_name: Yes ✅
                  continue_to: '_:Sign Up for Newsletter'
                - display_name: No ❌
                  continue_to: '_:Handle Exit'
        - message_thread:
            name: Sign Up for Newsletter
            messages:
              - text:
                  text: Awesome!
              - user_input_group:
                  require_confirmation: false
                  items:
                    - email:
                        slot_name: email
                        label: email
                        prompt: Can I have your email address?
            continue_to: '_:Say Welcome'
        - code:
            name: Say Welcome
            handler: sendWelcomeEmailToUser
            continue_to: 'Welcome:Handle Success'
        - code:
            name: Add to HubSpot
            handler: addUserToHubSpot
            continue_to: 'Welcome:Check for Signup'
        - message_thread:
            name: Handle Exit
            messages:
              - text:
                  text: "No problems! Have a nice day \U0001F600"
        - message_thread:
            name: Handle Success
            messages:
              - text:
                  text: Thanks for signing up! You should get a welcome email soon.
              - text:
                  text: "Have an amazing rest of the day \U0001F600"

Then, add the following two custom slots - name(type 'text') and email(type 'email').


Writing the Cloud Functions

When you arrive at this section, your bot should have two errors and would look like this:


Bolt with two errors

Bolt with two errors


Now, on to Cloud Functions. Let's switch to the Cloud Functions page. If you have any code in there, delete it all and save. We will write all the code we need from scratch.


To be able to store a user's details and send them a welcome email, we will need two functions.

  • addUserToHubSpot: To be able to add the details to HubSpot.
  • sendWelcomeEmailToUser: To be able to send a welcome email via SendGrid.

Let's add the two functions to our editor and save:

 function addUserToHubSpot(userData) {
    // ...
  }

  function sendWelcomeEmailToUser(userData) {
    // ...
  }

  module.exports = { 
    addUserToHubSpot, 
    sendWelcomeEmailToUser 
  }

If you check, both of the errors in your bot should have disappeared and your screen should look like this:


Bolt with no errors

Bolt with no errors


Now let's start with adding the user to HubSpot.


  • Note 1: The userData parameter is provided to every cloud function on every invocation. Read more here.

  • Note 2: While using the built-in editor, @stackchat/dynamic-content-toolkit and node-fetch are already available to us:

/**
 * Stackchat automatically makes the below libraries available to
 * your code at runtime. You do not need to explicitly import them.
 * 
 * import * as dc from '@stackchat/dynamic-content-sdk';
 * import * as fetch from 'node-fetch';
 */

HubSpot provides a Contacts API that allows us to create a new contact in our organisation. Let's implement that.

function addUserToHubSpot(userData) {
  const {slotData} = userData
  const name = slotData["name"]
  const email = slotData["email"]

  // You can get an API key for HubSpot from their
  // developer's section.
  fetch(
    `https://api.hubapi.com/contacts/v1/contact/?hapikey=<YOUR_API_KEY_HERE>`,
    {
      method: 'POST',
      body: JSON.stringify({
        properties: [
          {
            property: "email",
            value: email
          },
          {
            property: "firstname",
            value: name
          }
        ]
      })
    }
  )
  .then(res => res.json())
  .then(response => {
    // do something with response
  })
  .catch(err => {
    // handle error
  })
}

We do not need to worry about returning anything back. Returning from a cloud function is required only when you would like to override the set navigation target after the execution is complete. Add in the above implementation and save.


Congratulations 🎉🎊! You've just written your first cloud function.


Next, we need to send the new subscriber a welcome email if they have agreed to it. We have configured the bot such that the cloud function is only invoked if the user agrees to sign up for our newsletter.


Let's get to implementing that one. We will use SendGrid, a popular email delivery service to send the email to the user.

function sendWelcomeEmailToUser(userData) {
  const name = userData.slotData["name"]
  const email = userData.slotData["email"]

  fetch(
    `https://api.sendgrid.com/v3/mail/send`,
    {
      method: 'POST',
      headers: {
        'content-type': 'application/json',
        'authorization': 'Bearer <<YOUR_API_KEY_HERE>>'
      },
      body: JSON.stringify({
        personalizations: [
          {
            to: [{
              email,
              name
            }],
            subject: "Hello from Bolt!"
          }
        ],
        from: {
          email: "support@boltbot.com",
          name: "Bolt Bot"
        },
        content: [
          {
            type: 'text/plain',
            value: "Hi there!\n\nThis is just a email to welcome you to the Bolt family. I'll start sending newletters as and when we push them.\n\nThanks for signing up.\n\n-Bolt Bot"
          }
        ]
      })
    }
  )
  .then(res => res.json())
  .then(response => {
    // handle response or ignore
  })
  .catch(err => {
    // handle error or ignore
  })
}



Now you are all set. Ensure you have entered your real API Keys instead of the demo ones and then publish Bolt ⚡️


After the publish is complete, chat with Bolt to see your data being stored in HubSpot and emails being delivered via SendGrid 😀


I hope this gives you a great starting point for your own cloud functions. Built-in editor or otherwise, you can customise your bot to your heart's content so that your users get the best possible experience.


For more information about choosing the right chatbot for you, get in touch with the experts at Stackchat today.