CodeBit: Get data from Google Cloud Functions into your chatbot

In this article, we will show how you can use Google Cloud Function in your chatbot for getting data from any source. You can do it with a combination of any cloud function provider and API.chat platform.

The platform provides you the ability to get and send data to any REST endpoint using action attribute. In this code bit, we get a random word on chatbot request from arrays of words in Google Cloud Function.

This is a function in js for Google Cloud

exports.randomWord = (req, res) => {

var items = ['word1','word2', 'word'];

var item = items[Math.floor(Math.random() * items.length)];

res.status(200).send({ CorrelationId: req.query.request, Messages: [ item ] });

};

When chatbot performs GET request to function he pass a set of parameters in request query:

  • request - request-id, must be returned in correlation id
  • id - chat id of the user
  • channel - channel of the user (Telegram, Viber, etc)

You can use this parameter to identify users and provide personalized information.

This is API.chat scenario to call this function in chatbot

<bot>

<states>

<state name="Start">

<transition input="/random" next="Start" action="https://us-central1-REDACTED.cloudfunctions.net/function-1"/>

<transition input="*" next="Start">Hello. Send /random for a word</transition>

</state>

</states>

</bot>

If morfology="msg" attribute added you can pass user input into the request like this

<transition input="*" next="Start" morphology="msg" action="https://us-central1-REDACTED.cloudfunctions.net/function-1?name={msg}">Welcome! Your name is saved now</transition>

Build your chatbot 3x faster with API.chat

Contact us or sign up now.