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 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

-- CODE language-js -- /** * Responds to any HTTP request. * * @param {!express:Request} req HTTP request context. * @param {!express:Response} res HTTP response context. */ 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 scenario to call this function in chatbot

-- CODE lang-markup -- <bot> <states> <state name="Start"> <transition input="/random" next="Start" action="" /> <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

-- CODE lang-markup -- <transition input="*" next="Start" morphology="msg" action="{msg}">Welcome! Your name is saved now</transition>

Don't miss these stories: