firebase – Xenioo Wed, 14 Apr 2021 14:15:55 +0000 en-US hourly 1 https://wordpress.org/?v=5.6.12 /wp-content/uploads/2022/02/cropped-badge_611x611-32x32.png firebase – 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
How to make a Firebase chatbot using cloud data without code /firebase-chusing-firebase-cloud-data-without-code/ /firebase-chusing-firebase-cloud-data-without-code/#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 How to make a Firebase chatbot using cloud data without code 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. That’ why we made this article to talk about how to build a Firebase chatbot capable of extracting and updating data in real-time using Xenioo and no single line of code.

firebase chatbot example

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.

firebase integration

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.

create firebase account

Creating a database for your Firebase Chatbot

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.

create firebase databse

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: we can call our first collection “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 Firebase 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 Chatbot 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!

manage your firebase chatbot from the visual builder

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

firebase chatbot flow

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 we can use it 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.

We can translate our previuos example into 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.

if you like coding your Firebase chatbot you can do it too

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 seeing how you’re going to push also this feature to the extreme with dynamic, data-driven and capable chatbots.

The post How to make a Firebase chatbot using cloud data without code appeared first on Xenioo.

]]>
/firebase-chusing-firebase-cloud-data-without-code/feed/ 0