cloud – Xenioo Mon, 07 Dec 2020 09:02:03 +0000 en-US hourly 1 https://wordpress.org/?v=5.5.3 /wp-content/uploads/2018/09/cropped-xenioo-badge-32x32.png cloud – Xenioo 32 32 Usare un database Firebase in un chatbot /usare-un-database-firebase-in-un-chatbot/ /usare-un-database-firebase-in-un-chatbot/#respond Tue, 16 Apr 2019 08:58:12 +0000 https://wp-it.xenioo.com/?p=2019 In questo articolo andremo ad imparare come costruire un chatbot completamente dinamico, capace di estrarre e aggiornare dati in tempo reale da un database online usando Xenioo, Firebase e senza scrivere una sola riga di codice.

The post Usare un database Firebase in un chatbot appeared first on Xenioo.

]]>
In un nostro precedente articolo avevamo esplorarato come realizzare un chatbot completamente dinamico utilizzando dati letti da una fonte online, in quel caso si trattava di Sheetlabs.

In molti casi questo però non è sufficiente ed abbiamo bisogno della potenza di un vero e completo motore di database nel cloud.

In questo articolo vi faremo vedere come costruire un chatbot Xenioo integrando Firebase, la piattaforma Google che fornisce database e backend “as a service”.

La nuova integrazione Xenioo – Firebase

Firebase è la famosa piattaforma Google che fornisce un motore di database completamente online fruibile attraverso API restful.

Firebase offre un piano gratuito che è più che sufficiente per piccoli o medi scenari di utilizzo e consente di scalare progressivamente per gestire milioni di richieste.

Xenioo, in uno dei suoi ultimi aggiornamenti, ha introdotto l’integrazione nativa con Firebase, sia a livello di azioni che di scripting: andiamo subito a vedere come funziona!

Prima di tutto è necessario registrarsi per aprire un proprio account. Lo possiamo creare gratis da https://firebase.google.com/ seguendo tutta la procedura di registrazione. Se avete già un account Google attivo, il tutto risulterà ulteriormente rapido.

Dopo la registrazione, sarete pronti per creare il vostro primo progetto di database. Date un nome al progetto, accettate i termini del servizio e cliccate su Create.

Per il prototipo di questo articolo chiameremo il progetto XeniooIsAwesome.

Creiamo il Service Account

Dopo qualche secondo, il nosro nuovo database nel cloud sarà pronto.

Dobbiamo ora creare le informazioni di connessione che dovremo successivamente indicare in Xenioo.

Per creare una Firebase Admin Key, clicchiamo sulla piccolo ingranaggio in alto a sinistra e vicino a “Project Overview”, e poi clicchiamo su “Project Setings” e ancora sul tab “Service Account” (vedi figura qui sotto).

In fondo alla pagina dovrete ora cliccare il botton “Generate new private key”. Questo genererà un file JSON che conterrà le informazioni relative al vostro servizio di database appena creato: tenete questo file al sicuro in quanto vi servirà poi successivamente.

Creaiamo il database

Dopo aver creato il Service Account, cioè la nostra connessione privata con Firebase, siamo pronti per creare il nostro database. Lo faremo muovendoci nella sezione “Database”.

Clicchiamo sul bottone “Create Database” e Firebase creerà il databae per conto nostro.

A questo punto è doverosa una piccola precisazione. Come la maggior parte dei database online e di ultima generazione, Firebase è un database di tipo documentale e non relazionale.

Questo significa che non si avrà a che fare con tabelle a schema predefinito, come tipico per esempio in database come Sql Server oppure MySql.
In Firebase i dati sono memorizzati in collezioni che possono contenere un numero differente di oggetti (righe, se vogliamo usare un termine di paragone con la classica tabella del database relazionale) i quali possono avere ciascuno campi differenti.

Inizialmente questo potrà sembrare complesso, ma vederete con il tempo e la pratica come questo tipo di struttura permetterà di gestire con più flessibilità i dati che vorrete gestire all’interno del vostro chatbot.

Quello che faremo ora è ricreare la stessa tabella di colori che abbiamo usato in passato. Chiameremo quindi la nostra prima collection “Colors”.

Confermata la creazione della collection, siamo pronti per aggiungerci nuovi documenti all’interno.

Firebase fornisce un editor real-time molto ben fatto che rende molto semplice aggiungere e gestire dati all’intenro delle collection.

Aggiungiamo alcuni colori di esempio alla collection così da poterli poi utilizzare in Xenioo.

Quando siamo soddisfatti con i dati che abbiamo inserito, possiamo lasciare Firebase e tornare alla creazione del chatbot in Xenioo.

Faremo essenzialmente quanto già avevo visto nel chatbot dinamico per Whatsapp, ma con alcune interessanti modifiche.

Costruiamo il chatbot

La prima cosa che il nostro chatbot dovrà fare è mostrare agli utenti la lista dei possibili colori da selezionare, leggendo i colori dal database Firebase appena creato.

Per fare questo useremo l’azione Firebase Document, da inserire come prima azione nell’interazione di partenza.

I campi per configurare l’azione sono abbastanza esplicativi. Ricordatevi di fare copia e incolla del JSON generato precedentemente nel vostro account Firebase nel campo Firebase Account JSON dell’azione.

L’azione Firebase Document cosi configurata permetterà a Xenioo di connettersi automaticamente al vostro database Firebase per recuperare (comando LIST) l’elenco degli oggetti dalla collection Colors.

Ogni oggetto recuperato da Xenioo rispecchierà esattamente il modello dati creato nella collection su Firebase. Nel nostro esempio, il JSON risultante sarà qualcosa di simile all’immagine seguente:

Con questi dati recuperati, vogliamo che il chatbot mostri all’utente una serie di bottoni per ciascun colore in modo da permettere all’utente di selezionarne uno.

Abbiamo molteplici modi per fare questo con Xenioo, ma questa volta opteremo per la via più semplice. Sfrutteremo infatti capacità di Xenioo di tradurre le variabili al volo, caratteristiche che funziona anche con oggetti JSON come quellio appena recuperato da Firebase.

Aggiungiamo quindi una azione Quick Reply Array e, per i bottoni che vogliamo visualizzare, andremo a scrivere la variabile referenziando direttamente la proprietà colore in base alla posizione nell’array JSON.

Xenioo automaticamente sostituirà ogni riga {{ }} con il valore dell’oggetto, estraendone il valore della proprietà Color per la posizione nell’array come specificato.

Il risultato finale sarà che abbiamo costruito un chatbot a scelta dinamica e multipla basata su Firebase e senza scrivere una sola riga di codice!

Ovviamente, dovrete adattare il vostro array di bottoni in base alle opzioni che prevedete di visualizzare e gestire. Abbiamo già descritto come fare in uno dei nostri articoli precedenti utilizzando alcune righe di Xenioo cloud scripting.

Aggiungiamo dati nel database dal chatbot

Quello che potrebbe succedere prima o poi è l’esigenza di dover inserire o modificare il nostro database Firebase.

Potrebbe essere per registrare statistiche relative agli utenti, piuttosto che il tracking di azioni specifiche o ancora opzioni e settaggi da riutilizzare in conversazioni successive.

La buona notizia è che la stessa azione Firebase Document che abbiamo usato per leggere i dati, la possiamo confiugurare anche per inseririmenti ed aggiornamenti.

Riprendendo il nostro bot di esempio, vogliamo che l’utente possa indicare un colore personalizzato non presente in lista. E che questo colore venga poi inserito nel nostro database online.

Aggiungeremo quindi una nuova voce “Custom” nell’azione Quick Reply Array ed andremo a gestire la richiesta del colore personalizzato tramite l’azione Input Action.

La magia accade nella stessa azione che abbiamo usato precedentemente per leggere i colori.

L’unica differenza è che ora l’azione sarà configurata per gestire il comando CREATE e non LIST. Inoltre andremo a specificare il JSON dell’oggetto da inserire nel campo Document Payload.

Ecco nell’immagine seguente come andremo dinamicamente a specificare il nuovo colore da inserire tramite la variabile {{ custom color }} valorizzata dall’azione di Input.

E questo è tutto!

Se il nostro utente deciderà di selezionare un nuovo colore, questo verrà aggiunto alla collection Colors del nostro database Firebase e sarà disponibile per essere usato nel modo voluto.

Ancora, abbiamo appena costruito un chatbot a contenuto dinamico capace di estrarre e aggiornare dati in tempo reale da un database online, senza scrivere una sola riga di codice.

Ma, se volessi scrivere codice?

Certamente che potete! Infatti Firebase è strettamente integrato anche con l’azione Cloud Scripting di Xenioo.

Xenioo permette di accedere al database online via script, semplicemente ottenendo una referenza “live” al database in modo da poterlo usare direttamente per leggere e scrivere dati.

Il nostro esempio precedente potrebbe essere riprogettato utilizzando il codice seguente.

Meglio ancora, questo codice non usa gli indici per accedere e generare i bottoni ed è invece completamente dinamico: provate ad aggiungere nuovi colori all’oggetto db e vedrete come nuovi bottoni verranno visualizzati una volta fatta la preview del chatbot.

Come per tutte le nostre altre referenze tecniche, potete verificare sulle nostre pagine GitHub la lista compleata dei metodi Firebase disponibili con lo scripting.

Riassumendo

Il chatbot di esempio mostrato in questo articolo lo potete trovare qui. Scaricatelo ed importatelo nel vostro account Xenioo per provarlo, modificarlo o usarlo come punto di partenza per i vostri chatbot.

Non vediamo l’ora di sapere come e quanto vi spingerete oltre nell’utilizzare questa funzionalità per realizzare chatbot sempre più dinamici e capaci.

The post Usare un database Firebase in un chatbot appeared first on Xenioo.

]]>
/usare-un-database-firebase-in-un-chatbot/feed/ 0
Using Firebase cloud data with your chatbot /using-firebase-cloud-data-with-your-chatbot/ /using-firebase-cloud-data-with-your-chatbot/#respond Mon, 15 Apr 2019 16:22:15 +0000 /?p=2195 In this articole we are going to learn how to build a dynamic data based chatbot capable of extracting and updating data in real-time from online database using Xenioo, Firebase and no single line of code.

The post Using Firebase cloud data with your chatbot appeared first on Xenioo.

]]>
In our previous articles, we’ve already explored how we could use basic cloud data to create a completely dynamic chatbot.

For many cases, it may prove to be enough but sometimes we just need the power of a full-fledged cloud database engine.

Enter Firebase Integration

Firebase is a well-known cloud-based database engine with a very generous free tier and a scaling that can easily handle millions of requests.

Our latest Xenioo update added full Firebase integration for both actions and scripting: let’s see how it all works!

First of all, we need to signup to for a new Firebase account. This can be done for free starting at https://firebase.google.com/ and following the signup procedure. If you already have a google account it will be quite fast.

After signup, you’re ready to create your first database project. Give it a name you like, accept the terms and click on Create.

For this article I’ll just go ahead and call my project XeniooIsAwesome.

Creating a service account

After a short while, your brand new cloud database will be ready.

What we need to do now is create an admin connection information that we can give to Xenioo.

To create a Firebase admin key, click on the small gear near “Project Overview” then click on “Project Settings”. After that, click on the “Service Accounts” tab.
On the bottom of the page, click on “Generate new private key”. This will generate a service account JSON file: keep this file somewhere safe as we will need it later.

Creating your database

Once you’re done creating your service account, it is time to move to the “Database” section and create your first database.

Just click on the “Create Database” button and Firebase will create everything for you.

Now note that Firebase, like most cloud based and many of the last generation engines is a document/property based storage engine.

This means that you don’t really have a standard Table and Schema approach. Data is instead stored in collections that can contain a number of different objects (rows, if you want to use the table concept) that can all have multiple different fields.

This may sound confusing initially but it will become clear very quickly and gives you a lot more space to your chatbot and data to grow and adapt according to your requirements.

Firebase new version

Some times after this article was initially published, Firebase updated his offer with two different databases engines: Cloud Firestore and Realtime Database. This article is focusing on Cloud Firestore integration.

We have already used the colors approach in the past. Let’s use it here too: our first collection will be called “Colors”.

Confirm the creation of your new collection and you’re ready to add new documents. Firebase has a very nice realtime editor that makes it very easy to add some sample data.

I’ll just add some color examples to my collection so that I can later use them in Xenioo.

Once you’re happy with your data, we are ready to leave our database console and move to our chatbot creation. We will be doing something similar to our previous dynamic WhatsApp chatbot but with some interesting twists.

Let’s build the chatbot

With our database created, we’re now ready to start building our chatbot.

What we’re going to do at first, is showing the user the list of possible colors as options. To do so, we will start adding our Firebase integration action at the very start of our chatbot.

The required fields are quite simple. Just remember to copy and paste your service account JSON in the Firebase Account JSON field on top.

With the above action, Xenioo will automatically connect to our Firebase instance and retrieve (LIST) every object in our Colors collection.

Each item retrieved by Xenioo will reflect the model of your Firebase collection. In our example the resulting JSON would be something like the following:

We want to present our users with a simple set of buttons to allow them to pick their favorite color.

We’ve multiple ways to do that (as it is often with Xenioo) but this time we’re going for the easiest using the power of Xenioo in-place variable translation which works even with JSON models.

We add a new Quick Reply Array action and, for the buttons we want, we just write our variables making a direct reference to array position and property. Much like we would be when working with live object models.

What happens automatically for you is that Xenioo will replace each placeholder in the text with a direct translation of your object, extracting the items at each position and using the Color property.

As a result, you’ve just built a Firebase based multiple choice chatbot without writing a line of code!

Of course, as options grow or shrink you would need to adapt your buttons array, but we’ve already covered the fully dynamic chatbot version with just a couple of lines of Xenioo cloud scripting.

Adding new database objects from your chatbot

What you’ll need to do at some point will surely be to insert or update existing database objects.

It may be some user-related statistics as well as some kind of order tracking or options saving system that you may need to retrieve later.

The good news is that the very same action we’ve just used can be configured for every need.

Continuing our example, we will allow our user to pick a custom color and tell it to us. After that, we will add the color to our database.

So we just add a new, Custom entry in our buttons array and manage the custom color with a standard Input action.

The magic happens in the same action we used at the beginning.

The only difference is that now the action is performing a CREATE and not a LIST. Also, we’re adding our object/document directly in our JSON payload.

Note how we specify the color value using the very same variable we’ve just used in our input action.

And that’s it!

As our user tell us a new favorite color, the new object is added to our database and can now be used in any other way we want.

We’ve just made a dynamic cloud data based chatbot capable of extracting and updating data in real-time. And still, not a single line of code.

Ok, but I like code

Sure, we all do! That’s why Firebase is also deeply integrated into Xenioo cloud scripting!

Now, wherever you need to access your database from any script you can just get a living reference of your database and use that directly from code.

Our previous example could very well be translated to the following code. Better yet, this example does not use direct indexes and is truly fully dynamic: just try adding a new color to the db object and see a brand new button as soon as you preview.

As with all our reference, you can check the full list of firebase database methods here where all the other scripting reference is constantly updated.

Build Anything

You’re welcome to try our example chatbot inside your account and let us know what you think.

We’re looking forward to sseeing how you’re going to push also this feature to the extreme with dynamic, data-driven and capable chatbots.

The post Using Firebase cloud data with your chatbot appeared first on Xenioo.

]]>
/using-firebase-cloud-data-with-your-chatbot/feed/ 0
TUTORIAL #9: Using Cloud Scripting to drive chatbot results /using-cloud-scripting/ /using-cloud-scripting/#respond Fri, 08 Dec 2017 17:37:42 +0000 https://www.xenioo.com/?p=556 Now that we have learned how to call external API services and use the results in our chatbot, we can step a little further and alter the API results to create completely new content. In order to do so, in this lesson, we are going to use Xenioo’s Cloud Scripting Action, and directly change and create content dynamically. You can follow our lesson directly from the video below. At the end of the post you will find a Xenioo bot ...

Read MoreTUTORIAL #9: Using Cloud Scripting to drive chatbot results

The post TUTORIAL #9: Using Cloud Scripting to drive chatbot results appeared first on Xenioo.

]]>
Now that we have learned how to call external API services and use the results in our chatbot, we can step a little further and alter the API results to create completely new content.

In order to do so, in this lesson, we are going to use Xenioo’s Cloud Scripting Action, and directly change and create content dynamically.

You can follow our lesson directly from the video below. At the end of the post you will find a Xenioo bot file that simply restores the example bot into your account for playback and testing. Let’s start!

YouTube Video

An artist lookup service

For this example, we’re going to build a very simple artist lookup service.

To do so, we’ll be using the iTunes public search API that can be found here. The API is very easy to use and has a good amount of parameters.

First we are going to use an Input Action to get the artist’s name from the user and then the API Service Action to retrieve the data and store it in a variable.

This time the service will reply with a standard 500 error when no artist is found: to handle this, we will use a Variable Switch Operation to redirect the chat flow to another interaction whenever the user submits an artist that does not exist. If the call is successful, we will store the results into a Xenioo variable.

Multiple Results

Sometimes API calls will return complex results that are difficult to handle with a single variable. The call we are using returns a complex object with multiple information, so a simple variable would not suffice. Furthermore, to make our example more complex, we would like to display the results in a carousel, with multiple cards for multiple collections or albums. The general idea is to let the user say the name of an artist, and display the latest two albums found.

To do so, we need to retrieve the results, as we are doing, and then split them into multiple variables that can be assigned to our cards properties: an easy job for Xenioo’s Cloud Script Action.

Let’s Rock

Simply put, Xenioo Cloud Script Action will execute standard JavaScript code on Xenioo’s cloud servers.

The Xenioo JavaScript runtime has all of the usual JavaScript goodies, and then some: each script action can access Xenioo global conversation, user and messaging objects. This means that at any point, you can alter the conversation state, add or remove variables and generally control the flow by pure coding.

Going back to our artist lookup, what we need to do now is to get the API result variable, transform the JSON into a real JavaScript object and create as many variables as required with all the values we need.

Once we know the iTunes API model it is just a matter of a couple of lines of code.

Once we have all the variables we need we can create a Carousel Action and assign them to all the properties we want to fill.

The title of the carousel can be the Album title, the subtitle can be the track name and the image can be the Album art.

Putting it all together

Once all our components are in place, we’re ready to give our bot a test run.

Submit your favorite artist and see how Xenioo automatically handles everything to deliver our result. Also, take a moment to look at how simple our design is for such a complex result!

In this lesson, we’ve learned how to use Xenioo’s Cloud Script Action to manipulate data and API results to create a simple lookup service.

As with all our lessons, you can find the chatbot sample in your Xenioo account so that you can import it to further experiment and learn.

The post TUTORIAL #9: Using Cloud Scripting to drive chatbot results appeared first on Xenioo.

]]>
/using-cloud-scripting/feed/ 0